blob_id
stringlengths
40
40
language
stringclasses
1 value
repo_name
stringlengths
5
132
path
stringlengths
2
382
src_encoding
stringclasses
34 values
length_bytes
int64
9
3.8M
score
float64
1.5
4.94
int_score
int64
2
5
detected_licenses
listlengths
0
142
license_type
stringclasses
2 values
text
stringlengths
9
3.8M
download_success
bool
1 class
6d04613382f9a22ccb18bb4de5dc859a0413d8f3
Java
shareef-ragab/ERP
/HTERP/src/cn/joymates/erp/domain/base/BaseTransFlow.java
UTF-8
1,846
2.046875
2
[]
no_license
package cn.joymates.erp.domain.base; import java.math.BigDecimal; import java.util.Date; public class BaseTransFlow extends BaseVO { public BaseTransFlow() { tablename = "t_trans_flow"; fieldMap.put("uuid", "id"); fieldMap.put("transDate", "trans_date"); fieldMap.put("person", "person"); fieldMap.put("matOrPdct", "mat_or_pdct"); fieldMap.put("matPdctId", "mat_pdct_id"); fieldMap.put("srcWhSign", "src_wh_sign"); fieldMap.put("tgtWhSign", "tgt_wh_sign"); fieldMap.put("remark", "remark"); this.id = "id"; } private Integer uuid; private Date transDate; private String person; private String matOrPdct; private Integer matPdctId; private Integer srcWhSign; private Integer tgtWhSign; private String remark; public Integer getUuid() { return uuid; } public void setUuid(Integer uuid) { this.uuid = uuid; } public Date getTransDate() { return transDate; } public void setTransDate(Date transDate) { this.transDate = transDate; } public String getPerson() { return person; } public void setPerson(String person) { this.person = person; } public String getMatOrPdct() { return matOrPdct; } public void setMatOrPdct(String matOrPdct) { this.matOrPdct = matOrPdct; } public Integer getMatPdctId() { return matPdctId; } public void setMatPdctId(Integer matPdctId) { this.matPdctId = matPdctId; } public Integer getSrcWhSign() { return srcWhSign; } public void setSrcWhSign(Integer srcWhSign) { this.srcWhSign = srcWhSign; } public Integer getTgtWhSign() { return tgtWhSign; } public void setTgtWhSign(Integer tgtWhSign) { this.tgtWhSign = tgtWhSign; } public String getRemark() { return remark; } public void setRemark(String remark) { this.remark = remark; } }
true
d2e5f4dacd6521d29e78486428cdc5ffaaa53127
Java
JimSP/gate
/gate-ldap-data/src/main/java/com/github/jimsp/gate/ldap/repositories/LdapGateGroupRepository.java
UTF-8
478
1.890625
2
[]
no_license
package com.github.jimsp.gate.ldap.repositories; import javax.naming.Name; import org.springframework.data.ldap.repository.LdapRepository; import org.springframework.stereotype.Repository; import com.github.jimsp.gate.ldap.entities.LdapGateGroup; @Repository("ldapGateGroupRepository") public interface LdapGateGroupRepository extends LdapRepository<LdapGateGroup> { public LdapGateGroup findByDn(final Name name); public LdapGateGroup findByName(final String value); }
true
ccd3401fad554e14e2c44793e900e44fc9bfdfe8
Java
DetrembleurArthur/ElementEngine
/engine/src/main/java/com/elemengine/binding/IntegerProperty.java
UTF-8
712
3.125
3
[ "MIT" ]
permissive
package com.elemengine.binding; public abstract class IntegerProperty extends NumberProperty<Integer> { @Override public void bindAddition(Property<Integer> property, Integer factor) { addListener(() -> property.setValue(getValue() + factor)); } @Override public void bindMultiplication(Property<Integer> property, Integer factor) { addListener(() -> property.setValue(getValue() * factor)); } @Override public void bindSubstraction(Property<Integer> property, Integer factor) { addListener(() -> property.setValue(getValue() - factor)); } @Override public void bindDivision(Property<Integer> property, Integer factor) { addListener(() -> property.setValue(getValue() / factor)); } }
true
181516bdf0fb50c18684add7f8a5d66c1b230aab
Java
qstpss/learningSpring
/boot/src/main/java/com/noname/learningSpring/controllers/ProductController.java
UTF-8
1,289
1.953125
2
[]
no_license
/***************************************************************** * Gridnine AB http://www.gridnine.com * Project: BOF VIP-Service * * $Id: ProductController.java 2018-11-14 17:46 tkachenko $ *****************************************************************/ package com.noname.learningSpring.controllers; import com.noname.learningSpring.repositories.ProductRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.servlet.ModelAndView; import java.util.Optional; @Controller public class ProductController { private static final int BUTTONS_TO_SHOW = 3; private static final int INITIAL_PAGE = 0; private static final int INITIAL_PAGE_SIZE = 5; private static final int[] PAGE_SIZES = {5, 10}; @Autowired private ProductRepository productRepository; @GetMapping(value = {"/"}) public ModelAndView homepage( @RequestParam("pageSize") Optional<Integer> pageSize, @RequestParam("page") Optional<Integer> page) { return null; } }
true
d5511d5eb9d8913244e937175ec05819ee938b08
Java
kavyasri-coder/ananya-coding-practice
/src/main/java/in/kavyasri/udemy/sorting_algorithms/SelectionSort.java
UTF-8
722
3.515625
4
[]
no_license
package in.kavyasri.udemy.sorting_algorithms; public class SelectionSort { public static void main(String[] args) { SelectionSort selection = new SelectionSort(); int[] arr = {52,4,2,78,34,29}; selection.selectionSort(arr); } public void selectionSort(int[] arr) { for (int i = arr.length - 1; i > 0; i--) { int l = 0; for (int j = 0; j <= i; j++) { if (arr[j] > arr[l]) { l = j; } } int temp = arr[l]; arr[l] = arr[i]; arr[i] = temp; } for (int i = 0; i < arr.length; i++) { System.out.println(arr[i]); } } }
true
e4066fd052a4ef8f1b82382e7a5c57d4e4a5b475
Java
99najib/ProfoundRadianceTax
/src/main/java/com/qatest/PR/pages/MakeInOfficeAppointment.java
UTF-8
1,535
2.234375
2
[]
no_license
package com.qatest.PR.pages; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.FindBy; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.WebDriverWait; import org.testng.Assert; import org.testng.annotations.Test; public class MakeInOfficeAppointment { public WebDriver driver; public MakeInOfficeAppointment(WebDriver driver){ this.driver = driver; } // Web Elements - <<Make An Appointment For In-office Appointment>> form @FindBy(linkText="I Accept") WebElement iAcceptBtn; @FindBy(linkText="IN-OFFICE APPOINTMENT") WebElement inOfficeAppmnt; @FindBy(xpath="//h1[contains(text(), 'Make An Appointment')]") WebElement makeAppmntPgTitle; @Test () // Methods - <<Make An Appointment For In-office Appointment>> form public void makeInOfficeAppointmentElementsAndMethods() { try { System.out.println("I am here inside the methode:......."); Thread.sleep(4000); // Wait statement iAcceptBtn.click(); Thread.sleep(4000); // Wait statement inOfficeAppmnt.click(); Thread.sleep(6000); Assert.assertTrue(makeAppmntPgTitle.isDisplayed(), "<<Make An Appointment For In-office Appointment form>> page title is not displayed" ); } catch (InterruptedException e) { } } } /** * ********************************************************************* * End of the file * ********************************************************************* */
true
9687eadb533f50838a71713c0a3c140efca50ac0
Java
Bouddha-ctrl/spring-miniProjet-bll
/src/main/java/com/ensah/core/service/Implementation/EnseignantServiceImp.java
UTF-8
893
2.046875
2
[]
no_license
package com.ensah.core.service.Implementation; import java.util.List; import javax.transaction.Transactional; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.ensah.core.dao.IEnseignantDao; import com.ensah.core.metier.Enseignant; import com.ensah.core.service.Interface.IEnseignantService; @Service @Transactional public class EnseignantServiceImp implements IEnseignantService { @Autowired private IEnseignantDao dao; @Override public void add(Enseignant E) { } @Override public void update(Enseignant e) { } @Override public void delete(Enseignant e) { } @Override public void deleteById(int id) { } @Override public List<Enseignant> getAllEnseignant() { return dao.findAll(); } @Override public Enseignant GetEnseignantById(int id) { return dao.findById(id).get(); } }
true
8a4e973226f44e33cfe646791b249e483d6a34a2
Java
Sayantika23/Web-Checkers-Multiplayer
/src/test/java/MoveTests.java
UTF-8
1,794
3
3
[]
no_license
import com.webcheckers.model.Move; import javafx.util.Pair; import org.junit.After; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotEquals; import static org.junit.Assert.assertNotNull; /** * The Class MoveTests. * * @author <a href='mailto:kk3671@rit.edu'>Kishan K C</a> */ @SuppressWarnings("restriction") public class MoveTests { /** The game. */ private Move move; private Move move1; private Move move2; public int currRow = 0, currCol=0, movRow=1, movCol=1; @Before public void setup() { this.move = new Move(currRow, currCol, movRow, movCol); } @After public void destroy() { this.move = null; } /** * Move Space should not be null. */ @Test public void MoveSpaceShouldNotBeNull() { Pair<Integer, Integer> spaceMoved = this.move.getSpaceInbetween(); assertNotNull("Space moved must not be null", spaceMoved.getValue()); } /** * Move Jump should have one skip. */ @Test public void SpaceMustBeSkippedForJump() { this.move = new Move(0, 0, 2, 2); Pair<Integer, Integer> spaceMoved = this.move.getSpaceInbetween(); assertEquals(Long.valueOf(1),Long.valueOf(spaceMoved.getValue())); } /** * Move object should be equal with same value for rows and columns */ @Test public void MoveMustBeEqualForSameSourceAndTarget() { this.move = new Move(0, 0, 2, 2); this.move1 = new Move(0, 0, 2, 2); this.move2 = new Move(1, 1, 2, 2); assertEquals(this.move, this.move1); assertEquals(this.move, this.move); assertNotEquals(this.move, currCol); assertNotEquals(this.move, this.move2); } }
true
3dc447148f5af77fbb397c00741892fe50f0ff63
Java
lixiaogangyuanqitec/PackingLinesManage
/src/com/yuanqi/packinglines/service/task/TaskService.java
GB18030
1,275
2.25
2
[]
no_license
package com.yuanqi.packinglines.service.task; import java.util.List; import org.apache.ibatis.session.SqlSession; import org.eclipse.swt.SWT; import org.eclipse.swt.widgets.Table; import org.eclipse.swt.widgets.TableItem; import com.yuanqi.packinglines.entity.task.Task; import com.yuanqi.packinglines.inter.TaskOperation; import com.yuanqi.packinglines.mybatis.MyBatisUtil; /*** * ҵ߼ * @author lixiaogang * */ public class TaskService { private SqlSession session=MyBatisUtil.getSqlSession(); private TaskOperation taskOperation = session.getMapper(TaskOperation.class); /** * IDѯϢ * @author lixiaogang * @param table * @param orderId */ public void getDataTaskByOrderId(Table table,String orderId){ List<Task> task=taskOperation.selectTaskByOrderId(orderId); for(int i=0;i<task.size();i++){ TableItem item1_1 = new TableItem(table, SWT.NONE); String taskStatus="δ"; if(task.get(i).getTaskStatus().equals("1")){ taskStatus=""; } item1_1.setText(new String[] { ""+task.get(i).getTaskId()+"",""+task.get(i).getTaskName()+"",""+task.get(i).getNum()+"",""+taskStatus+"",""+task.get(i).getMaterialId()+""}); } } }
true
c2471b122b3134be7724bf346024dc332913ea82
Java
Fast0n/AixiaopingProjects
/app/src/main/java/com/weslide/lovesmallscreen/Application.java
UTF-8
4,940
1.703125
2
[]
no_license
package com.weslide.lovesmallscreen; import android.content.Context; import android.content.Intent; import android.util.Log; import android.view.View; import com.alibaba.baichuan.android.trade.AlibcTradeSDK; import com.alibaba.baichuan.android.trade.callback.AlibcTradeInitCallback; import com.igexin.sdk.PushManager; import com.rey.material.app.ThemeManager; import com.squareup.leakcanary.LeakCanary; import com.umeng.analytics.MobclickAgent; import com.umeng.socialize.PlatformConfig; import com.weslide.lovesmallscreen.activitys.CrashHandler; import com.weslide.lovesmallscreen.managers.LocationService; import com.weslide.lovesmallscreen.utils.AppUtils; import com.weslide.lovesmallscreen.view_yy.model.CustomizeMessage; import com.weslide.lovesmallscreen.view_yy.model.CustomizeMessageItemProvider; import net.aixiaoping.unlock.views.UnlockView; import io.rong.imkit.RongIM; import io.rong.imlib.model.Conversation; import io.rong.imlib.model.Message; import io.rong.imlib.model.UserInfo; import io.rong.message.RichContentMessage; //import com.umeng.analytics.MobclickAgent; /** * Created by xu on 2016/5/23. */ public class Application extends ArchitectureAppliation { public boolean alreadyInit = false; private UnlockView unlockView; public LocationService locationService; @Override public void onCreate() { super.onCreate(); LeakCanary.install(this); AlibcTradeSDK.asyncInit(this, new AlibcTradeInitCallback() { @Override public void onSuccess() { // T.showShort(Application.this,"初始化成功"); } @Override public void onFailure(int i, String s) { // T.showShort(Application.this,"初始化失败"); } }); //友盟数据统计场景设置 MobclickAgent.setScenarioType(this, MobclickAgent.EScenarioType.E_UM_NORMAL); //初始化融云 RongIM.init(this, Constants.RONGIM_APP_KEY); RongIM.registerMessageType(CustomizeMessage.class); RongIM.getInstance().registerMessageTemplate(new CustomizeMessageItemProvider()); RongIM.getInstance().setReadReceiptConversationTypeList(Conversation.ConversationType.PRIVATE); initListenner(); } private void initListenner() { //会话界面操作监听 RongIM.setConversationBehaviorListener(new RongIM.ConversationBehaviorListener() { @Override public boolean onUserPortraitClick(Context context, Conversation.ConversationType conversationType, UserInfo userInfo) { return false; } @Override public boolean onUserPortraitLongClick(Context context, Conversation.ConversationType conversationType, UserInfo userInfo) { return false; } @Override public boolean onMessageClick(Context context, View view, Message message) { if (message.getContent() instanceof RichContentMessage) { AppUtils.toGoods(context, ((RichContentMessage) message.getContent()).getExtra()); return true; } return false; } @Override public boolean onMessageLinkClick(Context context, String s) { return false; } @Override public boolean onMessageLongClick(Context context, View view, Message message) { return false; } }); } /** * 初始化整个应用程序 */ public void initApplication() { if (!alreadyInit) { super.init(); CrashHandler crashHandler = CrashHandler.getInstance(); crashHandler.init(getApplicationContext()); // SDK初始化,第三方程序启动时,都要进行SDK初始化工作 Log.d("GetuiSdkDemo", "initializing sdk..."); PushManager.getInstance().initialize(this.getApplicationContext()); locationService = new LocationService(getApplicationContext()); PlatformConfig.setQQZone(Constants.QQ_APP_ID, Constants.QQ_APP_KEY); PlatformConfig.setWeixin(Constants.WEXIN_APP_ID, Constants.WEXIN_APP_APPSECRET); ThemeManager.init(this, 2, 0, null); setUnlockView(new UnlockView(this)); Intent intent = new Intent(getApplicationContext(), AthanasiaService.class); startService(intent); //启动一个服务,长期在后台隔半个小时刷新一次 Intent refushIntent = new Intent(this, RefushService.class); startService(refushIntent); alreadyInit = true; } } public UnlockView getUnlockView() { return unlockView; } public void setUnlockView(UnlockView unlockView) { this.unlockView = unlockView; } }
true
f2e532c0ed2bdacdf0269adaf446c9218267ce6b
Java
kugimasa/DesignPattern
/Flyweight/MyPool.java
UTF-8
555
3.0625
3
[]
no_license
class MyPool{ java.util.HashMap pool = new java.util.HashMap(); void putPerson(Person person){ pool.put(person.job, person); } Person getPerson(String job, String name){ Person result = (Person) pool.get(job); if( result == null ){ //If there is no Object yet //Create new Object and add to HashMap result = new Person(job); pool.put(job, result); } //Changing the name of the shared object result.name = name; return result; } }
true
b1f57206bd996362e0717837a036d215f9b1da74
Java
handezVN/QuizOnline
/src/java/Servlet/CreateSubjectServlet.java
UTF-8
4,076
2.40625
2
[]
no_license
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package Servlet; import DAO.SubjectDao; import java.io.IOException; import java.io.PrintWriter; import java.sql.Date; import java.sql.SQLException; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.logging.Level; import java.util.logging.Logger; 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 javax.servlet.http.HttpSession; /** * * @author handez */ @WebServlet(name = "CreateSubjectServlet", urlPatterns = {"/CreateSubjectServlet"}) public class CreateSubjectServlet 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"); try (PrintWriter out = response.getWriter()) { String name = request.getParameter("name"); String password = request.getParameter("password"); HttpSession session = request.getSession(); String email = (String) session.getAttribute("email"); String date_tmp = request.getParameter("date"); String time_tmp = request.getParameter("time"); int attempt = Integer.parseInt(request.getParameter("attempt")); int time = Integer.parseInt(time_tmp); time = Math.abs(time); SubjectDao dao = new SubjectDao(); String id = "Sb"+(dao.getAllSubject().size()+1) ; Boolean status = Boolean.parseBoolean(request.getParameter("status")); String date_tmp1[] = date_tmp.split("T"); String date = date_tmp1[0]; date = date +" "+date_tmp1[1]+":00"; System.out.println(date); int result = -1; result = dao.addNewSubject(id, email, password, name, date, time,attempt,status); if(result!=-1){ request.getRequestDispatcher("AdminPage.jsp").forward(request, response); } } catch (SQLException ex) { Logger.getLogger(CreateSubjectServlet.class.getName()).log(Level.SEVERE, null, ex); } } // <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> }
true
006af23cffeb61c355b315859ea05aebe028547c
Java
oflarcade/lambda
/src/edu/esprit/univ/IEtudiantService.java
UTF-8
591
2.0625
2
[]
no_license
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package edu.esprit.univ; import java.util.TreeSet; /** * * @author Mehdi */ public interface IEtudiantService<T> { public void ajouterEtudiant(T t); public void supprimerEtudiant(T t); public boolean chercherEtudiant(Etudiant e); public boolean chercherEtudiant(int cin); public void afficher(); public TreeSet<Etudiant> trierEtudiantsNom(); }
true
579bd096721e1ba499c399a32a837546d414e9df
Java
Yans-Chou/CodePractise
/.github/workflows/AddTest.java
UTF-8
1,066
2.90625
3
[]
no_license
package Lanqiao; import java.util.Scanner; /** * @author Zhouyan * @create 2020-03-03 20:45 */ public class AddTest { public static void main(String[] args) { Scanner key = new Scanner(System.in); int[] a = new int[101]; int[] b = new int[101]; int[] c = new int[101]; String aa = key.next(); String bb = key.next(); int i, j = 0, k, t = 0; for (i = 0; i < aa.length(); i++) { a[i] = aa.charAt(aa.length() - 1 - i) - 48;//必须-48,将ASCII码转换 } for (i = 0; i < bb.length(); i++) { b[i] = bb.charAt(bb.length() - 1 - i) - 48; } for (i = 0; i < 101; i++) { k = a[i] + b[i] + j; j = k / 10; c[i] = k % 10; } for (i = c.length - 1; i >= 0; i--) { if (c[i] != 0) { t = i; break; } } for (i = t; i >= 0; i--) { System.out.print(c[i]); } } }
true
1e0d6ab14546288b547760c66c82efa87ce9855d
Java
LBouchara/myTennisTracker
/app/src/main/java/com/boucharalaura/mytennistracker/DisplayData.java
UTF-8
7,897
2.28125
2
[]
no_license
package com.boucharalaura.mytennistracker; /** * Created by BoucharaLaura on 26/04/2018. */ import android.content.Context; import android.graphics.Color; import android.graphics.Typeface; import android.net.Uri; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TableLayout; import android.widget.TableRow; import android.widget.TextView; import java.util.ArrayList; /** * A simple {@link Fragment} subclass. * Activities that contain this fragment must implement the * {@link DisplayData.OnFragmentInteractionListener} interface * to handle interaction events. * Use the {@link DisplayData#newInstance} factory method to * create an instance of this fragment. */ public class DisplayData extends Fragment { public View rootView; public TextView players; public TextView score; public TextView place; public TextView date; public TextView statistic; private OnFragmentInteractionListener mListener; public DisplayData() { // Required empty public constructor } /** * Use this factory method to create a new instance of * this fragment using the provided parameters. * * @return A new instance of fragment DisplayData. */ public static DisplayData newInstance() { DisplayData fragment = new DisplayData(); return fragment; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { rootView = inflater.inflate(R.layout.matches_list_tennis_traker, container, false); DBGestionnaire gestionnaire = new DBGestionnaire(getActivity()); gestionnaire.open(getActivity()); ArrayList<TennisMatch> matchesList = gestionnaire.getAllMatches(); if(matchesList != null) { TableLayout matchesListLayout = rootView.findViewById(R.id.matches_list); String playersData; String scoreData; String placeData; String dateData; String statisticData; for(int i=0 ; i<matchesList.size(); i ++) { playersData = matchesList.get(i).getPlayers().get(0) + " - " + matchesList.get(i).getPlayers().get(1); scoreData = matchesList.get(i).getScore(); placeData = matchesList.get(i).getPlace(); dateData = matchesList.get(i).getDate(); statisticData = matchesList.get(i).getStatistic(); TableRow match = new TableRow(this.getActivity()); match.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT, TableRow.LayoutParams.WRAP_CONTENT)); TableLayout matchInformation = new TableLayout(this.getActivity()); matchInformation.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT, TableRow.LayoutParams.WRAP_CONTENT)); TableRow matchMoreInformation = new TableRow(this.getActivity()); matchMoreInformation.setLayoutParams(new TableRow.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, TableRow.LayoutParams.WRAP_CONTENT)); TextView players = new TextView(this.getActivity()); players.setText(playersData); players.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT, TableRow.LayoutParams.WRAP_CONTENT, 1)); players.setBackgroundColor(Color.parseColor("#ff0099cc")); players.setTextColor(Color.WHITE); players.setTypeface(null, Typeface.BOLD); players.setTextSize(24); players.setPadding(5, 5, 5, 5); TextView score = new TextView(this.getActivity()); score.setText(scoreData); score.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT, TableRow.LayoutParams.WRAP_CONTENT, 1)); score.setBackgroundColor(Color.parseColor("#ff0099cc")); score.setTextColor(Color.WHITE); score.setTypeface(null, Typeface.BOLD); score.setTextSize(24); score.setPadding(5, 5, 5, 5); matchMoreInformation.addView(players); matchMoreInformation.addView(score); TableRow matchMainInformation = new TableRow(this.getActivity()); matchMainInformation.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT, TableRow.LayoutParams.WRAP_CONTENT)); TextView place = new TextView(this.getActivity()); place.setText(placeData); place.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT, TableRow.LayoutParams.WRAP_CONTENT, 1)); place.setTextSize(18); place.setPadding(5, 5, 5, 5); TextView date = new TextView(this.getActivity()); date.setText(dateData); date.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT, TableRow.LayoutParams.WRAP_CONTENT, 1)); date.setTextSize(18); date.setPadding(5, 5, 5, 5); matchMainInformation.addView(place); matchMainInformation.addView(date); TableRow matchStatistic = new TableRow(this.getActivity()); matchStatistic.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT, TableRow.LayoutParams.WRAP_CONTENT, 1)); TextView statistic = new TextView(this.getActivity()); statistic.setText(statisticData); statistic.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT, TableRow.LayoutParams.WRAP_CONTENT, 1)); statistic.setTextSize(18); statistic.setPadding(5, 5, 5, 5); matchStatistic.addView(statistic); matchInformation.addView(matchMoreInformation); matchInformation.addView(matchMainInformation); matchInformation.addView(matchStatistic); match.addView(matchInformation); matchesListLayout.addView(match); } } return rootView; } public void onButtonPressed(Uri uri) { if (mListener != null) { mListener.onFragmentInteraction(uri); } } public void setText(String txtPlayers, String txtScore, String txtPlace, String txtDate, String txtStatistic) { players.setText(txtPlayers); score.setText(txtScore); place.setText(txtPlace); date.setText(txtDate); statistic.setText(txtStatistic); } @Override public void onAttach(Context context) { super.onAttach(context); if (context instanceof OnFragmentInteractionListener) { mListener = (OnFragmentInteractionListener) context; } } @Override public void onDetach() { super.onDetach(); mListener = null; } /** * This interface must be implemented by activities that contain this * fragment to allow an interaction in this fragment to be communicated * to the activity and potentially other fragments contained in that * activity. * <p> * See the Android Training lesson <a href= * "http://developer.android.com/training/basics/fragments/communicating.html" * >Communicating with Other Fragments</a> for more information. */ public interface OnFragmentInteractionListener { void onFragmentInteraction(Uri uri); } }
true
a47dfbe83b37a8911685d4bc4193c012461231e3
Java
mafaldaluz14/crud.poc
/src/main/java/santander/crud/poc/user/UsersService.java
UTF-8
1,904
2.734375
3
[]
no_license
package santander.crud.poc.user; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import javax.transaction.Transactional; import java.util.List; import java.util.Objects; import java.util.Optional; @Service public class UsersService { private final UsersRepository usersRepository; @Autowired public UsersService(UsersRepository usersRepository) { this.usersRepository = usersRepository; } public List<Users> getUsers() { return usersRepository.findAll(); } public void addNewUser(Users user) { Optional<Users> userOptional = usersRepository.findUserByEmail(user.getEmail()); if (userOptional.isPresent()) { throw new IllegalStateException("Email taken"); } usersRepository.save(user); } public void deleteUser(Long userId) { boolean exists = usersRepository.existsById(userId); if (!exists) { throw new IllegalStateException( "user with id " + userId + " does not exist"); } usersRepository.deleteById(userId); } @Transactional public void updateUser(Long userId, String name, String email) { Users user = usersRepository.findById(userId) .orElseThrow( () -> new IllegalStateException( "user with Id " + userId + "does not exist") ); if (name!=null && name.length() > 0 && !Objects.equals(user.getName(), name)){ user.setName(name); } if (email!=null && email.length() > 0 && !Objects.equals(user.getEmail(), email)){ Optional<Users> userOptional = usersRepository.findUserByEmail(email); if (userOptional.isPresent()) { throw new IllegalStateException("Email taken"); } user.setEmail(email); } } }
true
5902438a4bf13d07ddfa5ce99cf8de6c49b8e937
Java
biosemantics/charaparser
/src/main/java/edu/arizona/biosemantics/semanticmarkup/markupelement/description/model/attributes/CharacterAttribute.java
UTF-8
3,136
1.8125
2
[ "Apache-2.0" ]
permissive
package edu.arizona.biosemantics.semanticmarkup.markupelement.description.model.attributes; public class CharacterAttribute { /* * <xs:attribute name="char_type" type="xs:NCName"/> <xs:attribute name="constraint"/> <xs:attribute name="constraintid"/> <xs:attribute name="from"/> <xs:attribute name="from_inclusive" type="xs:boolean"/> <xs:attribute name="from_unit" type="xs:NCName"/> <xs:attribute name="geographical_constraint"/> <xs:attribute name="in_brackets" type="xs:boolean"/> <xs:attribute name="modifier"/> <xs:attribute name="name"/> <xs:attribute name="organ_constraint"/> <xs:attribute name="other_constraint"/> <xs:attribute name="parallelism_constraint" type="xs:NCName"/> <xs:attribute name="taxon_constraint"/> <xs:attribute name="to"/> <xs:attribute name="to_inclusive" type="xs:boolean"/> <xs:attribute name="to_unit" type="xs:NCName"/> <xs:attribute name="type"/> <xs:attribute name="unit"/> <xs:attribute name="upper_restricted" type="xs:boolean"/> <xs:attribute name="value"/> <xs:attribute name="ontologyid" type="xs:string"/> <xs:attribute name="provenance" type="xs:string"/> <xs:attribute name="notes" type="xs:string"/> <xs:attribute name="is_modifier" type="xs:boolean"/> */ public static final String char_type = "char_type"; public static final String constraint = "constraint"; public static final String constraintid = "constraintid"; public static final String from = "from"; public static final String from_inclusive = "from_inclusive"; public static final String from_unit = "from_unit"; public static final String from_modifier = "from_modifier"; //elevation public static final String geographical_constraint = "geographical_constraint"; public static final String in_brackets = "in_brackets"; public static final String modifier = "modifier"; public static final String name = "name"; public static final String organ_constraint = "organ_constraint"; public static final String other_constraint = "other_constraint"; public static final String parallelism_constraint = "parallelism_constraint"; public static final String taxon_constraint = "taxon_constraint"; public static final String to = "to"; public static final String to_inclusive = "to_inclusive"; public static final String to_unit = "to_unit"; public static final String to_modifier = "to_modifier"; //elevation public static final String type = "type"; public static final String unit = "unit"; public static final String upper_restricted = "upper_restricted"; public static final String value = "value"; public static final String ontologyid = "ontologyid"; public static final String provenance = "provenance"; public static final String notes = "notes"; public static final String is_modifier="is_modifier"; public static final String establishment_means = "establishment_means"; public static final String src = "src"; // to hold src statement id. Information related to one BiologicalEntity could come from 2 or more sentences/statements. }
true
1649220a76bcb77fd906c26aee375f55bba183e1
Java
frankjunqi/FFMS
/src/org/openflashchart/chart/BaseGraphProperty.java
UTF-8
402
2.4375
2
[]
no_license
package org.openflashchart.chart; import org.openflashchart.json.JsonHelper; /** * * The basic elements of graphics,contains generally graphics as X or Y Axis etc. * @author zhuzhenhua */ public abstract class BaseGraphProperty implements BaseGraph { /** * @return String return string is formated by JsonHelper */ public String toString() { return JsonHelper.getJsonString(this); } }
true
91450caf0ce19c8e7bbe72fa16540f5b2ab8542c
Java
zhongxingyu/Seer
/Diff-Raw-Data/9/9_0ebfcc3b52909a2e5e40d98bf4c1497d3a0a1f1e/SQLInsert/9_0ebfcc3b52909a2e5e40d98bf4c1497d3a0a1f1e_SQLInsert_s.java
UTF-8
8,092
2.21875
2
[]
no_license
package org.cdlib.xtf.saxonExt.sql; import net.sf.saxon.expr.Expression; import net.sf.saxon.expr.SimpleExpression; import net.sf.saxon.expr.XPathContext; import net.sf.saxon.instruct.Executable; import net.sf.saxon.om.Axis; import net.sf.saxon.om.AxisIterator; import net.sf.saxon.om.Item; import net.sf.saxon.om.NodeInfo; import net.sf.saxon.style.ExtensionInstruction; import net.sf.saxon.trans.XPathException; import net.sf.saxon.value.AtomicValue; import net.sf.saxon.value.ObjectValue; import javax.xml.transform.TransformerConfigurationException; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; /** * An sql:insert element in the stylesheet. */ public class SQLInsert extends ExtensionInstruction { Expression connection; String table; boolean ignoreDuplicate = false; public void prepareAttributes() throws TransformerConfigurationException { table = getAttributeList().getValue("", "table"); if (table==null) { reportAbsence("table"); } String connectAtt = getAttributeList().getValue("", "connection"); if (connectAtt==null) { reportAbsence("connection"); } else { connection = makeExpression(connectAtt); } String ignoreAtt = getAttributeList().getValue("", "ignoreDuplicate"); if (ignoreAtt.matches("^true$|^yes$|^1$")) { ignoreDuplicate = true; } } public void validate() throws TransformerConfigurationException { super.validate(); connection = typeCheck("connection", connection); } public Expression compile(Executable exec) throws TransformerConfigurationException { return new InsertInstruction(connection, table, getColumnInstructions(exec), ignoreDuplicate); } public List getColumnInstructions(Executable exec) throws TransformerConfigurationException { List list = new ArrayList(10); AxisIterator kids = iterateAxis(Axis.CHILD); NodeInfo child; while (true) { child = (NodeInfo)kids.next(); if (child == null) { break; } if (child instanceof SQLColumn) { list.add(((SQLColumn)child).compile(exec)); } } return list; } private static class InsertInstruction extends SimpleExpression { public static final int CONNECTION = 0; public static final int FIRST_COLUMN = 1; String table; boolean ignoreDuplicate; public InsertInstruction(Expression connection, String table, List columnInstructions, boolean ignoreDuplicate) { Expression[] sub = new Expression[columnInstructions.size() + 1]; sub[CONNECTION] = connection; for (int i=0; i<columnInstructions.size(); i++) { sub[i+FIRST_COLUMN] = (Expression)columnInstructions.get(i); } this.table = table; setArguments(sub); this.ignoreDuplicate = ignoreDuplicate; } /** * A subclass must provide one of the methods evaluateItem(), iterate(), or process(). * This method indicates which of the three is provided. */ public int getImplementationMethod() { return Expression.EVALUATE_METHOD; } public String getExpressionType() { return "sql:insert"; } public Item evaluateItem(XPathContext context) throws XPathException { // Collect names of columns to be added StringBuffer statement = new StringBuffer(120); statement.append("INSERT "); if (ignoreDuplicate) statement.append("IGNORE "); statement.append("INTO " + table + " ("); for (int c=FIRST_COLUMN; c<arguments.length; c++) { if (c > FIRST_COLUMN) statement.append(','); SQLColumn.ColumnInstruction colInst = (SQLColumn.ColumnInstruction)arguments[c]; String colname = colInst.getColumnName(); statement.append(colname); } statement.append(") VALUES ("); // Add "?" marks for the variable parameters for (int c=FIRST_COLUMN; c<arguments.length; c++) { if (c > FIRST_COLUMN) statement.append(','); SQLColumn.ColumnInstruction colInst = (SQLColumn.ColumnInstruction)arguments[c]; if (colInst.evalSql()) { String val = colInst.getSelectValue(context).toString(); // Strip leading/trailing quotes from the expression. if ((val.startsWith("\"") && val.endsWith("\"")) || (val.startsWith("'") && val.endsWith("'"))) { val = val.substring(1, val.length()-1); } statement.append(val); } else statement.append("?"); } statement.append(')'); // Prepare the SQL statement (only do this once) Item conn = arguments[CONNECTION].evaluateItem(context); if (!(conn instanceof ObjectValue && ((ObjectValue)conn).getObject() instanceof Connection) ) { dynamicError("Value of connection expression is not a JDBC Connection", context); } Connection connection = (Connection)((ObjectValue)conn).getObject(); PreparedStatement ps = null; try { ps=connection.prepareStatement(statement.toString()); // Add the actual column values to be inserted int i = 1; for (int c=FIRST_COLUMN; c<arguments.length; c++) { AtomicValue v = (AtomicValue)((SQLColumn.ColumnInstruction)arguments[c]).getSelectValue(context); // TODO: the values are all strings. There is no way of adding to a numeric column String val = v.getStringValue(); // another hack: setString() doesn't seem to like single-character string values if (val.length()==1) val += " "; //System.err.println("Set statement parameter " + i + " to " + val); ps.setObject(i++, val); } ps.executeUpdate(); if (!connection.getAutoCommit()) { connection.commit(); } } catch (SQLException ex) { dynamicError("(SQL INSERT) " + ex.getMessage(), context); } finally { if (ps != null) { try { ps.close(); } catch (SQLException ignore) {} } } return null; } } } // // The contents of this file are subject to the Mozilla Public License Version 1.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.mozilla.org/MPL/ // // Software distributed under the License is distributed on an "AS IS" basis, // WITHOUT WARRANTY OF ANY KIND, either express or implied. // See the License for the specific language governing rights and limitations under the License. // // The Original Code is: all this file. // // The Initial Developer of the Original Code is Michael H. Kay. // // Portions created by (your name) are Copyright (C) (your legal entity). All Rights Reserved. // // Contributor(s): none. //
true
cfc1dd7de266a4b582ac9e60211fe10767a1647d
Java
lotusaa/jdk-source-code-reading
/java-collection/src/main/java/com/jpeony/collection/list/ListTest.java
UTF-8
742
3.140625
3
[]
no_license
package com.jpeony.collection.list; import java.util.ArrayList; import java.util.LinkedList; import java.util.Vector; /** * ArrayList、LinkedList、Vector、Set * * @author yihonglei */ public class ListTest { public static void main(String[] args) { // ArrayList:非线程安全,元素有顺序,高效,可重复 ArrayList<String> arrayList = new ArrayList<>(); arrayList.add("ooo"); // Vector:线程安全,效率低 Vector<String> vector = new Vector<>(); // LinkedList: LinkedList<String> linkedList = new LinkedList<>(); linkedList.addLast(""); linkedList.addFirst(""); linkedList.get(0); linkedList.remove("one"); } }
true
304be314693e11ac3836c002c9a42e8bf740314c
Java
MSZ0543/algorithm
/src/main/java/algorithm/greedy/Leetcode627_$$$.java
UTF-8
1,680
3.21875
3
[]
no_license
package algorithm.greedy; import org.junit.jupiter.api.Test; import java.util.Arrays; /** * @program: algorithm * @description: 任务调度器 * @author: szm * @create: 2020-02-22 17:28 **/ public class Leetcode627_$$$ { @Test public void test() { // System.out.println('----------start-----------'); char[] input = new char[]{'A','A','A','A','A','A','B','C','D','E','F','G'}; System.out.println(leastInterval(input, 2)); } /** * 解题思路: * 1、将任务按类型分组,正好A-Z用一个int[26]保存任务类型个数 * 2、对数组进行排序,优先排列个数(count)最大的任务, * 如题得到的时间至少为 retCount =(count-1)* (n+1) + 1 ==> A->X->X->A->X->X->A(X为其他任务或者待命) * 3、再排序下一个任务,如果下一个任务B个数和最大任务数一致, * 则retCount++ ==> A->B->X->A->B->X->A->B * 4、如果空位都插满之后还有任务,那就随便在这些间隔里面插入就可以,因为间隔长度肯定会大于n,在这种情况下就是任务的总数是最小所需时间 * * @param tasks * @param n * @return */ public int leastInterval(char[] tasks, int n) { int l = tasks.length; if(l < 2 || n < 1) return l; int[] map = new int[26]; for(char c : tasks) { map[c - 'A'] ++; } Arrays.sort(map); int maxCount = map[25]; int res = (maxCount - 1) * (n + 1) + 1; for(int i = 24; i >= 0 && map[i] == maxCount; i --) { res ++; } return Math.max(res, l); } }
true
eccc45a4024597b941e50e4b3622e3fd5e3ca07f
Java
arunvasudevan/AlgoImplementations
/src/main/java/com/ctci/chapter4/ValidateBST.java
UTF-8
770
3.546875
4
[]
no_license
package com.ctci.chapter4; import com.datastruct.TreeNode; //Validate if a given binary tree is a BST // Approach 2 - All left nodes are less than equal to root and all right nodes are greater than or equal to root. public class ValidateBST { Integer max = null; public boolean isBST(TreeNode root) { if (root == null) return false; final ValidateBST v = new ValidateBST(); return v.checkBST(root); } boolean checkBST(TreeNode root) { if (root == null) return true; if (!checkBST(root.left)) return false; System.out.println("Data:" + root.data); if (max == null || root.data > max) max = root.data; else return false; if (!checkBST(root.right)) return false; return true; } }
true
d69dcaef6efae0e26d6e7b4cd1481256107219cb
Java
mkumar7/Computer_Architecture_Organization
/MANISH_KUMAR_HW6/src/implementation/Writeback.java
UTF-8
4,184
2.484375
2
[]
no_license
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package implementation; import baseclasses.CpuCore; import baseclasses.InstructionBase; import baseclasses.Latch; import baseclasses.PipelineStageBase; import java.util.ArrayList; import java.util.List; import utilitytypes.EnumOpcode; import utilitytypes.ICpuCore; import utilitytypes.IGlobals; import utilitytypes.IProperties; import utilitytypes.IRegFile; import utilitytypes.Logger; import utilitytypes.Operand; /*** Writeback Stage ***/ class Writeback extends PipelineStageBase { public Writeback(CpuCore core) { super(core, "Writeback"); } boolean shutting_down = false; @Override public void compute() { // Things to get from globals: // - CPU run state // - PRF (type IRegFile) // - ROB (type InstructionBase[]) // Loop over all input ports, and for each input.... // Skip over any inputs without valid instruction // Update ROB entry to latest state of instruction. // (The entry is originally filled with the freshly renamed instruction. // Once it reaches Writeback, it now has all of its inputs and any // computed result value.) // call core.incCompleted() // If the run state is RUN_STATE_FLUSH *and* core.numCompleted()==core.numIssued()) // then change CPU run state to RUN_STATE_RECOVERY. // If a completing instruction needs writeback, copy the result value from // the instruction to the PRF entry. For diagnostic purposes, also // mark the PRF entry as being a FLOAT if the result is a float. // If the completing instruction DOES NOT need writeback, simply mark // the PRF entry as valid. // If the CPU run state is RUN_STATE_RUNNING and the completing instruction // has a fault, then mark its PRF entry as having a fault. // (Or you can just rely on the fact that updating the ROB entry // also carries with it fault information.) // Change the run state to RUN_STATE_FAULT. // Don't forget to consume the input. // Set the activity string to indicate all instructions just completed ICpuCore core = getCore(); List<String> doing = new ArrayList<String>(); if (shutting_down) { setActivity("Shutting down"); } IGlobals gbl = (GlobalData)core.getGlobals(); if (shutting_down && core.numCompleted() >= core.numDispatched()) { gbl.setProperty("run", false); } IRegFile register_file = gbl.getRegisterFile(); int inputs_nmb = this.getInputRegisters().size(); for (int j=0; j<inputs_nmb; j++) { Latch input = readInput(j); if (input.isNull()) continue; InstructionBase ins = input.getInstruction(); if (ins.getOpcode().needsWriteback()) { Operand op = ins.getOper0(); int register = op.getRegisterNumber(); int val = input.getResultValue(); String register_name = op.getRegisterName(); boolean isfloat = input.isResultFloat(); addStatusWord(register_name + "=" + input.getResultValueAsString()); register_file.setValue(register, val, isfloat); } doing.add(ins.toString()); if (ins.isValid()) core.incCompleted(); while (ins.getOpcode() == EnumOpcode.HALT) { shutting_down = true; } input.consume(); } setActivity(String.join("\n", doing)); } }
true
d0f293836efdd83c049ca367668c8ae51591eb7d
Java
LittleBoy1269/gitSwust
/Swust_Activity/src/com/swust/person/personAdviceActivity.java
UTF-8
1,935
2.125
2
[]
no_license
package com.swust.person; import com.swust.activity.R; import com.swust.delicious.DeliciousActivity; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.view.Window; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.Toast; public class personAdviceActivity extends Activity implements OnClickListener{ public EditText adviceEdit; public String advice=null; public Button Complete; public ImageView Back; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.person_advice); adviceEdit=(EditText) findViewById(R.id.adviceContent); Complete=(Button) findViewById(R.id.adviceComplete); Back=(ImageView) findViewById(R.id.advice_back); Back.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { // TODO Auto-generated method stub personAdviceActivity.this.finish(); } }); Complete.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { advice =adviceEdit.getText().toString().trim(); if(advice.length()==0) { Toast.makeText(personAdviceActivity.this, "请输入您的建议", Toast.LENGTH_SHORT).show(); } else{ Toast.makeText(personAdviceActivity.this, "感谢你的反馈,我们会努力的", Toast.LENGTH_SHORT).show(); Intent intent = new Intent(personAdviceActivity.this,com.swust.activity.MainActivity.class); intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); startActivity(intent); } } }); } @Override public void onClick(View arg0) { // TODO Auto-generated method stub } }
true
43d28b2232b500bea25784add35308ae6e85d54e
Java
DmitryVitutnev/object-oriented-design
/decorator/src/main/java/modifiers/AddModifier.java
UTF-8
496
3.40625
3
[]
no_license
package modifiers; public class AddModifier extends BaseModifier{ private double koef; public AddModifier(double koef) { this.koef = koef; } public AddModifier(IModifier previousModifier, double koef) { super(previousModifier); this.koef = koef; } public double applyModifier(double value) { if(previousModifier == null) { return value + koef; } return previousModifier.applyModifier(value) + koef; } }
true
0f90e0abf604a1498db421c3907b46831a65eb5a
Java
mcherif/bitmovinexp
/src/main/java/com/bitmovin/api/sdk/model/OutputType.java
UTF-8
1,267
1.773438
2
[ "MIT" ]
permissive
package com.bitmovin.api.sdk.model; import java.util.Objects; import java.util.Arrays; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonSubTypes; import com.fasterxml.jackson.annotation.JsonTypeInfo; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonValue; public enum OutputType { AKAMAI_NETSTORAGE("AKAMAI_NETSTORAGE"), AZURE("AZURE"), GENERIC_S3("GENERIC_S3"), GCS("GCS"), FTP("FTP"), LOCAL("LOCAL"), S3("S3"), S3_ROLE_BASED("S3_ROLE_BASED"), SFTP("SFTP"), AKAMAI_MSL("AKAMAI_MSL"), LIVE_MEDIA_INGEST("LIVE_MEDIA_INGEST"), GCS_SERVICE_ACCOUNT("GCS_SERVICE_ACCOUNT"); private String value; OutputType(String value) { this.value = value; } @JsonValue public String getValue() { return value; } @Override public String toString() { return String.valueOf(value); } @JsonCreator public static OutputType fromValue(String text) { for (OutputType b : OutputType.values()) { if (String.valueOf(b.value).equals(text)) { return b; } } return null; } }
true
0b845355778e4ed4b9156599e0ceb35422d1b68b
Java
wuzhen922/SmartCityProject
/SimCity/src/main/java/be/uantwerpen/sc/services/sim/SimWorkerService.java
UTF-8
1,117
2.28125
2
[]
no_license
package be.uantwerpen.sc.services.sim; import be.uantwerpen.sc.models.security.User; import be.uantwerpen.sc.models.sim.SimWorker; import be.uantwerpen.sc.repositories.sim.SimWorkerRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.ArrayList; import java.util.List; /** * Created by Thomas on 03/04/2016. */ @Service public class SimWorkerService { @Autowired private SimWorkerRepository simWorkerRepository; public Iterable<SimWorker> findAll() { return this.simWorkerRepository.findAll(); } public boolean delete(String workerName) { SimWorker w = findByWorkerName(workerName); if(w != null) { this.simWorkerRepository.delete(w.getId()); return true; } return false; } public int getNumberOfWorkers() { return this.simWorkerRepository.findAll().size(); } public SimWorker findByWorkerName(String workerName) { return simWorkerRepository.findByWorkerName(workerName); } }
true
3866fcff22279ec6f84c44178e587fdf7d04d34a
Java
umbertolia/BanqueManager
/BanqueManager/src/main/java/metier/interfaces/IBanqueDAO.java
ISO-8859-1
1,169
2.140625
2
[]
no_license
/** * */ package metier.interfaces; import java.util.List; import metier.beans.Badge; import metier.beans.Client; import metier.beans.Compte; import metier.beans.Employe; import metier.beans.Groupe; import metier.beans.Operation; /** * Auteur HDN * Cre le Nov 25, 2018 * * Cette classe permet de ... */ public interface IBanqueDAO { public Client addClient(Client c); public boolean addEmploye(Employe e); public void addGroupe(Groupe g); public void addEmployeToGroupe(Groupe groupe, Employe employe) ; public void addCompte(Compte c, Client client, Long numEmp ); public void addOperation(Operation op,Long numCpte,Long numEmp); public Client consulterClientsParNomParPrenom(String nom, String prenom); public List<Client> consulterClients(); public List<Groupe> consulterGroupes(); public Groupe consulterGroupeParId(Long numGroupe); public List<Employe> consulterEmployes(); public List<Employe> consulterEmployesParNomParPrenom(String nom, String prenom); public Employe consulterEmploye(Long idEmp); public void creerBadge(Badge badge, Employe employe); }
true
bfb785cb2d3c2e4e8697ed58460a69151d9230bb
Java
TelinkDev/EclipseTC32Plugin
/IDE_Eclipse/com.telink.tc32eclipse.core.managedbuildsystem/src/com/telink/tc32eclipse/mbs/SizeOptionsApplicabilityCalculator.java
UTF-8
5,053
1.851563
2
[]
no_license
/****************************************************************************** * Copyright (c) 2009-2016 Telink Semiconductor Co., LTD. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Public License v3 * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/gpl.html * ----------------------------------------------------------------------------- * Module: * Purpose: * Reference : * $Id: SizeOptionsApplicabilityCalculator.java 851 20.1.08-07 19:37:00Z innot $ * *******************************************************************************/ package com.telink.tc32eclipse.mbs; import org.eclipse.cdt.managedbuilder.core.BuildException; import org.eclipse.cdt.managedbuilder.core.IBuildObject; import org.eclipse.cdt.managedbuilder.core.IHoldsOptions; import org.eclipse.cdt.managedbuilder.core.IOption; import org.eclipse.cdt.managedbuilder.core.IOptionApplicability; import com.telink.tc32eclipse.PluginIDs; //import com.telink.tc32eclipse.core.toolinfo.Size; /** * Calculate which size options are applicable. * * Depending on the selected format some options are enabled / disabled * <ul> * <li>The -t option is only applicable for the berkeley format.</li> * <li>The -x option is not applicable for the TC32 format.</li> * <li>The -mcu option is only applicable for the TC32 format</li> * </ul> * * @author Peter Shieh * @version 1.0 * @since 0.1 * */ public class SizeOptionsApplicabilityCalculator implements IOptionApplicability { /* * (non-Javadoc) * * @see org.eclipse.cdt.managedbuilder.core.IOptionApplicability#isOptionEnabled(org.eclipse.cdt.managedbuilder.core.IBuildObject, * org.eclipse.cdt.managedbuilder.core.IHoldsOptions, * org.eclipse.cdt.managedbuilder.core.IOption) */ public boolean isOptionEnabled(IBuildObject configuration, IHoldsOptions holder, IOption option) { // the totals option is only enabled when the berkeley format // is selected. if (option.getId().contains("totals")) { if (berkeleySelected(option, holder)) { return true; } } // the bin option is only enabled when the TC32 format // is not selected. if (option.getId().contains("binary")) { //if (!TC32Selected(option, holder)) { return true; //} } // Don't need to handle the targetmcu option, as it is // invisible anyways. return false; } /* * (non-Javadoc) * * @see org.eclipse.cdt.managedbuilder.core.IOptionApplicability#isOptionUsedInCommandLine(org.eclipse.cdt.managedbuilder.core.IBuildObject, * org.eclipse.cdt.managedbuilder.core.IHoldsOptions, * org.eclipse.cdt.managedbuilder.core.IOption) */ public boolean isOptionUsedInCommandLine(IBuildObject configuration, IHoldsOptions holder, IOption option) { // the totals option is used on the command // line if berkeley is selected if (option.getId().contains("totals")) { return berkeleySelected(option, holder); } // the hex option is used on the command // line if TC32 format is not selected if (option.getId().contains("binary")) { return true; //return !TC32Selected(option, holder); } return true; } /* * (non-Javadoc) * * @see org.eclipse.cdt.managedbuilder.core.IOptionApplicability#isOptionVisible(org.eclipse.cdt.managedbuilder.core.IBuildObject, * org.eclipse.cdt.managedbuilder.core.IHoldsOptions, * org.eclipse.cdt.managedbuilder.core.IOption) */ public boolean isOptionVisible(IBuildObject configuration, IHoldsOptions holder, IOption option) { // all options are visible // the targetmcu option is invisible by default, as it has no category return true; } private boolean berkeleySelected(IOption option, IHoldsOptions holder) { //boolean hasTC32 = false; //Size.getDefault().hasTC32Option(); IOption formatoption = null; //if (hasTC32) { // formatoption = holder // .getOptionBySuperClassId(PluginIDs.PLUGIN_TOOLCHAIN_TOOL_SIZE_FORMATWITHTC32); //} else //{ formatoption = holder .getOptionBySuperClassId(PluginIDs.PLUGIN_TOOLCHAIN_TOOL_SIZE_FORMAT); //} try { if (formatoption.getSelectedEnum().endsWith("berkeley")) { return true; } } catch (BuildException e) { // should not happen e.printStackTrace(); } return false; } /* private boolean TC32Selected(IOption option, IHoldsOptions holder) { boolean hasTC32 = false; //Size.getDefault().hasTC32Option(); IOption formatoption = null; if (hasTC32) { formatoption = holder .getOptionBySuperClassId(PluginIDs.PLUGIN_TOOLCHAIN_TOOL_SIZE_FORMATWITHTC32); } else { return false; } try { if (formatoption.getSelectedEnum().endsWith("TC32")) { return true; } } catch (BuildException e) { // should not happen e.printStackTrace(); } return false; } */ }
true
37a38fe1ac0675e0d23f29bb561cf1844ff38221
Java
linruicheng1997/Cytomine-java-client
/src/main/java/be/cytomine/client/models/UploadedFile.java
UTF-8
2,770
2.171875
2
[ "Apache-2.0" ]
permissive
package be.cytomine.client.models; /* * Copyright (c) 2009-2019. Authors: see NOTICE file. * * 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. */ import be.cytomine.client.CytomineException; import be.cytomine.client.collections.Collection; import java.util.List; public class UploadedFile extends Model<UploadedFile> { public enum Status { UPLOADED (0), DETECTING_FORMAT (10), ERROR_FORMAT (11), // 3 EXTRACTING_DATA (20), ERROR_EXTRACTION (21), CONVERTING (30), ERROR_CONVERSION (31), // 4 DEPLOYING (40), ERROR_DEPLOYMENT (41), // 8 DEPLOYED (100), EXTRACTED (102), CONVERTED (104); private final int code; Status(int code) { this.code = code; } public int getCode() { return code; } } public UploadedFile(){} public UploadedFile(ImageServer server, String originalFilename, String realFilename, Long size, String ext, String contentType, Collection<Project> projects, Storage storage, User user, Status status, UploadedFile parent){ this(server.getId(), originalFilename, realFilename, size, ext, contentType, projects.getListIds(), storage.getId(), user.getId(), status, parent != null ? parent.getId() : null); } public UploadedFile(Long idImageServer, String originalFilename, String realFilename, Long size, String ext, String contentType, List idProjects, Long idStorage, Long idUser, Status status, Long idParent){ this.set("originalFilename", originalFilename); this.set("filename", realFilename); this.set("size", size); this.set("ext", ext); this.set("contentType", contentType); this.set("projects", idProjects); this.set("storage", idStorage); this.set("user", idUser); this.set("imageServer", idImageServer); this.set("parent", idParent); if (status != null) { this.set("status", status.code); } } public UploadedFile changeStatus(Status status) throws CytomineException { this.set("status", status.code); return this.update(); } }
true
b8f42b3bf309b0e3033d300cb29941d16ef21cfe
Java
feinoah/xueqiao-trade
/trade_hosting_apps/trade_hosting_position_fee/server/src/main/java/xueqiao/trade/hosting/position/fee/core/util/PositionRateUtil.java
UTF-8
22,475
2.078125
2
[]
no_license
package xueqiao.trade.hosting.position.fee.core.util; import com.longsheng.xueqiao.contract.standard.thriftapi.SledContract; import org.soldier.base.logger.AppLog; import org.soldier.platform.svr_platform.comm.ErrorInfo; import xueqiao.trade.hosting.BrokerTechPlatform; import xueqiao.trade.hosting.position.fee.core.bean.RouteCommodityNode; import xueqiao.trade.hosting.position.fee.core.bean.*; import xueqiao.trade.hosting.position.fee.core.util.currency.CNYRateHelper; import xueqiao.trade.hosting.position.fee.thriftapi.*; import java.math.BigDecimal; public class PositionRateUtil { private static final String CTP_CURRENCY_CNY = "CNY"; public static CommissionInfo getCommissionInfo(CommissionInfo baseCommissionInfo, DeltaCommissionInfo commissionDeltaInfo) throws ErrorInfo { CommissionInfo commissionInfo = new CommissionInfo(); CommissionInfo commissionDelta = commissionDeltaInfo.getCommissionDelta(); if (commissionDeltaInfo.getSettingsDataType() == XQSettingsDataType.SDT_NO_DATA) { /* * 无设置数据,则没有偏移值 * */ commissionInfo.setOpenRatioByMoney(baseCommissionInfo.getOpenRatioByMoney()); commissionInfo.setOpenRatioByVolume(baseCommissionInfo.getOpenRatioByVolume()); commissionInfo.setCloseRatioByMoney(baseCommissionInfo.getCloseRatioByMoney()); commissionInfo.setCloseRatioByVolume(baseCommissionInfo.getCloseRatioByVolume()); commissionInfo.setCloseTodayRatioByMoney(baseCommissionInfo.getCloseTodayRatioByMoney()); commissionInfo.setCloseTodayRatioByVolume(baseCommissionInfo.getCloseTodayRatioByVolume()); commissionInfo.setCurrency(baseCommissionInfo.getCurrency()); commissionInfo.setCurrencyGroup(baseCommissionInfo.getCurrencyGroup()); } else if (commissionDeltaInfo.getType() == FeeCalculateType.FR_DELTA_ADD) { /* * 在基数据上增加 * */ commissionInfo.setOpenRatioByMoney(MathUtil.add(baseCommissionInfo.getOpenRatioByMoney(), commissionDelta.getOpenRatioByMoney())); commissionInfo.setOpenRatioByVolume(PositionRateUtil.addPositionRate(baseCommissionInfo.getOpenRatioByVolume(), baseCommissionInfo.getCurrency(), commissionDelta.getOpenRatioByVolume(), commissionDelta.getCurrency())); commissionInfo.setCloseRatioByMoney(MathUtil.add(baseCommissionInfo.getCloseRatioByMoney(), commissionDelta.getCloseRatioByMoney())); commissionInfo.setCloseRatioByVolume(PositionRateUtil.addPositionRate(baseCommissionInfo.getCloseRatioByVolume(), baseCommissionInfo.getCurrency(), commissionDelta.getCloseRatioByVolume(), commissionDelta.getCurrency())); commissionInfo.setCloseTodayRatioByMoney(MathUtil.add(baseCommissionInfo.getCloseTodayRatioByMoney(), commissionDelta.getCloseTodayRatioByMoney())); commissionInfo.setCloseTodayRatioByVolume(PositionRateUtil.addPositionRate(baseCommissionInfo.getCloseTodayRatioByVolume(), baseCommissionInfo.getCurrency(), commissionDelta.getCloseTodayRatioByVolume(), commissionDelta.getCurrency())); commissionInfo.setCurrency(baseCommissionInfo.getCurrency()); commissionInfo.setCurrencyGroup(baseCommissionInfo.getCurrencyGroup()); } else { /* * 在基数据上减少 * */ commissionInfo.setOpenRatioByMoney(MathUtil.subtract(baseCommissionInfo.getOpenRatioByMoney(), commissionDeltaInfo.getCommissionDelta().getOpenRatioByMoney())); commissionInfo.setOpenRatioByVolume(PositionRateUtil.subtractPositionRate(baseCommissionInfo.getOpenRatioByVolume(), baseCommissionInfo.getCurrency(), commissionDelta.getOpenRatioByVolume(), commissionDelta.getCurrency())); commissionInfo.setCloseRatioByMoney(MathUtil.subtract(baseCommissionInfo.getCloseRatioByMoney(), commissionDeltaInfo.getCommissionDelta().getCloseRatioByMoney())); commissionInfo.setCloseRatioByVolume(PositionRateUtil.subtractPositionRate(baseCommissionInfo.getCloseRatioByVolume(), baseCommissionInfo.getCurrency(), commissionDelta.getCloseRatioByVolume(), commissionDelta.getCurrency())); commissionInfo.setCloseTodayRatioByMoney(MathUtil.subtract(baseCommissionInfo.getCloseTodayRatioByMoney(), commissionDeltaInfo.getCommissionDelta().getCloseTodayRatioByMoney())); commissionInfo.setCloseTodayRatioByVolume(PositionRateUtil.subtractPositionRate(baseCommissionInfo.getCloseTodayRatioByVolume(), baseCommissionInfo.getCurrency(), commissionDelta.getCloseTodayRatioByVolume(), commissionDelta.getCurrency())); commissionInfo.setCurrency(baseCommissionInfo.getCurrency()); commissionInfo.setCurrencyGroup(baseCommissionInfo.getCurrencyGroup()); } return commissionInfo; } public static MarginInfo getMarginInfo(MarginInfo baseMarginInfo, DeltaMarginInfo deltaMarginInfo) throws ErrorInfo { MarginInfo marginInfo = new MarginInfo(); MarginInfo marginDelta = deltaMarginInfo.getMarginDelta(); if (deltaMarginInfo.getSettingsDataType() == XQSettingsDataType.SDT_NO_DATA) { /* * 无设置数据,则没有偏移值 * */ marginInfo.setLongMarginRatioByMoney(baseMarginInfo.getLongMarginRatioByMoney()); marginInfo.setLongMarginRatioByVolume(baseMarginInfo.getLongMarginRatioByVolume()); marginInfo.setShortMarginRatioByMoney(baseMarginInfo.getShortMarginRatioByMoney()); marginInfo.setShortMarginRatioByVolume(baseMarginInfo.getShortMarginRatioByVolume()); marginInfo.setCurrency(baseMarginInfo.getCurrency()); marginInfo.setCurrencyGroup(baseMarginInfo.getCurrencyGroup()); } else if (deltaMarginInfo.getType() == FeeCalculateType.FR_DELTA_ADD) { /* * 在基数据上增加 * */ marginInfo.setLongMarginRatioByMoney(MathUtil.add(baseMarginInfo.getLongMarginRatioByMoney(), deltaMarginInfo.getMarginDelta().getLongMarginRatioByMoney())); marginInfo.setLongMarginRatioByVolume(PositionRateUtil.addPositionRate(baseMarginInfo.getLongMarginRatioByVolume(), baseMarginInfo.getCurrency(), marginDelta.getLongMarginRatioByVolume(), marginDelta.getCurrency())); marginInfo.setShortMarginRatioByMoney(MathUtil.add(baseMarginInfo.getShortMarginRatioByMoney(), deltaMarginInfo.getMarginDelta().getShortMarginRatioByMoney())); marginInfo.setShortMarginRatioByVolume(PositionRateUtil.addPositionRate(baseMarginInfo.getShortMarginRatioByVolume(), baseMarginInfo.getCurrency(), marginDelta.getShortMarginRatioByVolume(), marginDelta.getCurrency())); marginInfo.setCurrency(baseMarginInfo.getCurrency()); marginInfo.setCurrencyGroup(baseMarginInfo.getCurrencyGroup()); } else { /* * 在基数据上减少 * */ marginInfo.setLongMarginRatioByMoney(MathUtil.subtract(baseMarginInfo.getLongMarginRatioByMoney(), deltaMarginInfo.getMarginDelta().getLongMarginRatioByMoney())); marginInfo.setLongMarginRatioByVolume(PositionRateUtil.subtractPositionRate(baseMarginInfo.getLongMarginRatioByVolume(), baseMarginInfo.getCurrency(), marginDelta.getLongMarginRatioByVolume(), marginDelta.getCurrency())); marginInfo.setShortMarginRatioByMoney(MathUtil.subtract(baseMarginInfo.getShortMarginRatioByMoney(), deltaMarginInfo.getMarginDelta().getShortMarginRatioByMoney())); marginInfo.setShortMarginRatioByVolume(PositionRateUtil.subtractPositionRate(baseMarginInfo.getShortMarginRatioByVolume(), baseMarginInfo.getCurrency(), marginDelta.getShortMarginRatioByVolume(), marginDelta.getCurrency())); marginInfo.setCurrency(baseMarginInfo.getCurrency()); marginInfo.setCurrencyGroup(baseMarginInfo.getCurrencyGroup()); } return marginInfo; } public static UpsideContractCommission getUpsideContractCommission(long subAccountId, UpsidePositionRate upsidePositionRate, SledContract contract) { UpsideContractCommission upsideContractCommission = new UpsideContractCommission(); ContractInfo contractInfo = PositionRateUtil.getContractInfo(upsidePositionRate, contract); CommissionInfo commissionInfo; if (upsidePositionRate.getTechPlatform() == BrokerTechPlatform.TECH_CTP) { commissionInfo = PositionRateUtil.getCTPCommissionInfo(upsidePositionRate); } else { commissionInfo = PositionRateUtil.getESCommissionInfo(upsidePositionRate); } upsideContractCommission.setSubAccountId(subAccountId); upsideContractCommission.setContractInfo(contractInfo); upsideContractCommission.setCommission(commissionInfo); return upsideContractCommission; } public static UpsideContractMargin getUpsideContractMargin(long subAccountId, UpsidePositionRate upsidePositionRate, SledContract contract) { UpsideContractMargin upsideContractMargin = new UpsideContractMargin(); ContractInfo contractInfo = PositionRateUtil.getContractInfo(upsidePositionRate, contract); MarginInfo marginInfo; if (upsidePositionRate.getTechPlatform() == BrokerTechPlatform.TECH_CTP) { marginInfo = PositionRateUtil.getCTPMarginInfo(upsidePositionRate); } else { marginInfo = PositionRateUtil.getESMarginInfo(upsidePositionRate); } upsideContractMargin.setSubAccountId(subAccountId); upsideContractMargin.setContractInfo(contractInfo); upsideContractMargin.setMargin(marginInfo); return upsideContractMargin; } public static UpsideContractCommission getEmptyUpsideContractCommission(long subAccountId, RouteCommodityNode routeCommodityNode, SledContract contract) { ContractInfo contractInfo = new ContractInfo(); contractInfo.setTradeAccountId(routeCommodityNode.getTradeAccountId()); contractInfo.setCommodityId(contract.getSledCommodityId()); contractInfo.setContractCode(contract.getSledContractCode()); contractInfo.setContractId(contract.getSledContractId()); // CommissionInfo commission = new CommissionInfo(); UpsideContractCommission upsideContractCommission = new UpsideContractCommission(); upsideContractCommission.setSubAccountId(subAccountId); upsideContractCommission.setContractInfo(contractInfo); upsideContractCommission.setCommission(null); return upsideContractCommission; } public static UpsideContractMargin getEmptyUpsideContractMargin(long subAccountId, RouteCommodityNode routeCommodityNode, SledContract contract) { ContractInfo contractInfo = new ContractInfo(); contractInfo.setTradeAccountId(routeCommodityNode.getTradeAccountId()); contractInfo.setCommodityId(contract.getSledCommodityId()); contractInfo.setContractCode(contract.getSledContractCode()); contractInfo.setContractId(contract.getSledContractId()); UpsideContractMargin upsideContractMargin = new UpsideContractMargin(); upsideContractMargin.setSubAccountId(subAccountId); upsideContractMargin.setContractInfo(contractInfo); upsideContractMargin.setMargin(null); return upsideContractMargin; } // public static ContractInfo getContractInfo(UpsidePositionRate upsidePositionRate, String contractCode) { // ContractInfo contractInfo = new ContractInfo(); // contractInfo.setTradeAccountId(upsidePositionRate.getTradeAccountId()); // contractInfo.setCommodityId(upsidePositionRate.getSledCommodityId()); // contractInfo.setContractCode(contractCode); // contractInfo.setExchangeMic(upsidePositionRate.getSledExchangeMic()); // return contractInfo; // } public static ContractInfo getContractInfo(UpsidePositionRate upsidePositionRate, SledContract contract) { ContractInfo contractInfo = new ContractInfo(); contractInfo.setTradeAccountId(upsidePositionRate.getTradeAccountId()); contractInfo.setCommodityId(upsidePositionRate.getSledCommodityId()); contractInfo.setContractCode(contract.getSledContractCode()); contractInfo.setContractId(contract.getSledContractId()); contractInfo.setExchangeMic(upsidePositionRate.getSledExchangeMic()); return contractInfo; } public static ContractInfo getContractInfo(UpsidePositionRate upsidePositionRate, ContractInfo originalContractInfo) { ContractInfo contractInfo = new ContractInfo(); contractInfo.setTradeAccountId(upsidePositionRate.getTradeAccountId()); contractInfo.setCommodityId(upsidePositionRate.getSledCommodityId()); contractInfo.setContractCode(originalContractInfo.getContractCode()); contractInfo.setContractId(originalContractInfo.getContractId()); contractInfo.setExchangeMic(upsidePositionRate.getSledExchangeMic()); return contractInfo; } public static CommissionInfo getCTPCommissionInfo(UpsidePositionRate upsidePositionRate) { CommissionInfo commissionInfo = null; if (upsidePositionRate.getDetail() != null && upsidePositionRate.getDetail().getCtpCommissionRate() != null) { commissionInfo = new CommissionInfo(); UpsideCTPCommissionRate ctpCommissionRate = upsidePositionRate.getDetail().getCtpCommissionRate(); commissionInfo.setOpenRatioByMoney(ctpCommissionRate.getOpenRatioByMoney()); commissionInfo.setOpenRatioByVolume(ctpCommissionRate.getOpenRatioByVolume()); commissionInfo.setCloseRatioByMoney(ctpCommissionRate.getCloseRatioByMoney()); commissionInfo.setCloseRatioByVolume(ctpCommissionRate.getCloseRatioByVolume()); commissionInfo.setCloseTodayRatioByMoney(ctpCommissionRate.getCloseTodayRatioByMoney()); commissionInfo.setCloseTodayRatioByVolume(ctpCommissionRate.getCloseTodayRatioByVolume()); commissionInfo.setCurrency(CTP_CURRENCY_CNY); commissionInfo.setCurrencyGroup(""); } return commissionInfo; } public static CommissionInfo getESCommissionInfo(UpsidePositionRate upsidePositionRate) { CommissionInfo commissionInfo = null; if (upsidePositionRate.getDetail() != null && upsidePositionRate.getDetail().getEs9CommissionRate() != null) { UpsideES9CommissionRate es9CommissionRate = upsidePositionRate.getDetail().getEs9CommissionRate(); commissionInfo = new CommissionInfo(); if (es9CommissionRate.getCalculateMode() == ESAPICalculateMode.API_CALCULATE_MODE_COMBINE) { EsAPICombineModeCalculator openCloseFeeCalculator = new EsAPICombineModeCalculator(es9CommissionRate.getOpenCloseFee()); EsAPICombineModeCalculator closeTodayFeeCalculator = new EsAPICombineModeCalculator(es9CommissionRate.getCloseTodayFee()); commissionInfo.setOpenRatioByMoney(openCloseFeeCalculator.getPercentage()); commissionInfo.setOpenRatioByVolume(openCloseFeeCalculator.getQuota()); commissionInfo.setCloseRatioByMoney(openCloseFeeCalculator.getPercentage()); commissionInfo.setCloseRatioByVolume(openCloseFeeCalculator.getQuota()); commissionInfo.setCloseTodayRatioByMoney(closeTodayFeeCalculator.getPercentage()); commissionInfo.setCloseTodayRatioByVolume(closeTodayFeeCalculator.getQuota()); } else if (es9CommissionRate.getCalculateMode() == ESAPICalculateMode.API_CALCULATE_MODE_PERCENTAGE) { commissionInfo.setOpenRatioByMoney(es9CommissionRate.getOpenCloseFee()); commissionInfo.setOpenRatioByVolume(0); commissionInfo.setCloseRatioByMoney(es9CommissionRate.getOpenCloseFee()); commissionInfo.setCloseRatioByVolume(0); commissionInfo.setCloseTodayRatioByMoney(es9CommissionRate.getCloseTodayFee()); commissionInfo.setCloseTodayRatioByVolume(0); } else if (es9CommissionRate.getCalculateMode() == ESAPICalculateMode.API_CALCULATE_MODE_QUOTA) { commissionInfo.setOpenRatioByMoney(0); commissionInfo.setOpenRatioByVolume(es9CommissionRate.getOpenCloseFee()); commissionInfo.setCloseRatioByMoney(0); commissionInfo.setCloseRatioByVolume(es9CommissionRate.getOpenCloseFee()); commissionInfo.setCloseTodayRatioByMoney(0); commissionInfo.setCloseTodayRatioByVolume(es9CommissionRate.getCloseTodayFee()); } commissionInfo.setCurrency(es9CommissionRate.getCurrencyNo()); commissionInfo.setCurrencyGroup(es9CommissionRate.getCurrencyGroupNo()); } return commissionInfo; } public static MarginInfo getCTPMarginInfo(UpsidePositionRate upsidePositionRate) { MarginInfo marginInfo = null; if (upsidePositionRate.getDetail() != null && upsidePositionRate.getDetail().getCtpMarginRate() != null) { UpsideCTPInstrumentMarginRate upsideCTPInstrumentMarginRate = upsidePositionRate.getDetail().getCtpMarginRate().getInstrumentMarginRate(); if (upsideCTPInstrumentMarginRate != null) { if (upsideCTPInstrumentMarginRate.isRelative()) { /* * 因为正常来说,目前一般都是绝对值,而不是相对交易所的值 * 所以,有这种情况的话,需要警报一下 * */ AppLog.e("getCTPMarginInfo ---- isRelative : true"); UpsideCTPExchangeMarginRate upsideCTPExchangeMarginRate = upsidePositionRate.getDetail().getCtpMarginRate().getExchangeMarginRate(); if (upsideCTPExchangeMarginRate != null) { marginInfo = new MarginInfo(); marginInfo.setLongMarginRatioByMoney(upsideCTPExchangeMarginRate.getLongMarginRatioByMoney() + upsideCTPInstrumentMarginRate.getLongMarginRatioByMoney()); marginInfo.setLongMarginRatioByVolume(upsideCTPExchangeMarginRate.getLongMarginRatioByVolume() + upsideCTPInstrumentMarginRate.getLongMarginRatioByVolume()); marginInfo.setShortMarginRatioByMoney(upsideCTPExchangeMarginRate.getShortMarginRatioByMoney() + upsideCTPInstrumentMarginRate.getShortMarginRatioByMoney()); marginInfo.setShortMarginRatioByVolume(upsideCTPExchangeMarginRate.getShortMarginRatioByVolume() + upsideCTPInstrumentMarginRate.getShortMarginRatioByVolume()); marginInfo.setCurrency(CTP_CURRENCY_CNY); marginInfo.setCurrencyGroup(""); } } else { marginInfo = new MarginInfo(); marginInfo.setLongMarginRatioByMoney(upsideCTPInstrumentMarginRate.getLongMarginRatioByMoney()); marginInfo.setLongMarginRatioByVolume(upsideCTPInstrumentMarginRate.getLongMarginRatioByVolume()); marginInfo.setShortMarginRatioByMoney(upsideCTPInstrumentMarginRate.getShortMarginRatioByMoney()); marginInfo.setShortMarginRatioByVolume(upsideCTPInstrumentMarginRate.getShortMarginRatioByVolume()); marginInfo.setCurrency(CTP_CURRENCY_CNY); marginInfo.setCurrencyGroup(""); } } } return marginInfo; } public static MarginInfo getESMarginInfo(UpsidePositionRate upsidePositionRate) { MarginInfo marginInfo = null; if (upsidePositionRate.getDetail() != null && upsidePositionRate.getDetail().getEs9MarginRate() != null) { UpsideES9MarginRate upsideES9MarginRate = upsidePositionRate.getDetail().getEs9MarginRate(); if (upsideES9MarginRate.getCalculateMode() == ESAPICalculateMode.API_CALCULATE_MODE_PERCENTAGE) { marginInfo = new MarginInfo(); marginInfo.setLongMarginRatioByMoney(upsideES9MarginRate.getInitialMargin()); marginInfo.setLongMarginRatioByVolume(0); marginInfo.setShortMarginRatioByMoney(upsideES9MarginRate.getSellInitialMargin()); marginInfo.setShortMarginRatioByVolume(0); marginInfo.setCurrency(upsideES9MarginRate.getCurrencyNo()); marginInfo.setCurrencyGroup(upsideES9MarginRate.getCurrencyGroupNo()); } else if (upsideES9MarginRate.getCalculateMode() == ESAPICalculateMode.API_CALCULATE_MODE_QUOTA) { marginInfo = new MarginInfo(); marginInfo.setLongMarginRatioByMoney(0); marginInfo.setLongMarginRatioByVolume(upsideES9MarginRate.getInitialMargin()); marginInfo.setShortMarginRatioByMoney(0); marginInfo.setShortMarginRatioByVolume(upsideES9MarginRate.getSellInitialMargin()); marginInfo.setCurrency(upsideES9MarginRate.getCurrencyNo()); marginInfo.setCurrencyGroup(upsideES9MarginRate.getCurrencyGroupNo()); } else { /* * 易盛的接口说明上,只会有比例 和 定额 模式,如果出现其他模式,则警报 * */ AppLog.e("getESMarginInfo ---- calculateMode : " + upsideES9MarginRate.getCalculateMode()); } } return marginInfo; } public static double addPositionRate(double baseRate, String baseRateCurrency, double delta, String deltaCurrency) throws ErrorInfo { BigDecimal deltaBigDecimal = CNYRateHelper.getInstance().exchangeRate(deltaCurrency, baseRateCurrency, new BigDecimal(String.valueOf(delta))); BigDecimal ret = new BigDecimal(String.valueOf(baseRate)).add(deltaBigDecimal); return ret.doubleValue(); } public static double subtractPositionRate(double baseRate, String baseRateCurrency, double delta, String deltaCurrency) throws ErrorInfo { BigDecimal deltaBigDecimal = CNYRateHelper.getInstance().exchangeRate(deltaCurrency, baseRateCurrency, new BigDecimal(String.valueOf(delta))); BigDecimal ret = new BigDecimal(String.valueOf(baseRate)).subtract(deltaBigDecimal); return ret.doubleValue(); } }
true
af8ef7224619f7e2bdfe4a030db71dff9c592248
Java
sunlight3d/Aptech
/C2203L/Java2/14-12-2022/studentManagement/src/main/java/com/student/manangement/Main.java
UTF-8
434
2.328125
2
[]
no_license
package com.student.manangement; public class Main { public static void main(String[] args) { try { StudentTest studentTest = new StudentTest(); studentTest.input(); studentTest.writeToFile(); studentTest.readFromFile(); studentTest.filterStudents(); } catch (Exception e) { System.err.println("Error is: "+e.getMessage()); } } }
true
c70e21ef333573be717ffe1b798c6d3c5fa0453a
Java
ufcg-lsd/iguassu
/src/main/java/org/fogbowcloud/app/api/dtos/CredentialDTO.java
UTF-8
1,502
2.453125
2
[]
no_license
package org.fogbowcloud.app.api.dtos; import com.fasterxml.jackson.annotation.JsonProperty; import io.swagger.annotations.ApiModelProperty; import org.fogbowcloud.app.core.models.user.Credential; import java.io.Serializable; import java.util.Objects; /** Data transfer object projection */ public class CredentialDTO implements Serializable { @ApiModelProperty(notes = "The Iguassu Token of User", position = 1, example = "iguassu-token") @JsonProperty("iguassu_token") private String iguassuToken; @ApiModelProperty(notes = "A nonce is an arbitrary number that can only be used once", position = 2, dataType = "int", example = "100000") private int nonce; CredentialDTO(Credential credential) { this.iguassuToken = credential.getIguassuToken(); this.nonce = credential.getNonce(); } public String getIguassuToken() { return iguassuToken; } public void setIguassuToken(String iguassuToken) { this.iguassuToken = iguassuToken; } public int getNonce() { return nonce; } public void setNonce(int nonce) { this.nonce = nonce; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; CredentialDTO that = (CredentialDTO) o; return iguassuToken.equals(that.iguassuToken); } @Override public int hashCode() { return Objects.hash(iguassuToken); } }
true
a64dfae2753c280ac84589b2546aa6f48e22213a
Java
LeeMrChang/JavaTest01
/Day08_eight/src/com/itheima/_Demo04/Demo02_三天通信线程.java
UTF-8
2,808
3.609375
4
[]
no_license
package com.itheima._Demo04; public class Demo02_三天通信线程 { //创建静态共享变量 static int i = 1;//标记变量,用来分别三种情况 public static void main(String[] args) { String s = "锁对象"; //创建第一线程任务对象 new Thread(()->{ while(true){ //设置同步锁 synchronized (s){ while(i!=1){//不是1 的情况,此线程休眠 try { s.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } //如果以上判断没有运行,就是1的情况 String name = Thread.currentThread().getName(); System.out.println(name+"此线程运行"); //此时修改标记变量 i=2; //唤醒其他线程 s.notifyAll(); } } }).start(); //创建第二线程任务对象 new Thread(()->{ while(true){ //设置同步锁 synchronized (s){ while (i!=2){//不是2 的情况,此线程休眠 try { s.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } //如果以上判断没有运行,就是2的情况 String name = Thread.currentThread().getName(); System.out.println(name+"此线程运行"); //此时修改标记变量 i=3; //唤醒其他线程 s.notifyAll(); } } }).start(); //创建第三线程任务对象 new Thread(()->{ while(true){ //设置同步锁 synchronized (s){ while (i!=3){//不是3 的情况,此线程休眠 try { s.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } //如果以上判断没有运行,就是3的情况 String name = Thread.currentThread().getName(); System.out.println(name+"此线程运行"); //此时修改标记变量 i=1; //唤醒其他线程 s.notifyAll(); } } }).start(); } }
true
25cb2a4458988f577d740a16ff5aa25a51215dff
Java
qiyuanzhao/la-conllector
/src/main/java/com/lavector/collector/crawler/project/game/dota2/supergamer/page/NewsListPage.java
UTF-8
2,079
2.453125
2
[]
no_license
package com.lavector.collector.crawler.project.game.dota2.supergamer.page; import com.lavector.collector.crawler.base.PageParse; import us.codecraft.webmagic.Page; import us.codecraft.webmagic.Request; import us.codecraft.webmagic.selector.Html; import us.codecraft.webmagic.selector.Json; import us.codecraft.webmagic.selector.Selectable; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.List; /** * Created on 2017/10/23. * * @author zeng.zhao */ public class NewsListPage implements PageParse { @Override public boolean handleUrl(String url) { return url.equals("http://dota2.sgamer.com/"); } @Override public Result parse(Page page) { Result result = Result.get(); result.addRequests(parseNewsListPage(page)); return result; } @Override public String pageName() { return null; } private List<Request> parseNewsListPage (Page page) { List<Request> requests = new ArrayList<>(); Html html = page.getHtml(); List<Selectable> list = html.xpath("//div[@class='col-xs-8 col-md-8 col-lg-8 hnew-list']/b/a").nodes(); list.forEach(node -> { String url = node.xpath("a/@href").get(); String title = node.xpath("a/text()").get(); if (!url.contains("sgamer.com")) { url = "http://dota2.sgamer.com" + url; } requests.add(new Request(url).putExtra("title", title)); }); return requests; } public static void main(String[] args) throws Exception { String url = "http://dota2.sgamer.com/"; String content = org.apache.http.client.fluent.Request.Get(url) .execute() .returnContent() .asString(Charset.forName("utf-8")); Page page = new Page(); page.setRawText(content); page.setRequest(new Request(url)); page.setUrl(new Json(url)); NewsListPage newsListPage = new NewsListPage(); newsListPage.parseNewsListPage(page); } }
true
87596e905c6370c7a0883ca98ff411c722ffe310
Java
themockgraeme/sweat_coding_test
/app/src/main/java/com/kizio/sweat/task/ImageDownloadTask.java
UTF-8
3,971
2.828125
3
[]
no_license
package com.kizio.sweat.task; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.AsyncTask; import androidx.annotation.NonNull; import com.kizio.sweat.data.Trainer; import com.kizio.sweat.data.TrainingProgramme; import java.io.IOException; import java.lang.ref.WeakReference; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; /** * Downloads the trainer images from the web. * * @author Graeme Sutherland * @since 01/08/2019 */ public class ImageDownloadTask extends AsyncTask<TrainingProgramme, Void, List<ImageDownloadTask.Result>> { /** * Holds the result of a download from the web. */ static class Result { /** * The URL {@code String} that was used to download the image from the web. */ private final String url; /** * The downloaded {@link Bitmap}. */ private final Bitmap image; /** * Constructor. * * @param aUrl The URL {@code String} that was used to download the image * @param anImage The downloaded {@link Bitmap} */ Result(final String aUrl, final Bitmap anImage) { super(); this.url = aUrl; this.image = anImage; } /** * Gets the URL {@code String}. * * @return The URL {@code String} */ String getUrl() { return this.url; } /** * Gets the downloaded {@link Bitmap}. * @return The downloaded {@link Bitmap} */ Bitmap getImage() { return this.image; } } /** * Holds a {@link WeakReference} to the {@link ImageDownloadListener} class to prevent it from * being leaked. */ private final WeakReference<ImageDownloadListener> listenerReference; /** * Constructor. * * @param listener The {@link ImageDownloadListener} to call back to */ public ImageDownloadTask(final ImageDownloadListener listener) { super(); this.listenerReference = new WeakReference<>(listener); } /** * Runs in the background thread and downloads the {@link Trainer} portrait {@link Bitmap} * images from the web. * * @param programmes An array of {@link TrainingProgramme} objects * @return A {@link List} of bitmap and URL pairs */ @Override protected List<ImageDownloadTask.Result> doInBackground(final TrainingProgramme... programmes) { final List<ImageDownloadTask.Result> results = new ArrayList<>(); final Set<String> downloadedUrls = new HashSet<>(); for (final TrainingProgramme programme : programmes) { final Trainer trainer = programme.getTrainer(); final String url = trainer.getImageAddress(); if (!downloadedUrls.contains(url)) { final Bitmap bitmap = getBitmapFromUrl(url); downloadedUrls.add(url); results.add(new ImageDownloadTask.Result(url, bitmap)); } } return results; } /** * Handles the results when the download process has completed. * * @param results The URL / image pair for each download */ @Override protected void onPostExecute(final List<ImageDownloadTask.Result> results) { final ImageDownloadListener listener = this.listenerReference.get(); if (listener != null) { for (final ImageDownloadTask.Result result : results) { listener.onImageDownloaded(result.getUrl(), result.getImage()); } } } /** * Downloads a {@code Bitmap} from the supplied URL. * * @param address The URL {@code String} to download the image from * @return The downloaded {@code Bitmap} */ private static Bitmap getBitmapFromUrl(@NonNull final String address) { Bitmap bitmap = null; try { final URL url = new URL(address); final URLConnection connection = url.openConnection(); connection.setDoInput(true); connection.connect(); bitmap = BitmapFactory.decodeStream(connection.getInputStream()); } catch (final MalformedURLException mue) { mue.printStackTrace(); } catch (final IOException ioe) { ioe.printStackTrace(); } return bitmap; } }
true
877b9fb52d35d3a232a919ae63ec2d8d1ec2272a
Java
JungInBaek/shop
/src/main/java/com/shop/dto/ItemFormDto.java
UTF-8
1,199
2.34375
2
[]
no_license
package com.shop.dto; import com.shop.constant.ItemSellStatus; import com.shop.entity.Item; import lombok.Getter; import lombok.Setter; import org.modelmapper.ModelMapper; import javax.validation.constraints.NotBlank; import javax.validation.constraints.NotNull; import java.util.ArrayList; import java.util.List; @Getter @Setter public class ItemFormDto { private Long id; @NotBlank(message = "상품명을 필수 입력 값입니다.") private String itemName; @NotNull(message = "가격은 필수 입력 값입니다.") private Integer price; @NotBlank(message = "이름은 필수 입력 값입니다.") private String itemDetail; @NotNull(message = "재고는 필수 입력 값입니다.") private Integer stockNumber; private ItemSellStatus itemSellStatus; private List<ItemImgDto> itemImgDtoList = new ArrayList<>(); private List<Long> itemImgIds = new ArrayList<>(); private static ModelMapper modelMapper = new ModelMapper(); public Item createItem() { return modelMapper.map(this, Item.class); } public static ItemFormDto of(Item item) { return modelMapper.map(item, ItemFormDto.class); } }
true
10bf6a393c9d0972613f5cc1b10e8d552c5adf60
Java
navdeepsekhon/TopTenSongsAndroidApp
/app/src/main/java/co/navdeep/toptensongs/app/MainActivity.java
UTF-8
3,261
2.40625
2
[ "MIT" ]
permissive
package co.navdeep.toptensongs.app; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.Menu; import co.navdeep.toptensampler.R; import co.navdeep.toptensongs.adapter.ListViewAdapter; import co.navdeep.toptensongs.apiCalls.SpotifyApiCalls; import co.navdeep.toptensongs.utils.TopTenConstants; import co.navdeep.toptensongs.utils.Utility; public class MainActivity extends AppCompatActivity implements ListFragment.ListFragmentCallback { private String TAG = getClass().getSimpleName(); private boolean mTablet = false; private String TOP_SONGS_FRAGMENT_TAG = "topsongs"; private String mCurrentArtistName; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); if (findViewById(R.id.fragment_top_songs) != null) { mTablet = true; if (savedInstanceState == null) { getSupportFragmentManager().beginTransaction() .replace(R.id.fragment_top_songs, new ListFragment(), TOP_SONGS_FRAGMENT_TAG) .commit(); } } else { mTablet = false; } } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_main, menu); return true; } @Override public void onItemSelected(int position, ListViewAdapter listViewAdapter) { if(listViewAdapter.isSongView()){ startPlayerInDialog(position, listViewAdapter); } else { if(!mTablet) { Log.d(TAG, "Artist selected non tablet mode"); String artistId = listViewAdapter.getItem(position).getId(); String artistName = listViewAdapter.getItem(position).getName(); Intent topSongs = new Intent(this, TopSongsActivity.class); topSongs.putExtra(TopTenConstants.INTENT_KEY_ARTIST_ID, artistId); topSongs.putExtra(TopTenConstants.INTENT_KEY_ARTIST_NAME, artistName); Log.d(TAG, "starting topSongs activity for artist:" + artistName); startActivity(topSongs); } else{ String artistId = listViewAdapter.getItem(position).getId(); mCurrentArtistName = listViewAdapter.getItem(position).getName(); SpotifyApiCalls.getTopSongs(artistId, this); } } } private void startPlayerInDialog(int position, ListViewAdapter listViewAdapter){ Log.d(TAG, "startPlayerInDialog position:" + position); PlayerFragment pf = new PlayerFragment(); Bundle args = new Bundle(); args.putInt(TopTenConstants.INTENT_KEY_POSITION, position); args.putString(TopTenConstants.INTENT_KEY_ARTIST_NAME, mCurrentArtistName); args.putParcelableArrayList(TopTenConstants.INTENT_KEY_SONG_LIST, Utility.convertListViewAdapterToArrayList(listViewAdapter)); pf.setArguments(args); pf.show(getSupportFragmentManager(), "Player"); } }
true
49323b037b31f6addba05de203295745e6ad2110
Java
MarekDudek/FinancialEngineering
/src/main/java/interretis/financial_engineering/utilities/FunctionalUtilities.java
UTF-8
335
2.640625
3
[]
no_license
package interretis.financial_engineering.utilities; import java.math.BigDecimal; import java.util.List; import static java.math.BigDecimal.ZERO; public final class FunctionalUtilities { public static BigDecimal sum(final List<BigDecimal> numbers) { return numbers.stream().reduce(BigDecimal::add).orElse(ZERO); } }
true
75f4025b2cbccd6c0f48d2c7b9c1b7d8cf5d092a
Java
since85stas/yaStagProj
/src/com/company/practicum/Potter.java
UTF-8
2,189
3.265625
3
[]
no_license
package com.company.practicum; import java.io.File; import java.util.*; public class Potter { private static final int M = 3; private static int N; // private static int sumMin ; static List<Integer> tokens; public static String bitprint(int u){ String s= ""; for(int n= 0;u > 0;++n, u>>= 1) if((u & 1) > 0) s+= n + " "; return s; } public static int bitcount(int u){ int n; for(n= 0;u > 0;++n, u&= (u - 1));//Turn the last set bit to a 0 return n; } public static LinkedList<String> comb(int c, int n){ LinkedList<String> s= new LinkedList<String>(); for(int u= 0;u < 1 << n;u++) if(bitcount(u) == c) s.push(bitprint(u)); Collections.sort(s); return s; } public static void main(String[] args) { try { File file = new File("input.txt"); Scanner scanner = new Scanner(file); int goalNum = scanner.nextInt(); tokens = new ArrayList<>(); while (scanner.hasNextInt()) { tokens.add(scanner.nextInt()); } int[] arr = null; N = tokens.size(); // TreeMap<Integer, Integer> sums = new TreeMap<>(); int maxV = Integer.MAX_VALUE; int goalSum = 0; LinkedList<String> comb = comb(M,100); TreeMap<Integer, Integer> tree= new TreeMap<>(); for (String set: comb) { String[] strings = set.split(" "); int[] pos = new int[strings.length]; int sum = 0; for (int i = 0; i < pos.length; i++) { pos[i] = Integer.valueOf(strings[i]); sum += tokens.get(pos[i]); } int diff = Math.abs(sum - goalNum); tree.put(diff, sum); if (diff < maxV) { maxV = diff; goalSum = sum; } } System.out.println(tree.firstEntry().getValue()); } catch (Exception e) { System.out.println("" + e); } } }
true
50233f10ecd1f9f075db69a632ffc8932bed592d
Java
laudochei/assetc
/src/main/java/assetc/api/Suppliers.java
UTF-8
1,792
2.40625
2
[]
no_license
package assetc.api; import assetc.repository.SuppliersRepository; import java.io.IOException; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; 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.google.gson.Gson; /** * Servlet implementation class Suppliers */ @WebServlet("/builds/asset/api/suppliers") public class Suppliers extends HttpServlet { private static final long serialVersionUID = 1L; //private SuppliersRepository _repository; private SuppliersRepository _repository = null; private Gson _gson = new Gson(); /** * @see HttpServlet#HttpServlet() */ public Suppliers() { super(); // TODO Auto-generated constructor stub } public void init() throws ServletException { super.init(); _repository = new SuppliersRepository(this.getServletContext().getRealPath("data/sample.db")); } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { List<assetc.model.Supplier> suppliers = new ArrayList<assetc.model.Supplier>(); try { suppliers = _repository.listSuppliers(); // set the content type we are sending back as JSON response.setContentType("application/json"); // print the content to the response response.getWriter().print(_gson.toJson(suppliers)); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); response.sendError(500); } } }
true
1f433a44abd116019b024ffee1fc36d4e8dada49
Java
cckmit/egov-asset-component
/egov-asset-drc/src/main/java/com/bosssoft/egov/asset/drc/service/DrcAuthRuleServiceImpl.java
UTF-8
7,528
1.789063
2
[]
no_license
/** * 福建博思软件 1997-2017 版权所有 * Auto generated by Bosssoft Studio version 1.0 beta * Mon Jan 09 10:26:53 CST 2017 */ package com.bosssoft.egov.asset.drc.service; import java.util.HashMap; import java.util.List; import java.util.Map; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Service; import com.bosssoft.egov.asset.aims.api.org.entity.AimsBasicOrg; import com.bosssoft.egov.asset.aims.api.org.service.OrgService; import com.bosssoft.egov.asset.common.util.MapUtilsExt; import com.bosssoft.egov.asset.drc.DrcUtils; import com.bosssoft.egov.asset.drc.entity.DrcAuthRule; import com.bosssoft.egov.asset.drc.mapper.DrcAuthRuleMapper; import com.bosssoft.egov.asset.mapper.AssetGeneralMapper; import com.bosssoft.platform.common.lang.data.Page; import com.bosssoft.platform.persistence.entity.Condition; import com.bosssoft.platform.common.lang.data.Searcher; /** * 类说明: DrcAuthRuleService接口实现类. * * 类用途: * * <pre> * 修改记录: * 修改日期   修改人   修改原因 * 2017-01-09 Administrator   新建 * </pre> */ @Service public class DrcAuthRuleServiceImpl implements DrcAuthRuleService { private static Logger logger = LoggerFactory.getLogger(DrcAuthRuleServiceImpl.class); // TODO 添加需要的Mapper @Autowired private DrcAuthRuleMapper drcAuthRuleMapper; @Autowired @Qualifier(OrgService.REFERENCE_BEAN_NAME) private OrgService orgService; @Autowired private AssetGeneralMapper mapper; /** * * @param drcAuthRule */ public void addDrcAuthRule(DrcAuthRule drcAuthRule) { drcAuthRuleMapper.insert(drcAuthRule); } /** * * @param drcAuthRule */ public void delDrcAuthRule(DrcAuthRule drcAuthRule) { drcAuthRuleMapper.deleteByPrimaryKey(drcAuthRule); } /** * * @param drcAuthRule */ public void updateDrcAuthRule(DrcAuthRule drcAuthRule) { drcAuthRuleMapper.updateByPrimaryKey(drcAuthRule); } /** * * @param drcAuthRule * @retrun */ public List<DrcAuthRule> getDrcAuthRuleList(DrcAuthRule drcAuthRule) { return drcAuthRuleMapper.select(drcAuthRule); } /** * * @param searcher * @param page * @retrun */ public Page<DrcAuthRule> queryDrcAuthRulePage(Searcher searcher, Page<DrcAuthRule> page) { return drcAuthRuleMapper.queryDrcAuthRulePage(searcher, page); } @Override public DrcAuthRule getDrcAuthRule(DrcAuthRule drcAuthRule) { // TODO Auto-generated method stub return drcAuthRuleMapper.selectByPrimaryKey(drcAuthRule); } @Override public List<DrcAuthRule> getDrcAuthRuleListByParty(String partyId,String partyCode) { //根据用户id查找 Condition condition = new Condition(DrcAuthRule.class); condition.createCriteria().andEqualTo("partyType", partyCode) .andEqualTo("partyId", partyId) .andEqualTo("status", "1"); return drcAuthRuleMapper.selectByExample(condition); } @Override public List<DrcAuthRule> getDrcAuthRuleWithOrgType(String partyId, String partyCode) { Condition condition = new Condition(DrcAuthRule.class); condition.createCriteria().andEqualTo("partyType", partyCode) .andEqualTo("partyId", partyId) .andEqualTo("ruleType", "org") .andEqualTo("status", "1"); return drcAuthRuleMapper.selectByExample(condition); } @Override public List<AimsBasicOrg> getOrgListByParty(String partyId,String partyCode) { //先获取到权限规则列表 List<DrcAuthRule> authRules = getDrcAuthRuleWithOrgType(partyId, partyCode); if(authRules == null || authRules.isEmpty()){ return null; } //组合参数 StringBuffer condition = new StringBuffer(); condition.append(" SELECT * FROM AIMS_BASIC_ORG "); condition.append(" WHERE ORG_CODE IN (").append(DrcUtils.buildRuleInSql(authRules)).append(")"); return orgService.queryOrgListBySql(condition.toString()); } @Override public int getOrgCountByParty(String partyId, String partyCode) { //先获取到权限规则列表 List<DrcAuthRule> authRules = getDrcAuthRuleWithOrgType(partyId,partyCode); if (authRules == null || authRules.isEmpty()) { return 0; } //组合参数 StringBuffer condition = new StringBuffer(); condition.append(" SELECT * FROM AIMS_BASIC_ORG "); condition.append(" WHERE ORG_CODE IN (").append(DrcUtils.buildRuleInSql(authRules)).append(")"); List<AimsBasicOrg> list = orgService.queryOrgListBySql(condition.toString()); return list == null || list.isEmpty() ? 0 : list.size(); } @Override public List<AimsBasicOrg> queryOrg(String partyId, String partyCode, String searchStr) { //先获取到权限规则列表 // List<DrcAuthRule> authRules = getDrcAuthRuleWithOrgType(partyId, partyCode); // if(authRules == null || authRules.isEmpty()){ // return new ArrayList<AimsBasicOrg>(); // } //组合参数 StringBuffer condition = new StringBuffer(); // condition.append(" SELECT * FROM AIMS_BASIC_ORG "); // condition.append(" WHERE ORG_CODE IN (").append(DrcUtils.buildRuleInSql(authRules)).append(")"); // condition.append(" AND (ORG_CODE LIKE '%").append(searchStr).append("%'"); // condition.append(" OR ORG_NAME LIKE '%").append(searchStr).append("%'"); // condition.append(")"); // condition.append(" SELECT * FROM AIMS_BASIC_ORG ORG "); // condition.append(" WHERE ORG_ID IN ("); // condition.append(" SELECT ORG_ID FROM VDRC_RULE_USER_ORG DRC WHERE DRC.USER_ID = '").append(partyId).append("'"); // condition.append(" AND (ORG_CODE LIKE '%").append(searchStr).append("%'"); // condition.append(" OR ORG_NAME LIKE '%").append(searchStr).append("%'"); // condition.append(" ) "); // condition.append(" ) ORDER BY ORG_CODE"); condition.append(" SELECT * FROM VDRC_RULE_USER_ORG DRC "); condition.append(" WHERE DRC.USER_ID = '").append(partyId).append("'"); condition.append(" AND (ORG_CODE LIKE '%").append(searchStr).append("%'"); condition.append(" OR ORG_NAME LIKE '%").append(searchStr).append("%'"); condition.append(" OR FINANCE_BUDGET_CODE LIKE '%").append(searchStr).append("%'"); condition.append(" ) "); condition.append(" ORDER BY ORG_CODE "); logger.debug("查询登录单位数sql:" + condition.toString()); return orgService.queryOrgListBySql(condition.toString()); } @Override public List<DrcAuthRule> getDrcAuthRuleList(Condition condition) { return drcAuthRuleMapper.selectByExample(condition); } @Override public List<AimsBasicOrg> getOrgListByUser(String userCode) { StringBuffer sql = new StringBuffer(); // sql.append(" SELECT * FROM AIMS_BASIC_ORG ORG "); // sql.append(" WHERE ORG_ID IN ("); // sql.append(" SELECT ORG_ID FROM VDRC_RULE_USER_ORG DRC WHERE DRC.USER_CODE = '").append(userCode).append("'"); // sql.append(" ) ORDER BY ORG_CODE"); sql.append(" SELECT * FROM "); sql.append(" VDRC_RULE_USER_ORG DRC "); sql.append(" WHERE DRC.USER_CODE = '").append(userCode).append("'"); sql.append(" ORDER BY DRC.ORG_CODE "); return orgService.queryOrgListBySql(sql.toString()); } @Override public int getOrgCountByUserCode(String userCode) { StringBuffer sql = new StringBuffer(); sql.append(" SELECT COUNT(1) CNT FROM VDRC_RULE_USER_ORG WHERE USER_CODE = '").append(userCode).append("'"); List<Map<String,Object>> list = mapper.queryCommon(sql.toString(),new HashMap<String,Object>()); return (list == null || list.isEmpty()) ? 0 : MapUtilsExt.getInteger(list.get(0), "CNT"); } }
true
6cdfbe993430100ae3bdee7ca13b3259f058cdc0
Java
juaneulate/finaltaller
/src/services/src/main/java/service/ChapterService.java
UTF-8
1,134
2.3125
2
[]
no_license
package service; import dao.ChapterDao; import entity.ChapterEntity; import javax.inject.Inject; import javax.inject.Named; import javax.transaction.Transactional; import java.io.Serializable; import java.util.List; import java.util.Optional; @Named public class ChapterService implements Serializable { @Inject private ChapterDao chapterDao; public List<ChapterEntity> findAll() { return chapterDao.findAll(); } @Transactional public ChapterEntity save(ChapterEntity chapter) { return chapterDao.merge(chapter); } @Transactional public void remove(ChapterEntity chapter) { chapterDao.remove(chapter); } @Transactional public void deleteAll(List<ChapterEntity> listToDelete) { for (ChapterEntity chapter : listToDelete) { remove(chapter); } } public Optional<ChapterEntity> getById(long id) { return chapterDao.getById(id); } public List<ChapterEntity> findAllByCourseId(long courseId) { return chapterDao.findAllByCourseId(courseId); } }
true
6acc8247f9db45a266bc254a12f05d02512c3c68
Java
Vaitsakhouski/work
/transportWithUT/src/test/java/com/company/BicycleTest.java
UTF-8
849
2.609375
3
[]
no_license
package com.company; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.*; /** * Created by NotePad.by on 29.10.2016. */ public class BicycleTest { private Bicycle bicycle; @Before public void setUP() throws Exception { bicycle = new Bicycle(); } @Test public void moveToPoint() throws Exception { Assert.assertTrue(bicycle.moveToPoint()); } @Test public void calculateDistance() throws Exception { Assert.assertEquals(130, bicycle.calculateDistance(), 1); } @Test public void cost() throws Exception { Assert.assertEquals(0, bicycle.cost(), 0.01); } @Test public void time() throws Exception { Assert.assertEquals(780, bicycle.time(), 15); } }
true
b706f51d78d375d438621fc927b32f22c76bea20
Java
gopika4/CodeJava
/FreqOfC.java
UTF-8
243
2.734375
3
[]
no_license
public class FreqOfC { public static void main(String[] args) { int ctr=0; String s=args[0]; for(int i=0;i<s.length();i++) { if(s.charAt(i)=='C') ctr++; } System.out.println(ctr); } }
true
b3d430c548003f37215a406ff07c13827074952c
Java
moutainhigh/lxtx
/mobile/android/payBusiness/appclient/com/jxt/netpay/appclient/util/OneJumpFactory.java
UTF-8
778
2.296875
2
[]
no_license
package com.jxt.netpay.appclient.util; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.springframework.beans.factory.InitializingBean; import com.jxt.netpay.appclient.service.IOneJump; public class OneJumpFactory implements InitializingBean{ private Map<String, IOneJump> map = new HashMap<String, IOneJump>(); private List<IOneJump> list = new ArrayList<IOneJump>(); public IOneJump getPrePay(String key){ return map.get(key); } //ioc public void setList(List<IOneJump> list) { this.list = list; } @Override public void afterPropertiesSet() throws Exception { if(list != null && list.size() > 0){ for(IOneJump oneJump : list){ map.put(oneJump.getType(),oneJump); } } } }
true
28164acd77172345c907f82c32d86a88c55973c4
Java
barbinimichael/ScoreCreator
/app/src/main/java/com/example/scorecreator/MusicRecord2.java
UTF-8
15,946
2.140625
2
[]
no_license
package com.example.scorecreator; import android.media.AudioFormat; import android.media.AudioRecord; import android.media.MediaRecorder; import android.media.audiofx.Visualizer; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.TextView; import java.io.IOException; /** * MusicRecord2- used for audio processing */ public class MusicRecord2 extends AppCompatActivity { private static final int RECORDER_SAMPLERATE = 192000; // private static final int RECORDER_SAMPLERATE = 8192; private static final int RECORDER_CHANNELS = AudioFormat.CHANNEL_IN_MONO; private static final int RECORDER_AUDIO_ENCODING = AudioFormat.ENCODING_PCM_16BIT; private AudioRecord recorder = null; private Thread recordingThread = null; private boolean isRecording = false; // Potential buffer sizes (in bytes) // Will be able to match device specifications int bufferSize = AudioRecord.getMinBufferSize(RECORDER_SAMPLERATE, RECORDER_CHANNELS, RECORDER_AUDIO_ENCODING); // Get buffer size by multiplying following int BufferElements2Rec = 128; // want to play 2048 (2K) since 2 bytes we use only 1024 // int BytesPerElement = 2; // 2 bytes in 16bit format // Audio Visualizer Visualizer mVisualizer; WaveformView waveformView; // double[] real = new double[BufferElements2Rec]; byte[] bData = new byte[BufferElements2Rec]; // User buttons Button start, stop; private boolean started = false; // Tag for identifying in debugging final String LOG_TAG = "Recording"; // Frequency private int samplesperSnip = 5001; private int[] freqData = new int[samplesperSnip]; private int counter = 0; private String note = ""; TextView noteText; private String prediction = "Prediction"; TextView predictionText; private boolean madePrediction = false; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_music_record2); // Buttons start = (Button) findViewById(R.id.START_RECORDING); stop = (Button) findViewById(R.id.STOP_RECORDING); noteText = (TextView) findViewById(R.id.NoteText); predictionText = (TextView) findViewById(R.id.PredictionText); predictionText.setText(prediction); // Visualizer waveformView = (WaveformView) findViewById(R.id.waveform_view); } // Setup visualizer private void setupVisualizer() { Log.d(LOG_TAG, recorder.getAudioSessionId() + " Session ID"); mVisualizer = new Visualizer(0); mVisualizer.setCaptureSize(Visualizer.getCaptureSizeRange()[1]); mVisualizer.setDataCaptureListener( new Visualizer.OnDataCaptureListener() { public void onWaveFormDataCapture(Visualizer visualizer, byte[] bytes, int samplingRate) { /*byte[] waveform = new byte[real.length / 2]; for (int i = 0; i < real.length / 2; i++) waveform[i] = (byte) real[i];*/ byte[] waveform = new byte[bData.length / 2]; byte total = 0; // Getting the average for (int i = 0; i < bData.length / 2; i++) total += bData[i]; for(int i = 0; i < bData.length / 2; i++) waveform[i]= bData[i]; /*if(bData[i] < 0) waveform[i] = 0; else waveform[i]= bData[i];*/ waveformView.updateVisualizer(waveform); } public void onFftDataCapture(Visualizer visualizer, byte[] bytes, int samplingRate) { } }, Visualizer.getMaxCaptureRate() / 2, true, false); } /** * To handle recording process * * @param view */ public void startRecording(View view) { if (!started) { started = true; Log.d(LOG_TAG, "Started recording"); // Setup audio capture recorder = new AudioRecord(MediaRecorder.AudioSource.MIC, RECORDER_SAMPLERATE, RECORDER_CHANNELS, RECORDER_AUDIO_ENCODING, bufferSize); recorder.startRecording(); setupVisualizer(); mVisualizer.setEnabled(true); isRecording = true; recordingThread = new Thread(new Runnable() { public void run() { try { processing(); } catch (IOException e) { e.printStackTrace(); } } }, "AudioRecorder Thread"); recordingThread.start(); } } /** * Process sound information */ private void processing() throws IOException { Log.d(LOG_TAG, "Processing"); while (isRecording) { // gets the voice output from microphone Log.d(LOG_TAG, "Is recording"); String bDataString = ""; bData = new byte[BufferElements2Rec]; recorder.read(bData, 0, BufferElements2Rec); for (int i = 0; i < bData.length; i++) bDataString += bData[i]; // FFT Data double[] real = new double[bData.length]; double[] imag = new double[bData.length]; for (int i = 0; i < real.length; i++) { real[i] = bData[i]; imag[i] = 0; } transform(real, imag); String fftString = ""; double max = 0; int max_bin = 0; for (int i = 1; i < real.length / 2; i++) { if (Math.sqrt(Math.pow(real[i], 2) + Math.pow(imag[i], 2)) > max) { max = Math.sqrt(Math.pow(real[i], 2) + Math.pow(imag[i], 2)); max_bin = i; } /*if (imag[i] > max) max = imag[i];*/ fftString += real[i]; } // Log.d(LOG_TAG, max + ""); // Log.d(LOG_TAG, fftString + ""); // Log.d(LOG_TAG, real[max_bin] + ""); double frequency = 2 * max_bin * RECORDER_SAMPLERATE / BufferElements2Rec; Log.d(LOG_TAG, frequency + ""); note = determineNote(frequency); // note = determineNote(real[max_bin]); Log.d(LOG_TAG, note); // 56448 samples saved if(counter != samplesperSnip - 1) { freqData[counter] = (int)frequency; counter++; madePrediction = false; } else { Predict predict = new Predict(freqData, this); prediction = predict.predict(); Log.d(LOG_TAG, "Prediction " + prediction); madePrediction = true; freqData = new int[samplesperSnip]; counter = 0; } Log.d(LOG_TAG, "Counter + " + counter); runOnUiThread(new Runnable() { @Override public void run() { noteText.setText(note); if(madePrediction) predictionText.setText(prediction); } }); } } /** * To handle recording coming to a stop * * @param view */ public void stopRecording(View view) { Log.d(LOG_TAG, "Stop Recording"); started = false; // stops the recording activity if (null != recorder) { isRecording = false; recorder.stop(); recorder.release(); recorder = null; recordingThread = null; mVisualizer.setEnabled(false); } } // FFT /* * Computes the discrete Fourier transform (DFT) of the given complex vector, storing the result back into the vector. * The vector can have any length. This is a wrapper function. */ private String determineNote(double freq) { // Create table double aFour = 440.0; int tableLength = 12 * 15; double[] table = new double[tableLength]; for (int i = 0; i < table.length; i++) { table[i] = aFour * Math.pow(Math.pow(2.0, 1 / 12.0), i - 57.0); } double diff = table[table.length - 1]; int currentNote = 0; for (int i = 0; i < table.length; i++) { if (Math.abs(freq - table[i]) < diff) { diff = Math.abs(freq - table[i]); currentNote = i; } } Log.d(LOG_TAG, currentNote + " abc " + diff); String note = ""; String[] noteTable = new String[table.length]; for (int i = 0; i < noteTable.length; i += 12) { noteTable[i] = "C"; noteTable[i + 1] = "C#"; noteTable[i + 2] = "D"; noteTable[i + 3] = "D#"; noteTable[i + 4] = "E"; noteTable[i + 5] = "F"; noteTable[i + 6] = "F#"; noteTable[i + 7] = "G"; noteTable[i + 8] = "G#"; noteTable[i + 9] = "A"; noteTable[i + 10] = "A#"; noteTable[i + 11] = "B"; } note = noteTable[currentNote]; return note; } public static void transform(double[] real, double[] imag) { int n = real.length; if (n != imag.length) throw new IllegalArgumentException("Mismatched lengths"); if (n == 0) return; else if ((n & (n - 1)) == 0) // Is power of 2 transformRadix2(real, imag); else // More complicated algorithm for arbitrary sizes transformBluestein(real, imag); } /* * Computes the discrete Fourier transform (DFT) of the given complex vector, storing the result back into the vector. * The vector's length must be a power of 2. Uses the Cooley-Tukey decimation-in-time radix-2 algorithm. */ public static void transformRadix2(double[] real, double[] imag) { // Length variables int n = real.length; if (n != imag.length) throw new IllegalArgumentException("Mismatched lengths"); int levels = 31 - Integer.numberOfLeadingZeros(n); // Equal to floor(log2(n)) if (1 << levels != n) throw new IllegalArgumentException("Length is not a power of 2"); // Trigonometric tables double[] cosTable = new double[n / 2]; double[] sinTable = new double[n / 2]; for (int i = 0; i < n / 2; i++) { cosTable[i] = Math.cos(2 * Math.PI * i / n); sinTable[i] = Math.sin(2 * Math.PI * i / n); } // Bit-reversed addressing permutation for (int i = 0; i < n; i++) { int j = Integer.reverse(i) >>> (32 - levels); if (j > i) { double temp = real[i]; real[i] = real[j]; real[j] = temp; temp = imag[i]; imag[i] = imag[j]; imag[j] = temp; } } // Cooley-Tukey decimation-in-time radix-2 FFT for (int size = 2; size <= n; size *= 2) { int halfsize = size / 2; int tablestep = n / size; for (int i = 0; i < n; i += size) { for (int j = i, k = 0; j < i + halfsize; j++, k += tablestep) { int l = j + halfsize; double tpre = real[l] * cosTable[k] + imag[l] * sinTable[k]; double tpim = -real[l] * sinTable[k] + imag[l] * cosTable[k]; real[l] = real[j] - tpre; imag[l] = imag[j] - tpim; real[j] += tpre; imag[j] += tpim; } } if (size == n) // Prevent overflow in 'size *= 2' break; } } /* * Computes the discrete Fourier transform (DFT) of the given complex vector, storing the result back into the vector. * The vector can have any length. This requires the convolution function, which in turn requires the radix-2 FFT function. * Uses Bluestein's chirp z-transform algorithm. */ public static void transformBluestein(double[] real, double[] imag) { // Find a power-of-2 convolution length m such that m >= n * 2 + 1 int n = real.length; if (n != imag.length) throw new IllegalArgumentException("Mismatched lengths"); if (n >= 0x20000000) throw new IllegalArgumentException("Array too large"); int m = Integer.highestOneBit(n) * 4; // Trignometric tables double[] cosTable = new double[n]; double[] sinTable = new double[n]; for (int i = 0; i < n; i++) { int j = (int) ((long) i * i % (n * 2)); // This is more accurate than j = i * i cosTable[i] = Math.cos(Math.PI * j / n); sinTable[i] = Math.sin(Math.PI * j / n); } // Temporary vectors and preprocessing double[] areal = new double[m]; double[] aimag = new double[m]; for (int i = 0; i < n; i++) { areal[i] = real[i] * cosTable[i] + imag[i] * sinTable[i]; aimag[i] = -real[i] * sinTable[i] + imag[i] * cosTable[i]; } double[] breal = new double[m]; double[] bimag = new double[m]; breal[0] = cosTable[0]; bimag[0] = sinTable[0]; for (int i = 1; i < n; i++) { breal[i] = breal[m - i] = cosTable[i]; bimag[i] = bimag[m - i] = sinTable[i]; } // Convolution double[] creal = new double[m]; double[] cimag = new double[m]; convolve(areal, aimag, breal, bimag, creal, cimag); // Postprocessing for (int i = 0; i < n; i++) { real[i] = creal[i] * cosTable[i] + cimag[i] * sinTable[i]; imag[i] = -creal[i] * sinTable[i] + cimag[i] * cosTable[i]; } } /* * Computes the circular convolution of the given complex vectors. Each vector's length must be the same. */ public static void convolve(double[] xreal, double[] ximag, double[] yreal, double[] yimag, double[] outreal, double[] outimag) { int n = xreal.length; if (n != ximag.length || n != yreal.length || n != yimag.length || n != outreal.length || n != outimag.length) throw new IllegalArgumentException("Mismatched lengths"); xreal = xreal.clone(); ximag = ximag.clone(); yreal = yreal.clone(); yimag = yimag.clone(); transform(xreal, ximag); transform(yreal, yimag); for (int i = 0; i < n; i++) { double temp = xreal[i] * yreal[i] - ximag[i] * yimag[i]; ximag[i] = ximag[i] * yreal[i] + xreal[i] * yimag[i]; xreal[i] = temp; } inverseTransform(xreal, ximag); for (int i = 0; i < n; i++) { // Scaling (because this FFT implementation omits it) outreal[i] = xreal[i] / n; outimag[i] = ximag[i] / n; } } /* * Computes the inverse discrete Fourier transform (IDFT) of the given complex vector, storing the result back into the vector. * The vector can have any length. This is a wrapper function. This transform does not perform scaling, so the inverse is not a true inverse. */ public static void inverseTransform(double[] real, double[] imag) { transform(imag, real); } }
true
20f4899e6c53cd5adc0a829f587ac17f3b89ae90
Java
amritsahoo/infytq_python
/iteration control structure/src/com/IterAssignment2.java
UTF-8
661
3.03125
3
[]
no_license
package com; import java.util.Scanner; public class IterAssignment2 { public static void main(String[] args) { // TODO Auto-generated method stub Scanner sc = new Scanner(System.in); System.out.println("Enter the number of heads"); int heads=sc.nextInt(); System.out.println("Enter the number of legs"); int legs=sc.nextInt(); int chickens=0; int rabbits=0; if(legs%2==0 && heads<legs) { chickens=(int)(2*heads)-legs/2; rabbits=(int)(legs-2*heads)/2; System.out.println("chickens : "+chickens); System.out.println("rabbits : "+rabbits); } else { System.out.println("The number of chickens and rabbit cannot be found"); } } }
true
8a4ed1bd4bde07f8ead704d6ac69fa3b25b8084a
Java
mustamias/Roman-Numerals
/src/main/java/com/tr/model/Transformation.java
UTF-8
3,193
3.28125
3
[]
no_license
package com.tr.model; import java.util.Hashtable; // Class to implement the interface import org.springframework.stereotype.Service; @Service public class Transformation implements ITransformaion { private Hashtable<Character, Integer> format; @Override public int ToArabicNum(String roman_num) { // TODO Auto-generated method stub format = new Hashtable<Character, Integer>(); format.put('I',1); format.put('V',5); format.put('X',10); format.put('L',50); format.put('C',100); format.put('D',500); format.put('M',1000); //Methede with two parameters, our structure and the Roman number // local declaration for 2 integer first to save arabic number and second for int arabic_Num=0; int prev = 0; // change change the character oo capital letter roman_num=roman_num.toUpperCase(); // Loop of transformation for(int i = roman_num.length()-1; i>=0 ; i--) { // Test every caractraire from roman number if we have it in our structure from class Fromat_Rom if (format.get(roman_num.charAt(i))==null) throw new RuntimeException("Only the letters IVXLCDM"); //If i find it in structure i will transforme it to integer , else throw exception with some message // Transformation int temp = (int) format.get(roman_num.charAt(i)); //Test if(temp < prev) arabic_Num-=temp; else arabic_Num+=temp; prev = temp; } return arabic_Num; } @Override public String ToRomanNum( int arab_num) { //Other kind of implementation without data structure int loop; String roman=""; loop=arab_num/1000; for(int i=1; i<=loop;i++){ roman=roman+"M"; } arab_num=arab_num%1000; /*loop=arab_num/900; for(int i=1; i<=loop;i++){ roman=roman+"CM"; }*/ if( (arab_num/900)>=1 ) roman=roman+"CM"; arab_num=arab_num%900; if( (arab_num/500)>=1 ) roman=roman+"D"; arab_num=arab_num%500; if( (arab_num/400)>=1 ) roman=roman+"CD"; arab_num=arab_num%400; loop=arab_num/100; for(int i=1; i<=loop;i++){ roman=roman+"C"; } arab_num=arab_num%100; if( (arab_num/90)>=1 ) roman=roman+"XC"; arab_num=arab_num%90; if( (arab_num/50)>=1 ) roman=roman+"L"; arab_num=arab_num%50; if( (arab_num/40)>=1 ) roman=roman+"XL"; arab_num=arab_num%40; loop=arab_num/10; for(int i=1; i<=loop;i++){ roman=roman+"X"; } arab_num=arab_num%10; if( (arab_num/9)>=1 ) roman=roman+"IX"; arab_num=arab_num%9; if( (arab_num/5)>=1 ) roman=roman+"V"; arab_num=arab_num%5; if( (arab_num/4)>=1 ) roman=roman+"IV"; arab_num=arab_num%4; loop=arab_num/1; for(int i=1; i<=loop;i++){ roman=roman+"I"; } //----------------------------------------------------------------------- return roman; } }
true
6dde7007b4214a9158ada0ca4703d56d86bae18e
Java
sebuaa2019/Team106
/sub/frontend/app/src/main/java/com/example/alarmapp/MainActivity.java
UTF-8
3,097
2.28125
2
[]
no_license
package com.example.alarmapp; import android.os.Bundle; import android.support.design.widget.BottomNavigationView; import android.support.v4.view.ViewPager; import android.support.v7.app.ActionBar; import android.support.v7.app.AppCompatActivity; import android.support.annotation.NonNull; import android.view.MenuItem; import android.view.Window; import com.example.alarmapp.Adapter.MyFragmentPagerAdapter; public class MainActivity extends AppCompatActivity implements ViewPager.OnPageChangeListener { public static final int PAGE_HOME = 0; public static final int PAGE_NOTIFICATION = 1; public static final int PAGE_SETTINGS = 2; private ViewPager viewPager; private MyFragmentPagerAdapter myFragmentPagerAdapter; private BottomNavigationView navView; private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener = new BottomNavigationView.OnNavigationItemSelectedListener() { @Override public boolean onNavigationItemSelected(@NonNull MenuItem item) { switch (item.getItemId()) { case R.id.navigation_home: viewPager.setCurrentItem(PAGE_HOME); return true; case R.id.navigation_notifications: viewPager.setCurrentItem(PAGE_NOTIFICATION); return true; case R.id.navigation_settings: viewPager.setCurrentItem(PAGE_SETTINGS); return true; } return false; } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); ActionBar actionBar = getSupportActionBar(); actionBar.hide(); setContentView(R.layout.main_layout); navView = findViewById(R.id.nav_view); myFragmentPagerAdapter = new MyFragmentPagerAdapter(getSupportFragmentManager()); viewPager = findViewById(R.id.vpager); viewPager.setAdapter(myFragmentPagerAdapter); viewPager.setCurrentItem(PAGE_HOME); viewPager.addOnPageChangeListener(this); navView.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener); } @Override public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { } @Override public void onPageSelected(int position) { } @Override public void onPageScrollStateChanged(int state) { //state的状态有三个,0表示什么都没做,1正在滑动,2滑动完毕 if(state==2){ switch (viewPager.getCurrentItem()){ case PAGE_HOME: navView.setSelectedItemId(R.id.navigation_home); break; case PAGE_NOTIFICATION: navView.setSelectedItemId(R.id.navigation_notifications); break; case PAGE_SETTINGS: navView.setSelectedItemId(R.id.navigation_settings); break; } } } }
true
27a7026a2ce99e95140305d2863fd32d3b90b251
Java
Leroy-Merlin-France/lm-labs
/lm-labs-webapp/src/test/java/com/leroymerlin/corp/fr/nuxeo/labs/site/operations/GetChildrenPagesOperationTest.java
UTF-8
2,816
1.914063
2
[]
no_license
package com.leroymerlin.corp.fr.nuxeo.labs.site.operations; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import java.util.List; import org.junit.Test; import org.junit.runner.RunWith; import org.nuxeo.ecm.automation.AutomationService; import org.nuxeo.ecm.automation.OperationChain; import org.nuxeo.ecm.automation.OperationContext; import org.nuxeo.ecm.core.api.CoreSession; import org.nuxeo.ecm.core.api.DocumentModel; import org.nuxeo.ecm.core.test.annotations.RepositoryConfig; import org.nuxeo.runtime.test.runner.Deploy; import org.nuxeo.runtime.test.runner.Features; import org.nuxeo.runtime.test.runner.FeaturesRunner; import org.nuxeo.runtime.test.runner.Jetty; import com.google.inject.Inject; import com.leroymerlin.corp.fr.nuxeo.labs.site.features.LabsWebAppFeature; import com.leroymerlin.corp.fr.nuxeo.labs.site.labssite.LabsSite; import com.leroymerlin.corp.fr.nuxeo.labs.site.test.OfmRepositoryInit; import com.leroymerlin.corp.fr.nuxeo.labs.site.test.PageClasseurPageRepositoryInit; @RunWith(FeaturesRunner.class) @Features( { LabsWebAppFeature.class }) @Deploy({ "org.nuxeo.ecm.automation.core" }) @RepositoryConfig(init = PageClasseurPageRepositoryInit.class) @Jetty(port=9090) public class GetChildrenPagesOperationTest extends AbstractTestOperation { @Inject AutomationService service; @Inject CoreSession session; @Test public void iCanGetChildrenPagesOfTreeUsingDocId() throws Exception { LabsSite site = getSiteManager().getSite(session, OfmRepositoryInit.SITE_URL); DocumentModel treeDocument = site.getTree(); assertNotNull(treeDocument); OperationContext ctx = new OperationContext(session); OperationChain chain = new OperationChain("test" + GetChildrenPages.ID); chain.add(GetChildrenPages.ID).set("docId", treeDocument.getId()); @SuppressWarnings("unchecked") List<DocumentModel> operationChildrenPageDocuments = (List<DocumentModel>) service.run(ctx, chain); assertEquals(2, operationChildrenPageDocuments.size()); } @Test public void iCanGetChildrenPagesOfTreeUsingDocPath() throws Exception { LabsSite site = getSiteManager().getSite(session, OfmRepositoryInit.SITE_URL); DocumentModel treeDocument = site.getTree(); assertNotNull(treeDocument); OperationContext ctx = new OperationContext(session); OperationChain chain = new OperationChain("test" + GetChildrenPages.ID); chain.add(GetChildrenPages.ID).set("docPath", treeDocument.getPathAsString()); @SuppressWarnings("unchecked") List<DocumentModel> operationChildrenPageDocuments = (List<DocumentModel>) service.run(ctx, chain); assertEquals(2, operationChildrenPageDocuments.size()); } }
true
dd90ef9d9c5b7c0c7bd830bd142f7393b7bd68d9
Java
ionutmedrea/DxPlatform-Control-Statements-Counter
/src/main/java/Main.java
UTF-8
5,733
2.640625
3
[ "Apache-2.0" ]
permissive
import com.fasterxml.jackson.databind.ObjectMapper; import com.github.javaparser.ast.CompilationUnit; import com.github.javaparser.ast.Node; import com.github.javaparser.ast.stmt.Statement; import java.io.*; import java.nio.file.Files; import java.nio.file.NoSuchFileException; import java.nio.file.Paths; import java.util.ArrayList; import java.util.List; import static com.github.javaparser.StaticJavaParser.parse; public class Main { static String projectId, baseFolderPath, outputFilePath; static List<ProjectFile> projectFiles = new ArrayList<>(); public static void main(String[] args) { if(args.length != 1) { System.out.println("Error: incorrect program invocation. Correct: control_stmt_counter.jar config/config.txt"); return; } else { BufferedReader reader; try { reader = new BufferedReader(new FileReader(args[0])); projectId = reader.readLine().substring(10); baseFolderPath = reader.readLine().substring(15); reader.close(); } catch (FileNotFoundException e) { System.out.println("The configuration file path does not exist or it is incorrect."); return; } catch (IOException e){ e.printStackTrace(); return; } outputFilePath = projectId + "_control_stmt_count.json"; try { File results = new File(outputFilePath); FileWriter myWriter = new FileWriter(results); myWriter.write("test"); myWriter.close(); } catch (NoSuchFileException|FileNotFoundException e) { System.out.println("The results file path does not exist or it is incorrect."); return; } catch (IOException e) { e.printStackTrace(); } try { int start_path = baseFolderPath.lastIndexOf('\\')+1; int project_name_length = baseFolderPath.substring(start_path).length(); Files.walk(Paths.get(baseFolderPath)) .filter(Files::isRegularFile) .filter(f -> f.getFileName().toString().endsWith(".java")) .forEach(file -> { nr_if_stmt = 0; nr_while_stmt = 0; nr_for_stmt = 0; nr_do_stmt = 0; nr_try_stmt = 0; try { CompilationUnit cUnit = parse(new File(file.toString())); parc(cUnit); String relative_file_path = file.toString().substring(start_path + project_name_length + 1); if(nr_if_stmt>0) projectFiles.add(new ProjectFile("if", "Control Statements", relative_file_path.replace("\\","/"), nr_if_stmt)); if(nr_while_stmt>0) projectFiles.add(new ProjectFile("while", "Control Statements", relative_file_path.replace("\\","/"), nr_while_stmt)); if(nr_for_stmt>0) projectFiles.add(new ProjectFile("for", "Control Statements", relative_file_path.replace("\\","/"), nr_for_stmt)); if(nr_do_stmt>0) projectFiles.add(new ProjectFile("do", "Control Statements", relative_file_path.replace("\\","/"), nr_do_stmt)); if(nr_try_stmt>0) projectFiles.add(new ProjectFile("try", "Control Statements", relative_file_path.replace("\\","/"), nr_try_stmt)); } catch (FileNotFoundException e) { e.printStackTrace(); } }); ObjectMapper objectMapper = new ObjectMapper(); String projectFiles_json_string = objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(projectFiles); try { File results = new File(outputFilePath); FileWriter myWriter = new FileWriter(results); myWriter.write(projectFiles_json_string); myWriter.close(); } catch (IOException e){ e.printStackTrace(); } } catch (NoSuchFileException e){ System.out.println("The project path does not exist or it is incorrect."); return; } catch (IOException e) { e.printStackTrace(); } System.out.println("The analysis completed successfully."); } } static int nr_if_stmt; static int nr_while_stmt; static int nr_for_stmt; static int nr_do_stmt; static int nr_try_stmt; public static void parc(Node node) { if (node instanceof Statement){ if(((Statement) node).isIfStmt()) nr_if_stmt++; if(((Statement) node).isWhileStmt()) nr_while_stmt++; if(((Statement) node).isForStmt() || ((Statement) node).isForEachStmt()) nr_for_stmt++; if(((Statement) node).isDoStmt()) nr_do_stmt++; if(((Statement) node).isTryStmt()) nr_try_stmt++; } for (Node child : node.getChildNodes()) { parc(child); } } }
true
8bfd6f6d894c53adf46f84218b7073b703180119
Java
c1028131070/JavaNotes
/JavaSE/DAY2-数据类型-运算符/Code/Ex05.java
GB18030
414
3.546875
4
[]
no_license
class Ex05{ public static void main(String[] args){ //-- ַ System.out.println("A"); //-- System.out.println(1); System.out.println(1.0); //-- ֻҪ˫ŵľַ System.out.println("1"); //-- ַ ַʹõǵ System.out.println('A'); //-- System.out.println(true); System.out.println(false); } }
true
09c1c401bbc0092438de4eb6118984fe590e5b68
Java
nats-afs/app-wilson
/app/src/main/java/com/asforsoft/nats/firebaseapp/FirebaseService.java
UTF-8
869
2.078125
2
[]
no_license
package com.asforsoft.nats.firebaseapp; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.auth.FirebaseUser; import com.google.firebase.firestore.CollectionReference; import com.google.firebase.firestore.FirebaseFirestore; public class FirebaseService { static FirebaseAuth auth = FirebaseAuth.getInstance(); static FirebaseFirestore db = FirebaseFirestore.getInstance(); public static FirebaseAuth getAuth() { return auth; } public static FirebaseFirestore getRoot() { return db; } public static FirebaseUser getCurrentUser() { return auth.getCurrentUser(); } public static CollectionReference getUsersCollection() { return db.collection("users"); } public static CollectionReference getProductsCollection() { return db.collection("products"); } }
true
4d6e4cf3950ec156ec4fce91f345052b4b4ff7a4
Java
kmisztal/TLetters
/src/main/java/tletters/knnclassification/KNNClassifier.java
UTF-8
2,887
3.1875
3
[]
no_license
package tletters.knnclassification; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.SortedSet; import java.util.TreeSet; /** * @param <VAL> * @author Piotr */ public class KNNClassifier<VAL extends Number> implements Classifier<VAL> { private Collection<Collection<VAL>> descriptions; private Collection<Integer> classes; private DistanceMeter<VAL> distanceMeter; private int K; public KNNClassifier(int K) { this.K = K; } @Override public void fit(Collection<Collection<VAL>> descriptions, Collection<Integer> classes, DistanceMeter<VAL> distanceMeter) { this.descriptions = descriptions; this.classes = classes; this.distanceMeter = distanceMeter; } @Override public int predict(Collection<VAL> description) { SortedSet<Pair> neighbours = new TreeSet<>((Pair o1, Pair o2) -> o1.distance.compareTo(o2.distance)); Iterator<Collection<VAL>> itDescriptions = descriptions.iterator(); Iterator<Integer> itClasses = classes.iterator(); double dist; int objClass; while (itDescriptions.hasNext() && itClasses.hasNext()) { dist = distanceMeter.distance(description, itDescriptions.next()); objClass = itClasses.next(); if (neighbours.size() < K) { neighbours.add(new Pair(dist, objClass)); } else if (dist < neighbours.last().distance) { neighbours.add(new Pair(dist, objClass)); //can be ommited, but it changes complexity from O(n*logn) to O(n*logK) if (neighbours.size() > K) { neighbours.remove(neighbours.last()); } } } // count classes HashMap<Integer, Integer> classCounter = new HashMap<>(); for (Pair p : neighbours) { Integer valueWrapper = classCounter.get(p.objClass); if (valueWrapper == null) { classCounter.put(p.objClass, 1); } else { classCounter.put(p.objClass, valueWrapper + 1); } } // find most common class int maxCount = 1; int commonClass = neighbours.first().objClass; for (Pair p : neighbours) { Integer valueWrapper = classCounter.get(p.objClass); if (valueWrapper > maxCount) { maxCount = valueWrapper; commonClass = p.objClass; } } // might be different due to solving cases of equal number of neighbour classes return commonClass; } private class Pair { public Double distance; public int objClass; public Pair(double distance, int objClass) { this.distance = distance; this.objClass = objClass; } } }
true
c49490cef236215c0b91dfd9021476d18d7a8631
Java
abassawo/Sherpa
/app/src/main/java/abasscodes/com/sherpa/data/repository/remote/BookRemoteDataSource.java
UTF-8
1,159
2.390625
2
[]
no_license
package abasscodes.com.sherpa.data.repository.remote; import java.util.List; import javax.inject.Inject; import abasscodes.com.sherpa.data.api.BookResponse; import abasscodes.com.sherpa.data.api.BookService; import abasscodes.com.sherpa.data.model.Book; import abasscodes.com.sherpa.data.repository.BookDataSource; import abasscodes.com.sherpa.data.Config; import io.reactivex.Flowable; public class BookRemoteDataSource implements BookDataSource { private BookService bookService; @Inject public BookRemoteDataSource(BookService bookService) { this.bookService = bookService; } @Override public Flowable<List<Book>> loadBooks(boolean forceRemote) { return bookService.loadBooks(Config.USER_ID).map(BookResponse::getBooks); } @Override public void addBook(Book question) { //Currently, we do not need this for remote source. throw new UnsupportedOperationException("Unsupported operation"); } @Override public void clearData() { //Currently, we do not need this for remote source. throw new UnsupportedOperationException("Unsupported operation"); } }
true
1609a5eb893d1e84e8fc2f5d5afd9147c30d6bb1
Java
Victor-Andrade/Gerenciador-Escolar
/src/model/classesUtilitarias/Formatador.java
UTF-8
2,255
3.34375
3
[]
no_license
package model.classesUtilitarias; /** * Classe responsável por fazer as formatações de dados das pessoas do repositório * @author: Victor Hugo */ public abstract class Formatador { public static String removerCaracteresCpf(String cpf){ return cpf.replaceAll("[\\p{P}\\p{S}]", "").toLowerCase(); } public static String removerCaracteresNome(String nome){ return nome.toUpperCase(); } public static String removerCaracteresNumero(String numero){ return numero.replaceAll("[\\p{P}\\p{S}]", ""); } public static String formatarCpf(String cpf){ char[] cpfArray = new char[cpf.length() + 3]; char[] cpfArrayTemp = cpf.toCharArray(); int posicoes = 0; for(int i = 0; i < cpf.length(); i++){ if(i == 2 || i == 5){ cpfArray[i + posicoes] = cpfArrayTemp[i]; posicoes++; cpfArray[i + posicoes] = '.'; }else if(i == 8){ cpfArray[i + posicoes] = cpfArrayTemp[i]; posicoes++; cpfArray[i + posicoes] = '-'; }else{ cpfArray[i + posicoes] = cpfArrayTemp[i]; } } return String.copyValueOf(cpfArray); } public static String formatarNumero(String numero){ char[] numeroArray = new char[numero.length() + 4]; char[] numeroArrayTemp = numero.toCharArray(); int posicoes = 0; for(int i = 0; i < numero.length(); i++){ if(i == 0){ numeroArray[i + posicoes] = '('; posicoes++; numeroArray[i + posicoes] = numeroArrayTemp[i]; }else if(i == 2){ numeroArray[i + posicoes] = ')'; posicoes++; numeroArray[i + posicoes] = ' '; posicoes++; numeroArray[i + posicoes] = numeroArrayTemp[i]; }else if(i == 6){ numeroArray[i + posicoes] = numeroArrayTemp[i]; posicoes++; numeroArray[i + posicoes] = '-'; }else{ numeroArray[i + posicoes] = numeroArrayTemp[i]; } } return String.copyValueOf(numeroArray); } }
true
685e3ca02742134ca000724a05e358ba312c56f4
Java
savvas-leoussis/Internet-Applications-Course-Exercises
/Lab3/BVShop/VehicleBean.java
UTF-8
1,365
3.375
3
[]
no_license
package BVShop; //if present 'package' MUST be the first statement (possibly) followed by 'import' // The following class follows the structure of a 'Java Bean' public class VehicleBean { /**The properties of the VehicleBean*/ String VModel; ManBean VMan; String VYear; /** The following non-argument constructor MUST be always present*/ /** for this class to be a Java Bean*/ public VehicleBean(){} /** Another constructor CAN also be always present*/ /** the following initializes all properties whenever a new object is instantiated (with 'new') - */ public VehicleBean(String model,ManBean manu, String year){ VModel= model; VMan = manu; VYear= year;} /** get & set methods for all properties MUST be present*/ public String getVModel(){return VModel;} public void setVModel(String model){VModel= model;} public ManBean getVManufacturer(){return VMan;} public void setVManufacturer(ManBean manu){VMan= manu;} public String getVYear(){return VYear;} public void setVYear(String year){VYear= year;} //toString is an in-built method for every Java object. Outputs an informative string public String toString(){ return "'" + VModel + "' manufacted by " + VMan.toString() + " during year " + VYear;} }
true
e7213bc225f75990817e5bc81044985d4191dc1a
Java
guoguangkai/tatisticianReposities
/tatistician40/src/main/java/cn/zgx/tatistician/pojo/MobilePojo.java
UTF-8
443
1.984375
2
[]
no_license
package cn.zgx.tatistician.pojo; import lombok.Data; import java.util.List; @Data public class MobilePojo { private String owner; private String mobile; public String getOwner() { return owner; } public void setOwner(String owner) { this.owner = owner; } public String getMobile() { return mobile; } public void setMobile(String mobile) { this.mobile = mobile; } }
true
1dbee317138d7ae54f2e5bd59cb98db931801d13
Java
RobJLeonard/Algos
/Algorithms Assignment 2/src/DoublyLinkedList.java
UTF-8
14,368
3.890625
4
[]
no_license
import java.util.Iterator; import java.util.ListIterator; import java.util.NoSuchElementException; // ------------------------------------------------------------------------- /** * This class contains the methods of Doubly Linked List. * * @author Robert Leonard * @version 13/10/16 18:15 */ /** * Class DoublyLinkedList: implements a *generic* Doubly Linked List. * @param <T> This is a type parameter. T is used as a class name in the * definition of this class. * * When creating a new DoublyLinkedList, T should be instantiated with an * actual class name that extends the class Comparable. * Such classes include String and Integer. * * For example to create a new DoublyLinkedList class containing String data: * DoublyLinkedList<String> myStringList = new DoublyLinkedList<String>(); * * The class offers a toString() method which returns a comma-separated sting of * all elements in the data structure. * * This is a bare minimum class you would need to completely implement. * You can add additional methods to support your code. Each method will need * to be tested by your jUnit tests -- for simplicity in jUnit testing * introduce only public methods. */ class DoublyLinkedList<T extends Comparable<T>> { /** * private class DLLNode: implements a *generic* Doubly Linked List node. */ private class DLLNode { public final T data; // this field should never be updated. It gets its // value once from the constructor DLLNode. public DLLNode next; public DLLNode prev; /** * Constructor * @param theData : data of type T, to be stored in the node * @param prevNode : the previous Node in the Doubly Linked List * @param nextNode : the next Node in the Doubly Linked List * @return DLLNode */ public DLLNode(T theData, DLLNode prevNode, DLLNode nextNode) { data = theData; prev = prevNode; next = nextNode; } } // Fields head and tail point to the first and last nodes of the list. private DLLNode head, tail; private int size; /** * Constructor * @return DoublyLinkedList */ public DoublyLinkedList() { head = null; tail = null; size = 0; } /** * Tests if the doubly linked list is empty * @return true if list is empty, and false otherwise * * Worst-case asymptotic runtime cost: Theta(1). * * Justification: * Because this method will only run once and perform 1 comparison regardless of list size we don't need to take that into account so the * method will have a worst-case asymptotic runtime cost of Theta(1) */ public boolean isEmpty() { return (size==0); } /** * Inserts an element in the doubly linked list * @param pos : The integer location at which the new data should be * inserted in the list. We assume that the first position in the list * is 0 (zero). If pos is less than 0 then add to the head of the list. * If pos is greater or equal to the size of the list then add the * element at the end of the list. * @param data : The new data of class T that needs to be added to the list * @return none * * Worst-case asymptotic runtime cost: Theta(n) * * Justification: * As with stated in the toString method justification we assume all other method calls here (e.g., the iterator methods above, and the toString method) will execute in Theta(1) time. * Thus, every one iteration of the while-loop will have cost Theta(1). * Suppose the doubly-linked list has 'n' elements. * The while-loop will always iterate over all n elements of the list, and therefore the total cost of this method will be n*Theta(1) = Theta(n). */ public void insertBefore( int pos, T data ) { //DLLNode temp = new DLLNode(data, null, null); //add DLLNode to the head of the linked list if(pos<=0) { DLLNode temp = new DLLNode(data, null, head); if(head != null ) { head.prev = temp; } head = temp; if(tail == null) { tail = temp; } size++; } else if(pos>this.size-1) { DLLNode temp = new DLLNode(data, tail, null); if(tail != null) { tail.next = temp; } tail = temp; if(head == null) { head = temp; } size++; } else { int nodePos = 0; DLLNode temp = new DLLNode(data, null, null); if(pos>=(this.size)/2) { nodePos = this.size - 1; DLLNode iter = tail; while(iter!=null) { if(pos==nodePos) { temp.prev = iter.prev; temp.next = iter; iter.prev.next = temp; iter.prev = temp; size++; return; } iter=iter.prev; nodePos--; } } else if(pos<=(this.size)/2) { nodePos = 0; DLLNode iter = head; while(iter!=null) { if(pos==nodePos) { temp.prev = iter.prev; temp.next = iter; iter.prev.next = temp; iter.prev = temp; size++; return; } iter=iter.next; nodePos++; } } } } /** * Returns the data stored at a particular position * @param pos : the position * @return the data at pos, if pos is within the bounds of the list, and null otherwise. * * Worst-case asymptotic runtime cost: Theta(n) * * Justification: * As with stated in the toString method justification we assume all other method calls here (e.g., the iterator methods above, and the toString method) will execute in Theta(1) time. * Thus, every one iteration of the while-loop will have cost Theta(1). * Suppose the doubly-linked list has 'n' elements. * The while-loop will always iterate over all n elements of the list, and therefore the total cost of this method will be n*Theta(1) = Theta(n). * * Worst-case precise runtime cost: Theta(n/2) * * Justification: * Although the runtime is still increased by increasing the input size, because the method iterates over the list, this does not mean the precise time would be Theta(n) * because the implementation of the method will start at the beginning or the end of the list depending on which half of the list the desired data is in. Meaning the method * will only ever iterate over have the list Theta(n) / 2 = Theta(n/2). */ public T get(int pos) { int nodePos = 0; if(pos>=(this.size)/2) { nodePos = this.size - 1; DLLNode iter = tail; while(iter!=null) { if(pos==nodePos) { return iter.data; } iter=iter.prev; nodePos--; } } else if(pos<=(this.size)/2) { nodePos = 0; DLLNode iter = head; while(iter!=null) { if(pos==nodePos) { return iter.data; } iter=iter.next; nodePos++; } } return null; } /** * Deletes the element of the list at position pos. * First element in the list has position 0. If pos points outside the * elements of the list then no modification happens to the list. * @param pos : the position to delete in the list. * @return true : on successful deletion, false : list has not been modified. * * Worst-case asymptotic runtime cost: Theta(n) * * Justification: * As with stated in the toString method justification we assume all other method calls here (e.g., the iterator methods above, and the toString method) will execute in Theta(1) time. * Thus, every one iteration of the while-loop will have cost Theta(1). * Suppose the doubly-linked list has 'n' elements. * The while-loop will always iterate over all n elements of the list, and therefore the total cost of this method will be n*Theta(1) = Theta(n). */ public boolean deleteAt(int pos) { int nodePos = 0; if(pos>=(this.size)/2) { nodePos = this.size - 1; DLLNode iter = tail; while(iter!=null) { if(pos==nodePos) { if(size==1) { head = null; tail = null; } else if(iter==tail) { iter.prev.next = null; tail = iter.prev; } else { iter.prev.next = iter.next; iter.next.prev = iter.prev; } size--; return true; } iter=iter.prev; nodePos--; } } else if(pos<=(this.size)/2) { nodePos = 0; DLLNode iter = head; while(iter!=null) { if(pos==nodePos) { if(iter==head) { iter.next.prev = null; head = iter.next; } else { iter.prev.next = iter.next; iter.next.prev = iter.prev; } size--; return true; } iter=iter.next; nodePos++; } } return false; } /** * Reverses the list. * If the list contains "A", "B", "C", "D" before the method is called * Then it should contain "D", "C", "B", "A" after it returns. * * Worst-case asymptotic runtime cost: Theta(n) * * Justification: * As with stated in the toString method justification we assume all other method calls here (e.g., the iterator methods above, and the toString method) will execute in Theta(1) time. * Thus, every one iteration of the while-loop will have cost Theta(1). * Suppose the doubly-linked list has 'n' elements. * The while-loop will always iterate over all n elements of the list, and therefore the total cost of this method will be n*Theta(1) = Theta(n). */ public void reverse() { if(this.isEmpty()) return; else { DLLNode iter; DLLNode swap = new DLLNode(null, null, null); DLLNode temp = new DLLNode(null, null, null); swap = head; head = tail; tail = swap; iter = head; while(iter!=null) { temp.next = iter.next; iter.next = iter.prev; iter.prev = temp.next; iter = iter.next; } } } /*----------------------- STACK */ /** * This method should behave like the usual push method of a Stack ADT. * If only the push and pop methods are called the data structure should behave like a stack. * How exactly this will be represented in the Doubly Linked List is up to the programmer. * @param item : the item to push on the stack * * Worst-case asymptotic runtime cost: Theta(1). * * Justification: * Because this method will only run once regardless of list size we don't need to take that into account so the * method will have a worst-case asymptotic runtime cost of Theta(1) */ public void push(T item) { if(this.isEmpty()) { DLLNode newItem = new DLLNode(item, null, null); head = newItem; tail = newItem; } else { DLLNode newItem = new DLLNode(item, null, head); head.prev = newItem; head = newItem; } size++; } /** * This method should behave like the usual pop method of a Stack ADT. * If only the push and pop methods are called the data structure should behave like a stack. * How exactly this will be represented in the Doubly Linked List is up to the programmer. * @return the last item inserted with a push; or null when the list is empty. * * Worst-case asymptotic runtime cost: Theta(1). * * Justification: * Because this method will only run once regardless of list size we don't need to take that into account so the * method will have a worst-case asymptotic runtime cost of Theta(1) */ public T pop() { if(this.isEmpty()) return null; else if(size == 1) { DLLNode popItem = head; head=null; tail=null; size--; return popItem.data; } else { DLLNode popItem = head; head.next.prev = null; head = head.next; size--; return popItem.data; } } /*----------------------- QUEUE */ /** * This method should behave like the usual enqueue method of a Queue ADT. * If only the enqueue and dequeue methods are called the data structure should behave like a FIFO queue. * How exactly this will be represented in the Doubly Linked List is up to the programmer. * @param item : the item to be enqueued to the stack * * Worst-case asymptotic runtime cost: Theta(1). * * Justification: * Because this method will only run once regardless of list size we don't need to take that into account so the * method will have a worst-case asymptotic runtime cost of Theta(1) */ public void enqueue(T item) { if(!this.isEmpty()) { DLLNode newItem = new DLLNode(item, null, head); head.prev = newItem; head = newItem; } else { DLLNode newItem = new DLLNode(item, null, null); head=newItem; tail=newItem; } size++; } /** * This method should behave like the usual dequeue method of a Queue ADT. * If only the enqueue and dequeue methods are called the data structure should behave like a FIFO queue. * How exactly this will be represented in the Doubly Linked List is up to the programmer. * @return the earliest item inserted with a push; or null when the list is empty. * * Worst-case asymptotic runtime cost: Theta(1). * * Justification: * Because this method will only run once regardless of list size we don't need to take that into account so the * method will have a worst-case asymptotic runtime cost of Theta(1) */ public T dequeue() { if(this.isEmpty()) return null; else if(size==1) { DLLNode dequeuItem = tail; tail = null; head = null; size--; return dequeuItem.data; } else { DLLNode dequeuItem = tail; tail.prev.next = null; tail = tail.prev; size--; return dequeuItem.data; } } /** * @return a string with the elements of the list as a comma-separated * list, from beginning to end * * Worst-case asymptotic runtime cost: Theta(n) * * Justification: * We know from the Java documentation that StringBuilder's append() method runs in Theta(1) asymptotic time. * We assume all other method calls here (e.g., the iterator methods above, and the toString method) will execute in Theta(1) time. * Thus, every one iteration of the for-loop will have cost Theta(1). * Suppose the doubly-linked list has 'n' elements. * The for-loop will always iterate over all n elements of the list, and therefore the total cost of this method will be n*Theta(1) = Theta(n). */ public String toString() { StringBuilder s = new StringBuilder(); boolean isFirst = true; // iterate over the list, starting from the head for (DLLNode iter = head; iter != null; iter = iter.next) { if (!isFirst) { s.append(","); } else { isFirst = false; } s.append(iter.data.toString()); } return s.toString(); } }
true
d05d99c651207c5e5ec906ec825c77bd73f612ad
Java
Praqma/vans
/src/main/java/net/praqma/vans/report/QACReporter.java
UTF-8
2,924
2.390625
2
[]
no_license
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package net.praqma.vans.report; import java.io.BufferedWriter; import java.io.DataOutputStream; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; import java.util.ArrayList; import java.util.HashMap; import java.util.logging.Level; import java.util.logging.Logger; import java.util.regex.Pattern; import net.praqma.vans.VANSReport; import net.praqma.vans.filter.Finding; import net.praqma.vans.util.Status; /** * * @author jssu */ public class QACReporter { private String input; private File reportFile; public QACReporter(String input, File filePath) { this.input = input; this.reportFile = filePath; } public void report() { String xml = parseResult(); FileOutputStream fos = null; try { fos = new FileOutputStream(reportFile); } catch (FileNotFoundException ex) { Logger.getLogger(QACReporter.class.getName()).log(Level.SEVERE, null, ex); } DataOutputStream dos = new DataOutputStream(fos); BufferedWriter br = new BufferedWriter(new OutputStreamWriter(dos)); try { br.write(xml); br.close(); } catch (IOException ex) { System.out.println("Could not write xml to file:\n" + ex.getMessage()); } } private String parseResult() { ArrayList<String> result = new ArrayList<String>(); VANSReport report = new VANSReport("QAC errors"); String path = ""; for (String s : input.split("\n")) { if (s.matches("") || s.matches(".*-.*")) { continue; } Pattern totalP = Pattern.compile("^Total.*\\d$"); if (!totalP.matcher(s).find()) { continue; } HashMap<Integer, String> temp = new HashMap<Integer, String>(); int i = 0; for (String s1 : s.split("\\s++")) { temp.put(i, s1); i++; } int errors = Integer.parseInt(temp.get(i - 1)); while (errors > 0) { Finding finding = new Finding("QAC has " + temp.get(i - 1) + " errors", Finding.Level.ERROR); report.addCase(finding, errors, "QAC", new Status(temp.get(0), "QAC errors", "QAC has " + errors + " errors", true)); errors--; } /* * Finding finding = new Finding("QAC has " + temp.get(i - 1) + " errors", Finding.Level.ERROR); * * report.addCase(finding, errors, "QAC", new Status(temp.get(0), "QAC errors", "QAC has " + errors + " errors", true)); * */ } return report.getXML(); } }
true
704552b1b875cf296a0b666dd8a99124164f9548
Java
itayB/ExpensesCalculator
/src/trip/main/AddActivity.java
UTF-8
6,259
2.140625
2
[]
no_license
package trip.main; import java.util.Calendar; import android.app.AlertDialog; import android.app.DatePickerDialog; import android.app.Dialog; import android.content.ContentValues; import android.content.DialogInterface; import android.content.Intent; import android.os.Bundle; import android.util.Log; import android.view.MotionEvent; import android.view.View; import android.view.View.OnClickListener; import android.view.View.OnTouchListener; import android.widget.Button; import android.widget.DatePicker; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; public class AddActivity extends BaseActivity { private static final String TAG = AddActivity.class.getSimpleName(); private static final int DIALOG_DATE_PICKER = 0; private static final int DIALOG_CURRENCY_LIST = 1; EditText textDescription; EditText textPrice; EditText textDate; TextView textCurrency; Button buttonChangeCurrency; Button buttonSave; Button buttonCancel; int currency = 0; // should change later on to default value from settings int mYear = 2011; int mMonth = 1; int mDay = 1; int rowId; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.add); textDescription = (EditText) findViewById(R.id.editTextDescription); textPrice = (EditText) findViewById(R.id.editTextPrice); textDate = (EditText) findViewById(R.id.editTextDate); textCurrency = (TextView) findViewById(R.id.textCurrency); buttonChangeCurrency = (Button) findViewById(R.id.buttonChangeCurrency); buttonSave = (Button) findViewById(R.id.buttonSave); buttonCancel = (Button) findViewById(R.id.buttonCancel); Bundle extras = getIntent().getExtras(); if (extras != null) { rowId = extras.getInt("rowId"); // get row data from DB ContentValues values = calc.statusData.getRow(rowId); textDescription.setText(values.getAsString(StatusData.C_DESCRIPTION)); textPrice.setText("" + values.getAsDouble(StatusData.C_PRICE)); textCurrency.setText(calc.currencyIdToMark(values.getAsInteger(StatusData.C_CURRENCY))); textDate.setText(values.getAsString(StatusData.C_DATE)); currency = values.getAsInteger(StatusData.C_CURRENCY); } else { rowId = -1; // set default currency mark textCurrency.setText(calc.currencyIdToMark(currency)); } buttonChangeCurrency.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { showDialog(DIALOG_CURRENCY_LIST); } }); buttonSave.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { String description = textDescription.getText().toString(); String price = textPrice.getText().toString(); String date = textDate.getText().toString(); //String currency = textCurrency.getText().toString(); Log.d(TAG, "### description: " + description); Log.d(TAG, "### price: " + price); Log.d(TAG, "### date: " + date); Log.d(TAG, "### currency: " + currency); if (description.equals("")) { Toast.makeText(AddActivity.this, R.string.errorMsgDescription, Toast.LENGTH_LONG) .show(); return; } if (price.equals("")) { Toast.makeText(AddActivity.this, R.string.errorMsgPrice, Toast.LENGTH_LONG).show(); return; } if (rowId == -1) // new expense calc.statusData.insert(description, Double.parseDouble(price), date, currency); else calc.statusData.update(rowId,description, Double.parseDouble(price), date, currency); startActivity(new Intent(AddActivity.this, ExpensesActivity.class).addFlags( Intent.FLAG_ACTIVITY_SINGLE_TOP).addFlags( Intent.FLAG_ACTIVITY_REORDER_TO_FRONT)); } }); buttonCancel.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { //startActivity(new Intent(AddActivity.this, // ExpensesActivity.class).addFlags( // Intent.FLAG_ACTIVITY_SINGLE_TOP).addFlags( // Intent.FLAG_ACTIVITY_REORDER_TO_FRONT)); finish(); } }); textDate.setOnTouchListener(new OnTouchListener() { public boolean onTouch(View v, MotionEvent event) { Calendar rightNow = Calendar.getInstance(); Log.d("itay", "### " + rightNow.get(Calendar.YEAR) + " " + rightNow.get(Calendar.MONTH) + " " + rightNow.get(Calendar.DAY_OF_MONTH)); showDialog(DIALOG_DATE_PICKER); return true; } }); } DatePickerDialog.OnDateSetListener mDateSetListener = new DatePickerDialog.OnDateSetListener() { public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) { mYear = year; mMonth = monthOfYear; mDay = dayOfMonth; updateDisplay(); } }; @Override protected Dialog onCreateDialog(int id) { switch (id) { case DIALOG_DATE_PICKER: return new DatePickerDialog(this, mDateSetListener, mYear, mMonth, mDay); case DIALOG_CURRENCY_LIST: return new AlertDialog.Builder(AddActivity.this) .setTitle(R.string.changeCurrency) .setItems(R.array.select_dialog_items, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { /* User clicked so do some stuff */ currency = which; String mark = calc.currencyIdToMark(currency); textCurrency.setText(mark); //String[] items = getResources() // .getStringArray( // R.array.select_dialog_items); //new AlertDialog.Builder(AddActivity.this) // .setMessage( // "You selected: " + which // + " , " // + items[which]) // .show(); } }).create(); } return null; } protected void updateDisplay() { textDate.setText("" + mDay + "/" + (mMonth + 1) + "/" + mYear); } @Override protected void onPrepareDialog(int id, Dialog dialog) { if (id == DIALOG_DATE_PICKER) { Calendar rightNow = Calendar.getInstance(); mYear = rightNow.get(Calendar.YEAR); mMonth = rightNow.get(Calendar.MONTH); mDay = rightNow.get(Calendar.DAY_OF_MONTH); ((DatePickerDialog) dialog).updateDate(mYear, mMonth, mDay); } } }
true
a9f79e430c9fb0df1c36436100b9ab49ce8a45ec
Java
847238158/coorperation
/src/main/java/com/objectspace/coorperation/dao/CaptchaDao.java
UTF-8
232
1.726563
2
[ "Apache-2.0" ]
permissive
package com.objectspace.coorperation.dao; import com.objectspace.coorperation.entity.Captcha; import org.apache.ibatis.annotations.Mapper; @Mapper public interface CaptchaDao { public Integer insertCaptcha(Captcha captcha); }
true
df0c2730b4446b69bedb3f333913abe795143d40
Java
adilsonv77/nobugssnackbar
/utils/nobugssnackbar/TestXML.java
UTF-8
1,729
2.15625
2
[]
no_license
package nobugssnackbar; import java.io.ByteArrayInputStream; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import org.w3c.dom.Document; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.InputSource; public class TestXML { public static void main(String[] args) throws Exception { DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); String xml = "<xml return='ChooseCategory(#{command})'><row><item type='text'>LOUCURA</item><item type=\"text\">According the commands available in this mission, select the category which is showed the hint</item></row><row><item type=\"list\" name=\"command\">#{mm.missionContent.commands}</item></row></xml>"; Document doc = dBuilder.parse(new InputSource(new ByteArrayInputStream(xml.getBytes("utf-8")))); doc.getDocumentElement().normalize(); System.out.println(doc.getDocumentElement().getAttributes().getNamedItem("return").getNodeValue()); NodeList nodes = doc.getDocumentElement().getChildNodes(); for (int i = 0; i < nodes.getLength(); i++) { Node row = nodes.item(i); NodeList rowNodes = row.getChildNodes(); for (int j = 0; j < rowNodes.getLength(); j++) { Node item = rowNodes.item(j); String type = item.getAttributes().getNamedItem("type").getNodeValue(); Node value = item.getLastChild(); if (type.equals("text")) { System.out.print("text " + value.getNodeValue()); } else if (type.equals("list")) { System.out.print("lista " + value.getNodeValue()); } } System.out.println(); } } }
true
30d0ff7ac932237e56db5e6ea78ff2f7083f1ecf
Java
JamesWillLewis/WSIntelliAuction
/WSIntelliAuction/src/com/uct/cs/wsintelliauction/client/frontend/controls/NewBidController.java
UTF-8
2,762
2.59375
3
[]
no_license
package com.uct.cs.wsintelliauction.client.frontend.controls; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.text.ParseException; import javax.swing.JOptionPane; import javax.swing.JTable; import javax.swing.table.DefaultTableModel; import com.uct.cs.wsintelliauction.client.frontend.models.NewBidModel; import com.uct.cs.wsintelliauction.client.frontend.views.NewBidView; import com.uct.cs.wsintelliauction.utility.ErrorLogger; import com.uct.cs.wsintelliauction.window.Controller; public class NewBidController extends Controller<NewBidModel, NewBidView> { private JTable bidTable; public NewBidController(NewBidView view, NewBidModel model, JTable bidTable) { super(view, model); this.bidTable = bidTable; } @Override protected void assignListeners() { view.getBtnSubmitBid().addActionListener(new SubmitBidEvent()); view.getBtnCancel().addActionListener(new CancelEvent()); } public class SubmitBidEvent implements ActionListener { @Override public void actionPerformed(ActionEvent e) { int selectedSegment = view.getTable().getSelectedRow(); try { view.getBidAmountField().commitEdit(); } catch (ParseException e1) { ErrorLogger.log(e1.getMessage()); } if (selectedSegment < 0) { JOptionPane.showMessageDialog(null, "You must select a segment to bid for.", "Error", JOptionPane.ERROR_MESSAGE); } else if (view.getBidAmountField().getValue() == null || ((Number) view.getBidAmountField().getValue()) .intValue() <= 0) { JOptionPane.showMessageDialog(null, "You must bid a positive, non-negative amount.", "Error", JOptionPane.ERROR_MESSAGE); } else { int opt = JOptionPane .showConfirmDialog( null, "Are you sure you want to submit this bid? \n " + "Once a bid has been submitted it cannot be reversed.\n" + "You are financially committed to your bid.\n" + "If this bid wins, you are legally required to pay the bid price.", "Confirm bid", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE); if (opt == JOptionPane.YES_OPTION) { double bidAmount = ((Number) view.getBidAmountField() .getValue()).doubleValue(); model.submitBid(selectedSegment, bidAmount); ((DefaultTableModel) bidTable.getModel()) .fireTableDataChanged(); view.getWrapper().setVisible(false); view.getWrapper().dispose(); } } } } public class CancelEvent implements ActionListener { @Override public void actionPerformed(ActionEvent e) { view.getWrapper().setVisible(false); view.getWrapper().dispose(); } } }
true
7a65e71d42b21202034fd95b391b8857c7d86992
Java
dmgerman/gerrit
/java/com/google/gerrit/common/data/GlobalCapability.java
UTF-8
14,777
1.734375
2
[ "Apache-2.0" ]
permissive
begin_unit|revision:0.9.5;language:Java;cregit-version:0.0.1 begin_comment comment|// Copyright (C) 2011 The Android Open Source Project end_comment begin_comment comment|// end_comment begin_comment comment|// Licensed under the Apache License, Version 2.0 (the "License"); end_comment begin_comment comment|// you may not use this file except in compliance with the License. end_comment begin_comment comment|// You may obtain a copy of the License at end_comment begin_comment comment|// end_comment begin_comment comment|// http://www.apache.org/licenses/LICENSE-2.0 end_comment begin_comment comment|// end_comment begin_comment comment|// Unless required by applicable law or agreed to in writing, software end_comment begin_comment comment|// distributed under the License is distributed on an "AS IS" BASIS, end_comment begin_comment comment|// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. end_comment begin_comment comment|// See the License for the specific language governing permissions and end_comment begin_comment comment|// limitations under the License. end_comment begin_package DECL|package|com.google.gerrit.common.data package|package name|com operator|. name|google operator|. name|gerrit operator|. name|common operator|. name|data package|; end_package begin_import import|import name|java operator|. name|util operator|. name|ArrayList import|; end_import begin_import import|import name|java operator|. name|util operator|. name|Arrays import|; end_import begin_import import|import name|java operator|. name|util operator|. name|Collection import|; end_import begin_import import|import name|java operator|. name|util operator|. name|Collections import|; end_import begin_import import|import name|java operator|. name|util operator|. name|List import|; end_import begin_comment comment|/** * Server wide capabilities. Represented as {@link Permission} objects. * *<p>Contrary to {@link Permission}, global capabilities do not need a resource to check * permissions on. */ end_comment begin_class DECL|class|GlobalCapability specifier|public class|class name|GlobalCapability block|{ comment|/** Ability to view code review metadata refs in repositories. */ DECL|field|ACCESS_DATABASE specifier|public specifier|static specifier|final name|String name|ACCESS_DATABASE init|= literal|"accessDatabase" decl_stmt|; comment|/** * Denotes the server's administrators. * *<p>This is similar to UNIX root, or Windows SYSTEM account. Any user that has this capability * can perform almost any other action, or can grant themselves the power to perform any other * action on the site. Most of the other capabilities and permissions fall-back to the predicate * "OR user has capability ADMINISTRATE_SERVER". */ DECL|field|ADMINISTRATE_SERVER specifier|public specifier|static specifier|final name|String name|ADMINISTRATE_SERVER init|= literal|"administrateServer" decl_stmt|; comment|/** Maximum number of changes that may be pushed in a batch. */ DECL|field|BATCH_CHANGES_LIMIT specifier|public specifier|static specifier|final name|String name|BATCH_CHANGES_LIMIT init|= literal|"batchChangesLimit" decl_stmt|; comment|/** * Default maximum number of changes that may be pushed in a batch, 0 means no limit. This is just * used as a suggestion for prepopulating the field in the access UI. */ DECL|field|DEFAULT_MAX_BATCH_CHANGES_LIMIT specifier|public specifier|static specifier|final name|int name|DEFAULT_MAX_BATCH_CHANGES_LIMIT init|= literal|0 decl_stmt|; comment|/** Can create any account on the server. */ DECL|field|CREATE_ACCOUNT specifier|public specifier|static specifier|final name|String name|CREATE_ACCOUNT init|= literal|"createAccount" decl_stmt|; comment|/** Can create any group on the server. */ DECL|field|CREATE_GROUP specifier|public specifier|static specifier|final name|String name|CREATE_GROUP init|= literal|"createGroup" decl_stmt|; comment|/** Can create any project on the server. */ DECL|field|CREATE_PROJECT specifier|public specifier|static specifier|final name|String name|CREATE_PROJECT init|= literal|"createProject" decl_stmt|; comment|/** * Denotes who may email change reviewers and watchers. * *<p>This can be used to deny build bots from emailing reviewers and people who watch the change. * Instead, only the authors of the change and those who starred it will be emailed. The allow * rules are evaluated before deny rules, however the default is to allow emailing, if no explicit * rule is matched. */ DECL|field|EMAIL_REVIEWERS specifier|public specifier|static specifier|final name|String name|EMAIL_REVIEWERS init|= literal|"emailReviewers" decl_stmt|; comment|/** Can flush any cache except the active web_sessions cache. */ DECL|field|FLUSH_CACHES specifier|public specifier|static specifier|final name|String name|FLUSH_CACHES init|= literal|"flushCaches" decl_stmt|; comment|/** Can terminate any task using the kill command. */ DECL|field|KILL_TASK specifier|public specifier|static specifier|final name|String name|KILL_TASK init|= literal|"killTask" decl_stmt|; comment|/** * Can perform limited server maintenance. * *<p>Includes tasks such as reindexing changes and flushing caches that may need to be performed * regularly. Does<strong>not</strong> grant arbitrary read/write/ACL management permissions as * does {@link #ADMINISTRATE_SERVER}. */ DECL|field|MAINTAIN_SERVER specifier|public specifier|static specifier|final name|String name|MAINTAIN_SERVER init|= literal|"maintainServer" decl_stmt|; comment|/** Can modify any account on the server. */ DECL|field|MODIFY_ACCOUNT specifier|public specifier|static specifier|final name|String name|MODIFY_ACCOUNT init|= literal|"modifyAccount" decl_stmt|; comment|/** Queue a user can access to submit their tasks to. */ DECL|field|PRIORITY specifier|public specifier|static specifier|final name|String name|PRIORITY init|= literal|"priority" decl_stmt|; comment|/** Maximum result limit per executed query. */ DECL|field|QUERY_LIMIT specifier|public specifier|static specifier|final name|String name|QUERY_LIMIT init|= literal|"queryLimit" decl_stmt|; comment|/** Default result limit per executed query. */ DECL|field|DEFAULT_MAX_QUERY_LIMIT specifier|public specifier|static specifier|final name|int name|DEFAULT_MAX_QUERY_LIMIT init|= literal|500 decl_stmt|; comment|/** Can impersonate any user to see which refs they can read. */ DECL|field|READ_AS specifier|public specifier|static specifier|final name|String name|READ_AS init|= literal|"readAs" decl_stmt|; comment|/** Ability to impersonate another user. */ DECL|field|RUN_AS specifier|public specifier|static specifier|final name|String name|RUN_AS init|= literal|"runAs" decl_stmt|; comment|/** Can run the Git garbage collection. */ DECL|field|RUN_GC specifier|public specifier|static specifier|final name|String name|RUN_GC init|= literal|"runGC" decl_stmt|; comment|/** Can perform streaming of Gerrit events. */ DECL|field|STREAM_EVENTS specifier|public specifier|static specifier|final name|String name|STREAM_EVENTS init|= literal|"streamEvents" decl_stmt|; comment|/** Can view all accounts, regardless of {@code accounts.visibility}. */ DECL|field|VIEW_ALL_ACCOUNTS specifier|public specifier|static specifier|final name|String name|VIEW_ALL_ACCOUNTS init|= literal|"viewAllAccounts" decl_stmt|; comment|/** Can view the server's current cache states. */ DECL|field|VIEW_CACHES specifier|public specifier|static specifier|final name|String name|VIEW_CACHES init|= literal|"viewCaches" decl_stmt|; comment|/** Can view open connections to the server's SSH port. */ DECL|field|VIEW_CONNECTIONS specifier|public specifier|static specifier|final name|String name|VIEW_CONNECTIONS init|= literal|"viewConnections" decl_stmt|; comment|/** Can view all installed plugins. */ DECL|field|VIEW_PLUGINS specifier|public specifier|static specifier|final name|String name|VIEW_PLUGINS init|= literal|"viewPlugins" decl_stmt|; comment|/** Can view all pending tasks in the queue (not just the filtered set). */ DECL|field|VIEW_QUEUE specifier|public specifier|static specifier|final name|String name|VIEW_QUEUE init|= literal|"viewQueue" decl_stmt|; comment|/** Can query permissions for any (project, user) pair */ DECL|field|VIEW_ACCESS specifier|public specifier|static specifier|final name|String name|VIEW_ACCESS init|= literal|"viewAccess" decl_stmt|; DECL|field|NAMES_ALL specifier|private specifier|static specifier|final name|List argument_list|< name|String argument_list|> name|NAMES_ALL decl_stmt|; DECL|field|NAMES_LC specifier|private specifier|static specifier|final name|List argument_list|< name|String argument_list|> name|NAMES_LC decl_stmt|; DECL|field|RANGE_NAMES specifier|private specifier|static specifier|final name|String index|[] name|RANGE_NAMES init|= block|{ name|QUERY_LIMIT block|, name|BATCH_CHANGES_LIMIT block|, } decl_stmt|; static|static block|{ name|NAMES_ALL operator|= operator|new name|ArrayList argument_list|<> argument_list|() expr_stmt|; name|NAMES_ALL operator|. name|add argument_list|( name|ACCESS_DATABASE argument_list|) expr_stmt|; name|NAMES_ALL operator|. name|add argument_list|( name|ADMINISTRATE_SERVER argument_list|) expr_stmt|; name|NAMES_ALL operator|. name|add argument_list|( name|BATCH_CHANGES_LIMIT argument_list|) expr_stmt|; name|NAMES_ALL operator|. name|add argument_list|( name|CREATE_ACCOUNT argument_list|) expr_stmt|; name|NAMES_ALL operator|. name|add argument_list|( name|CREATE_GROUP argument_list|) expr_stmt|; name|NAMES_ALL operator|. name|add argument_list|( name|CREATE_PROJECT argument_list|) expr_stmt|; name|NAMES_ALL operator|. name|add argument_list|( name|EMAIL_REVIEWERS argument_list|) expr_stmt|; name|NAMES_ALL operator|. name|add argument_list|( name|FLUSH_CACHES argument_list|) expr_stmt|; name|NAMES_ALL operator|. name|add argument_list|( name|KILL_TASK argument_list|) expr_stmt|; name|NAMES_ALL operator|. name|add argument_list|( name|MAINTAIN_SERVER argument_list|) expr_stmt|; name|NAMES_ALL operator|. name|add argument_list|( name|MODIFY_ACCOUNT argument_list|) expr_stmt|; name|NAMES_ALL operator|. name|add argument_list|( name|PRIORITY argument_list|) expr_stmt|; name|NAMES_ALL operator|. name|add argument_list|( name|QUERY_LIMIT argument_list|) expr_stmt|; name|NAMES_ALL operator|. name|add argument_list|( name|READ_AS argument_list|) expr_stmt|; name|NAMES_ALL operator|. name|add argument_list|( name|RUN_AS argument_list|) expr_stmt|; name|NAMES_ALL operator|. name|add argument_list|( name|RUN_GC argument_list|) expr_stmt|; name|NAMES_ALL operator|. name|add argument_list|( name|STREAM_EVENTS argument_list|) expr_stmt|; name|NAMES_ALL operator|. name|add argument_list|( name|VIEW_ALL_ACCOUNTS argument_list|) expr_stmt|; name|NAMES_ALL operator|. name|add argument_list|( name|VIEW_CACHES argument_list|) expr_stmt|; name|NAMES_ALL operator|. name|add argument_list|( name|VIEW_CONNECTIONS argument_list|) expr_stmt|; name|NAMES_ALL operator|. name|add argument_list|( name|VIEW_PLUGINS argument_list|) expr_stmt|; name|NAMES_ALL operator|. name|add argument_list|( name|VIEW_QUEUE argument_list|) expr_stmt|; name|NAMES_ALL operator|. name|add argument_list|( name|VIEW_ACCESS argument_list|) expr_stmt|; name|NAMES_LC operator|= operator|new name|ArrayList argument_list|<> argument_list|( name|NAMES_ALL operator|. name|size argument_list|() argument_list|) expr_stmt|; for|for control|( name|String name|name range|: name|NAMES_ALL control|) block|{ name|NAMES_LC operator|. name|add argument_list|( name|name operator|. name|toLowerCase argument_list|() argument_list|) expr_stmt|; block|} block|} comment|/** @return all valid capability names. */ DECL|method|getAllNames () specifier|public specifier|static name|Collection argument_list|< name|String argument_list|> name|getAllNames parameter_list|() block|{ return|return name|Collections operator|. name|unmodifiableList argument_list|( name|NAMES_ALL argument_list|) return|; block|} comment|/** @return true if the name is recognized as a capability name. */ DECL|method|isGlobalCapability (String varName) specifier|public specifier|static name|boolean name|isGlobalCapability parameter_list|( name|String name|varName parameter_list|) block|{ return|return name|NAMES_LC operator|. name|contains argument_list|( name|varName operator|. name|toLowerCase argument_list|() argument_list|) return|; block|} comment|/** @return true if the capability should have a range attached. */ DECL|method|hasRange (String varName) specifier|public specifier|static name|boolean name|hasRange parameter_list|( name|String name|varName parameter_list|) block|{ for|for control|( name|String name|n range|: name|RANGE_NAMES control|) block|{ if|if condition|( name|n operator|. name|equalsIgnoreCase argument_list|( name|varName argument_list|) condition|) block|{ return|return literal|true return|; block|} block|} return|return literal|false return|; block|} DECL|method|getRangeNames () specifier|public specifier|static name|List argument_list|< name|String argument_list|> name|getRangeNames parameter_list|() block|{ return|return name|Collections operator|. name|unmodifiableList argument_list|( name|Arrays operator|. name|asList argument_list|( name|RANGE_NAMES argument_list|) argument_list|) return|; block|} comment|/** @return the valid range for the capability if it has one, otherwise null. */ DECL|method|getRange (String varName) specifier|public specifier|static name|PermissionRange operator|. name|WithDefaults name|getRange parameter_list|( name|String name|varName parameter_list|) block|{ if|if condition|( name|QUERY_LIMIT operator|. name|equalsIgnoreCase argument_list|( name|varName argument_list|) condition|) block|{ return|return operator|new name|PermissionRange operator|. name|WithDefaults argument_list|( name|varName argument_list|, literal|0 argument_list|, name|Integer operator|. name|MAX_VALUE argument_list|, literal|0 argument_list|, name|DEFAULT_MAX_QUERY_LIMIT argument_list|) return|; block|} if|if condition|( name|BATCH_CHANGES_LIMIT operator|. name|equalsIgnoreCase argument_list|( name|varName argument_list|) condition|) block|{ return|return operator|new name|PermissionRange operator|. name|WithDefaults argument_list|( name|varName argument_list|, literal|0 argument_list|, name|Integer operator|. name|MAX_VALUE argument_list|, literal|0 argument_list|, name|DEFAULT_MAX_BATCH_CHANGES_LIMIT argument_list|) return|; block|} return|return literal|null return|; block|} DECL|method|GlobalCapability () specifier|private name|GlobalCapability parameter_list|() block|{ comment|// Utility class, do not create instances. block|} block|} end_class end_unit
true
2dfdb91f2dbbc164648f97bfe9f76cc5b55df0ac
Java
dzonekl/netxstudio
/screens/com.netxforge.netxflows.screens/src/com/netxforge/netxstudio/callflow/screens/internal/CallFlowsActivator.java
UTF-8
2,377
1.734375
2
[]
no_license
/******************************************************************************* * Copyright (c) 5 jul. 2013 NetXForge. * * 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/> * * Contributors: Christophe Bouhier - initial API and implementation and/or * initial documentation *******************************************************************************/ package com.netxforge.netxstudio.callflow.screens.internal; import static org.ops4j.peaberry.Peaberry.osgiModule; import org.eclipse.ui.plugin.AbstractUIPlugin; import org.osgi.framework.BundleContext; import com.google.inject.Guice; import com.google.inject.Injector; import com.google.inject.Module; /** * The activator class controls the plug-in life cycle */ public class CallFlowsActivator extends AbstractUIPlugin { // The plug-in ID public static final String PLUGIN_ID = "com.netxforge.client.callflow.screens"; //$NON-NLS-1$ // The shared instance private static CallFlowsActivator plugin; private Injector callFlowsInjector; /* * (non-Javadoc) * * @see * org.eclipse.ui.plugin.AbstractUIPlugin#start(org.osgi.framework.BundleContext * ) */ public void start(BundleContext context) throws Exception { super.start(context); plugin = this; Module om = new CallFlowModule(); callFlowsInjector = Guice.createInjector(osgiModule(context),om); } /* * (non-Javadoc) * * @see * org.eclipse.ui.plugin.AbstractUIPlugin#stop(org.osgi.framework.BundleContext * ) */ public void stop(BundleContext context) throws Exception { plugin = null; super.stop(context); } /** * Returns the shared instance * * @return the shared instance */ public static CallFlowsActivator getDefault() { return plugin; } public Injector getInjector() { return callFlowsInjector; } }
true
a1de188fee1ded35685954fd8dc144d55135b4e8
Java
alexjavyer/proyectoFinal
/farmaciaSistema/src/interfaces/pedidos.java
UTF-8
31,764
2.015625
2
[]
no_license
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package interfaces; import java.awt.Image; import java.io.File; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.text.SimpleDateFormat; import javax.swing.ImageIcon; import javax.swing.JOptionPane; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; import javax.swing.table.DefaultTableModel; /** * * @author javy */ public class pedidos extends javax.swing.JInternalFrame { DefaultTableModel model; /** * Creates new form clientes */ public pedidos() { initComponents(); getContentPane().setBackground(new java.awt.Color(10,120,200)); setTitle("P E D I D O S"); if(ingresoAlSistema.usuarios=="BODEGUERO"){ jbtActualizar.setEnabled(false); jbtBorrar.setEnabled(false); jbtCancelar.setEnabled(false); jbtGuardar.setEnabled(false); jbtNuevo.setEnabled(true); jbtSalir.setEnabled(true); }else{ botonesIniciales(); } jtbPedidos.getSelectionModel().addListSelectionListener(new ListSelectionListener() { @Override public void valueChanged(ListSelectionEvent lse) { if(jtbPedidos.getSelectedRow()!=-1){ int fila = jtbPedidos.getSelectedRow(); desbloquear(); txtNumero.setText(jtbPedidos.getValueAt(fila, 0).toString()); date.setDateFormatString(jtbPedidos.getValueAt(fila, 1).toString()); txtTotal.setText(jtbPedidos.getValueAt(fila, 2).toString()); txtBodeguero.setText(jtbPedidos.getValueAt(fila, 3).toString()); txtVisitador.setText(jtbPedidos.getValueAt(fila, 4).toString()); if(ingresoAlSistema.usuarios=="BODEGUERO"){ jbtActualizar.setEnabled(true); jbtBorrar.setEnabled(false); jbtCancelar.setEnabled(true); }else{ jbtActualizar.setEnabled(true); jbtBorrar.setEnabled(true); jbtCancelar.setEnabled(true); } } } } ); cargarPedidos(""); CargarBodeguero(); CargarVisitador(); //botonesIniciales(); bloquear(); limpiar(); } public void botonesIniciales(){ jbtNuevo.setEnabled(true); jbtBorrar.setEnabled(false); jbtActualizar.setEnabled(false); jbtCancelar.setEnabled(false); jbtGuardar.setEnabled(false); jbtSalir.setEnabled(true); jcbBodegueros.setEnabled(false); jcmVisitador.setEnabled(false); } public void limpiar(){ txtNumero.setText(""); txtTotal.setText(""); date.setDate(null); txtBodeguero.setText(""); txtVisitador.setText(""); } public void desbloquear(){ txtNumero.setEnabled(true); date.setEnabled(true); txtBodeguero.setEnabled(true); txtVisitador.setEnabled(true); txtBusqueda.setEnabled(true); jcbBodegueros.setEnabled(true); jcmVisitador.setEnabled(true); } public void bloquear(){ txtNumero.setEnabled(false); date.setEnabled(false); txtBodeguero.setEnabled(false); txtVisitador.setEnabled(false); jcbBodegueros.setEnabled(false); jcmVisitador.setEnabled(false); } public void Nuevo(){ desbloquear(); jbtGuardar.setEnabled(true); jbtCancelar.setEnabled(true); limpiar(); } public void CargarBodeguero() { try { conexion cc = new conexion(); Connection cn = cc.conectar(); String sql = ""; sql = "SELECT * FROM BODEGUEROS ORDER BY CI_BOD"; Statement psd = cn.createStatement(); ResultSet rs = psd.executeQuery(sql); while (rs.next()) { jcbBodegueros.addItem(rs.getString("CI_BOD")); } } catch (Exception ex) { JOptionPane.showMessageDialog(null, ex); } } public void CargarVisitador() { try { conexion cc = new conexion(); Connection cn = cc.conectar(); String sql = ""; sql = "SELECT * FROM VISITADORES_MEDICOS ORDER BY CI_VIS"; Statement psd = cn.createStatement(); ResultSet rs = psd.executeQuery(sql); while (rs.next()) { jcmVisitador.addItem(rs.getString("CI_VIS")); } } catch (Exception ex) { JOptionPane.showMessageDialog(null, ex); } } public void cargarPedidos(String dato){ conexion cc = new conexion(); Connection cn = cc.conectar(); String titulo[] = {"NÚMERO","FECHA","TOTAL","CÉDULA BODEGUERO","CÉDULA VISITADOR"}; model = new DefaultTableModel(null,titulo); String registros [] = new String[5]; String sql; sql = "select * from pedidos where NUM_PED like '%"+dato+"%'"; try{ Statement psd = cn.createStatement(); ResultSet rs = psd.executeQuery(sql); while(rs.next()){ registros[0]=rs.getString("NUM_PED"); registros[1]=rs.getString("FEC_HOR_PED"); registros[2]=rs.getString("TOTAL_PED"); registros[3]=rs.getString("CI_BOD_PER"); registros[4]=rs.getString("CI_VIS_PER"); model.addRow(registros); } jtbPedidos.setModel(model); }catch(Exception ex){ JOptionPane.showMessageDialog(null, ex); } } public void Guardar(){ try { conexion cc = new conexion(); Connection cn = cc.conectar(); String sql=""; String fecha=new SimpleDateFormat("dd/MM/yyyy").format(date.getDate()); sql="insert into pedidos (NUM_PED,FEC_HOR_PED,TOTAL_PED,CI_BOD_PER,CI_VIS_PER) values (?,TO_DATE('"+fecha+"','DD/MM/YYYY'),?,?,?)"; PreparedStatement psd = cn.prepareStatement(sql); psd.setString(1, txtNumero.getText()); psd.setInt(2, 0); psd.setString(3, txtBodeguero.getText()); psd.setString(4, txtVisitador.getText()); int n=psd.executeUpdate(); if(n>0){ JOptionPane.showMessageDialog(null, "Se inserto correctamente"); limpiar(); botonesIniciales(); bloquear(); cargarPedidos(""); } } catch (SQLException ex) { JOptionPane.showMessageDialog(null, ex); } } public void Cancelar(){ botonesIniciales(); limpiar(); bloquear(); } public void Actualizar(){ conexion cc = new conexion(); Connection cn = cc.conectar(); String sql=""; sql="UPDATE PEDIDOS SET FEC_HOR_PED='"+date.getDate()+"',TOTAL_PED = '"+txtTotal.getText()+"',CI_BOD_PER='"+txtBodeguero.getText()+"',CI_VIS_PER='"+txtVisitador.getText()+"' WHERE NUM_PED='"+txtNumero.getText()+"'"; try{ PreparedStatement psd = cn.prepareStatement(sql); if(psd.executeUpdate()>0){ JOptionPane.showMessageDialog(null,"Se actualizó correctamente"); cargarPedidos(""); botonesIniciales(); limpiar(); bloquear(); } }catch(Exception ex ){ JOptionPane.showMessageDialog(null, ex); } } public void Borrar(){ if(JOptionPane.showConfirmDialog(null, "DESEA ELIMINAR", "ELIMINAR", JOptionPane.YES_NO_OPTION,JOptionPane.WARNING_MESSAGE)==JOptionPane.YES_OPTION){ conexion cc = new conexion(); Connection cn = cc.conectar(); String sql=""; sql="DELETE FROM pedidos WHERE NUM_PED = '"+txtNumero.getText()+"'"; try{ PreparedStatement psd = cn.prepareStatement(sql); if(psd.executeUpdate()>0){ JOptionPane.showMessageDialog(null,"Se eliminó correctamente"); cargarPedidos(""); botonesIniciales(); limpiar(); bloquear(); } }catch(Exception ex){ JOptionPane.showMessageDialog(null, ex); } } } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jpnBotones = new javax.swing.JPanel(); jbtNuevo = new javax.swing.JButton(); jbtGuardar = new javax.swing.JButton(); jbtCancelar = new javax.swing.JButton(); jbtActualizar = new javax.swing.JButton(); jbtBorrar = new javax.swing.JButton(); jbtSalir = new javax.swing.JButton(); jbtDetalles = new javax.swing.JButton(); jpnBusqueda = new javax.swing.JPanel(); jLabel6 = new javax.swing.JLabel(); txtBusqueda = new javax.swing.JTextField(); jScrollPane1 = new javax.swing.JScrollPane(); jtbPedidos = new javax.swing.JTable(); jpnDatos = new javax.swing.JPanel(); txtNumero = new javax.swing.JTextField(); txtTotal = new javax.swing.JTextField(); txtBodeguero = new javax.swing.JTextField(); txtVisitador = new javax.swing.JTextField(); jLabel1 = new javax.swing.JLabel(); jLabel2 = new javax.swing.JLabel(); jLabel3 = new javax.swing.JLabel(); jLabel4 = new javax.swing.JLabel(); jLabel5 = new javax.swing.JLabel(); date = new com.toedter.calendar.JDateChooser(); jcbBodegueros = new javax.swing.JComboBox(); jcmVisitador = new javax.swing.JComboBox(); jLabel7 = new javax.swing.JLabel(); setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); setTitle("PEDIDOS"); addPropertyChangeListener(new java.beans.PropertyChangeListener() { public void propertyChange(java.beans.PropertyChangeEvent evt) { formPropertyChange(evt); } }); jpnBotones.setBackground(new java.awt.Color(10, 120, 200)); jpnBotones.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED)); jbtNuevo.setText("NUEVO"); jbtNuevo.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jbtNuevoActionPerformed(evt); } }); jbtGuardar.setText("GUARDAR"); jbtGuardar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jbtGuardarActionPerformed(evt); } }); jbtCancelar.setText("CANCELAR"); jbtCancelar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jbtCancelarActionPerformed(evt); } }); jbtActualizar.setText("ACTUALIZAR"); jbtActualizar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jbtActualizarActionPerformed(evt); } }); jbtBorrar.setText("BORRAR"); jbtBorrar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jbtBorrarActionPerformed(evt); } }); jbtSalir.setText("SALIR"); jbtSalir.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jbtSalirActionPerformed(evt); } }); jbtDetalles.setText("DETALLES"); jbtDetalles.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jbtDetallesActionPerformed(evt); } }); javax.swing.GroupLayout jpnBotonesLayout = new javax.swing.GroupLayout(jpnBotones); jpnBotones.setLayout(jpnBotonesLayout); jpnBotonesLayout.setHorizontalGroup( jpnBotonesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jpnBotonesLayout.createSequentialGroup() .addGap(36, 36, 36) .addGroup(jpnBotonesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(jbtActualizar, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jbtCancelar, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jbtGuardar, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jbtNuevo, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jbtBorrar, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jbtDetalles, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jbtSalir, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); jpnBotonesLayout.setVerticalGroup( jpnBotonesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jpnBotonesLayout.createSequentialGroup() .addContainerGap() .addComponent(jbtNuevo) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jbtGuardar) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jbtCancelar) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jbtActualizar) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jbtBorrar) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jbtDetalles) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jbtSalir) .addContainerGap(37, Short.MAX_VALUE)) ); jpnBusqueda.setBackground(new java.awt.Color(10, 120, 200)); jpnBusqueda.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED)); jLabel6.setText("Busqueda"); javax.swing.GroupLayout jpnBusquedaLayout = new javax.swing.GroupLayout(jpnBusqueda); jpnBusqueda.setLayout(jpnBusquedaLayout); jpnBusquedaLayout.setHorizontalGroup( jpnBusquedaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jpnBusquedaLayout.createSequentialGroup() .addContainerGap() .addComponent(jLabel6) .addGap(48, 48, 48) .addComponent(txtBusqueda) .addContainerGap()) ); jpnBusquedaLayout.setVerticalGroup( jpnBusquedaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jpnBusquedaLayout.createSequentialGroup() .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(jpnBusquedaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel6) .addComponent(txtBusqueda, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addContainerGap()) ); jtbPedidos.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { {}, {}, {}, {} }, new String [] { } )); jScrollPane1.setViewportView(jtbPedidos); jpnDatos.setBackground(new java.awt.Color(10, 120, 200)); jpnDatos.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED)); txtTotal.setEnabled(false); jLabel1.setText("Número"); jLabel2.setText("Fecha"); jLabel3.setText("Total"); jLabel4.setText("Cédula del Bodeguero"); jLabel5.setText("Cédula del Visitador"); jcbBodegueros.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jcbBodeguerosActionPerformed(evt); } }); jcmVisitador.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jcmVisitadorActionPerformed(evt); } }); javax.swing.GroupLayout jpnDatosLayout = new javax.swing.GroupLayout(jpnDatos); jpnDatos.setLayout(jpnDatosLayout); jpnDatosLayout.setHorizontalGroup( jpnDatosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jpnDatosLayout.createSequentialGroup() .addContainerGap() .addGroup(jpnDatosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel1) .addComponent(jLabel2) .addComponent(jLabel3) .addComponent(jLabel4) .addComponent(jLabel5)) .addGap(32, 32, 32) .addGroup(jpnDatosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jpnDatosLayout.createSequentialGroup() .addComponent(txtBodeguero, javax.swing.GroupLayout.PREFERRED_SIZE, 219, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jcbBodegueros, javax.swing.GroupLayout.PREFERRED_SIZE, 118, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(jpnDatosLayout.createSequentialGroup() .addComponent(txtVisitador, javax.swing.GroupLayout.PREFERRED_SIZE, 219, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jcmVisitador, javax.swing.GroupLayout.PREFERRED_SIZE, 118, javax.swing.GroupLayout.PREFERRED_SIZE)) .addComponent(txtTotal, javax.swing.GroupLayout.PREFERRED_SIZE, 219, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(date, javax.swing.GroupLayout.PREFERRED_SIZE, 219, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(txtNumero, javax.swing.GroupLayout.PREFERRED_SIZE, 219, javax.swing.GroupLayout.PREFERRED_SIZE)) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); jpnDatosLayout.setVerticalGroup( jpnDatosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jpnDatosLayout.createSequentialGroup() .addGap(34, 34, 34) .addGroup(jpnDatosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addGroup(jpnDatosLayout.createSequentialGroup() .addGroup(jpnDatosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addGroup(jpnDatosLayout.createSequentialGroup() .addGroup(jpnDatosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(txtNumero, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel1)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(date, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addComponent(jLabel2)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(txtTotal, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addComponent(jLabel3)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(jpnDatosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(txtBodeguero, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel4) .addComponent(jcbBodegueros, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(14, 14, 14) .addGroup(jpnDatosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel5) .addComponent(txtVisitador, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jcmVisitador, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addContainerGap(64, Short.MAX_VALUE)) ); jLabel7.setFont(new java.awt.Font("Tahoma", 3, 24)); // NOI18N jLabel7.setForeground(new java.awt.Color(255, 255, 255)); jLabel7.setText("P E D I D O S"); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(jpnDatos, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(52, 52, 52) .addComponent(jpnBotones, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false) .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 689, Short.MAX_VALUE) .addComponent(jpnBusqueda, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))) .addContainerGap(40, Short.MAX_VALUE)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jLabel7, javax.swing.GroupLayout.PREFERRED_SIZE, 180, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(266, 266, 266)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(jLabel7) .addGap(9, 9, 9) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(jpnDatos, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jpnBotones, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jpnBusqueda, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 306, Short.MAX_VALUE) .addContainerGap()) ); pack(); }// </editor-fold>//GEN-END:initComponents private void jbtNuevoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtNuevoActionPerformed // TODO add your handling code here: Nuevo(); }//GEN-LAST:event_jbtNuevoActionPerformed private void jbtGuardarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtGuardarActionPerformed // TODO add your handling code here: Guardar(); }//GEN-LAST:event_jbtGuardarActionPerformed private void jbtCancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtCancelarActionPerformed // TODO add your handling code here: Cancelar(); }//GEN-LAST:event_jbtCancelarActionPerformed private void jbtActualizarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtActualizarActionPerformed // TODO add your handling code here: Actualizar(); }//GEN-LAST:event_jbtActualizarActionPerformed private void jbtBorrarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtBorrarActionPerformed // TODO add your handling code here: Borrar(); }//GEN-LAST:event_jbtBorrarActionPerformed private void jbtSalirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtSalirActionPerformed // TODO add your handling code here: this.dispose(); }//GEN-LAST:event_jbtSalirActionPerformed private void jbtDetallesActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtDetallesActionPerformed // TODO add your handling code here: detalles_pedidos pe=new detalles_pedidos(); menu1.jDesktopPane1.add(pe); pe.setVisible(true); pe.show(); }//GEN-LAST:event_jbtDetallesActionPerformed private void formPropertyChange(java.beans.PropertyChangeEvent evt) {//GEN-FIRST:event_formPropertyChange // TODO add your handling code here: }//GEN-LAST:event_formPropertyChange private void jcbBodeguerosActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jcbBodeguerosActionPerformed // TODO add your handling code here: txtBodeguero.setText(jcbBodegueros.getSelectedItem().toString()); }//GEN-LAST:event_jcbBodeguerosActionPerformed private void jcmVisitadorActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jcmVisitadorActionPerformed // TODO add your handling code here: txtVisitador.setText(jcmVisitador.getSelectedItem().toString()); }//GEN-LAST:event_jcmVisitadorActionPerformed /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(pedidos.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(pedidos.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(pedidos.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(pedidos.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new pedidos().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private com.toedter.calendar.JDateChooser date; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JLabel jLabel5; private javax.swing.JLabel jLabel6; private javax.swing.JLabel jLabel7; private javax.swing.JScrollPane jScrollPane1; public javax.swing.JButton jbtActualizar; public javax.swing.JButton jbtBorrar; public javax.swing.JButton jbtCancelar; public javax.swing.JButton jbtDetalles; public javax.swing.JButton jbtGuardar; public javax.swing.JButton jbtNuevo; public javax.swing.JButton jbtSalir; private javax.swing.JComboBox jcbBodegueros; private javax.swing.JComboBox jcmVisitador; private javax.swing.JPanel jpnBotones; private javax.swing.JPanel jpnBusqueda; private javax.swing.JPanel jpnDatos; private javax.swing.JTable jtbPedidos; private javax.swing.JTextField txtBodeguero; private javax.swing.JTextField txtBusqueda; private javax.swing.JTextField txtNumero; private javax.swing.JTextField txtTotal; private javax.swing.JTextField txtVisitador; // End of variables declaration//GEN-END:variables }
true
0f015d95932f0f0218c97e60ef9fb6a86fe9774d
Java
popasmuerf/jcode_lab
/src/main/java/java_core/enumeration/EnumDriver.java
UTF-8
950
4.0625
4
[]
no_license
package java_core.enumeration; import static java.lang.System.out; /** * Created by mdb on 4/15/18. */ enum Day{ SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY } public class EnumDriver { Day day ; public EnumDriver(Day day){ this.day = day ; } public void tellItLikeItIs(){ switch(day){ case MONDAY: out.println("Mondays are bad."); break ; case FRIDAY: System.out.println("Fridays are better."); break; case SATURDAY: case SUNDAY: System.out.println("Weekends are best."); break; default: System.out.println("Midweek days are so-so."); break; } } public static void main(String[] args){ EnumDriver firstDay = new EnumDriver(Day.MONDAY); firstDay.tellItLikeItIs(); } }
true
ec45cede5d050dfa5569fbdce6b5de771a606eb6
Java
florinvasilie/Spring-rest
/src/main/java/com/endava/internship/rest/repository/RankUserRepository.java
UTF-8
1,502
2.625
3
[]
no_license
package com.endava.internship.rest.repository; import com.endava.internship.rest.model.RankUser; import com.endava.internship.rest.model.User; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; import javax.annotation.PostConstruct; import java.util.ArrayList; import java.util.List; /** * Created by fvasile on 7/15/2016. */ @Repository public class RankUserRepository { @Autowired private UserRepository userRepository; private List<RankUser> rankUsers = new ArrayList<>(); public List<RankUser> list(){ return this.rankUsers; } public void saveRankUser(RankUser rankUser){ rankUsers.add(rankUser); } public RankUser getRankUser(Integer id){ for (RankUser user : list()){ if(id==user.getId()) return user; } return null; } @PostConstruct public void init(){ User user1=new User(1,"Florin"); User user2=new User(2,"Paul"); List<User> users=userRepository.list(); users.add(user1); users.add(user2); List<User> users1=new ArrayList<>(); User user3=new User(1,"Florin"); User user4=new User(2,"Paul"); users1.add(user3); users1.add(user4); RankUser rankUser1=new RankUser(users,1,"admin"); List<User> rank=rankUser1.getUsers(); for(User user:rank) { System.out.println(user.getUsername()+user.getId()); } } }
true
fd5606e15038dace7770b50f10c166d2c2dccea4
Java
Abdulmoeezz/MOSQUE
/app/src/main/java/com/example/mymosque/AdapterRVFavorite.java
UTF-8
6,518
1.804688
2
[]
no_license
package com.example.mymosque; import android.annotation.SuppressLint; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.support.annotation.NonNull; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentTransaction; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.RelativeLayout; import android.widget.TextView; import android.widget.Toast; import com.example.mymosque.Fragments.FragementProfile; import com.example.mymosque.Fragments.FragmentFeedback; import com.example.mymosque.Fragments.FragmentNearestMasajid; import com.example.mymosque.Fragments.FragmentPrayerTimes; import com.example.mymosque.R; import com.google.android.gms.maps.model.LatLng; import com.squareup.picasso.Picasso; import java.util.ArrayList; import java.util.HashMap; import static android.content.Context.MODE_PRIVATE; import static com.google.maps.android.SphericalUtil.computeDistanceBetween; public class AdapterRVFavorite extends RecyclerView.Adapter<com.example.mymosque.AdapterRVFavorite.ViewHolder>{ ArrayList<HashMap<String, String>> modelList; private Context mContext; double CurrentLatitude,CurrentLongitude,DestinationLatitude,DestinationLongitude,rad; String Miles; private static final String TAG = "AdapterRVFavorite"; public AdapterRVFavorite(Context Context, ArrayList<HashMap<String, String>> Names) { this.mContext = Context; this.modelList = Names; } @NonNull @Override public com.example.mymosque.AdapterRVFavorite.ViewHolder onCreateViewHolder (@NonNull ViewGroup parent, int viewType){ View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.favorite_item, parent, false); return new com.example.mymosque.AdapterRVFavorite.ViewHolder(view); } @SuppressLint("DefaultLocale") @Override public void onBindViewHolder (@NonNull com.example.mymosque.AdapterRVFavorite.ViewHolder holder, final int position){ try { SharedPreferences prefs = mContext.getSharedPreferences("LatLang", Context.MODE_PRIVATE); CurrentLatitude = Double.parseDouble(prefs.getString("Lat", null)); CurrentLongitude = Double.parseDouble(prefs.getString("Lag", null)); holder.MasajidName.setText(modelList.get(position).get("name_")); String path = modelList.get(position).get("imageurl_"); holder.MasajidAddress.setText(modelList.get(position).get("address")); DestinationLongitude = Double.parseDouble(modelList.get(position).get("longitute_")); DestinationLatitude = Double.parseDouble(modelList.get(position).get("latitude_")); LatLng CurrentLOcation= new LatLng(CurrentLatitude, CurrentLongitude); LatLng DesLOcation= new LatLng(DestinationLatitude, DestinationLongitude); rad=computeDistanceBetween(CurrentLOcation,DesLOcation); Miles = String.format("%.2f",rad/1609.344); // Miles = meterDistanceBetweenPoints(CurrentLatitude, CurrentLongitude, DestinationLatitude, DestinationLongitude); holder.MasajidMiles.setText(Miles); Picasso.get().load(path).into(holder.Image, new com.squareup.picasso.Callback() { @Override public void onSuccess() { } @Override public void onError(Exception e) { Toast.makeText(mContext, "No Map Found !!", Toast.LENGTH_SHORT).show(); } }); holder.Layout.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { SharedPreferences.Editor editor = mContext.getSharedPreferences("PassFavouriteMosque", MODE_PRIVATE).edit(); editor.putString("M_ID", modelList.get(position).get("id_")); editor.putString("M_name", modelList.get(position).get("name_")); editor.putString("M_Image_", modelList.get(position).get("imageurl_")); editor.putString("M_Address_", modelList.get(position).get("address")); editor.putString("M_Longitude_", modelList.get(position).get("longitute_")); editor.putString("M_Latitude_", modelList.get(position).get("latitude_")); editor.putString("miles",Miles); editor.apply(); AppCompatActivity activity = (AppCompatActivity) v.getContext(); activity.getSupportFragmentManager().beginTransaction().replace(R.id.Screen_Area, new FavoriteProfileFragment()).commit(); } }); }catch (Exception ex){ holder.MasajidMiles.setText("Not Difined"); } }//End of On BindHolder @Override public int getItemCount () { return modelList.size(); } public class ViewHolder extends RecyclerView.ViewHolder { TextView MasajidName,MasajidAddress,MasajidMiles; ImageView Image; RelativeLayout Layout; public ViewHolder(View itemView) { super(itemView); MasajidName = itemView.findViewById(R.id.txt_Masajid); Image = itemView.findViewById(R.id.img_); Layout= itemView.findViewById(R.id.ItemView_); MasajidAddress= itemView.findViewById(R.id.txt_address_); MasajidMiles=itemView.findViewById(R.id.TextMiles); } } @SuppressLint("DefaultLocale") @org.jetbrains.annotations.NotNull private String meterDistanceBetweenPoints(double lat_a, double lng_a, double lat_b, double lng_b) { double pk = (double) (180.f/Math.PI); double a1 = lat_a / pk; double a2 = lng_a / pk; double b1 = lat_b / pk; double b2 = lng_b / pk; double t1 = Math.cos(a1) * Math.cos(a2) * Math.cos(b1) * Math.cos(b2); double t2 = Math.cos(a1) * Math.sin(a2) * Math.cos(b1) * Math.sin(b2); double t3 = Math.sin(a1) * Math.sin(b1); double tt = Math.acos(t1 + t2 + t3); return String.format("%.2f",6366000 * tt); } }
true
6824936a5ec51bef67e298c0f6f7a100f4f475ae
Java
zengshunyao/test
/src/test/java/category/thread/ch03/stack_4/extthread/P_Thread.java
UTF-8
388
2.78125
3
[ "Apache-2.0" ]
permissive
package category.thread.ch03.stack_4.extthread; import category.thread.ch03.stack_4.service.P; public class P_Thread extends Thread { private P p; public P_Thread(P p) { super(); this.p = p; } @Override public void run() { while (p.getMyStack().isFlag()) { p.pushService(); } System.out.println(Thread.currentThread().toString()+":生产者完了。。。"); } }
true
9365d0f3e3a73e15b1e7ef81141c329c7a0d0a22
Java
benyap/java-programming-tutorial
/src/sorting/IntegerArraySorter.java
UTF-8
983
3.671875
4
[ "MIT" ]
permissive
package sorting; import java.util.HashMap; public abstract class IntegerArraySorter extends Sorter<int[]>{ @Override public boolean verify(int[] original, int[] sorted) { // Check that values are in order for(int i = 0; i < sorted.length - 1; i++) { if (sorted[i] > sorted[i + 1]) return false; } // Check that each number in the original list is also contained in the sorted list HashMap<Integer, Integer> originalCount = new HashMap<Integer, Integer>(); HashMap<Integer, Integer> sortedCount = new HashMap<Integer, Integer>(); for(int i : original) { if (originalCount.containsKey(i)) originalCount.put(i, originalCount.get(i) + 1); else originalCount.put(i, 1); } for(int i : sorted) { if (sortedCount.containsKey(i)) sortedCount.put(i, sortedCount.get(i) + 1); else sortedCount.put(i, 1); } for(int k : originalCount.keySet()) { if (originalCount.get(k) != sortedCount.get(k)) return false; } return true; } }
true
e97de403a02292a2c5fd36dc8c10124f60d2c3d8
Java
pratikdimble/Executive_ERP
/src/com/erp/controller/AttendanceControllerServlet.java
UTF-8
4,579
2.34375
2
[ "MIT" ]
permissive
package com.erp.controller; import java.io.IOException; import java.io.PrintWriter; import java.util.List; import javax.servlet.RequestDispatcher; 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 javax.servlet.http.HttpSession; import com.erp.delegate.AttendanceOperationsBusinessDelegate; import com.erp.dto.AttendanceDTO; import com.erp.errors.InsertOperationProblemException; import com.erp.errors.InternalProblemException; @WebServlet("/attendance") public class AttendanceControllerServlet extends HttpServlet { public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { String pval=null; AttendanceOperationsBusinessDelegate delegate=null; List<AttendanceDTO> listattendDTOs=null; RequestDispatcher rd=null; String attenductRemovalMsg=null; String attendDate=null,empName=null,entryStatus=null,inTime=null,outTime=null; int empId=0,attendId=0; String insertResult=null; PrintWriter out=res.getWriter(); HttpSession session = req.getSession(true); //read additional req param value pval=req.getParameter("operation"); if(pval.equalsIgnoreCase("link1")){ delegate=new AttendanceOperationsBusinessDelegate(); try{ listattendDTOs=delegate.getAllAttendances(); req.setAttribute("listattendDTOs",listattendDTOs); rd=req.getRequestDispatcher("/list_attend.jsp"); rd.forward(req,res); } catch(InternalProblemException ipe){ req.setAttribute("errMsg",ipe.getMessage()); rd=req.getRequestDispatcher("/error.jsp"); rd.forward(req,res); } }//if else if(pval.equalsIgnoreCase("Details")){ delegate=new AttendanceOperationsBusinessDelegate(); try{ listattendDTOs=delegate.getAttendance(req.getParameter("choice")); req.setAttribute("listattendDTOs",listattendDTOs); rd=req.getRequestDispatcher("/list_attend.jsp"); rd.forward(req,res); } catch(InternalProblemException ipe){ req.setAttribute("errMsg",ipe.getMessage()); rd=req.getRequestDispatcher("/error.jsp"); rd.forward(req,res); } }//if /*else if(pval.equalsIgnoreCase("View")){ delegate=new AttendanceOperationsBusinessDelegate(); try{ listattendDTOs=delegate.getAttendance(req.getParameter("choice")); req.setAttribute("listattendDTOs",listattendDTOs); rd=req.getRequestDispatcher("/selectattend_emp.jsp"); rd.forward(req,res); } catch(InternalProblemException ipe){ req.setAttribute("errMsg",ipe.getMessage()); rd=req.getRequestDispatcher("/error.jsp"); rd.forward(req,res); } }//else if*/ else if(pval.equalsIgnoreCase("ADD")){ attendDate=req.getParameter("attenddate"); empName=req.getParameter("ename"); empId=Integer.parseInt(req.getParameter("eid")); entryStatus=req.getParameter("entry"); inTime=req.getParameter("intime"); outTime=req.getParameter("outtime"); //use Delegage delegate=new AttendanceOperationsBusinessDelegate(); try{ insertResult=delegate.addAttendance(attendDate, empId, empName, entryStatus, inTime, outTime); out.println("<script type=\"text/javascript\">"); out.println("alert('"+insertResult+"');"); out.println("location='hr_firstpage.jsp';"); out.println("</script>"); } catch(InsertOperationProblemException iop){ req.setAttribute("errMsg",iop.getMessage()); rd=req.getRequestDispatcher("/error.jsp"); rd.forward(req,res); } catch(InternalProblemException ipe){ req.setAttribute("errMsg",ipe.getMessage()); rd=req.getRequestDispatcher("/error.jsp"); rd.forward(req,res); } catch(Exception e){ req.setAttribute("errMsg",e.getMessage()); rd=req.getRequestDispatcher("/error.jsp"); rd.forward(req,res); } } }//doGet(-,-) public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { doGet(req, res); }//doPost(-,-) }//class
true
dcf69c4a00e23e555df5f65370f9c8c43cc8c9c7
Java
deusimarferreira/java-gof-patterns
/src/com/udemy/structures/facade/Cliente.java
UTF-8
366
3.0625
3
[]
no_license
package br.com.udemy.structures.facade; class Cliente { private short comprar; private short alugar; public void addComprar() { this.comprar++; } public void addAlugar() { this.alugar++; } public String toString() { return "[Cliente] compras: " + this.comprar + " aluguel: " + this.alugar; } }
true
fa051d674533e770d2a0cf08227c2765b7ab7d28
Java
thejenigrace/thsst-calvis
/Instructions/fxam.bsh.java
UTF-8
1,414
2.296875
2
[]
no_license
execute(registers, memory) { String st0 = registers.get("ST0"); Double result = Double.parseDouble(st0); Converter converter = new Converter(st0); st0 = converter.toDoublePrecisionHex(); // examine st0 String first = st0.charAt(0) + ""; converter = new Converter(first); first = converter.toBinaryString(); registers.x87().status().set("C1", first.charAt(0)); String top = registers.x87().status().getTop() + ""; if ( registers.x87().tag().getTag(top).equals("11") ) { // empty registers.x87().status().set("C3", '1'); registers.x87().status().set("C2", '0'); registers.x87().status().set("C0", '1'); } else if ( result.isNaN() ) { registers.x87().status().set("C3", '0'); registers.x87().status().set("C2", '0'); registers.x87().status().set("C0", '1'); } else if ( result.isInfinite() ) { registers.x87().status().set("C3", '0'); registers.x87().status().set("C2", '1'); registers.x87().status().set("C0", '1'); } else if ( result.compareTo(new Double(0.0d)) == 0 ) { registers.x87().status().set("C3", '1'); registers.x87().status().set("C2", '0'); registers.x87().status().set("C0", '0'); } else { registers.x87().status().set("C3", '0'); registers.x87().status().set("C2", '1'); registers.x87().status().set("C0", '0'); } }
true
41be3a3b665fd13063f07cd0a8a6e116431a7e86
Java
ZhouSilverBullet/GuardianApp
/app/src/main/java/com/sdxxtop/guardianapp/ui/activity/kaoqin/fragment/KQMX_AttendanceFragment.java
UTF-8
2,729
1.867188
2
[]
no_license
package com.sdxxtop.guardianapp.ui.activity.kaoqin.fragment; import com.haibin.calendarview.Calendar; import com.sdxxtop.guardianapp.R; import com.sdxxtop.guardianapp.base.BaseFragment; import com.sdxxtop.guardianapp.model.bean.KqmxMonthBean; import com.sdxxtop.guardianapp.model.bean.RequestBean; import com.sdxxtop.guardianapp.model.http.callback.IRequestCallback; import com.sdxxtop.guardianapp.model.http.net.Params; import com.sdxxtop.guardianapp.model.http.util.RxUtils; import com.sdxxtop.guardianapp.ui.activity.kaoqin.adapter.KQMX_Adapter; import com.sdxxtop.guardianapp.ui.activity.kaoqin.calendar.MyAssessCalendarView; import com.sdxxtop.guardianapp.utils.Date2Util; import java.util.List; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import butterknife.BindView; import io.reactivex.Observable; import io.reactivex.disposables.Disposable; import static com.sdxxtop.guardianapp.model.http.net.RetrofitHelper.getEnvirApi; /** * @author : lwb * Date: 2019/12/31 * Desc: */ public class KQMX_AttendanceFragment extends BaseFragment { @BindView(R.id.mcv_view) MyAssessCalendarView mcvView; @BindView(R.id.attendance_detail_recycler) RecyclerView recyclerView; private KQMX_Adapter adapter; @Override protected int getFragmentLayout() { return R.layout.fragment_kqmx; } @Override protected void initView() { recyclerView.setLayoutManager(new LinearLayoutManager(getActivity())); adapter = new KQMX_Adapter(); recyclerView.setAdapter(adapter); mcvView.setOnDataChoose(new MyAssessCalendarView.OnDataChooseListener() { @Override public void selected(List<Calendar> data) { if (data.size() > 0) { loadData(Date2Util.getCalendarDate(data.get(0)),Date2Util.getCalendarDate(data.get(data.size()-1))); } } }); } @Override protected void initData() { loadData(mcvView.currentDate, mcvView.currentDate); } private void loadData(String startTime, String endTime) { Params params = new Params(); params.put("sd", startTime); params.put("ed", endTime); Observable<RequestBean<KqmxMonthBean>> observable = getEnvirApi().kqmxDayInfo(params.getData()); Disposable disposable = RxUtils.handleDataHttp(observable, new IRequestCallback<KqmxMonthBean>() { @Override public void onSuccess(KqmxMonthBean bean) { adapter.replaceData(bean.sign_log); } @Override public void onFailure(int code, String error) { } }); } }
true
ae8572d8c2fcf616ba90e46b16dc334a9aa5a0f0
Java
hushuai86/BeautySalonManagement
/src/main/java/com/java/controller/AccountController.java
UTF-8
13,348
1.929688
2
[]
no_license
/* * $Id$ * * Copyright (c) 2001-2015 Accentrix Company Limited. All Rights Reserved. */ package com.java.controller; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.transaction.annotation.Transactional; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.multipart.MultipartFile; import com.java.pojo.Account; import com.java.pojo.FreeTime; import com.java.pojo.HairdresserInfo; import com.java.pojo.HairdressingReservation; import com.java.pojo.UserInfo; import com.java.service.FreeTimeService; import com.java.service.HairdresserInfoService; import com.java.service.HairdressingReservationService; import com.java.service.UserInfoService; import com.java.service.AccountService; import com.java.util.DefaultErrMsg; import com.java.util.MD5Password; import com.java.util.ResponseResult; @Controller @RequestMapping("/account") public class AccountController { @Autowired private AccountService accountService; @Autowired private HairdresserInfoService hairdresserInfoService; @Autowired private UserInfoService userInfoService; @Autowired private FreeTimeService freeTimeService; @Autowired private HairdressingReservationService hairdressingReservationService; private Runnable runnable; // 登录 @RequestMapping("/login") @ResponseBody public ResponseResult login(Account account, HttpServletRequest request, HttpServletResponse response) { try { Map<String, Object> map = new HashMap<String, Object>(); map.put("loginId", account.getLoginId()); String password = MD5Password.putPasswordMD5(account.getPassword()); account = accountService.selectAccount(map); if (account != null && account.getPassword() != null && account.getPassword().equals(password)) { if (account.getStatus().equals(0)) {// 用戶未激活 return ResponseResult.ok(false, DefaultErrMsg.APP_NOT_EXIST, account); } else { HttpSession session = request.getSession(); session.setAttribute("loginId", account.getLoginId()); session.setAttribute("account", account); if (account.getType() == 1) {// 会员 UserInfo userInfo = userInfoService .selectByAccountId(account.getId()); session.setAttribute("userInfo", userInfo); } else if (account.getType() == 2) {// 美发师 HairdresserInfo hairdresserInfo = hairdresserInfoService .selectByAccountId(account.getId()); session.setAttribute("hairdresserInfo", hairdresserInfo); } scheduledResertHairdresserStatus(); return ResponseResult.ok(false, DefaultErrMsg.SUCCESS,account); } } else { return ResponseResult.ok(false, DefaultErrMsg.FAILD); } } catch (Exception e) { e.printStackTrace(); return ResponseResult.ok(false, DefaultErrMsg.FAILD); } } // 定时任务 重置美发师的空闲时间 private void scheduledResertHairdresserStatus() { if (runnable == null) { //首次登陆执行一次。 resertHairdresserStatus(); runnable = new Runnable() { public void run() { resertHairdresserStatus(); } }; ScheduledExecutorService service = Executors .newSingleThreadScheduledExecutor(); Calendar todayCal = Calendar.getInstance(); todayCal.set(Calendar.DATE, todayCal.get(Calendar.DATE)); Calendar twmCal = Calendar.getInstance(); twmCal.set(Calendar.DATE, twmCal.get(Calendar.DATE) + 1); twmCal.set(Calendar.HOUR_OF_DAY, 0); twmCal.set(Calendar.MINUTE, 0); twmCal.set(Calendar.SECOND, 0); twmCal.set(Calendar.MILLISECOND, 0); //当前时间 Date today = todayCal.getTime(); //明天的零点 Date twmZero = twmCal.getTime(); //计算距离下个零点的分钟数 long delay = (twmZero.getTime() -today.getTime())/(1000*60); //从下个零点开始执行,执行间隔24小时 // 参数:1、任务体 2、首次执行的延时时间 3、任务执行间隔 4、间隔时间单位 service.scheduleAtFixedRate(runnable,delay, 24*60, TimeUnit.MINUTES); } } private void resertHairdresserStatus(){ //获取今天的 日期和 明天的日期格式化 Calendar twmCal = Calendar.getInstance(); twmCal.set(Calendar.DATE, twmCal.get(Calendar.DATE)+1); Date twmDate = twmCal.getTime(); SimpleDateFormat daydf = new SimpleDateFormat("yyyy-MM-dd"); //查找明天的订单 List<HairdressingReservation> twmReservations = hairdressingReservationService. selectAllReservationsByDay(daydf.format(twmDate)); List<String> codes = new ArrayList<String>(); //查询所有理发师的编号 List<HairdresserInfo> hfs = hairdresserInfoService.selectCharge(new HairdresserInfo()); for (HairdresserInfo hairdresserInfo : hfs) { codes.add(hairdresserInfo.getCode()); } for (String code : codes) { FreeTime freetime = new FreeTime(0,0,0,0,0,0,0,0); //如果明天没预约将理发师的对应的预约时间状态改为空闲 for(HairdressingReservation twmR: twmReservations){ if(twmR.getHairdresserInfoCode().equals(code)){ Integer hour = Integer.parseInt(twmR.getAppointmentTime().split(" ")[1].split(":")[0]); updateFreeTime(freetime,hour,1); } } if(!freetime.equals(new FreeTime(0,0,0,0,0,0,0,0))){ freetime.setHairdresserCode(code); freeTimeService.updateFreeTime(freetime); } } } private void updateFreeTime(FreeTime freeTime,Integer time,Integer status) { // 修改 FreeTime表 将对应时间设置为1 表示改时间已被预约, 0表示空闲 if (time == 8) { freeTime.setAm8(status); } if (time == 10) { freeTime.setAm10(status); } if (time == 12) { freeTime.setAm12(status); } if (time == 14) { freeTime.setPm2(status); } if (time == 16) { freeTime.setPm4(status); } if (time == 18) { freeTime.setPm6(status); } if (time == 20) { freeTime.setPm8(status); } } // 注册会员 @RequestMapping(value = "/registerUser", method = RequestMethod.POST) @ResponseBody @Transactional public ResponseResult registerUser(Account account, UserInfo userInfo) { try { Map<String, Object> map = new HashMap<String, Object>(); map.put("loginId", account.getLoginId()); // 查看账号是否注册 if (accountService.selectAccount(map) != null) { return ResponseResult.ok(false, DefaultErrMsg.HAVE_USER); } // 查看手机号是否注册 else if (userInfoService.selectByPhone(userInfo.getPhone()) != null || hairdresserInfoService .selectByPhone(userInfo.getPhone()) != null) { return ResponseResult.ok(false, DefaultErrMsg.HAVE_PHONE); } else { account.setType(1); account.setStatus(1); account.setPassword(MD5Password.putPasswordMD5(account .getPassword())); accountService.insert(account); Integer accountId = accountService.selectAccount(map).getId(); userInfo.setAccountId(accountId); userInfoService.insert(userInfo); return ResponseResult.ok(false, DefaultErrMsg.SUCCESS); } } catch (Exception e) { e.printStackTrace(); return ResponseResult.ok(false, DefaultErrMsg.FAILD); } } // 注册理发师 @RequestMapping(value = "/register", method = RequestMethod.POST) @ResponseBody @Transactional public ResponseResult register(Account account, HairdresserInfo hairdresserInfo, @RequestParam(value = "file", required = false) MultipartFile file) { try { Map<String, Object> map = new HashMap<String, Object>(); map.put("loginId", account.getLoginId()); // 查看账号是否注册 if (accountService.selectAccount(map) != null) { return ResponseResult.ok(false, DefaultErrMsg.HAVE_USER); } // 查看手机号是否注册 else if (userInfoService.selectByPhone(hairdresserInfo.getPhone()) != null || hairdresserInfoService.selectByPhone(hairdresserInfo .getPhone()) != null) { return ResponseResult.ok(false, DefaultErrMsg.HAVE_PHONE); } else { account.setType(2); account.setStatus(0); account.setPassword(MD5Password.putPasswordMD5(account .getPassword())); accountService.insert(account); account = accountService.selectAccount(map); hairdresserInfo.setAccountId(account.getId()); // 生成美发师编号 String code = hairdresserInfoService.getNextCode(); hairdresserInfo.setCode(code); SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd"); Date date = new Date(); // 理发师注册日期为当前日期 hairdresserInfo.setDateOfEntry(df.format(date).toString()); if (file != null && !file.isEmpty() && file.getSize() > 0) { hairdresserInfo.setPicUrl(file.getBytes()); } hairdresserInfoService.insert(hairdresserInfo); // 空闲时间表插入信息 FreeTime freeTime = new FreeTime(); freeTime.setHairdresserCode(code); freeTimeService.insertSelective(freeTime); return ResponseResult.ok(false, DefaultErrMsg.SUCCESS); } } catch (Exception e) { e.printStackTrace(); return ResponseResult.ok(false, DefaultErrMsg.FAILD); } } // 删除美发师信息 @RequestMapping("/deleteHairdresser") @ResponseBody public ResponseResult deleteHairdresser(Integer accountId) { try { String code = hairdresserInfoService.selectByAccountId(accountId).getCode(); hairdresserInfoService.deleteByAccountId(accountId); accountService.deleteByPrimaryKey(accountId); freeTimeService.deleteByCode(code); return ResponseResult.ok(false, DefaultErrMsg.SUCCESS); } catch (Exception e) { e.printStackTrace(); return ResponseResult.ok(false, DefaultErrMsg.FAILD); } } // 删除用户信息 @RequestMapping("/deleteUser") @ResponseBody public ResponseResult deleteUser(Integer accountId) { try { userInfoService.deleteByAccountId(accountId); accountService.deleteByPrimaryKey(accountId); return ResponseResult.ok(false, DefaultErrMsg.SUCCESS); } catch (Exception e) { e.printStackTrace(); return ResponseResult.ok(false, DefaultErrMsg.FAILD); } } // 获取当前session 账号信息 @RequestMapping("/getSessionAccount") @ResponseBody public ResponseResult getSessionAccount(HttpServletRequest request) { try { HttpSession session = request.getSession(); Account account = (Account) session.getAttribute("account"); return ResponseResult.ok(false, DefaultErrMsg.SUCCESS, account); } catch (Exception e) { e.printStackTrace(); return ResponseResult.ok(false, DefaultErrMsg.FAILD); } } // 修改用户状态 @RequestMapping("/updateInfo") @ResponseBody public ResponseResult updateInfo(Account account) { try { if (account != null) { accountService.updateByPrimaryKeySelective(account); } return ResponseResult.ok(false, DefaultErrMsg.SUCCESS); } catch (Exception e) { e.printStackTrace(); return ResponseResult.ok(false, DefaultErrMsg.FAILD); } } // 修改理发师信息 @RequestMapping("/updateInfo2") @ResponseBody public ResponseResult updateInfo2(HairdresserInfo hairdresserInfo) { try { hairdresserInfoService.updateByPrimaryKeySelective(hairdresserInfo); return ResponseResult.ok(false, DefaultErrMsg.SUCCESS); } catch (Exception e) { e.printStackTrace(); return ResponseResult.ok(false, DefaultErrMsg.FAILD); } // } // 修改密码 @RequestMapping("/updatePassword") @ResponseBody public ResponseResult updatePassword(Account account, HttpServletRequest request) { try { String password = MD5Password.putPasswordMD5(request .getParameter("oldPassword")); account.setPassword(MD5Password.putPasswordMD5(account .getPassword())); Account sessionaAccount = (Account) request.getSession() .getAttribute("account"); if (!sessionaAccount.getPassword().equals(password)) { return ResponseResult.ok(false, DefaultErrMsg.USER_PASSWORD_FAILD); } else if (password.equals(account.getPassword())) { return ResponseResult.ok(false, DefaultErrMsg.USER_CHANGE_PASSWORD_FAILD); } accountService.updateByPrimaryKeySelective(account); request.getSession().invalidate(); return ResponseResult.ok(false, DefaultErrMsg.SUCCESS); } catch (Exception e) { e.printStackTrace(); return ResponseResult.ok(false, DefaultErrMsg.FAILD); } } // 注销 // 退出 @RequestMapping(value = "/logout") @ResponseBody public boolean logout(HttpServletRequest request) { request.getSession().invalidate(); return true; } }
true
d29bcb76b21cb9d28636870f3bfde57226931003
Java
cz1996/boot-bysj
/src/main/java/com/bysj/service/SensorService.java
UTF-8
2,413
2.484375
2
[]
no_license
package com.bysj.service; import com.bysj.model.EquipmentAttribute; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.RowMapper; import org.springframework.stereotype.Service; import java.sql.ResultSet; import java.sql.SQLException; import java.util.List; /** * Created by cccz1996 on 2018/5/2 */ @Service public class SensorService { @Autowired private JdbcTemplate jdbcTemplate; public boolean insertIntoSensor(String attrName,int attrTiming, Double attrCommon,Double attrFloat,int attrEquId){ String sql = "insert into sensor (SENSOR_NAME, SENSOR_TIMING,SENSOR_COMMON," + "SENSOR_FLOAT,SENSOR_EQU_ID) values (?,?,?,?,?)"; int insert = jdbcTemplate.update(sql,new Object[]{attrName,attrTiming,attrCommon,attrFloat,attrEquId}); if(insert > 0){ return true; }else{ return false; } } public List<EquipmentAttribute> getSensorByEquId(int attrEquId){ String sql = "select * from sensor where sensor.SENSOR_EQU_ID = ?"; List<EquipmentAttribute> equipmentAttributes = jdbcTemplate.query(sql,new Object[]{attrEquId},new SensorService.MyRowMapper()); return equipmentAttributes; } public List<EquipmentAttribute> getSensorBySenId(int sensorId){ String sql = "select * from sensor where sensor.SENSOR_ID = ?"; List<EquipmentAttribute> equipmentAttributes = jdbcTemplate.query(sql,new Object[]{sensorId},new SensorService.MyRowMapper()); return equipmentAttributes; } class MyRowMapper implements RowMapper<EquipmentAttribute> { @Override public EquipmentAttribute mapRow(ResultSet rs, int num) throws SQLException { EquipmentAttribute equipmentAttribute = new EquipmentAttribute(); equipmentAttribute.setAttrId(rs.getInt("SENSOR_ID")); equipmentAttribute.setAttrName(rs.getString("SENSOR_NAME")); equipmentAttribute.setAttrTiming(rs.getInt("SENSOR_TIMING")); equipmentAttribute.setAttrCommon(rs.getDouble("SENSOR_COMMON")); equipmentAttribute.setAttrFloat(rs.getDouble("SENSOR_FLOAT")); equipmentAttribute.setSensorEquId(rs.getInt("SENSOR_EQU_ID")); return equipmentAttribute; } } }
true
487cc0606d0bf2f25e2c7e5cea5fa5c37a545582
Java
StelioBraga/Dispesas
/app/src/main/java/stelio/braga/steliobrga/MyListe/fragment/CategoriaFragment.java
UTF-8
3,438
2.21875
2
[]
no_license
package stelio.braga.steliobrga.MyListe.fragment; import android.content.Context; import android.os.AsyncTask; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Toast; import com.kishannareshpal.examescomponents.StateMode; import com.kishannareshpal.examescomponents.StateView; import java.util.List; import stelio.braga.steliobrga.MyListe.databasesCategoria.DatabaseCategoria; import stelio.braga.steliobrga.MyListe.utils.PostAdapter; import stelio.braga.steliobrga.MyListe.R; import stelio.braga.steliobrga.MyListe.entities.Categoria; public class CategoriaFragment extends Fragment { StateView stateView; RecyclerView rv_posts; Context ctx; public CategoriaFragment() { // Required empty public constructor } // @Override // public void onCreate(@Nullable Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // ctx = getActivity(); // } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { ctx = getActivity(); // Inflate the layout for this fragment View view = inflater.inflate(R.layout.fragment_categoria, container, false); stateView = view.findViewById(R.id.stateView); //vazio stateView.iconRes(R.drawable.ic_box).title("Não tem nenhuma categoria disponivel ").message("Adicione uma categoria!!"); rv_posts = view.findViewById(R.id.rv_categoria); rv_posts.setLayoutManager(new CustomLinearLayoutManager(getContext(),LinearLayoutManager.VERTICAL,false)); // set the list_item layout style to vertical. //Toast.makeText(ctx, getUsuarios(), Toast.LENGTH_SHORT).show(); getUsuarios(); return view; } // get data private final void getUsuarios(){ class Getusuarios extends AsyncTask<Void,Void, List<Categoria>> { @Override protected List<Categoria> doInBackground(Void... voids) { List<Categoria> categoriaslista = DatabaseCategoria.getmInstance(ctx) .getDatabases() .categoriaDAO() .getAll(); return categoriaslista; } @Override protected void onPostExecute(List<Categoria> categorias) { super.onPostExecute(categorias); if (categorias.isEmpty()) { stateView.stateMode(StateMode.ALTERNATE); } else { Toast.makeText(ctx, "Here", Toast.LENGTH_SHORT).show(); PostAdapter posts = new PostAdapter(categorias, ctx); stateView.stateMode(StateMode.NORMAL); rv_posts.setAdapter(posts); } } } Getusuarios user = new Getusuarios(); user.execute(); } // Layout manager for recycler view public class CustomLinearLayoutManager extends LinearLayoutManager { public CustomLinearLayoutManager(Context context, int orientation, boolean reverseLayout) { super(context, orientation, reverseLayout); } } }
true
eabe9d481350f3c8f1f7c95dc1846a6001d61d3c
Java
hezrom12/PI2-N5-2015-2
/ClienteProdutoRest/src/bean/Cliente.java
UTF-8
2,771
2.5625
3
[]
no_license
package bean; import java.io.Serializable; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.xml.bind.annotation.XmlRootElement; @XmlRootElement @Entity public class Cliente implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; public final static int MASCULINO = 1; public final static int FEMININO = 2; private String nome; private String telefone; private String email; private String cpf; private String rg; private int sexo; private String cidade; public Cliente(String nome,String email) { } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getNome() { return nome; } public void setNome(String nome) { this.nome = nome; } public String getTelefone() { return telefone; } public void setTelefone(String telefone) { this.telefone = telefone; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getCpf() { return cpf; } public void setCpf(String cpf) { this.cpf = cpf; } public String getRg() { return rg; } public void setRg(String rg) { this.rg = rg; } public int getSexo() { return sexo; } public String getSexoString() { if(sexo==1) return "Masculino"; else return "Feminino"; } public void setSexo(int sexo) { this.sexo = sexo; } public String getCidade() { return cidade; } public void setCidade(String cidade) { this.cidade = cidade; } @Override public int hashCode() { int hash = 0; hash += (id != null ? id.hashCode() : 0); return hash; } @Override public boolean equals(Object object) { // TODO: Warning - this method won't work in the case the id fields are not set if (!(object instanceof Cliente)) { return false; } Cliente other = (Cliente) object; if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) { return false; } return true; } @Override public String toString() { return "entidade.Cliente[ id=" + id + " ]"; } }
true
3500fc4bba3fc554a06be84f715a26428d608499
Java
samgorial/alljoyn-app-2
/src/main/java/com/covisint/platform/device/pi/PiBusInterface.java
UTF-8
1,088
2.046875
2
[]
no_license
package com.covisint.platform.device.pi; import org.alljoyn.bus.BusException; import org.alljoyn.bus.BusObject; import org.alljoyn.bus.annotation.BusInterface; import org.alljoyn.bus.annotation.BusMethod; import org.alljoyn.bus.annotation.BusProperty; import org.alljoyn.bus.annotation.BusSignal; @BusInterface(name = "com.covisint.platform.devices.bigassfan", announced = "true") public interface PiBusInterface extends BusObject { @BusProperty public double getSpeed() throws BusException; @BusProperty public int getState() throws BusException; @BusProperty public int getLedState() throws BusException; @BusMethod public String ping(String text) throws BusException; @BusMethod public void setTargetSpeed(double targetSpeed) throws BusException; @BusSignal public void targetSpeedReached() throws BusException; @BusMethod public void turnOnLight() throws BusException; @BusMethod public void turnOffLight() throws BusException; @BusSignal public void lightTurnedOn() throws BusException; @BusSignal public void lightTurnedOff() throws BusException; }
true
f0efe7044be37608c8d512d26932d1532ead216b
Java
sengeiou/ocp
/ocp-platform/src/main/java/com/topideal/supplychain/ocp/amway/dto/OrderLine.java
UTF-8
4,233
2.03125
2
[]
no_license
package com.topideal.supplychain.ocp.amway.dto; public class OrderLine { private String itemSku; //产品SKU编号 private String unitDp; //产品单价 private String orderingItemName; //产品名称 private String orderingItemNumber; //产品下单编号 private String isReturn; //是否可退货 private String orderQty; //申报数量 private String rsvst1; //备用字段 private String rsvst2; private String rsvst3; private String rsvdc1; private String rsvdc2; private String rsvdc3; private String masterOrderingItemNumber; //主产品编号 private String masterOrderQty; //主产品数量 private String masterOrderingItemName; //主产品名称 private String masterOrderingPrice; //主产品价格 // OCP-196,接口新增转发字段 private String mixLogisticsCode; private String mixLogisticsName; public String getItemSku() { return itemSku; } public void setItemSku(String itemSku) { this.itemSku = itemSku; } public String getUnitDp() { return unitDp; } public void setUnitDp(String unitDp) { this.unitDp = unitDp; } public String getOrderingItemName() { return orderingItemName; } public void setOrderingItemName(String orderingItemName) { this.orderingItemName = orderingItemName; } public String getOrderingItemNumber() { return orderingItemNumber; } public void setOrderingItemNumber(String orderingItemNumber) { this.orderingItemNumber = orderingItemNumber; } public String getIsReturn() { return isReturn; } public void setIsReturn(String isReturn) { this.isReturn = isReturn; } public String getOrderQty() { return orderQty; } public void setOrderQty(String orderQty) { this.orderQty = orderQty; } public String getRsvst1() { return rsvst1; } public void setRsvst1(String rsvst1) { this.rsvst1 = rsvst1; } public String getRsvst2() { return rsvst2; } public void setRsvst2(String rsvst2) { this.rsvst2 = rsvst2; } public String getRsvst3() { return rsvst3; } public void setRsvst3(String rsvst3) { this.rsvst3 = rsvst3; } public String getRsvdc1() { return rsvdc1; } public void setRsvdc1(String rsvdc1) { this.rsvdc1 = rsvdc1; } public String getRsvdc2() { return rsvdc2; } public void setRsvdc2(String rsvdc2) { this.rsvdc2 = rsvdc2; } public String getRsvdc3() { return rsvdc3; } public void setRsvdc3(String rsvdc3) { this.rsvdc3 = rsvdc3; } public String getMasterOrderingItemNumber() { return masterOrderingItemNumber; } public void setMasterOrderingItemNumber(String masterOrderingItemNumber) { this.masterOrderingItemNumber = masterOrderingItemNumber; } public String getMasterOrderQty() { return masterOrderQty; } public void setMasterOrderQty(String masterOrderQty) { this.masterOrderQty = masterOrderQty; } public String getMasterOrderingItemName() { return masterOrderingItemName; } public void setMasterOrderingItemName(String masterOrderingItemName) { this.masterOrderingItemName = masterOrderingItemName; } public String getMasterOrderingPrice() { return masterOrderingPrice; } public void setMasterOrderingPrice(String masterOrderingPrice) { this.masterOrderingPrice = masterOrderingPrice; } public String getMixLogisticsCode() { return mixLogisticsCode; } public void setMixLogisticsCode(String mixLogisticsCode) { this.mixLogisticsCode = mixLogisticsCode; } public String getMixLogisticsName() { return mixLogisticsName; } public void setMixLogisticsName(String mixLogisticsName) { this.mixLogisticsName = mixLogisticsName; } }
true
20cee785be91f3ebdb4a89b12f221871f9cd86ee
Java
cerko2/monte-bot
/montyBot/src/javabot/macro/UnitProductionManager.java
UTF-8
13,209
2.734375
3
[]
no_license
package javabot.macro; import java.awt.Point; import java.util.ArrayList; import java.util.Collections; import java.util.Random; import java.util.Vector; import javabot.AbstractManager; import javabot.JNIBWAPI; import javabot.model.Unit; import javabot.types.UnitType.UnitTypes; //Azder UPM /*TODO*/ /* * lepsie spravit navysovanie pomeru. * otestovat funciu createUnit */ public class UnitProductionManager extends AbstractManager{ private boolean testing = true; //testovacie vypisy. private boolean freeMode = false; // dokym neskonci opening som obmedzeny. private JNIBWAPI game = null; private Boss boss = null; private int minerals = 0; private int gas = 0; private ArrayList<Double> rateArmy = new ArrayList<Double>(); // sucet = 100;??? private ArrayList<Double> rateArmyActual = new ArrayList<Double>(); private ArrayList<MyArmyGap> rateArmyGap = new ArrayList<MyArmyGap>(); private ArrayList<Unit> useBuilding = new ArrayList<Unit>(); private Vector<Integer> createStack = new Vector<Integer>(); private Vector<Integer> createStackExternal = new Vector<Integer>(); private double rate = 1; private static int numArmy = 13; // velkos rozmanitosti armady. private static int maxRate = 100; private static int actFrequency = 30; //frekvecia myAct private class MyArmyGap implements Comparable<MyArmyGap>{ private double gap = 0; private int ID = -1; public MyArmyGap(double gap,int ID){ this.gap = gap; this.ID = ID; } @Override public int compareTo(MyArmyGap o) { return (int)( o.gap- gap); } } //----------------------------------------------------------------------------------------- public UnitProductionManager(Boss boss){ this.boss = boss; this.game = boss.game; sendText("Start: Unit Production"); for(int i = 0 ; i < numArmy ; i++){ rateArmy.add(0.0); } // testing /*TODO*/ rateArmy.set(0, 50.0); rateArmy.set(1, 50.0); } public void setAddResources(int minerals,int gas){ this.minerals += minerals; this.gas += gas; } public void gameUpdate(){ if((game.getFrameCount() % actFrequency == 0 ) ){ setSettings(); if(minerals > 0) myAct(); } drawDebugInfo(); } public Vector<Integer> getConstructionPlans(){ Vector<Integer> vect = new Vector<Integer>(); setCrateStack(); vect.addAll(createStackExternal); vect.addAll(createStack); return vect; } /** * Void function to switch Unit Production Manager into "Free Mode", it must be done * after Opening Manager has ended. * @param Boolean freeMode - set private variable to false(Unit Production Manager * produce units requested by Opening Manager) or true(Unit Production Manager * manage unit production by self) * */ public void setFreeMode(Boolean freeMode){ this.freeMode = freeMode; } /** * * @param typeID - ID of unit, that you want to train */ public void createUnit(int typeID){ createStackExternal.add(typeID); buildExternalStack(); } /** * * @param rateArmy * @return */ public boolean setRateArmy( ArrayList<Double> rateArmy){ //true ak to akceptujem if(this.rateArmy.size() == rateArmy.size()){ double sum = sumRate(rateArmy); if(sum != 100){ // normalizujem to na 100 double correctD = 100.0 / sum ; rateArmy = correctRate(rateArmy,correctD); } this.rateArmy = rateArmy; return true; } return false; } public ArrayList<Double> getRateArmy( ){ return rateArmy; } //----------------------------------------------------------------------------------------- private double sumRate(ArrayList<Double> rateArmy){ double sum = 0.0; for(Double d : rateArmy) sum += d; return sum; } private ArrayList<Double> correctRate(ArrayList<Double> rateArmy,double correctD){ ArrayList<Double> rate = new ArrayList<Double>(); for(Double d : rateArmy) rate.add(d * correctD); return rate; } //----------------------------------------------------------------------------------------- private void setSettings(){ if(boss != null){ this.minerals = boss.getUnitProductionMinerals(); this.gas = boss.getUnitProductionGas(); if(testing){ /*TODO*/ this.minerals = game.getSelf().getMinerals(); this.gas = game.getSelf().getGas(); } }else sendText("err: boss = null"); } private void myAct(){ useBuilding = new ArrayList<Unit>(); if(!boss.getOpeningManager().isActive()) freeMode = true; if(!freeMode){ boolean unitID = boss.getOpeningManager().nextWorker(); if(unitID){ createStackExternal.add(UnitTypes.Protoss_Probe.ordinal()); } } if(!freeMode){ int unitID = boss.getOpeningManager().nextUnit(); if(unitID >= 0) createStackExternal.add(unitID); } buildExternalStack(); if(freeMode){ // AK je modul aktivny setRateArmyActual(); setRateArmyGap(); setCrateStack(); //---------->> while (!createStack.isEmpty() && minerals > 0) { int typeID = createStack.get(0); createStack.remove(0); productionUnit(typeID); } for(int i =0 ; i < numArmy;i++){ if(rateArmy.get(i) > 0){ boss.getBuildManager().needBuilding(InternalID_To_UnitTypeID(i)); } } } useBuilding = new ArrayList<Unit>(); } //----------------------------------------------------------------------------------------- private void buildExternalStack(){ boolean createExternal = true; while (!createStackExternal.isEmpty() && minerals > 0 && createExternal) { int typeID = createStackExternal.get(0); createExternal = productionUnit(typeID); if(createExternal) // ak ju dalo stavat tak vyraz createStackExternal.remove(0); } } private void setRateArmyActual(){ rateArmyActual = new ArrayList<Double>(); for(int i = 0 ; i < numArmy ; i++){ rateArmyActual.add(0.0); } int sumID = -1; for(Unit u : game.getMyUnits()){ sumID = UnitTypeID_To_InternalID(u.getTypeID()); if(sumID != -1) //jednotka je v zozname if(rateArmy.get(sumID) > 0) // mam take jednotky vyrabat rateArmyActual.set(sumID, rateArmyActual.get(sumID)+ 1); } Double countArmy = (double) countArmy(); if(countArmy <= 0) countArmy = 1.0; for(int i = 0 ; i < numArmy ; i++){ rateArmyActual.set(i,( rateArmyActual.get(i) / countArmy)*100); } rate = maxRate / countArmy ; } private int countArmy(){ int sum = 0; for(Unit u : game.getMyUnits()){ if(UnitTypeID_To_InternalID(u.getTypeID()) != - 1) sum++; } if(sum == 0) return 1; return sum; } private void setRateArmyGap(){ rateArmyGap = new ArrayList<MyArmyGap>();; for(int i = 0 ; i < numArmy ; i++){ rateArmyGap.add(new MyArmyGap(0.0, i)); } for(int i = 0 ; i < numArmy ; i++){ rateArmyGap.get(i).gap = rateArmy.get(i) - rateArmyActual.get(i); } Collections.sort(rateArmyGap); } private void setCrateStack(){ createStack = new Vector<Integer>(); double pomRate = 0.0; int count = 0; for(int i =0 ; i < numArmy;i++){ pomRate = rateArmyGap.get(i).gap; if(pomRate > 0){ count = (int)(pomRate / rate); for(int j=0 ; j < count; j++){ createStack.add(InternalID_To_UnitTypeID(rateArmyGap.get(i).ID)); } } } for(int i =0 ; i < numArmy;i++){ // TODO dako rozumne Random r = new Random(); int s = r.nextInt(numArmy); pomRate = rateArmy.get(s); if(pomRate > 0){ createStack.add(InternalID_To_UnitTypeID(s)); } } Vector<Integer> productBuild = new Vector<Integer>(); for(int i = 0; i < createStack.size();i++) { int typeID = createStack.get(i); int buildingID = game.getUnitType(typeID).getWhatBuildID(); Unit building = findBuilding(buildingID,productBuild); if(building != null){ productBuild.add(building.getID()); }else{ createStack.remove(i); } } } //---------->>"" private boolean productionUnit(int typeID){ if(typeID == UnitTypes.Protoss_Archon.ordinal()||typeID == UnitTypes.Protoss_Dark_Archon.ordinal()){ return productionArchon(typeID); }else{ int buildingID = game.getUnitType(typeID).getWhatBuildID(); Unit building = findBuilding(buildingID); if(building != null) return createUnit(building, typeID); return false; } } private boolean productionArchon(int typeID){ //TODO zavolat MC nech vytvory unit. return true; } private Unit findBuilding(int building){ for(Unit u : game.getMyUnits()){ if(u.getTypeID() == building ){ if(!u.isTraining() && u.isCompleted()) return u; } } return null; } private Unit findBuilding(int building,Vector<Integer> array){ for(Unit u : game.getMyUnits()){ if(u.getTypeID() == building ){ if(!u.isTraining() && !inArray( u.getID(),array) && u.isCompleted()) return u; } } return null; } private boolean createUnit(Unit building, int typeID){ Boolean testInGroup = false; int freeSuply = game.getSelf().getSupplyTotal() - game.getSelf().getSupplyUsed(); if(freeSuply >= game.getUnitType(typeID).getSupplyRequired() && minerals >= game.getUnitType(typeID).getMineralPrice() && gas >= game.getUnitType(typeID).getGasPrice()){ testInGroup = isInGroup(building, useBuilding); if(!building.isTraining() && !testInGroup){ game.train(building.getID(), typeID); useBuilding.add(building); return true; } } return false; } //------------------------------------------------------------------------------------------ private boolean isInGroup(Unit u, ArrayList<Unit> list){ for(Unit l:list){ if(l.getID() == u.getID()) return true; } return false; } private boolean inArray(Integer ID,Vector<Integer> zoz){ for(Integer i: zoz){ if (i == ID) return true; } return false; } //------------------------------------ FROM-TO --------------------------------------------- private int UnitTypeID_To_InternalID(int typeID){ if(typeID == UnitTypes.Protoss_Zealot.ordinal()) return 0; // 0 if(typeID == UnitTypes.Protoss_Dragoon.ordinal()) return 1; // 1 if(typeID == UnitTypes.Protoss_High_Templar.ordinal()) return 2; // 2 if(typeID == UnitTypes.Protoss_Dark_Templar.ordinal()) return 3; // 3 if(typeID == UnitTypes.Protoss_Shuttle.ordinal()) return 4; // 4 if(typeID == UnitTypes.Protoss_Reaver.ordinal()) return 5; // 5 if(typeID == UnitTypes.Protoss_Observer.ordinal()) return 6; // 6 if(typeID == UnitTypes.Protoss_Scout.ordinal()) return 7; // 7 if(typeID == UnitTypes.Protoss_Corsair.ordinal()) return 8; // 8 if(typeID == UnitTypes.Protoss_Carrier.ordinal()) return 9; // 9 if(typeID == UnitTypes.Protoss_Arbiter.ordinal()) return 10; // 10 if(typeID == UnitTypes.Protoss_Archon.ordinal()) return 11; // 11 if(typeID == UnitTypes.Protoss_Dark_Archon.ordinal()) return 12; // 12 return -1; } private int InternalID_To_UnitTypeID(int InternalID){ if(InternalID == 0) return UnitTypes.Protoss_Zealot.ordinal(); // 0 if(InternalID == 1) return UnitTypes.Protoss_Dragoon.ordinal(); // 1 if(InternalID == 2) return UnitTypes.Protoss_High_Templar.ordinal(); // 2 if(InternalID == 3) return UnitTypes.Protoss_Dark_Templar.ordinal(); // 3 if(InternalID == 4) return UnitTypes.Protoss_Shuttle.ordinal(); // 4 if(InternalID == 5) return UnitTypes.Protoss_Reaver.ordinal(); // 5 if(InternalID == 6) return UnitTypes.Protoss_Observer.ordinal(); // 6 if(InternalID == 7) return UnitTypes.Protoss_Scout.ordinal(); // 7 if(InternalID == 8) return UnitTypes.Protoss_Corsair.ordinal(); // 8 if(InternalID == 9) return UnitTypes.Protoss_Carrier.ordinal(); // 9 if(InternalID == 10) return UnitTypes.Protoss_Arbiter.ordinal(); // 10 if(InternalID == 11) return UnitTypes.Protoss_Archon.ordinal(); // 11 if(InternalID == 12) return UnitTypes.Protoss_Dark_Archon.ordinal(); // 12 return -1; } //------------------------------------ only testing ---------------------------------------- private void sendText(String msg){ if(testing) game.sendText("UPM-" + msg); } private void drawDebugInfo() { if(testing){ int hh = 180 ; int ww = 500; for(int i = 0; i < rateArmyGap.size();i++){ if(i == 0) game.drawText(new Point(ww,hh - 15), "Rate: "+rate, true); int s = (int) Math.round(rateArmyGap.get(i).gap); game.drawText(new Point(ww,hh+(i*10)), rateArmyGap.get(i).ID + ": "+ s, true); int ss = (int) Math.round( rateArmyActual.get(i)); game.drawText(new Point(ww+40,hh+(i*10)), i + ": "+ ss, true); int sss = (int) Math.round( rateArmy.get(i)); game.drawText(new Point(ww+80,hh+(i*10)), i + ": "+ sss , true); } for(int i = 0; i < createStackExternal.size(); i++ ){ int s = (int) Math.round(createStackExternal.get(i)); game.drawText(new Point(ww,20 + (i*10)), i + ": "+ s, true); } if(createStackExternal.isEmpty()) game.drawText(new Point(ww,20),"-1 : empty", true); } } }
true
5e274e49d33d951ccfd6fb765dd00616040122ac
Java
ioananicolae8/cts_recuperare_seminar
/nicolae.ioana.as/src/nicolae/ioana/as/adapter/MesageriaFolosita.java
UTF-8
306
2.109375
2
[]
no_license
package nicolae.ioana.as.adapter; public class MesageriaFolosita implements Mesagerie { private MesagerieAdapter adapter; @Override public void trimiteMesaj(TipMesaj tipMesaj, String continut) { this.adapter = new MesagerieAdapter(tipMesaj); this.adapter.trimiteMesaj(tipMesaj, continut); } }
true
5334085348f2ffc259a283d2fa1f3db4a4b0fd7a
Java
Dhwanil-Patel/design_patterns
/src/main/java/com/world_of_anonymous/design_patterns/behavioural_design_pattern/flyweight_design_pattern/enumration/BrushSize.java
UTF-8
160
2.1875
2
[]
no_license
package com.world_of_anonymous.design_patterns.behavioural_design_pattern.flyweight_design_pattern.enumration; public enum BrushSize { THIN, MEDIUM, THICK }
true
0bcadcb4ca4e023fbf4085b4919844cd46405719
Java
abhilucks93Personal/Cabs-App
/app/src/main/java/com/abhi/taxiapp/settings/ChangePasswordActivity.java
UTF-8
4,940
2.0625
2
[]
no_license
package com.abhi.taxiapp.settings; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.MenuItem; import android.view.View; import android.widget.EditText; import android.widget.TextView; import com.abhi.taxiapp.R; import com.abhi.taxiapp.Utils.Constants; import com.abhi.taxiapp.Utils.Utility; import com.abhi.taxiapp.profile.model.SignUpResponseData; import com.abhi.taxiapp.profile.model.SignUpResponseMain; import com.abhi.taxiapp.profile.view.SignUpActivity; import com.abhi.taxiapp.retrofit.RetrofitApi; /** * Created by neha on 3/3/17. */ public class ChangePasswordActivity extends AppCompatActivity implements RetrofitApi.ResponseListener { EditText etOldPwd, etNewPwd, etConfirmPwd; String strOldPwd, strNewPwd, strConfirmPwd; TextView tvDone; private String uniqueDeviceId, deviceId; private String id; private SignUpResponseData data; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_change_password); findViewByID(); setUpActionBar(); initUI(); } private void initUI() { uniqueDeviceId = Utility.getUniqueId(ChangePasswordActivity.this); deviceId = Utility.getPreferences(ChangePasswordActivity.this, Constants.DeviceId); data = Utility.getProfileData(this, Constants.ProfileData); tvDone.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Utility.hideKeyboard(ChangePasswordActivity.this); strOldPwd = etOldPwd.getText().toString().trim(); strNewPwd = etNewPwd.getText().toString().trim(); strConfirmPwd = etConfirmPwd.getText().toString().trim(); if (isValid()) { callChangePasswordApi(); } } }); } private void callChangePasswordApi() { RetrofitApi.getInstance().changePassword(this, this, uniqueDeviceId, deviceId, "" + data.getId(), strNewPwd); } private boolean isValid() { if (strOldPwd.length() == 0) { Utility.showSnackBar(this, getResources().getString(R.string.error_fields_mandatory)); etOldPwd.setText(""); return false; } if (!strOldPwd.equals(data.getPassword())) { Utility.showSnackBar(this, "Please enter the correct old password"); return false; } if (strNewPwd.length() == 0) { Utility.showSnackBar(this, getResources().getString(R.string.error_fields_mandatory)); etNewPwd.setText(""); return false; } if (strConfirmPwd.length() == 0) { Utility.showSnackBar(this, getResources().getString(R.string.error_fields_mandatory)); etConfirmPwd.setText(""); return false; } if (strNewPwd.length() < 5) { Utility.showSnackBar(this, getResources().getString(R.string.error_password_length)); return false; } if (!strNewPwd.equals(strConfirmPwd)) { Utility.showSnackBar(this, getResources().getString(R.string.error_password_mismatch)); return false; } return true; } private void findViewByID() { tvDone = (TextView) findViewById(R.id.change_password_save); etOldPwd = (EditText) findViewById(R.id.change_password_old); etNewPwd = (EditText) findViewById(R.id.change_password_new); etConfirmPwd = (EditText) findViewById(R.id.change_password_confirm); } private void setUpActionBar() { setTitle("Change Password"); if (getSupportActionBar() != null) { getSupportActionBar().setDisplayHomeAsUpEnabled(true); getSupportActionBar().setDisplayShowHomeEnabled(true); } } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: onBackPressed(); return true; default: return super.onOptionsItemSelected(item); } } @Override public void _onNext(Object obj) { SignUpResponseMain responseMain = (SignUpResponseMain) obj; if (responseMain.getStatusCode().equals(Constants.StatusCodeSuccess)) { data = responseMain.getData().get(0); Utility.addPreferences(ChangePasswordActivity.this, Constants.ProfileData, data); Utility.showToast(ChangePasswordActivity.this, "Password changed successfully."); } else { Utility.showToast(ChangePasswordActivity.this, responseMain.getStatusMsg()); } } @Override public void _onComplete() { } @Override public void _onError(Throwable e) { } }
true
7378bef047ff796cb64bc418750a5b4a3b438172
Java
Pratyaksh777/JCallRecorderapp
/app/src/main/java/in/ac/vitbhopal/projects/callrecorder/recorder/VersionedRecorderFactory.java
UTF-8
854
2.296875
2
[]
no_license
package in.ac.vitbhopal.projects.callrecorder.recorder; import android.content.Context; import android.media.MediaRecorder; import android.os.Build; import androidx.annotation.RequiresApi; @RequiresApi(api = Build.VERSION_CODES.N) public class VersionedRecorderFactory { private VersionedRecorderFactory() { } public static AbstractRecorder getRecorder(Context ctx) { int CURRENT_VERSION = Build.VERSION.SDK_INT; MediaRecorder mediaRecorder = new MediaRecorder(); if (CURRENT_VERSION >= Build.VERSION_CODES.Q) { return new Android10Recorder(ctx, mediaRecorder); } else { // temporary solution since just testing for android 10 return new Android10Recorder(ctx, mediaRecorder); // throw new IllegalArgumentException("Invalid android version."); } } }
true
76d3056fba6a44e8f3895121c3299d9fff20750d
Java
keneyfofe/perago-project
/src/main/java/za/co/perago/services/DiffRendererService.java
UTF-8
558
2
2
[]
no_license
package za.co.perago.services; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import za.co.perago.exceptions.DiffException; import za.co.perago.model.Diff; import za.co.perago.model.Person; //this service must implements DiffRenderer interface. @Service public class DiffRendererService implements DiffRenderer { @Autowired private DiffRenderer diffRenderer; @Override public String render(Diff<?> diff) throws DiffException { // TODO Auto-generated method stub return null; } }
true
8958e952e7331a82f751a37a4fc84dba917e7201
Java
SigmaITC/competencebyjava-microservice-springboot
/src/main/java/se/sigma/microservice/springboot/data/UserStore.java
UTF-8
1,206
2.609375
3
[ "MIT" ]
permissive
package se.sigma.microservice.springboot.data; import io.vavr.collection.List; import io.vavr.control.Option; import java.util.UUID; import lombok.Getter; import lombok.NoArgsConstructor; import org.springframework.stereotype.Component; import se.sigma.microservice.springboot.model.User; @Component @NoArgsConstructor @Getter public class UserStore { private List<User> users = List.of( new User(UUID.fromString("8390159a-87b3-4364-9202-8d0cd73ee06b"), "Chris"), new User(UUID.fromString("c95dc295-1aa7-4ec2-8007-afee43b31b16"), "Kevin")); public Option<User> getUser(final UUID uuid) { return this.users.find(user -> user.getId().equals(uuid)); } public User addUser(final User user) { this.users = this.users.append(user); return user; } public Option<User> removeUser(final UUID uuid) { final var user = getUser(uuid); this.users = user.map(x -> this.users.remove(x)).getOrElse(this.users); return user; } public Option<User> updateUser(final UUID uuid, final User updatedUser) { final var user = getUser(uuid); this.users = user.map(x -> this.users.replace(x, updatedUser)).getOrElse(this.users); return user; } }
true
f6e831d0c980348c479dfb9b39b451301504c93b
Java
zhongxingyu/Seer
/Diff-Raw-Data/2/2_918fb9c75edd067e2595d8b9e9b7259477478c86/SimpleRevisionServer/2_918fb9c75edd067e2595d8b9e9b7259477478c86_SimpleRevisionServer_t.java
UTF-8
2,480
2.328125
2
[]
no_license
/* Copyright (c) 2010-2012, Revori Contributors Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. */ package com.readytalk.revori.server; import com.readytalk.revori.Revision; import com.readytalk.revori.Revisions; import com.readytalk.revori.ConflictResolver; import com.readytalk.revori.ForeignKeyResolver; import com.readytalk.revori.subscribe.Subscription; import java.util.Set; import java.util.HashSet; import java.util.concurrent.atomic.AtomicReference; public class SimpleRevisionServer implements RevisionServer { private final ConflictResolver conflictResolver; private final ForeignKeyResolver foreignKeyResolver; private final AtomicReference<Revision> head = new AtomicReference (Revisions.Empty); public final AtomicReference<Set<Runnable>> listeners = new AtomicReference(new HashSet()); public SimpleRevisionServer(ConflictResolver conflictResolver, ForeignKeyResolver foreignKeyResolver) { this.conflictResolver = conflictResolver; this.foreignKeyResolver = foreignKeyResolver; } public Revision head() { return head.get(); } public void merge(Revision base, Revision fork) { if (base != fork || base != head.get()) { while (! head.compareAndSet(base, fork)) { Revision h = head.get(); fork = base.merge (h, fork, conflictResolver, foreignKeyResolver); base = h; } for (Runnable listener: listeners.get()) { listener.run(); } } } public Subscription registerListener(final Runnable listener) { while (true) { Set<Runnable> oldListeners = listeners.get(); Set<Runnable> newListeners = new HashSet(oldListeners); newListeners.add(listener); if (listeners.compareAndSet(oldListeners, newListeners)) { break; } } listener.run(); return new Subscription() { public void cancel() { while (true) { Set<Runnable> oldListeners = listeners.get(); Set<Runnable> newListeners = new HashSet(oldListeners); newListeners.remove(listener); if (listeners.compareAndSet(oldListeners, newListeners)) { break; } } } }; } }
true
7c955269ecdf2c2c66766e22622030867890d92c
Java
zc1249274251/baseio
/baseio-core/src/main/java/com/generallycloud/nio/component/DatagramSelectorEventLoopGroup.java
UTF-8
2,008
2.15625
2
[ "Apache-2.0" ]
permissive
/* * Copyright 2015-2017 GenerallyCloud.com * * 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.generallycloud.nio.component; import com.generallycloud.nio.component.concurrent.AbstractEventLoopGroup; import com.generallycloud.nio.component.concurrent.EventLoop; /** * @author wangkai * */ public class DatagramSelectorEventLoopGroup extends AbstractEventLoopGroup implements SelectorEventLoopGroup { private DatagramSelectorEventLoop[] selectorEventLoops = null; private DatagramChannelContext channelContext; public DatagramSelectorEventLoopGroup(DatagramChannelContext context, String eventLoopName, int eventQueueSize, int eventLoopSize) { super(eventLoopName, eventQueueSize, eventLoopSize); this.channelContext = context; } @Override public DatagramSelectorEventLoop getNext() { return selectorEventLoops[getNextEventLoopIndex()]; } @Override public DatagramSelectorEventLoop[] getSelectorEventLoops() { return selectorEventLoops; } @Override protected EventLoop[] initEventLoops() { selectorEventLoops = new DatagramSelectorEventLoop[getEventLoopSize()]; return selectorEventLoops; } @Override protected EventLoop[] getEventLoops() { return getSelectorEventLoops(); } @Override protected DatagramSelectorEventLoop newEventLoop(int coreIndex, int eventQueueSize) { return new DatagramSelectorEventLoopImpl(this,coreIndex); } @Override public DatagramChannelContext getChannelContext() { return channelContext; } }
true
ab8978486dde8605b73e2cc766c92d852d9efe8f
Java
agarboni/MadeInTM
/app/src/main/java/ro/madeintm/madeintm/controller/StoryActivity.java
UTF-8
814
2.265625
2
[]
no_license
package ro.madeintm.madeintm.controller; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v7.app.AppCompatActivity; import android.util.Log; import ro.madeintm.madeintm.R; import ro.madeintm.madeintm.model.Story; /** * Created by validraganescu on 21/05/16. */ public class StoryActivity extends AppCompatActivity{ private Story story; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_story); Object oStory = getIntent().getSerializableExtra("object"); story = null; if (oStory != null && oStory instanceof Story) { story = (Story) oStory; Log.d("Story", story.getTitle()); } } }
true
2fea4f02086c318a4077d690ee1d5e8ed10ada4c
Java
narang-amit/Java
/Semester2/14FrontierSolver/FrontierStack.java
UTF-8
335
2.953125
3
[]
no_license
//SOrry import java.util.*; public class FrontierStack implements Frontier { private Stack<Location> set; public FrontierStack() { set = new Stack<Location>(); } public Location next() { return set.pop(); } public void add(Location temp) { set.add(temp); } public boolean hasNext() { return !(set.size() == 0); } }
true
b8fa8d4649021f1655f4edf174bf16a734bebcf1
Java
1Will/Work1
/wms2014/src/main/java/com/yongjun/tdms/presentation/webwork/action/runmaintenance/device/lubrication/ListLubricationProcAction.java
UTF-8
4,879
1.921875
2
[]
no_license
/* * Copyright (c) 2001-2007 YongJun Technology Pte.,Ltd. All Rights Reserved. * * This software is the confidential and proprietary information of YongJun * Technology Pte.,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 YongJun. * * YONGJUN MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE SUITABILITY OF THE * SOFTWARE, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED * WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR * NON-INFRINGEMENT. YONGJUN SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY * LICENSEE AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS * DERIVATIVES. */ package com.yongjun.tdms.presentation.webwork.action.runmaintenance.device.lubrication; import java.util.List; import com.yongjun.pluto.model.LabelValue; import com.yongjun.pluto.webwork.action.valuelist.ValueListAction; import com.yongjun.tdms.model.runmaintenance.lubrication.LubricationPlan; import com.yongjun.tdms.model.runmaintenance.lubrication.LubricationPlanStatus; /** * <p>Title: ListLubricationProcAction * <p>Description: 润滑实施列表访问控制类</p> * <p>Copyright: Copyright (c) 2007 yj-technology</p> * <p>Company: www.yj-technology.com</p> * @author mwei@yj-technology.com * @version $Id: ListLubricationProcAction.java 10415 2008-01-16 01:52:19Z mwei $ */ public class ListLubricationProcAction extends ValueListAction { private static final long serialVersionUID = -1130945198078325553L; //private final DepartmentManager departmentManager; //private final LubricationProcManager lubricationProcManager; private String lubricationPlanInfo; private String lubricationProcInfo; private List<LubricationPlan> lubricationProcs; public ListLubricationProcAction() { //this.departmentManager = departmentManager; //this.lubricationProcManager = lubricationProcManager; } public void prepare() { if (this.lubricationPlanInfo == null) { if (this.hasId("lubricationPlanInfo")) { this.lubricationPlanInfo = (String) request .getParameter("lubricationPlanInfo"); } else { this.lubricationPlanInfo = ""; } } if (this.lubricationProcInfo == null) { if (this.hasId("lubricationProcInfo")) { this.lubricationProcInfo = (String) request .getParameter("lubricationProcInfo"); } else { lubricationProcInfo = ""; } } /* if (this.lubricationProcs == null && this.hasIds("lubricationProcIds")) { this.lubricationProcs = this.lubricationProcManager .loadAllLubricationProc(this.getIds("lubricationProcIds")); } */ } public String execute() { if (isSaveLubricationProc()) { return saveLubricationProc(); } if(isSaveLubrication()){ return modify(); } if(this.isDelete()){ return delete(); } return SUCCESS; } private boolean isSaveLubricationProc() { if (this.lubricationPlanInfo.equals("")) { return false; } return true; } private String saveLubricationProc() { //this.lubricationProcManager.storeLubricationProc(lubricationPlanInfo); this.addActionMessage(this.getText("lubricationproc.add.success")); return SUCCESS; } @Override protected String getAdapterName() { return "lubricationProc"; } public List getDepartments() { //return departmentManager.createSelectDepartments(this //.getText("select.option.all")); return null; } public String getLubricationPlanInfo() { return lubricationPlanInfo; } public void setLubricationPlanInfo(String lubricationPlanInfo) { this.lubricationPlanInfo = lubricationPlanInfo; } private String delete() { try { //this.lubricationProcManager.deleteAllLubricationProc(lubricationProcs); this.addActionMessage(this .getText("lubricationProc.delete.success")); } catch (Exception ex) { ex.printStackTrace(); this.addActionMessage(this .getText("lubricationProc.delete.failure")); } return SUCCESS; } private boolean isSaveLubrication() { return this.hasKey("save"); } private String modify(){ if (!this.lubricationProcInfo.equals("")) { //this.lubricationProcManager.modifyLubricationProc(lubricationProcInfo); this.addActionMessage(this .getText("lubricationproc.modify.success")); } return SUCCESS; } public List<LubricationPlan> getLubricationProcs() { return lubricationProcs; } public void setLubricationProcs(List<LubricationPlan> lubricationProcs) { this.lubricationProcs = lubricationProcs; } public String getLubricationProcInfo() { return lubricationProcInfo; } public void setLubricationProcInfo(String lubricationProcInfo) { this.lubricationProcInfo = lubricationProcInfo; } public LabelValue[] getLubricationPlanStatus() { return this.wrapEnum(LubricationPlanStatus.class); } }
true
1906c5206de95f9b8ef7f32fdacc1afb2fe22c9c
Java
ArtistScript/data-structure
/src/com/leetcode/Solution11.java
UTF-8
668
3.171875
3
[]
no_license
package com.leetcode; /** * ClassName: Solution11 <br/> * Function: <br/> * Date: 2019-07-20 14:13<br/> * */ import java.util.Stack; import java.util.Vector; /** * 如果后面的数字比现在大,一直往后就好 * 如果开始下降 */ public class Solution11 { public int maxArea(int[] height) { int i=0,j=height.length-1; int maxarare=-1; while (i<j){ maxarare=Math.max((j-i)*Math.min(height[i],height[j]),maxarare); if(height[i]<height[j]) i++; else j--; } return maxarare; } }
true
81c34bae14b1a8c22ac564a336fe2c37d2e3f8b8
Java
uncleliuchuan/fruit
/src/main/java/com/jclz/fruit/dao/OrderInfoMapper.java
UTF-8
1,184
1.921875
2
[]
no_license
package com.jclz.fruit.dao; import com.jclz.fruit.entity.OrderInfo; import org.apache.ibatis.annotations.Mapper; import org.springframework.stereotype.Repository; import java.util.List; @Mapper @Repository public interface OrderInfoMapper { int deleteByPrimaryKey(Integer id); int insert(OrderInfo record); int insertSelective(OrderInfo record); OrderInfo selectByPrimaryKey(Integer id); int updateByPrimaryKeySelective(OrderInfo record); int updateByPrimaryKey(OrderInfo record); OrderInfo selectByOrderNo(String orderNo); List<OrderInfo> selectByOuterTradeNo(String outerTradeNo); int updateOrderStatus(OrderInfo o); List<OrderInfo> selectExpiredOrders(); /** * 查询待发货-待收货-待评价等的订单 * @param userId * @return */ List<OrderInfo> selectOrdersByUserId(Integer userId); List<OrderInfo> selectOtherOrders(Integer userId, Integer orderStatus); /** * 查询指定用户各个状态的订单数量 * @param orderStatus * @return */ int selectOrderStatus(Integer userId, Integer orderStatus); List<OrderInfo> refundAfterAale(Integer userId); }
true
4b52349a78f0e139cf4874fd7ebfdfb374ea3266
Java
AndreyKryshtapovich/WebProject_v1_Kryshtapovich
/src/by/epamtr/totalizator/dao/ClientDAO.java
UTF-8
386
1.898438
2
[]
no_license
package by.epamtr.totalizator.dao; import java.util.List; import by.epamtr.totalizator.bean.entity.Event; import by.epamtr.totalizator.bean.entity.User; import by.epamtr.totalizator.dao.exception.DAOException; public interface ClientDAO { boolean RegistrationUser(User user, String login, String password)throws DAOException; List<Event> getCurrentEvents() throws DAOException; }
true
2285ed00926c94744026c97f661978896a9650a7
Java
maheshmanchala92/spring-training
/spring-java-conf-web/src/main/java/com/training/spring/spring_java_conf_web/model/ItEmployee.java
UTF-8
1,075
2.5
2
[]
no_license
package com.training.spring.spring_java_conf_web.model; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; @Entity public class ItEmployee extends Employee { @Id @GeneratedValue private Integer emplId; private Integer salary; private String email; public Integer getSalary() { return salary; } public void setSalary(Integer salary) { this.salary = salary; } public ItEmployee(Integer salary) { super(); this.salary = salary; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public ItEmployee() { } public ItEmployee(Integer salary, String email) { this.salary = salary; this.email = email; } public long getEmplId() { return emplId; } public void setEmplId(Integer emplId) { this.emplId = emplId; } public ItEmployee(Integer emplId, Integer salary, String email) { super(); this.emplId = emplId; this.salary = salary; this.email = email; } }
true
f7aa935fe57faa225b799bdc2504dc9593db8271
Java
tgame14/tgame-core
/src/main/java/com/tgame/mods/libs/registry/RegistryHandler.java
UTF-8
1,250
2.203125
2
[ "MIT" ]
permissive
package com.tgame.mods.libs.registry; import cpw.mods.fml.common.SidedProxy; import cpw.mods.fml.common.registry.EntityRegistry; import net.minecraft.block.Block; import net.minecraft.entity.Entity; import net.minecraft.item.Item; import net.minecraft.tileentity.TileEntity; /** * @author tgame14 * @since 25/04/14 */ public class RegistryHandler { @SidedProxy(clientSide = "com.tgame.mods.libs.registry.ClientRegistryProxy", serverSide = "com.tgame.mods.libs.registry.CommonRegistryProxy") private static CommonRegistryProxy registryProxy; public IItemDefinition registerBlock(Block block, Class<? extends Block> clazz) { IItemDefinition itemdef = new ItemDefinition(block, clazz); registryProxy.registerBlock(itemdef); return itemdef; } public void registerTile(Class<? extends TileEntity> clazz) { registryProxy.registerTile(clazz); } public IItemDefinition registerItem(Item item, Class<? extends Item> clazz) { IItemDefinition itemdef = new ItemDefinition(item, clazz); registryProxy.registerItem(itemdef); return itemdef; } public void registerEntity(Class<? extends Entity> clazz) { EntityRegistry.registerGlobalEntityID(clazz, clazz.getSimpleName(), EntityRegistry.findGlobalUniqueEntityId()); } }
true