blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
4
410
content_id
stringlengths
40
40
detected_licenses
listlengths
0
51
license_type
stringclasses
2 values
repo_name
stringlengths
5
132
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringlengths
4
80
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
5.85k
689M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
22 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
131 values
src_encoding
stringclasses
34 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
3
9.45M
extension
stringclasses
32 values
content
stringlengths
3
9.45M
authors
listlengths
1
1
author_id
stringlengths
0
313
e8fb2d4ee2587baa507135f7295283d60fd71530
83df4fc79fabd482c9be5a97389dc855e25906b6
/app/src/main/java/com/nahtredn/fragments/StudyDoneFragment.java
b5c5d2acb425e34c921791751dad6f732f4d8a23
[]
no_license
AlexMtz/adso-android
ccf4df53e4314366f6a5057c28ddb2b508908ec7
0fc72930457b047b46f5351bb009f0bea72d3967
refs/heads/master
2021-04-03T06:10:57.461591
2018-04-25T02:47:01
2018-04-25T02:47:01
124,703,064
0
0
null
null
null
null
UTF-8
Java
false
false
2,126
java
package com.nahtredn.fragments; import android.content.Intent; 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.AdapterView; import android.widget.ListView; import com.nahtredn.adso.R; import com.nahtredn.adso.StudyDoneActivity; import com.nahtredn.adapters.StudyDoneAdapter; import com.nahtredn.entities.StudyDone; import com.nahtredn.utilities.RealmController; public class StudyDoneFragment extends Fragment implements AdapterView.OnItemClickListener{ private ListView list; private StudyDoneAdapter adapter; public StudyDoneFragment() { } public static StudyDoneFragment newInstance() { StudyDoneFragment fragment = new StudyDoneFragment(); return fragment; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View root = inflater.inflate(R.layout.fragment_study_done, container, false); list = root.findViewById(R.id.study_done_list); adapter = new StudyDoneAdapter(getActivity(), RealmController.with(this).findAllStudiesDone()); list.setAdapter(adapter); list.setOnItemClickListener(this); setHasOptionsMenu(true); return root; } @Override public void onResume() { super.onResume(); adapter = new StudyDoneAdapter(getActivity(), RealmController.with(this).findAllStudiesDone()); adapter.notifyDataSetChanged(); list.setAdapter(adapter); } @Override public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) { StudyDone studyDone = adapter.getItem(position); Intent intent = new Intent(getActivity(), StudyDoneActivity.class); intent.putExtra("study_done_id", studyDone.getId()); getActivity().startActivity(intent); } }
29b9f5d2c9733c1c692faf8707c501a9b3271fe4
95d68f00389c99f880fdea196dff26640b82180c
/app/src/main/java/projectppb/com/Number_Sexagesimal_Complex.java
1c21554cc31e4c0ef345f7459adbd7bad2c42c11
[]
no_license
DheaOkySafitri-170411100006/Aplikasi-Math-Theory
c02e968a0380be933be5bff047bce8e979b7e62c
da5aa8b59e09c0f83993e605bfb61f760ea7eb66
refs/heads/master
2021-05-21T06:22:50.226812
2020-07-03T11:25:49
2020-07-03T11:25:49
256,417,116
0
0
null
null
null
null
UTF-8
Java
false
false
751
java
package projectppb.com; import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; import android.widget.Toast; import com.github.barteksc.pdfviewer.PDFView; public class Number_Sexagesimal_Complex extends AppCompatActivity { PDFView pdfView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_number__sexagesimal__complex); pdfView= (PDFView) findViewById(R.id.pdfView1); pdfView.fromAsset("Number_Sexagesimal_Complex.pdf") .load(); pdfView.zoomTo((float) 3.5); Toast.makeText(this, "Tunggu beberapa saat. \n Sedang memuat data. . .", Toast.LENGTH_SHORT).show(); } }
c67cf2b84b0cd7c2a9b36b4ecea5fe9c3df649ff
bb94627a9f79ddf204f658fd33ecfc7b59247584
/test/Backend/Model/Builder/KpversenyzoTest.java
02a5a0dced08d54458cf5d748383db15c3502bfb
[]
no_license
H7David/Progtech
2bcd1d0997563df7947c13af12e9ca32601e8db3
f3b9121b1c62e0cc54ff7fddceadcb91d527169a
refs/heads/master
2022-07-01T14:55:56.114242
2020-05-11T21:21:51
2020-05-11T21:21:51
262,637,606
0
0
null
null
null
null
UTF-8
Java
false
false
2,956
java
/* * 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 Backend.Model.Builder; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; /** * * @author prog */ public class KpversenyzoTest { public KpversenyzoTest() { } @BeforeClass public static void setUpClass() { } @AfterClass public static void tearDownClass() { } @Before public void setUp() { } @After public void tearDown() { } /** * Test of getKerekpar method, of class Kpversenyzo. */ @Test public void testGetKerekpar() { System.out.println("getKerekpar teszt"); Kpversenyzo instance = new Kpversenyzo(); String expResult = "gyarto"; instance.setKerekpargyarto("gyarto"); String result = instance.getKerekpar(); assertEquals(expResult, result); } /** * Test of getNev method, of class Kpversenyzo. */ @Test public void testGetNev() { System.out.println("getNev teszt"); Kpversenyzo instance = new Kpversenyzo(); String expResult = "nev"; instance.setNev("nev"); String result = instance.getNev(); assertEquals(expResult, result); } /** * Test of getKptipus method, of class Kpversenyzo. */ @Test public void testGetKptipus() { System.out.println("Kptipus teszt"); Kpversenyzo instance = new Kpversenyzo(); String expResult = "DH"; instance.setKptipus("DH"); String result = instance.getKptipus(); assertEquals(expResult, result); } /** * Test of setKptipus method, of class Kpversenyzo. */ @Test public void testSetKptipus() { System.out.println("setKptipus teszt"); String kptipus = "DH"; Kpversenyzo instance = new Kpversenyzo(); instance.setKptipus(kptipus); assertEquals(kptipus, instance.getKptipus()); } /** * Test of setKerekpargyarto method, of class Kpversenyzo. */ @Test public void testSetKerekpargyarto() { System.out.println("setKerekpargyarto ellenőrzése"); String kerekpargyarto = "Scott"; Kpversenyzo instance = new Kpversenyzo(); instance.setKerekpargyarto(kerekpargyarto); assertEquals(kerekpargyarto, instance.getKerekpar()); } /** * Test of setNev method, of class Kpversenyzo. */ @Test public void testSetNev() { System.out.println("setNev tesztelése"); String nev = "David"; Kpversenyzo instance = new Kpversenyzo(); instance.setNev(nev); assertEquals(nev, instance.getNev()); } }
f370b29c0360ba1f43e4cc634fad628617f6255e
0afa717dd15910bcbd26ff0ec3be80a72851f17d
/app/src/androidTest/java/project5/rhodes/com/project5/ApplicationTest.java
5af541527d5d801dea1c6a984212a22cebedf73d
[]
no_license
connorrhodes/Project5
a016f291f07ac428bc3bd6f3cbbcccd23b171776
1486b82f38b15c52ae82292c96cf89043df2512d
refs/heads/master
2020-06-26T22:20:27.788773
2015-02-25T20:51:59
2015-02-25T20:51:59
31,334,595
0
0
null
null
null
null
UTF-8
Java
false
false
359
java
package project5.rhodes.com.project5; import android.app.Application; import android.test.ApplicationTestCase; /** * <a href="http://d.android.com/tools/testing/testing_android.html">Testing Fundamentals</a> */ public class ApplicationTest extends ApplicationTestCase<Application> { public ApplicationTest() { super(Application.class); } }
2bb1b9c7ebb1350aba9308b757a54b8697b96f71
7b9a7e5b3410f0566256e0574b931945ec34c8e9
/src/main/java/com/kaitait/statemachine/AddressValidator.java
8935a92bd95dd07937e85709c6be3d12ea84d8ac
[]
no_license
spik3r/statemachine
bf8cf1a482ef887533bf7e75fa7c652f45245a98
27b79f794de17ea19c799fc3f1926091423690e8
refs/heads/master
2020-03-13T22:09:40.050203
2018-05-17T14:59:57
2018-05-17T14:59:57
131,311,118
0
1
null
null
null
null
UTF-8
Java
false
false
913
java
package com.kaitait.statemachine; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.statemachine.StateContext; import org.springframework.stereotype.Component; @Component public class AddressValidator implements org.springframework.statemachine.guard.Guard<Pages, Events> { private static final Logger LOG = LoggerFactory.getLogger(AddressValidator.class); public AddressValidator(){} @Override public boolean evaluate(final StateContext<Pages, Events> stateContext) { LOG.info(String.valueOf(stateContext.getExtendedState().getVariables().get("addressId"))); LOG.info("____ AddressValidator: " + stateContext.getExtendedState().getVariables()); final CheckoutModel checkoutModel = (CheckoutModel) stateContext.getExtendedState().getVariables().get("checkoutModel"); return checkoutModel.getAddressId().length() >= 6; } }
bd96a9f29184eaf606574e8d4da566e4f2e5aaea
fb21927ac95b596b0a3bf7de63d8180299a2cf50
/src/com/inetpsa/boz/rpv/rp/business/RpProcess.java
ac81478fc177f790a44a6ec2e28c2a78e7eccb51
[]
no_license
javaImportadores2017/codigoJAVA
2798d6c9ba939708f9f664605e7aa3f4e6c4edf9
6313669c8f5b33cfa4eed24dfc82d2027db24df7
refs/heads/master
2021-07-16T17:46:20.639236
2017-10-23T12:21:45
2017-10-23T12:21:45
null
0
0
null
null
null
null
UTF-8
Java
false
false
18,935
java
package com.inetpsa.boz.rpv.rp.business; import java.io.BufferedReader; import java.io.File; import java.sql.Connection; import java.sql.SQLException; import java.text.SimpleDateFormat; import org.exolab.castor.xml.Unmarshaller; import com.inetpsa.boz.common.bean.SuiviModuleBean; import com.inetpsa.boz.common.bean.SuiviProcessBean; import com.inetpsa.boz.common.constant.BozConstants; import com.inetpsa.boz.common.dao.RpvDao; import com.inetpsa.boz.common.db.DbManager; import com.inetpsa.boz.common.exception.BozException; import com.inetpsa.boz.common.exception.BozExceptionFactory; import com.inetpsa.boz.common.log.LoggerManager; import com.inetpsa.boz.common.utils.FileUtils; import com.inetpsa.boz.rpv.rp.dao.RpDao; import com.inetpsa.boz.rpv.rp.start.Context; import com.inetpsa.boz.rpv.rp.xml.TECHNICAL_HEADER; /** * Process du traitement du load du SAS */ public class RpProcess { /** * Effectue l'unmarshalling des fichiers XML du r�pertoire inputPath <li> * Puis int�gre les r�seaux points de ventes dans le SAS</li> */ public void execute() { Unmarshaller unmarshaller = new Unmarshaller(TECHNICAL_HEADER.class); Connection con = DbManager.getInstance().getConnection(); // SuiviProcessBean report = new SuiviProcessBean(); // -- Init date de suivi du process java.util.Date dateDebutProcess = new java.util.Date(); SuiviProcessBean suiviProcessBean = new SuiviProcessBean(); SuiviModuleBean suiviModuleBean = null; String etatProcess = BozConstants.statusOK; int nbFichierOk = 0; int nbFichierKo = 0; // SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy"); SimpleDateFormat sdf2 = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss"); SimpleDateFormat sdfReject = new SimpleDateFormat("yyyyMMddHHmmss"); try { // -- R�cup�ration du num�ro du process int numProcess = RpvDao.getInstance().getNumProcess(con); File[] tabFile = FileUtils.listFilterFiles(Context.getInputPath(), Context.getPrefixFileName()); // System.out.println("tabfile:" + tabFile.length); int nbFichier = 0; if (tabFile != null) nbFichier = tabFile.length; // -- Maj du FLG_OLD � Y pour les lignes de SAS recyclages et // erreurs // RpvDao.getInstance().insertFlagDebut(con); // -- Suppression des enregistrement dans OPDV RpDao.getInstance().delete(con); try { LoggerManager.getInstance().info( "/*********** DEBUT PROCESS ***********/"); for (int i = 0; i < nbFichier; i++) { if (tabFile[i].isFile()) { String etatModule = BozConstants.statusOK; LoggerManager.getInstance().info( "/*********** DEBUT MODULE ***********/"); java.util.Date startDateModule = new java.util.Date(); TECHNICAL_HEADER myMsg = null; int nbEnrATraiter = 0; int nbEnrRejete = 0; BufferedReader br = null; String rejectFile = Context.getRejectPath() + File.separator + tabFile[i].getName() + "." + sdfReject.format(startDateModule); // int nbLigneMaj = 0; // int nbLigneCree = 0; try { suiviModuleBean = new SuiviModuleBean(); br = FileUtils.read(tabFile[i], "UTF-8"); myMsg = (TECHNICAL_HEADER) unmarshaller .unmarshal(br); validateMandatoryTags(myMsg); nbEnrATraiter = getNbEnrATraiter(myMsg); suiviModuleBean = RpDao.getInstance().insert(con, myMsg, tabFile[i].getName(), numProcess); // nbLigneCree++; nbFichierOk++; File out = new File(Context.getOutputPath() + File.separator + tabFile[i].getName() + "." + sdfReject.format(startDateModule)); FileUtils.copyFile(tabFile[i], out); tabFile[i].delete(); } catch (Exception ex) { // ex.printStackTrace(); // On sort en erreur du module ==> etatModule == KO etatModule = BozConstants.statusKO; etatProcess = BozConstants.statusKO; suiviModuleBean.setNumErreur(-1); suiviModuleBean.setLibErreur(ex.getMessage()); suiviProcessBean.setLibErreur(ex.getMessage()); suiviProcessBean.setNumErreur(-1); suiviProcessBean.setCodeEtatProcess(etatProcess); nbFichierKo++; treatException(tabFile[i], rejectFile, ex); } finally { if (br != null) br.close(); suiviModuleBean.setCodeTypeProcess("LOAD_SASINF"); suiviModuleBean.setNumProcess(numProcess); suiviModuleBean.setCodeModule("LOAD_RPR"); suiviModuleBean.setCodeSource(tabFile[i].getName()); suiviModuleBean.setCodeCible("BOZQTPRPR"); if (myMsg != null) { suiviModuleBean.setCodePays("XX"); suiviModuleBean.setCodeMarque("XX"); /* * suiviModuleBean.setCodeMarque(myMsg. * getTECHNICAL_HEADER().getAP_AC().toString()); * try { if * (myMsg.getTECHNICAL_HEADER().getEXTRACT_VERSION * () != null && * !"".equals(myMsg.getTECHNICAL_HEADER * ().getEXTRACT_VERSION().trim())) * suiviModuleBean * .setNumVersion(Integer.parseInt * (myMsg.getTECHNICAL_HEADER * ().getEXTRACT_VERSION())); } catch * (NumberFormatException nbfex) { * LoggerManager.getInstance().info( * "Le num�ro de l'extraction n'est pas un num�rique" * ); } * suiviModuleBean.setNbEnrATraiter(nbEnrATraiter * ); * suiviModuleBean.setNbEnrRejete(nbEnrRejete); * * try { suiviModuleBean.setDateDebutExtract(new * Date * (sdf.parse(myMsg.getTECHNICAL_HEADER().getDATE * ()).getTime())); } catch (ParseException pex) * { * LoggerManager.getInstance().error(pex.getMessage * ()); } try { * suiviModuleBean.setDateFinExtract(new * Date(sdf * .parse(myMsg.getTECHNICAL_HEADER().getDATE * ()).getTime())); } catch (ParseException pex) * { * LoggerManager.getInstance().error(pex.getMessage * ()); } * suiviModuleBean.setLibTypeFichier(myMsg * .getTECHNICAL_HEADER().getFILE_TYPE()); try { * suiviModuleBean.setDateTransfer(new * Date(sdf.parse * (myMsg.getTECHNICAL_HEADER().getDATE * ()).getTime())); } catch (ParseException pex) * { * LoggerManager.getInstance().error(pex.getMessage * ()); } */ suiviModuleBean.setNumVersion(Integer .parseInt("1")); suiviModuleBean.setNbEnrATraiter(nbEnrATraiter); suiviModuleBean.setNbEnrRejete(nbEnrRejete); suiviModuleBean .setLibTypeFichier("Fichier RPR"); try { // suiviModuleBean.setDateTransfer(new // java.sql.Date(sdf2.parse(myMsg.getTRANSFER_DATE()).getTime())); SimpleDateFormat sdf3 = new SimpleDateFormat( "dd/MM/yyyy HH:mm:ss"); java.util.Date date = sdf3.parse(myMsg .getTRANSFER_DATE()); java.sql.Timestamp timest = new java.sql.Timestamp( date.getTime()); // System.out.println(timest); suiviModuleBean.setDateTransfer(timest); } catch (Exception pex) { LoggerManager.getInstance().error( pex.getMessage()); } } suiviModuleBean.setDateDebutModule(sdf2 .format(startDateModule)); suiviModuleBean.setDateFinModule(sdf2 .format(new java.util.Date())); suiviModuleBean.setCodeEtatModule(etatModule); logModule(suiviModuleBean, tabFile[i].getName()); try { RpvDao.getInstance().insertSuiviModule(con, suiviModuleBean); } catch (BozException bex) { LoggerManager.getInstance().error( bex.getMessage()); } } } } } catch (Exception ex) { etatProcess = BozConstants.statusKO; suiviProcessBean.setNumErreur(-1); suiviProcessBean.setLibErreur(ex.getMessage()); suiviProcessBean.setCodeEtatProcess(etatProcess); suiviModuleBean.setLibErreur(ex.getMessage()); suiviModuleBean.setNumErreur(-1); LoggerManager.getInstance().error(ex.getMessage()); // ex.printStackTrace(); } // -- Maj de BOZQTSTAB avec 'Y' RpvDao.getInstance().insertFlagFin(con, "BOZQTORPR"); // -- Suivi du process suiviProcessBean.setCodeTypeProcess("LOAD_SASINF"); suiviProcessBean.setNumProcess(numProcess); suiviProcessBean.setDateDebut(sdf2.format(dateDebutProcess)); suiviProcessBean.setDateFin((sdf2.format(new java.util.Date()))); suiviProcessBean.setNbFichierATraiter(nbFichier); suiviProcessBean.setNbFichierOk(nbFichierOk); suiviProcessBean.setNbFichierRejet(nbFichierKo); suiviProcessBean.setCodeEtatProcess(etatProcess); try { logProcess(suiviProcessBean); RpvDao.getInstance().insertSuiviProcess(con, suiviProcessBean); if (!con.isReadOnly()) con.commit(); } catch (SQLException sqlex) { LoggerManager.getInstance().error(sqlex.getMessage()); } } catch (BozException bex) { bex.printStackTrace(); } } /** * * @param xmlMessage * @throws BozException */ private void validateMandatoryTags(TECHNICAL_HEADER xmlMessage) throws BozException { // Connection con = DbManager.getInstance().getConnection(); SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss"); if (xmlMessage.getTRANSFER_DATE() == null || xmlMessage.getTRANSFER_DATE().trim().equals("")) { throw BozExceptionFactory.getInstance().newException( "Label TRANSFER_DATE empty"); } try { sdf.setLenient(false); sdf.parse(xmlMessage.getTRANSFER_DATE()); } catch (Exception e) { throw BozExceptionFactory.getInstance().newException( "Label TRANSFER_DATE failed. Incorrect format"); } /* * int nbAct = xmlMessage.getACTIVITYCount(); * * for (int i = 0; i < nbAct; i++) { * * int nbSubsidiary = xmlMessage.getACTIVITY(i).getSUBSIDIARYCount(); * * for (int j = 0; j < nbSubsidiary; j++) { * * int nbDealer = * xmlMessage.getACTIVITY(i).getSUBSIDIARY(j).getDEALERCount(); * * for (int k = 0; k < nbDealer; k++) { * * if * (xmlMessage.getACTIVITY(i).getSUBSIDIARY(j).getDEALER(k).getDEALER_CODE * ().length() < 7 || * xmlMessage.getACTIVITY(i).getSUBSIDIARY(j).getDEALER * (k).getDEALER_CODE().length() > 10) { throw * BozExceptionFactory.getInstance * ().newException("Label DEALER CODE. Length is not allowed"); } } * * } } */ /* * int nbAct = xmlMessage.getACTIVITYCount(); * * for (int i = 0; i < nbAct; i++) { * * if (xmlMessage.getACTIVITY(i).getACTIVITY_CODE() == null || * xmlMessage.getACTIVITY(i).getACTIVITY_CODE().trim().equals("")) { * throw * BozExceptionFactory.getInstance().newException("Label ACTITY_CODE empty" * ); } * * int nbSubsidiary = xmlMessage.getACTIVITY(i).getSUBSIDIARYCount(); * * for (int j = 0; j < nbSubsidiary; j++) { * * if (xmlMessage.getACTIVITY(i).getSUBSIDIARY(j).getCOUNTRY_CODE() == * null || * xmlMessage.getACTIVITY(i).getSUBSIDIARY(j).getCOUNTRY_CODE().trim * ().equals("")) { throw * BozExceptionFactory.getInstance().newException( * "Label COD_COUNTRY empty"); } * * if (xmlMessage.getACTIVITY(i).getSUBSIDIARY(j).getAP_AC().toString() * == null || * xmlMessage.getACTIVITY(i).getSUBSIDIARY(j).getAP_AC().toString * ().trim().equals("")) { throw * BozExceptionFactory.getInstance().newException("Label AP_AC empty"); * } * * String CodePays = RpvDao.getInstance().ValidateCountry(con, * xmlMessage.getACTIVITY(i).getSUBSIDIARY(j).getCOUNTRY_CODE()); if * (CodePays == null) { throw * BozExceptionFactory.getInstance().newException * ("The Country code does not exist. Verify it."); } * * int nbDealer = * xmlMessage.getACTIVITY(i).getSUBSIDIARY(j).getDEALERCount(); * * for (int k = 0; k < nbDealer; k++) { if * (xmlMessage.getACTIVITY(i).getSUBSIDIARY * (j).getDEALER(k).getDEALER_CODE() == null || * xmlMessage.getACTIVITY(i) * .getSUBSIDIARY(j).getDEALER(k).getDEALER_CODE().trim().equals("")) { * throw * BozExceptionFactory.getInstance().newException("Label DEALER_CODE empty" * ); } } * * } * * } */ } /** * Renvoie le nombre de ligne � cr�er = au nombre total d'activit� * * @param myMsg * Le message XML * @param Le * nombre de ligne � cr�er */ private int getNbEnrATraiter(TECHNICAL_HEADER myMsg) { int nbActiviteTotal = 0; int nbAct = myMsg.getACTIVITYCount(); for (int i = 0; i < nbAct; i++) { // int nbIndividual = myMsg.getDEALER(k).getINDIVIDUALCount(); int nbSubsidiary = myMsg.getACTIVITY(i).getSUBSIDIARYCount(); if (nbSubsidiary == 0) nbActiviteTotal++; else for (int j = 0; j < nbSubsidiary; j++) { int nbDealer = myMsg.getACTIVITY(i).getSUBSIDIARY(j) .getDEALERCount(); if (nbSubsidiary == 0) nbActiviteTotal++; else nbActiviteTotal = nbActiviteTotal + nbDealer; } } return nbActiviteTotal; } /** * Logge les informations relatives � un module * * @param suiviModuleBean * L'objet qui repr�sente un module */ private void logModule(SuiviModuleBean suiviModuleBean, String fileName) { LoggerManager.getInstance().info( "Nom du fichier \t\t\t\t\t: " + fileName); LoggerManager.getInstance().info( "Num�ro du process \t\t\t\t: " + suiviModuleBean.getNumProcess()); LoggerManager.getInstance().info( "Code �tat du module \t\t\t\t: " + suiviModuleBean.getCodeEtatModule()); LoggerManager.getInstance().info( "Nombre de ligne ins�r�e \t\t: " + suiviModuleBean.getNbLigneInsere()); LoggerManager.getInstance().info( "Nombre d'enregistrement � traiter : " + suiviModuleBean.getNbEnrATraiter()); LoggerManager.getInstance().info( "Nombre d'enregistrement rejet� : " + suiviModuleBean.getNbEnrRejete()); LoggerManager.getInstance().info( "Nombre de ligne rejet�e \t\t: " + suiviModuleBean.getNbEnrRejete()); LoggerManager.getInstance() .info("/*********** FIN MODULE ***********/"); } /** * Logge les informations relatives � un process * * @param suiviProcessBean * L'objet qui repr�sente un process */ private void logProcess(SuiviProcessBean suiviProcessBean) { LoggerManager.getInstance().info( "Num�ro du process : " + suiviProcessBean.getNumProcess()); LoggerManager.getInstance().info( "Code �tat du process : " + suiviProcessBean.getCodeEtatProcess()); LoggerManager.getInstance().info( "Nombre de fichier � traiter : " + suiviProcessBean.getNbFichierATraiter()); LoggerManager.getInstance().info( "Nombre de fichier OK : " + suiviProcessBean.getNbFichierOk()); LoggerManager.getInstance().info( "Nombre de fichier rejet� : " + suiviProcessBean.getNbFichierRejet()); LoggerManager.getInstance().info( "/*********** FIN PROCESS ***********/"); } /** * Traitement d'une exception * * @param inpuFile * Le fichier en entr�e * @param rejectFile * Le nom du fichier de rejet chemin absolu + nom * @param ex * L'exception qui a �t� lev� */ private void treatException(File inputFile, String rejectFile, Exception ex) throws Exception { LoggerManager.getInstance().error(ex.getMessage()); File out = new File(rejectFile); FileUtils.copyFile(inputFile, out); inputFile.delete(); } /** * * @param xmlMessage * @throws BozException */ /* * private void validateMandatoryTags(TECHNICAL_HEADER xmlMessage) throws * BozException { * * int nbAct = xmlMessage.getACTIVITYCount(); for (int j = 0; j < nbAct; * j++) { * * if (xmlMessage.getPDV(j).getPAYS_ORIGINE() == null || * xmlMessage.getPDV(j).getPAYS_ORIGINE().trim().equals("")) { throw * BozExceptionFactory.getInstance().newException("PAYS_ORIGINE"); } * * if (xmlMessage.getPDV(j).getMARQUE_ORIGINE() == null || * xmlMessage.getPDV(j).getMARQUE_ORIGINE().trim().equals("")) { throw * BozExceptionFactory.getInstance().newException("MARQUE_ORIGINE"); } * * if (xmlMessage.getPDV(j).getID_PDV_RRDI() == null || * xmlMessage.getPDV(j).getID_PDV_RRDI().trim().equals("")) { throw * BozExceptionFactory.getInstance().newException("ID_PDV_RRDI"); } * * if (xmlMessage.getPDV(j).getNOM_COMMERCIAL() == null || * xmlMessage.getPDV(j).getNOM_COMMERCIAL().trim().equals("")) { throw * BozExceptionFactory.getInstance().newException("NOM_COMMERCIAL"); } * * if (xmlMessage.getPDV(j).getTYPE_PDV1() == null || * xmlMessage.getPDV(j).getTYPE_PDV1().trim().equals("")) { throw * BozExceptionFactory.getInstance().newException("TYPE_PDV1"); } * * if * (!xmlMessage.getPDV(j).getTYPE_PDV1().equals(BozConstants.BOZ_PDV_PLAQUE * )) { if (xmlMessage.getPDV(j).getACTIVITE() == null || * xmlMessage.getPDV(j).getACTIVITE().trim().equals("")) { throw * BozExceptionFactory.getInstance().newException("ACTIVITE"); } } * * if (xmlMessage.getPDV(j).getDATE_CREATION() == null || * xmlMessage.getPDV(j).getDATE_CREATION().trim().equals("")) { throw * BozExceptionFactory.getInstance().newException("DATE_CREATION"); } * * if * (xmlMessage.getPDV(j).getTYPE_PDV1().equals(BozConstants.BOZ_PDV_PLAQUE)) * { int nbContrat = xmlMessage.getPDV(j).getCONTRAT_PLAQUECount(); * * for (int k = 0; k < nbContrat; k++) { if * (xmlMessage.getPDV(j).getCONTRAT_PLAQUE(k).getID_CONTRAT_PLAQUE() == null * || * xmlMessage.getPDV(j).getCONTRAT_PLAQUE(k).getID_CONTRAT_PLAQUE().trim() * .equals("")) { throw * BozExceptionFactory.getInstance().newException("ID_CONTRAT_PLAQUE"); } * * if * (xmlMessage.getPDV(j).getCONTRAT_PLAQUE(k).getACTIVITE_CONTRAT_PLAQUE() * == null || * xmlMessage.getPDV(j).getCONTRAT_PLAQUE(k).getACTIVITE_CONTRAT_PLAQUE * ().trim().equals("")) { throw * BozExceptionFactory.getInstance().newException * ("ACTIVITE_CONTRAT_PLAQUE"); } * * if (xmlMessage.getPDV(j).getCONTRAT_PLAQUE(k).getDATE_CREATION_LIEN() == * null || * xmlMessage.getPDV(j).getCONTRAT_PLAQUE(k).getDATE_CREATION_LIEN(). * trim().equals("")) { throw * BozExceptionFactory.getInstance().newException("DATE_CREATION_LIEN"); } * * } } * * } * * } */ }
96b6c587647f4ca921dfde728ead26f8ac82c2dc
6ee6f6b053bed43a78f5a64b6bb9c3a935abfbd5
/src/main/resources/archetype-resources/src/main/java/__microserviceNameFolder__/config/__microserviceName__SwaggerConfiguration.java
8b1ab270d4749d4bc8b8b0041512a36d557db571
[]
no_license
Manilab2309/Microtemplate
cbce59328496e71f95cfa1dc1895e2b5148f9b72
56960509c90698f6dd79f3834d22d5dc590dcf6d
refs/heads/master
2020-05-01T00:09:46.039450
2019-04-09T16:17:28
2019-04-09T16:17:28
177,161,800
0
0
null
null
null
null
UTF-8
Java
false
false
2,216
java
/** * API SWAGGER 2 CONFIGURATION */ package ${package}.${microserviceNameFolder.replace('/','.')}.config; import java.util.Collections; import org.slf4j.LoggerFactory; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import com.google.common.base.Predicates; import org.slf4j.Logger; import springfox.documentation.builders.RequestHandlerSelectors; import springfox.documentation.service.ApiInfo; import springfox.documentation.service.Contact; import springfox.documentation.spi.DocumentationType; import springfox.documentation.spring.web.plugins.Docket; import springfox.documentation.swagger2.annotations.EnableSwagger2; /** * @author Ramón Cigüenza * */ @Configuration @EnableSwagger2 public class ${microserviceName}SwaggerConfiguration { // Logger private final Logger logger = LoggerFactory.getLogger(${microserviceName}SwaggerConfiguration.class); // Información API private static final String title = "API ${microserviceName}"; private static final String description = "API REST for Services ${microserviceName}"; private static final String version = "1.0"; private static final String termsOfServiceUrl = "Software Licence Swagger"; private static final String license = "@Copyright Ramón Cigüenza Fuster 2018"; private static final String licenseUrl = "https://swagger.io/"; // Configuración Personalizada del API Swagger @Bean public Docket api() { logger.debug("-- Application API EleccCore: Cargando Docket de preferencias API"); // Disable default API Controller methods return new Docket(DocumentationType.SWAGGER_2).select() .apis(Predicates.not(RequestHandlerSelectors.basePackage("org.springframework.boot"))).build() .apiInfo(apiInfo()); } private ApiInfo apiInfo() { logger.debug("-- Application API ${microserviceName}: Loading API info"); // Detalles del API a mostrar en la página de bienvenida de Swagger-UI // 2.0 ApiInfo apiInfo = new ApiInfo(title, description, version, termsOfServiceUrl, new Contact("Ramón Cigüenza Fuster", "https://swagger.io/", "[email protected]"), license, licenseUrl, Collections.emptyList()); return apiInfo; } }
[ "rcifuster@gmail" ]
rcifuster@gmail
3e757ff48b8e67f7dd28f7533c3396244c1e99af
fa52984fe23e6ebe86e5278f68dd9a8ccd545fa5
/czzZ_AnyQuant/Code/AQAS_Web/src/main/java/com/bigwork/controller/ATRController.java
95fede2a217d2ea35c04639d627852fc5188cab4
[]
no_license
czzz4/Se3_BigWork
2d55b61aa2bdeccf0d14ee0f4babd178059d56ee
97ac9dd0596ff2eabfbffff59e2137dc5f877461
refs/heads/master
2021-01-17T12:54:43.127763
2016-07-13T07:12:42
2016-07-13T07:12:42
59,571,893
0
1
null
null
null
null
UTF-8
Java
false
false
2,988
java
package com.bigwork.controller; import com.bigwork.bl.managementServiceImpl.ATR_Impl; import com.bigwork.bl_service.ATR_service; import com.bigwork.model.ATR3Value; import com.bigwork.model.ATRValue; import org.springframework.stereotype.Controller; 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 java.text.ParseException; import java.util.ArrayList; /** * Created by asus on 2016/5/31. */ @Controller public class ATRController { private ATR_service atr = new ATR_Impl(); @RequestMapping(value = "/ATRGraph", method = RequestMethod.GET) @ResponseBody public ArrayList<ATR3Value> getATRGraph(@RequestParam("id")String id, @RequestParam(value = "from", required = false)String from, @RequestParam(value = "to", required = false) String to){ if(from==null){ from = "2015-05-10"; } if(to==null){ to="2016-06-10"; } ArrayList<ATR3Value> result = new ArrayList<>(); ArrayList<ATRValue> atr1 = atr.getATRGraphValue(id, from, to , 6); ArrayList<ATRValue> atr2 = atr.getATRGraphValue(id, from, to , 26); ArrayList<ATRValue> atr3 = atr.getATRGraphValue(id, from, to , 65); // System.out.println(atr1.size() + " " + atr1.get(0).getDate() + " " + atr1.get(atr1.size()-1).getDate()); // System.out.println(atr2.size() + " " + atr2.get(0).getDate() + " " + atr2.get(atr2.size()-1).getDate()); // System.out.println(atr3.size() + " " + atr3.get(0).getDate() + " " + atr3.get(atr3.size()-1).getDate()); int size = atr1.size(); for(int i = 0; i< size; i++){ ATR3Value tmp = new ATR3Value(atr1.get(i).getDate(), atr1.get(i).getATR(), atr2.get(i).getATR(), atr3.get(i).getATR()); result.add(tmp); } return result; } @RequestMapping(value = "ATRSinDay", method = RequestMethod.GET) @ResponseBody public double getSingleATR(@RequestParam("id")String id, @RequestParam("day")int day, @RequestParam("to") String to){ try{ double result = atr.GetATR(id, day, to); return result; }catch (ParseException e){ return 0; } } // @RequestMapping(value = "ATRGraph", method = RequestMethod.GET) // @ResponseBody // public ArrayList<ATRValue> getSingleATR(/*@RequestParam("id")String id*/){ // //@RequestParam("id")String id, @RequestParam("from")String from, @RequestParam("to") String to, @RequestParam("day")int day){ // ArrayList<ATRValue> result = atr.getATRGraphValue("sz002644", "2015-10-11", "2016-05-01", 6); // return result; // } public static void main(String[] args) { ATRController atr = new ATRController(); atr.getATRGraph("sh300", "2015-05-10", "2016-06-01"); } }
ee641abca1ae2c3fc142d4ee9c546a1eb5d5d725
4477b91c94088554128c48314d0ada93c135f959
/Java-Basic/Extract Emails.java
160e957386cbe494281c5b345868366fc3816bda
[]
no_license
KaloyanDragiev/Software-University
32fa506f1fcc2122a336ba696e960ffee60ad27d
6f9bf1d289ed15a4ac3d0417d0ed03192ed50010
refs/heads/master
2020-04-30T22:13:18.459567
2019-03-25T22:47:49
2019-03-25T22:47:49
177,113,099
1
0
null
null
null
null
UTF-8
Java
false
false
479
java
package com.company; import java.util.Scanner; import java.util.regex.*; public class Main { public static void main(String[] args) { Scanner input = new Scanner(System.in); String regex = "([-._0-9a-zA-Z]+@)([a-zA-Z.-]+)[.]"; Pattern pattern = Pattern.compile(regex); Matcher matcher = pattern.matcher(input.nextLine()); while (matcher.find()) { System.out.println(matcher.group(1)+matcher.group(2)); } } }
762619653407ac67c825262b325afc5be9e8bc6e
2add986114ddfcd92501e2043d2a8fdf27394719
/src/chartadvancedpie/Container.java
612effa280954ec52761596703baabe5148c7996
[]
no_license
thegoodhen/Instrumentation-platform-GUI
28e180295a004ae521712c6bd3ef11ac23762fa5
4988b173293e6c1b8186a3db01d72efb052a1bc7
refs/heads/master
2020-07-09T22:51:15.591017
2017-05-13T08:11:03
2017-05-13T08:11:03
74,027,656
1
0
null
null
null
null
UTF-8
Java
false
false
2,162
java
/* * 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 chartadvancedpie; import java.util.ArrayList; import java.util.HashMap; /** *@deprecated * Deprecated class, related to the old way GUI was loaded from the connected * child module * @author thegoodhen */ public class Container { ArrayList<Container> containerList; HashMap<Integer, Variable> variableList; public HashMap<Integer, Variable> getVariableList() { return this.variableList; } public ArrayList<Variable> getVariableListRecursive() { ArrayList<Variable> returnList = new ArrayList<Variable>(); returnList.addAll(getVariableList().values()); for (Container c : containerList) { returnList.addAll(c.getVariableListRecursive()); } return returnList; } public ArrayList<Container> getContainerList() { return this.containerList; } public Container() { containerList = new ArrayList<>(); variableList = new HashMap<>(); } public void addContainer(Container c) { this.containerList.add(c); } public void addVariable(Variable v) { this.variableList.put(v.getNumber(), v); } public String shortDesc() { return "Unknown container"; } public String getVariablesString() { StringBuilder sb = new StringBuilder(); sb.append("Variables stored inside:\n"); for (Variable v : variableList.values()) { sb.append(v.getDesc()).append("\n"); } if (variableList.isEmpty()) { sb.append("(NONE)\n"); } return sb.toString(); } public String getContainersString() { StringBuilder sb = new StringBuilder(); sb.append("Containers stored inside:\n"); for (Container c : containerList) { sb.append(c.toString()).append("\n"); } if (containerList.isEmpty()) { sb.append("(NONE)\n"); } return sb.toString(); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(shortDesc()).append(" begin\n"); sb.append(getVariablesString()); sb.append(getContainersString()); sb.append(shortDesc()).append(" end\n"); return sb.toString(); } }
8868266813e2c3441261023f89357581de82c5c5
419e7d0850157d739b31bcdcc9cfe1a427205074
/adoph-test/src/main/java/com/adoph/test/design/pattern/chain/v2/Filter.java
7492baba49e8b99e6b253981e797e5876e69eaad
[]
no_license
SmithAdoph/AdophCloud
55cbd4cb21c18ab9e7e5a9cfa1f2fd932c5dc263
c2aedfb1b2a8c85d3b2a0fa5a70e4b457b1b529e
refs/heads/master
2022-09-15T10:21:29.699397
2022-09-12T04:38:35
2022-09-12T04:38:35
137,837,895
1
0
null
2022-09-12T04:09:38
2018-06-19T03:58:53
Java
UTF-8
Java
false
false
239
java
package com.adoph.test.design.pattern.chain.v2; /** * TODO * * @author Adoph * @version v1.0 * @since 2018/7/11 */ public interface Filter<T> { void doFilter(Request<T> request, Response<T> response, FilterChain filterChain); }
4569a52254249960905ae9f496b5eeb884718b43
7fbe4e40baedfdbafd1e8831eb92abf7307321dc
/Section18_UnitTestingBankAccountExample/src/com/company/Main.java
bfe905917281f8aa9f579cf9fe363aedbcff84ee
[]
no_license
ahowe442/Masterclass
c2ee1c29494189b83a852bc8298788e71467669a
bf52e624db14e513b470d94b56502b712b515cc5
refs/heads/master
2020-12-20T21:12:59.693207
2020-01-25T18:25:26
2020-01-25T18:25:26
236,211,271
0
0
null
null
null
null
UTF-8
Java
false
false
150
java
package com.company; public class Main { public static void main(String[] args) { System.out.println("The program is running"); } }
e9631b1ed0bfd37ae0e3a8cf2fd764ff2a93541d
0ed1f3e30eb8e2bd38c45d879a339a5536585235
/app/src/main/java/com/material/nereeducation/activity/gridlist/GridSectioned.java
885f093906abc465b428f749e68d883458aeb2b6
[]
no_license
imranhamzah/richpleasure_academy_std_dev
fefc45cbf7d125738a67ad9005c3f9cbd77d198f
179ace6d831f9d47acd3dccc569d4eff1f93cb02
refs/heads/master
2021-09-07T19:52:25.996684
2018-02-28T05:26:43
2018-02-28T05:26:43
115,767,571
0
0
null
null
null
null
UTF-8
Java
false
false
3,411
java
package com.material.nereeducation.activity.gridlist; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.StaggeredGridLayoutManager; import android.support.v7.widget.Toolbar; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.Toast; import com.material.nereeducation.R; import com.material.nereeducation.adapter.AdapterGridSectioned; import com.material.nereeducation.data.DataGenerator; import com.material.nereeducation.model.SectionImage; import java.util.ArrayList; import java.util.List; public class GridSectioned extends AppCompatActivity { private View parent_view; private RecyclerView recyclerView; private AdapterGridSectioned mAdapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_grid_sectioned); parent_view = findViewById(android.R.id.content); initToolbar(); initComponent(); } private void initToolbar() { Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); toolbar.setNavigationIcon(R.drawable.ic_menu); setSupportActionBar(toolbar); getSupportActionBar().setTitle("Sectioned"); getSupportActionBar().setDisplayHomeAsUpEnabled(true); } private void initComponent() { recyclerView = (RecyclerView) findViewById(R.id.recyclerView); recyclerView.setLayoutManager(new StaggeredGridLayoutManager(3, StaggeredGridLayoutManager.VERTICAL)); recyclerView.setHasFixedSize(true); List<Integer> items_img = DataGenerator.getNatureImages(this); items_img.addAll(DataGenerator.getNatureImages(this)); items_img.addAll(DataGenerator.getNatureImages(this)); items_img.addAll(DataGenerator.getNatureImages(this)); items_img.addAll(DataGenerator.getNatureImages(this)); List<SectionImage> items = new ArrayList<>(); for (Integer i : items_img) { items.add(new SectionImage(i, "IMG_" + i + ".jpg", false)); } int sect_count = 0; int sect_idx = 0; List<String> months = DataGenerator.getStringsMonth(this); for (int i = 0; i < items.size() / 10; i++) { items.add(sect_count, new SectionImage(-1, months.get(sect_idx), true)); sect_count = sect_count + 10; sect_idx++; } //set data and list adapter mAdapter = new AdapterGridSectioned(this, items); recyclerView.setAdapter(mAdapter); // on item list clicked mAdapter.setOnItemClickListener(new AdapterGridSectioned.OnItemClickListener() { @Override public void onItemClick(View view, SectionImage obj, int position) { } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.menu_search_setting, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { if (item.getItemId() == android.R.id.home) { finish(); } else { Toast.makeText(getApplicationContext(), item.getTitle(), Toast.LENGTH_SHORT).show(); } return super.onOptionsItemSelected(item); } }
a51817ea826c6930e4429e79c0b25aed79708820
d07f54caf1ddb892d9e797782a2239a2bd338dbd
/app/src/main/java/com/yunlin/xihai/user/elder/http/NetworkInterceptor.java
116eb1a8700fb3081a415ec715d36c99703fe9a0
[]
no_license
wanwantang0220/MVPRxJava2
3784fc14a3a1fddc55c9adc9df287461f2b2ec63
5d1ca991a7fbcaaed8b4d2a6bb3cafc74b92f03c
refs/heads/master
2020-05-03T00:47:21.557065
2019-03-29T02:46:54
2019-03-29T02:46:54
178,318,363
0
0
null
null
null
null
UTF-8
Java
false
false
1,550
java
package com.yunlin.xihai.user.elder.http; import com.yunlin.xihai.user.elder.app.App; import com.yunlin.xihai.user.elder.util.NetUtil; import java.io.IOException; import okhttp3.CacheControl; import okhttp3.Interceptor; import okhttp3.Request; import okhttp3.Response; public class NetworkInterceptor implements Interceptor { @Override public Response intercept(Chain chain) throws IOException { Request request = chain.request(); //无网络时强制使用缓存 if (!NetUtil.isConnected(App.getContext())) { request = request.newBuilder() .cacheControl(CacheControl.FORCE_CACHE) .build(); } Response response = chain.proceed(request); if (NetUtil.isConnected(App.getContext())) { // 有网络时,设置超时为0 int maxStale = 0; response.newBuilder() .header("Cache-Control", "public, max-age=" + maxStale) // 清除头信息,因为服务器如果不支持,会返回一些干扰信息,不清除下面无法生效 .removeHeader("Pragma") .build(); } else { // 无网络时,设置超时为3周 int maxStale = 60 * 60 * 24 * 21; response.newBuilder() .header("Cache-Control", "public, only-if-cached, max-stale=" + maxStale) .removeHeader("Pragma") .build(); } return response; } }
c06f8cd5ed1d458f0af2a9cde14f78e86097fd09
808035f3b3cd96dbf33df9b5d93a8657eb00be73
/src/main/java/com/example/spotify/modelRelatedArtist/Followers.java
8f33589ed3a4316b1dc8bdb9b38b719f851f3609
[]
no_license
SaadProgrammer/spotify
332c9b24277a486260365c54125b203e2092f02b
0fab2656d0d8b27c75501f8aef360a9929591c4d
refs/heads/master
2022-12-26T16:25:54.628330
2020-04-16T14:10:06
2020-04-16T14:10:06
255,925,668
0
0
null
null
null
null
UTF-8
Java
false
false
1,400
java
package com.example.spotify.modelRelatedArtist; import java.util.HashMap; import java.util.Map; import com.fasterxml.jackson.annotation.JsonAnyGetter; import com.fasterxml.jackson.annotation.JsonAnySetter; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonPropertyOrder; @JsonInclude(JsonInclude.Include.NON_NULL) @JsonPropertyOrder({ "href", "total" }) public class Followers { @JsonProperty("href") private Object href; @JsonProperty("total") private Integer total; @JsonIgnore private Map<String, Object> additionalProperties = new HashMap<String, Object>(); @JsonProperty("href") public Object getHref() { return href; } @JsonProperty("href") public void setHref(Object href) { this.href = href; } @JsonProperty("total") public Integer getTotal() { return total; } @JsonProperty("total") public void setTotal(Integer total) { this.total = total; } @JsonAnyGetter public Map<String, Object> getAdditionalProperties() { return this.additionalProperties; } @JsonAnySetter public void setAdditionalProperty(String name, Object value) { this.additionalProperties.put(name, value); } }
836c115f3491ab44b89aa22ac60a9b563cf4f021
90995efafd2fc9937ee32784d51022e0b8d4daf7
/src/SolutionApp/Dao/EmployeeDAO.java
399666ff666454cb9b3c39c6c3962c522e9fdcf0
[]
no_license
guptashivani/RestraProj
eeac572de1b9b1eb02effb017a0f521c927ee4bc
714ab4c3bda8d737b104b032edb44d7dc539597c
refs/heads/master
2020-05-18T17:20:51.404163
2015-08-17T07:38:25
2015-08-17T07:38:25
40,866,929
0
0
null
null
null
null
UTF-8
Java
false
false
9,984
java
package SolutionApp.Dao; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import SolutionApp.Exception.AppException; import SolutionApp.model.Auth; import SolutionApp.model.Employee; import SolutionApp.model.Record; import SolutionApp.model.Seating; import SolutionREST.Utils.DBUtils; /* * CREATE TABLE `emp_db`.`reservation` ( `name` VARCHAR(45) NULL , `table_id` INT NULL , `size` INT NULL , `email` VARCHAR(45) NULL , `phone` VARCHAR(45) NULL, `date` VARCHAR(45) NULL , `time` VARCHAR(45) NULL , `code` INT NOT NULL AUTO_INCREMENT , `status` VARCHAR(45) NULL, PRIMARY KEY (`code`) ); * */ public class EmployeeDAO { public List<Record> getAll()throws AppException { List<Record> resList=new ArrayList<Record>(); Connection con=DBUtils.connectToDB(); PreparedStatement ps=null; ResultSet rs=null; try { ps=con.prepareStatement("SELECT * from emp_db.reservation"); rs=ps.executeQuery(); //printing db rows while(rs.next()) { Record rec=new Record(); rec.setCode(rs.getInt("code")); rec.setDate(rs.getString("date")); rec.setEmail(rs.getString("email")); rec.setPhone(rs.getString("phone")); rec.setSize(rs.getInt("size")); rec.setTime(rs.getString("time")); rec.setName(rs.getString("name")); rec.setStatus(rs.getString("status")); rec.setTable_id(rs.getInt("table_id")); resList.add(rec); } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); throw new AppException("Error in fetching records from db",e.getCause()); } finally{ DBUtils.closeResources(ps, con, rs); } return resList; } public List<Seating> getTables()throws AppException { List<Seating> tabList=new ArrayList<Seating>(); Connection con=DBUtils.connectToDB(); PreparedStatement ps=null; ResultSet rs=null; try { ps=con.prepareStatement("SELECT * from emp_db.seating"); rs=ps.executeQuery(); //printing db rows while(rs.next()) { Seating rec=new Seating(); rec.setTable_id(rs.getInt("table_id")); rec.setSize(rs.getInt("size")); tabList.add(rec); } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); throw new AppException("Error in fetching records from db",e.getCause()); } finally{ DBUtils.closeResources(ps, con, rs); } return tabList; } public Record getReservation(int code)throws AppException { Record rec=new Record(); Connection con=DBUtils.connectToDB(); PreparedStatement ps=null; ResultSet rs=null; try { ps=con.prepareStatement("SELECT * from emp_db.reservation WHERE code=?"); ps.setInt(1,code); rs=ps.executeQuery(); //printing db rows if(rs.next()) { rec.setName(rs.getString("name")); rec.setCode(rs.getInt("code")); rec.setSize(rs.getInt("size")); rec.setDate(rs.getString("date")); rec.setEmail(rs.getString("email")); rec.setPhone(rs.getString("phone")); rec.setTime(rs.getString("time")); rec.setStatus(rs.getString("status")); //em.add(emp); } else{ throw new AppException("record with code"+code+" does not exist"); } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); throw new AppException("Error in fetching records from db",e.getCause()); } finally{ DBUtils.closeResources(ps, con, rs); } return rec; } //method to cancel an existing reservation public boolean cancelReservation(int code)throws AppException { //Employee emp=new Employee(); //Record rec=new Record(); Connection con=DBUtils.connectToDB(); PreparedStatement ps=null; ResultSet rs=null; try { ps=con.prepareStatement("DELETE FROM emp_db.reservation WHERE code=?"); ps.setInt(1,code); ps.executeUpdate(); //printing db rows } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); throw new AppException("Error in fetching records from db",e.getCause()); } finally{ DBUtils.closeResources(ps, con, rs); } return true; } //method to edit an existing reservation public boolean editReservation(Record rec)throws AppException { //Employee emp=new Employee(); //Record rec=new Record(); Connection con=DBUtils.connectToDB(); PreparedStatement ps=null; ResultSet rs=null; try { ps=con.prepareStatement("UPDATE emp_db.reservation SET name=?,size=?,email=?,phone=?,date=?,time=? WHERE code=?"); ps.setString(1,rec.getName()); ps.setInt(2, rec.getSize()); ps.setString(3, rec.getEmail()); ps.setString(4, rec.getPhone()); ps.setString(5, rec.getDate()); ps.setString(6, rec.getTime()); ps.executeUpdate(); //printing db rows } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); throw new AppException("Error in fetching records from db",e.getCause()); } finally{ DBUtils.closeResources(ps, con, rs); } return true; } public Record addRecord(Record rec)throws AppException { Connection con=DBUtils.connectToDB(); PreparedStatement ps1=null; ResultSet rs=null; PreparedStatement ps2=null; try { ps1=con.prepareStatement("SELECT table_id FROM emp_db.seating WHERE size=?"); ps1.setInt(1, rec.getSize()); rs=ps1.executeQuery(); System.out.println("first query executed:answer: "+rs.next()); System.out.println("first query executed:answer: "+rs.getInt("table_id")); int val=rs.getInt("table_id"); String s= "confirmed"; rec.setTable_id(val); ps2=con.prepareStatement("INSERT IGNORE INTO emp_db.reservation (name,table_id,size,email,phone,date,time,status) VALUES(?,?,?,?,?,?,?,?)",PreparedStatement.RETURN_GENERATED_KEYS); ps2.setString(1, rec.getName()); System.out.println("1"); ps2.setInt(2, val); System.out.println("2"); ps2.setInt(3, rec.getSize()); ps2.setString(4, rec.getEmail()); System.out.println("3"); ps2.setString(5, rec.getPhone()); System.out.println("4"); ps2.setString(6, rec.getDate()); System.out.println("5"); ps2.setString(7, rec.getTime()); ps2.setString(8,s); if(ps2.executeUpdate()!=0){ rs=ps2.getGeneratedKeys(); System.out.println("statement2 executed:reservation confirmed"); if(rs.next()) { rec.setCode(rs.getInt(1)); rec.setStatus(s); System.out.println("code is:"+rec.getCode()); System.out.println(rec.getStatus()); } } // else{ System.out.println("first query 2 executed:answer: "); ps2=con.prepareStatement("INSERT IGNORE INTO emp_db.reservation (name,table_id,size,email,phone,date,time,status) VALUES(?,?,?,?,?,?,?,?)",PreparedStatement.RETURN_GENERATED_KEYS); ps2.setString(1, rec.getName()); System.out.println("1"); ps2.setInt(2, rs.getInt("table_id")); System.out.println("2"); ps2.setInt(3, rec.getSize()); ps2.setString(4, rec.getEmail()); System.out.println("3"); ps2.setString(5, rec.getPhone()); System.out.println("4"); ps2.setString(6, rec.getDate()); System.out.println("5"); ps2.setString(7, rec.getTime()); ps2.setString(8, "waiting"); ps2.executeUpdate(); //System.out.println("statement executed"); rs=ps2.getGeneratedKeys(); if(rs.next()) { rec.setCode(rs.getInt(1)); rec.setStatus("waiting"); System.out.println(rec.getStatus()); } } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); throw new AppException("Error in inserting records in db",e.getCause()); } finally{ DBUtils.closeResources(ps1, con, rs); } return rec; } //method to confirm the reservation by admin //method to edit an existing reservation public boolean confirmReservation(Auth obj)throws AppException { //Employee emp=new Employee(); //Record rec=new Record(); Connection con=DBUtils.connectToDB(); PreparedStatement ps=null; ResultSet rs=null; try { System.out.println("trying to update sql query"); ps=con.prepareStatement("UPDATE emp_db.reservation SET table_id=?,status=? WHERE code=?"); ps.setInt(1,obj.getTable_id()); ps.setString(2, "waiting"); ps.setInt(3, obj.getCode()); ps.executeUpdate(); //printing db rows } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); throw new AppException("Error in fetching records from db",e.getCause()); } finally{ DBUtils.closeResources(ps, con, rs); } return true; } //method to authenticate admin /*public boolean authenticate(Auth obj)throws AppException{ Connection con=DBUtils.connectToDB(); PreparedStatement ps=null; ResultSet rs=null; try { ps=con.prepareStatement("SELECT * FROM emp_db.admin",PreparedStatement.RETURN_GENERATED_KEYS); ps.executeUpdate(); rs=ps.getGeneratedKeys(); if(rs.next()) { if(obj.getEmail().equals(rs.getString(1)) && obj.getPassword().equals(rs.getString(2))) return true; else return false; } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); throw new AppException("Error in authentication",e.getCause()); } finally{ DBUtils.closeResources(ps, con, rs); } return false; }*/ }
594b8d8a028e4420c441032e7623d3f07674bce4
6920f01f29996c70decf531259081d3c99cceb60
/Spring-05-JavaAnnotations-Component/src/main/java/com/cybertek/services/Java.java
d8276e823fc94693e34f5149341e12d90981697b
[]
no_license
letmedevelop-sam/jd-spring-sam
99dcced28486d40caab821b3f8f6fdca6a0aa1c0
da65c4b64fc85cd374142cd769ce2f18704ef8be
refs/heads/main
2023-06-11T07:20:59.638162
2021-07-06T08:17:30
2021-07-06T08:17:30
362,062,130
0
0
null
null
null
null
UTF-8
Java
false
false
283
java
package com.cybertek.services; import com.cybertek.interfaces.Course; import org.springframework.stereotype.Component; @Component public class Java implements Course { public void getTeachingHours() { System.out.println("Weekly Java Teaching Hours : 30"); } }
34a714b55deeee9b5042ca5304cc6e16fa9a30c9
54ca901b161509d231518b3819dbced2de4743cc
/src/com/timelock/abstractpattern/Loan.java
40fe31eab23c5050eb294ed2bb9fe740346cc338
[]
no_license
Tulasi-N/myworkspace
9cb43e7efb4389a63226abec3b1bd5c1b98c50f7
c466eb9f6fb843fd148689ff8415f0b209930a9b
refs/heads/master
2020-03-15T20:40:22.116031
2018-05-06T15:01:32
2018-05-06T15:01:32
132,338,455
0
0
null
null
null
null
UTF-8
Java
false
false
520
java
package com.timelock.abstractpattern; abstract class Loan{ protected double rate; abstract void getInterestRate(double rate); public void calculateLoanPayment(double loanamount, int years) { double EMI; int n; n=years*12; rate=rate/1200; EMI=((rate*Math.pow((1+rate),n))/((Math.pow((1+rate),n))-1))*loanamount; System.out.println("your monthly EMI is "+ EMI +" for the amount"+loanamount+" you have borrowed"); } }
a43a546324f22658ea6c71fc910e3421ada90ba0
2b7d13c832b22de99c57b09d54a6bd5ed659d705
/YTubeDownloader20131225/src/com/tools/tommydev/videofinder/themewin8/Windows8_bookmark_activity.java
3e0cbd6347c6854c50dce3360421804541688d41
[]
no_license
TomMyDevX/YTubeDownloader
92ab98924c531ed557efe8c4d4c1cf1601c023be
8fc1c3ff8c36d0b4f41159dff00ee0560c4ed351
refs/heads/master
2021-05-27T06:19:17.351361
2014-06-16T07:15:20
2014-06-16T07:15:20
null
0
0
null
null
null
null
UTF-8
Java
false
false
731
java
package com.tools.tommydev.videofinder.themewin8; import com.tools.tommydev.videofinder.R; import android.os.Bundle; import android.support.v4.app.FragmentActivity; public class Windows8_bookmark_activity extends FragmentActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_windows8__setting_); Windows8_bookmark_fm firstFragment = new Windows8_bookmark_fm(); firstFragment.setArguments(getIntent().getExtras()); getSupportFragmentManager().beginTransaction().replace(R.id.FrameLayout1, firstFragment).commit(); } @Override public void onBackPressed() { finish(); } }
9e14d43399b2e9c3b55dfeec4c64fade10ee2ec9
811db4fe9bd05fda0c4d3bf2b6be46383d398a46
/src/main/java/com/example/springbootshirodemo/controller/IndexController.java
e2e867d492cf67f331b9c4b501c158294ddce01e
[]
no_license
smallfatsheep/springboot-shiro-demo
1931a14cbda0c40c0e0b29635ef8a77e405e5c85
5b9f46323fe948d460e58c26c870cc7910feaef2
refs/heads/master
2022-12-06T01:48:59.323501
2020-08-26T03:13:15
2020-08-26T03:13:15
289,898,416
0
0
null
null
null
null
UTF-8
Java
false
false
722
java
package com.example.springbootshirodemo.controller; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import javax.servlet.http.HttpServletResponse; @Controller public class IndexController { @RequestMapping("/login") public String loginout(Model model){ model.addAttribute("msg","请登录,认证失败"); return "login"; } @RequestMapping("/") public String defaultPage(HttpServletResponse response){ return "forward:/login"; } @RequestMapping("/unauthorized") public String unauthorized(HttpServletResponse response){ return "unauthorized"; } }
8ba0d6a85c2a90ffa54e610ecc29d8dd86c92863
79ce03f9279b146d1f9a544d3dc0a1335dbdb4f7
/src/main/java/com/ruimin/oadsp/web/StuentController.java
5c9f64e38d3b62a4aa0993efa538ff4574c98c37
[]
no_license
huang0319/MyProject
cdf8020633c5f52801479ace72374779d830ac49
bc21b1ef6744d23814dc18b06aadc405396a9eaf
refs/heads/master
2021-08-19T19:36:01.481177
2017-11-27T08:19:48
2017-11-27T08:19:48
112,166,993
0
0
null
null
null
null
UTF-8
Java
false
false
2,684
java
package com.ruimin.oadsp.web; import java.util.List; import javax.annotation.Resource; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import com.github.pagehelper.PageHelper; import com.github.pagehelper.PageInfo; import com.ruimin.oadsp.core.Result; import com.ruimin.oadsp.core.ResultGenerator; import com.ruimin.oadsp.model.Student; import com.ruimin.oadsp.service.StudentService; import com.ruimin.oadsp.service.impl.StudentServiceImpl; @RequestMapping("/student") public class StuentController { @Resource private StudentService studentservice; @Resource private StudentServiceImpl studentserviceimpl; @PostMapping("/add") public Result add(Student student){ studentservice.save(student); return ResultGenerator.genSuccessResult(); } @PostMapping("/addstudent") public Result addstudent(Student student) { studentserviceimpl.addstudent(student); return ResultGenerator.genSuccessResult(); } @PostMapping("/delete") public Result delete(@RequestParam Integer graceid){ studentservice.deleteById(graceid); return ResultGenerator.genSuccessResult(); } @PostMapping("/update") public Result delete(Student student) { studentservice.update(student); return ResultGenerator.genSuccessResult(); } @PostMapping("/updatestudent") public Result updatestudent(Student student) { studentserviceimpl.updateStudent(student); return ResultGenerator.genSuccessResult(); } @PostMapping("/delectByGraceid") public Result delectByGraceid(int graceid) { studentserviceimpl.delectByGraceid(graceid); return ResultGenerator.genSuccessResult(); } @PostMapping("/detail") public Result detail(@RequestParam Integer graceid) { Student student=studentservice.findById(graceid); return ResultGenerator.genSuccessResult(); } @PostMapping("/list") public Result list(@RequestParam(defaultValue="0")Integer page, @RequestParam(defaultValue="0") Integer size) { PageHelper.startPage(page,size); List<Student> list=studentservice.findAll(); PageInfo pageInfo = new PageInfo(list); return ResultGenerator.genSuccessResult(pageInfo); } @PostMapping("/selectAllstudent") public Result selectAll(@RequestParam(defaultValue="0" )Integer page, @RequestParam(defaultValue="0 ") Integer size) { PageHelper.startPage(page,size); List<Student> list=studentserviceimpl.selectAllstudent(null); PageInfo pageInfo = new PageInfo(list); return ResultGenerator.genSuccessResult(pageInfo); } }
4b1ecaf105dcfe5772b3d187277226db799d20fe
478106dd8b16402cc17cc39b8d65f6cd4e445042
/l2junity-gameserver/src/main/java/org/l2junity/gameserver/network/client/send/ExPutIntensiveResultForVariationMake.java
5b58b7e54371e2502d3f207292b556143c41b503
[]
no_license
czekay22/L2JUnderGround
9f014cf87ddc10d7db97a2810cc5e49d74e26cdf
1597b28eab6ec4babbf333c11f6abbc1518b6393
refs/heads/master
2020-12-30T16:58:50.979574
2018-09-28T13:38:02
2018-09-28T13:38:02
91,043,466
1
0
null
null
null
null
UTF-8
Java
false
false
1,754
java
/* * Copyright (C) 2004-2015 L2J Unity * * This file is part of L2J Unity. * * L2J Unity 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. * * L2J Unity 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/>. */ package org.l2junity.gameserver.network.client.send; import org.l2junity.gameserver.network.client.OutgoingPackets; import org.l2junity.network.PacketWriter; public class ExPutIntensiveResultForVariationMake implements IClientOutgoingPacket { private final int _refinerItemObjId; private final int _lifestoneItemId; private final int _gemstoneItemId; private final int _gemstoneCount; private final int _unk2; public ExPutIntensiveResultForVariationMake(int refinerItemObjId, int lifeStoneId, int gemstoneItemId, int gemstoneCount) { _refinerItemObjId = refinerItemObjId; _lifestoneItemId = lifeStoneId; _gemstoneItemId = gemstoneItemId; _gemstoneCount = gemstoneCount; _unk2 = 1; } @Override public boolean write(PacketWriter packet) { OutgoingPackets.EX_PUT_INTENSIVE_RESULT_FOR_VARIATION_MAKE.writeId(packet); packet.writeD(_refinerItemObjId); packet.writeD(_lifestoneItemId); packet.writeD(_gemstoneItemId); packet.writeQ(_gemstoneCount); packet.writeD(_unk2); return true; } }
4085eed81c929ef05a170d8197aa8def2a93f0e6
3c753ab1cad59878e45d773d41db02aab7d72a58
/src/main/java/com/lanou/mapper/AdminRoleMapper.java
91d1e91c4407335ae269855c2e3cc8bb4dbd6a95
[]
no_license
dadaxiaozhang/SSMNetCloud
829e3bd7082c53f43e028a923e0997bb94e13bfa
a3b5528ca5def1470ee82cdb66e489df009c033d
refs/heads/master
2021-09-01T13:01:48.211325
2017-12-27T04:40:54
2017-12-27T04:40:54
113,397,647
5
0
null
null
null
null
UTF-8
Java
false
false
212
java
package com.lanou.mapper; import com.lanou.bean.AdminRole; public interface AdminRoleMapper { int insert(AdminRole record); int insertSelective(AdminRole record); int delAR(AdminRole adminRole); }
a49a25107b323bbe49f3e5001de4fdeaaed4ab8d
eb8892b8496d2ec19eadc6608d591dc3faa690ef
/src/main/java/com/marta/springernaturetest/strategies/RectangleUpdateAction.java
007de10613886fda0f225b627fb94cb7aa8cf335
[]
no_license
martika810/springer-test
ddacc1e8c705501b57eba41e8f206e39bd932056
9125890a81d04e52f79c74ebcb0edd9a788ccc55
refs/heads/master
2020-06-27T19:16:52.026588
2016-09-11T22:36:32
2016-09-11T22:36:32
67,814,745
0
0
null
null
null
null
UTF-8
Java
false
false
527
java
package com.marta.springernaturetest.strategies; import com.marta.springernaturetest.domainbeans.Arguments; import com.marta.springernaturetest.domainbeans.CanvasImpl; import com.marta.springernaturetest.domainbeans.PairPointArguments; public class RectangleUpdateAction implements Action{ @Override public void execute(Arguments arguments) { PairPointArguments rectangleArguments = (PairPointArguments)arguments; CanvasImpl.getInstance().addRectangule(rectangleArguments); CanvasImpl.getInstance().display(); } }
add0eb7d21f50696f1f7b3002ee9ea873f9b3b50
d11ade5355949e3e6c54ffa87fbd861279662b90
/application/src/com/v2soft/rssdemo/providers/FeedDatabaseHelper.java
b90315f73d2929ddb05b18b5d217c0b16cb41936
[]
no_license
vshcryabets/AndroidRSSDemo
aad7f41c7e68e2ab23dcaf0dfd721da70cc4c58c
8f0d8ec6b13d014f643e6883e493c197d9e303d2
refs/heads/master
2021-01-19T18:35:29.976915
2013-09-05T13:19:59
2013-09-05T13:19:59
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,966
java
package com.v2soft.rssdemo.providers; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.util.Log; import com.v2soft.rssdemo.domains.FeedItem; /** * Local data base open helper. * @author Vladimir Shcryabets <[email protected]> * */ public class FeedDatabaseHelper extends SQLiteOpenHelper { private static final String LOG_TAG = FeedDatabaseHelper.class.getSimpleName(); private static final String DATABASE_NAME = "rssfeed.sqlite"; private static final int DATABASE_VERSION = 4; // Database table public static final String TABLE_FEED_ITEMS = "feeditems"; // Database creation SQL statement private static final String DATABASE_CREATE = "create table " + TABLE_FEED_ITEMS + "("+FeedItem.FIELD_ID+" integer primary key autoincrement, " + FeedItem.FIELD_AUTHOR + " text not null, " + FeedItem.FIELD_DESCRIPTION + " text not null, " + FeedItem.FIELD_FULLTEXT + " text, " + FeedItem.FIELD_IMAGE + " text, " + FeedItem.FIELD_LINK + " text, " + FeedItem.FIELD_TITLE + " text not null, " + FeedItem.FIELD_PUBLISH_DATE + " integer not null, " + "UNIQUE ("+FeedItem.FIELD_PUBLISH_DATE+", "+FeedItem.FIELD_TITLE+")" + ");"; public FeedDatabaseHelper(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); } @Override public void onCreate(SQLiteDatabase db) { db.execSQL(DATABASE_CREATE); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { Log.w(LOG_TAG, "Upgrading database from version " + oldVersion + " to " + newVersion + ", which will destroy all old data"); db.execSQL("DROP TABLE IF EXISTS " + TABLE_FEED_ITEMS); onCreate(db); } }
5cbd253ca01cfc90e3f5b267248ce68c74fcaca3
ed9a57343702e58866b38af6107dbc342fdba7e2
/doitjava/src/chapter10/RoundRobin.java
6e4411c0928e9729a37329f388d18ffaf54c020c
[]
no_license
namwookyung/doitjava
354413809bed61ce2074ad0d2cfb0589c981ae6b
4c2c95dc7d297d44875d6a86a112a63014f07e33
refs/heads/master
2022-12-25T08:39:34.987652
2020-10-06T07:04:33
2020-10-06T07:04:33
286,651,694
0
0
null
null
null
null
UHC
Java
false
false
336
java
package chapter10; public class RoundRobin implements Scheduler { @Override public void getNextCall() { System.out.println("상담 전화를 순서대로 대기열에서 가져옵니다"); } @Override public void sendCallToAgent() { System.out.println("다음 순서 상담원에게 배분합니다."); } }
913d0186f67e535637418e592c3d99c51a2071e2
f364f2469132301dca52f3707ddc0cf3af575081
/src/test/java/com/cg/starter/controller/ControllerTest.java
8b21da25e68e37db909ff5145a1d24716c7b205a
[]
no_license
rahul619302/jenkins-springboot-test
3d8331fb164aa97922bd86575ba799319e369685
488a07264d5871dc3b59df61dcdde0a0771ce67a
refs/heads/master
2020-04-07T08:33:01.847767
2018-11-21T08:35:37
2018-11-21T08:35:37
158,218,684
0
0
null
null
null
null
UTF-8
Java
false
false
1,209
java
package com.cg.starter.controller; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.http.MediaType; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import org.springframework.test.web.servlet.setup.MockMvcBuilders; @ExtendWith(MockitoExtension.class) class ControllerTest { @InjectMocks private Controller controller; private MockMvc mockMvc; /** * Before run any test setup */ @BeforeEach public void setUp() { mockMvc = MockMvcBuilders.standaloneSetup(controller).build(); } /** * Junit Test helloworld method of controller * * @throws Exception */ @Test public void helloWorldTest() throws Exception { String response = mockMvc.perform(MockMvcRequestBuilders .get("/") .accept(MediaType.APPLICATION_JSON)) .andReturn() .getResponse() .getContentAsString(); } }
e3401953d2c72e94512bd2a8ef537d018d88fcf3
4995ebf5ab849387277ebcc222ed0e2d26021bc3
/nitrite/src/main/java/org/dizitart/no2/index/fulltext/languages/Polish.java
8d89591310b68011de7670500f4bb4db478e648e
[ "Apache-2.0" ]
permissive
nitrite/nitrite-java
7041749949a2a4c14ef6d4563ae6d37977d52b9c
6d0476c5fc028258cf2ee2508fdab3231f8f26be
refs/heads/main
2023-08-29T03:49:33.521159
2023-08-24T04:13:53
2023-08-24T04:13:53
88,777,477
350
33
Apache-2.0
2023-09-14T16:49:36
2017-04-19T18:26:54
Java
UTF-8
Java
false
false
8,443
java
/* * Copyright (c) 2017-2020. Nitrite author or authors. * * 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 org.dizitart.no2.index.fulltext.languages; import org.dizitart.no2.index.fulltext.Language; import java.util.Arrays; import java.util.HashSet; import java.util.Set; /** * Polish stop words * * @author Anindya Chatterjee * @since 2.1.0 */ public class Polish implements Language { @Override public Set<String> stopWords() { return new HashSet<>(Arrays.asList( "a", "aby", "ach", "acz", "aczkolwiek", "aj", "albo", "ale", "ależ", "ani", "aż", "bardziej", "bardzo", "bez", "bo", "bowiem", "by", "byli", "bym", "bynajmniej", "byä‡", "być", "był", "była", "było", "były", "będzie", "będą", "cali", "cała", "cały", "chce", "choć", "ci", "ciebie", "ciä™", "cię", "co", "cokolwiek", "coraz", "coś", "czasami", "czasem", "czemu", "czy", "czyli", "często", "daleko", "dla", "dlaczego", "dlatego", "do", "dobrze", "dokä…d", "dokąd", "doå›ä‡", "dość", "dr", "duå¼o", "dużo", "dwa", "dwaj", "dwie", "dwoje", "dzisiaj", "dziå›", "dziś", "gdy", "gdyby", "gdyż", "gdzie", "gdziekolwiek", "gdzieś", "go", "godz", "hab", "i", "ich", "ii", "iii", "ile", "im", "inna", "inne", "inny", "innych", "inż", "iv", "ix", "iż", "ja", "jak", "jakaś", "jakby", "jaki", "jakichś", "jakie", "jakiś", "jakiż", "jakkolwiek", "jako", "jakoś", "je", "jeden", "jedna", "jednak", "jednakże", "jedno", "jednym", "jedynie", "jego", "jej", "jemu", "jest", "jestem", "jeszcze", "jeå¼eli", "jeå›li", "jeśli", "jeżeli", "juå¼", "już", "jä…", "ją", "kaå¼dy", "każdy", "kiedy", "kierunku", "kilka", "kilku", "kimś", "kto", "ktokolwiek", "ktoś", "która", "które", "którego", "której", "który", "których", "którym", "którzy", "ku", "lat", "lecz", "lub", "ma", "majä…", "mają", "mam", "mamy", "mało", "mgr", "mi", "miał", "mimo", "między", "mnie", "mnä…", "mną", "mogą", "moi", "moim", "moja", "moje", "moå¼e", "może", "możliwe", "można", "mu", "musi", "my", "mã³j", "mój", "na", "nad", "nam", "nami", "nas", "nasi", "nasz", "nasza", "nasze", "naszego", "naszych", "natomiast", "natychmiast", "nawet", "nic", "nich", "nie", "niech", "niego", "niej", "niemu", "nigdy", "nim", "nimi", "niä…", "niå¼", "nią", "niż", "no", "nowe", "np", "nr", "o", "o.o.", "obok", "od", "ok", "okoå‚o", "około", "on", "ona", "one", "oni", "ono", "oraz", "oto", "owszem", "pan", "pana", "pani", "pl", "po", "pod", "podczas", "pomimo", "ponad", "poniewaå¼", "ponieważ", "powinien", "powinna", "powinni", "powinno", "poza", "prawie", "prof", "przecież", "przed", "przede", "przedtem", "przez", "przy", "raz", "razie", "roku", "również", "sam", "sama", "siä™", "się", "skä…d", "skąd", "sobie", "sobą", "sposób", "swoje", "sä…", "są", "ta", "tak", "taka", "taki", "takich", "takie", "także", "tam", "te", "tego", "tej", "tel", "temu", "ten", "teraz", "też", "to", "tobie", "tobä…", "tobą", "toteż", "totobą", "trzeba", "tu", "tutaj", "twoi", "twoim", "twoja", "twoje", "twym", "twã³j", "twój", "ty", "tych", "tylko", "tym", "tys", "tzw", "tę", "u", "ul", "vi", "vii", "viii", "vol", "w", "wam", "wami", "was", "wasi", "wasz", "wasza", "wasze", "we", "według", "wie", "wiele", "wielu", "wiä™c", "więc", "więcej", "wszyscy", "wszystkich", "wszystkie", "wszystkim", "wszystko", "wtedy", "www", "wy", "właśnie", "wśród", "xi", "xii", "xiii", "xiv", "xv", "z", "za", "zapewne", "zawsze", "zaś", "ze", "zeznowu", "znowu", "znów", "został", "zł", "å¼aden", "å¼e", "żaden", "żadna", "żadne", "żadnych", "że", "żeby" )); } }
fb38fecb483cb762622e936416296a1c99660153
cbb75ebbee3fb80a5e5ad842b7a4bb4a5a1ec5f5
/com/jd/fridge/bean/requestBody/GetMessages.java
d0fb0c0c78f73106cd2ac15b0337a3b13b1ef795
[]
no_license
killbus/jd_decompile
9cc676b4be9c0415b895e4c0cf1823e0a119dcef
50c521ce6a2c71c37696e5c131ec2e03661417cc
refs/heads/master
2022-01-13T03:27:02.492579
2018-05-14T11:21:30
2018-05-14T11:21:30
null
0
0
null
null
null
null
UTF-8
Java
false
false
376
java
package com.jd.fridge.bean.requestBody; /* compiled from: TbsSdkJava */ public class GetMessages { private int count; private long feed_id; private String pin; private int start_index; public GetMessages(String str, long j, int i, int i2) { this.pin = str; this.feed_id = j; this.start_index = i; this.count = i2; } }
b6d241c3a2d52670d8b6c9e973e3a86487059e44
323566fb716af05a65c1a28a0113f88840f3bc2f
/src/inheritance/Child.java
9c104949e4a9a6c0a25c25f5bd46332de4c7c429
[]
no_license
myae3080/java-practice
fba172f9c144563d2ff44a3b533045bf8b15e5e2
401c7876cc3aba413778c8cbb677944a26eeae78
refs/heads/master
2023-07-02T06:03:22.605990
2021-08-02T08:11:50
2021-08-02T08:11:50
370,532,095
0
0
null
null
null
null
UTF-8
Java
false
false
379
java
package inheritance; public class Child extends Parent{ private int privateNum; public String nameCard; public Child(String name) { super(name); // cannot directly access to private member variable of Parent class // super.name -> compile error } public void setNameCard(String nameCard) { this.nameCard = nameCard; } }
c320e73ea02994d8e2b4786a4e89754071b51ed2
bc23ce3b40a99c6281b8970d978d7c6b9a1489e2
/eco/src/main/java/im/grusis/mkb/eco/model/ProductionCriteria.java
46defa347949e55f544daa350a32f2961c1364c7
[]
no_license
freelunchcap/mkb
ec6ee80a5c431242c74d4e246d5be20cd743c2b3
20d5fdc63603f7e84d1ad6ae26c7dbff735e23ce
refs/heads/master
2023-01-07T14:36:15.087898
2022-12-26T02:39:11
2022-12-26T02:39:11
14,970,700
0
0
null
null
null
null
UTF-8
Java
false
false
848
java
package im.grusis.mkb.eco.model; import java.util.Map; /** * User: Mothership * Date: 13-6-27 * Time: 上午12:32 */ public class ProductionCriteria extends Criteria { private Map<Integer, Integer> cardCount; public ProductionCriteria() { } public ProductionCriteria(Map<Integer, Integer> cardCount) { this.cardCount = cardCount; } public Map<Integer, Integer> getCardCount() { return cardCount; } public void setCardCount(Map<Integer, Integer> cardCount) { this.cardCount = cardCount; } @Override public boolean equals(Object o) { if(this == o) return true; if(!(o instanceof ProductionCriteria)) return false; ProductionCriteria that = (ProductionCriteria)o; return cardCount.equals(that.cardCount); } @Override public int hashCode() { return cardCount.hashCode(); } }
456ba5b0be0aa149f9ca7ea09e824e05e4fb5fb1
a7fcf4966bf2d5ac9e544e218b697057d5885c71
/app/src/main/java/com/gemalto/assignment/db/Converters.java
ba0164be337d400159e2ff5544736206de7e0c76
[ "MIT" ]
permissive
jacksondeng/assignment
1feab4cefe6b6dc1044cbd18cda5beac1bb33397
489f9f5f0368c6627d4e551d2fa6cd93fd8e317f
refs/heads/master
2020-04-11T20:25:06.593687
2018-12-17T04:24:07
2018-12-17T04:24:07
162,070,112
0
0
null
null
null
null
UTF-8
Java
false
false
1,778
java
package com.gemalto.assignment.db; import android.arch.persistence.room.TypeConverter; import com.gemalto.assignment.data.Dob; import com.gemalto.assignment.data.Info; import com.gemalto.assignment.data.Picture; import com.gemalto.assignment.data.Username; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import java.lang.reflect.Type; /** * Created by jacksondeng on 15/12/18. */ public class Converters { @TypeConverter public static Username stringtoUsername(String username) { Type type = new TypeToken<Username>(){}.getType(); return new Gson().fromJson(username,type); } @TypeConverter public static String UsernameToString(Username username) { Gson gson = new Gson(); return gson.toJson(username); } @TypeConverter public static Dob stringToDob(String dob){ Type type = new TypeToken<Dob>(){}.getType(); return new Gson().fromJson(dob,type); } @TypeConverter public static String DobToString(Dob dob){ Gson gson = new Gson(); return gson.toJson(dob); } @TypeConverter public static Info stringToInfo(String info){ Type type = new TypeToken<Info>(){}.getType(); return new Gson().fromJson(info,type); } @TypeConverter public static String InfoToString(Info info){ Gson gson = new Gson(); return gson.toJson(info); } @TypeConverter public static Picture stringToPicture(String picture){ Type type = new TypeToken<Picture>(){}.getType(); return new Gson().fromJson(picture,type); } @TypeConverter public static String ProfilePicToString(Picture picture){ Gson gson = new Gson(); return gson.toJson(picture); } }
eb48ae333ad23c98288879c0e2a36dc85b523ab9
b32306ef07caa5375b7b77aac02aae82bf89bfcf
/app/src/main/java/com/bubenheimer/bizsearch/rest/model/result/PlacesLocation.java
3688af41ad8d8422ba8e324651597fb147fd56fb
[]
no_license
bubenheimer/bizsearch
36cf7b25aa968d34f891abb2fd656c20906fe680
4b504303de359653a559af87ef0c7878bc044527
refs/heads/master
2021-01-13T12:50:15.175909
2017-10-19T16:00:02
2017-10-19T16:00:02
69,912,434
0
0
null
null
null
null
UTF-8
Java
false
false
332
java
/* * Copyright (c) 2015-2016 Uli Bubenheimer. All rights reserved. */ package com.bubenheimer.bizsearch.rest.model.result; import com.google.api.client.util.Key; /** * Places API JSON POJO for Google HTTP client parsing */ public final class PlacesLocation { @Key public Double lat; @Key public Double lng; }
726a5f29723eaa426468629873030abab4f08e42
0320081f85b30a11144946be26159a49d58365ae
/My_creately/src/UMLObject/UMLDataAbstract.java
85b21fd291922357a3be291e120a0f501d375a19
[]
no_license
VladCostin/MyCreately
a1d7ed5ce708292e6f3908f9b3868b8fbaa027d3
5d2dec501ff981a2497a3edba49d632e34ece6f6
refs/heads/master
2020-05-29T13:17:34.099875
2014-11-16T03:26:49
2014-11-16T03:26:49
null
0
0
null
null
null
null
UTF-8
Java
false
false
554
java
package UMLObject; public abstract class UMLDataAbstract implements UMLDataInterface{ /** * where the object starts, coordonate ox */ int m_xStart; /** * where the object starts, coordonate oy */ int m_yStart; public boolean isSelected(int mouse_x, int mouse_y) { return false; } public int getM_xStart() { return m_xStart; } public void setM_xStart(int m_xStart) { this.m_xStart = m_xStart; } public int getM_yStart() { return m_yStart; } public void setM_yStart(int m_yStart) { this.m_yStart = m_yStart; } }
[ "vlad.costin_h" ]
vlad.costin_h
96a6ab0fc4c7627b11994e01dfbdaa7220935777
d4f2f31ca4c143200d1f5c81c6fb6e3583f477a2
/ca-gateway/scep-client/src/test/java/org/xipki/scep/serveremulator/RaEmulator.java
c709f6cda40f47e4c308bd43c954432758e2eb56
[ "Apache-2.0" ]
permissive
xipki/xipki
63b2f5074a3afc14ca24c33a716101743822558c
322c27ff87c31f8f717b274d961e429d485525b3
refs/heads/master
2023-09-03T09:39:08.247923
2023-08-31T20:45:22
2023-08-31T20:45:22
18,249,859
481
142
Apache-2.0
2023-09-08T21:22:41
2014-03-29T20:16:04
Java
UTF-8
Java
false
false
652
java
// Copyright (c) 2013-2023 xipki. All rights reserved. // License Apache License 2.0 package org.xipki.scep.serveremulator; import org.xipki.security.X509Cert; import org.xipki.util.Args; import java.security.PrivateKey; /** * RA emulator. * * @author Lijun Liao (xipki) */ public class RaEmulator { private final PrivateKey raKey; private final X509Cert raCert; public RaEmulator(PrivateKey raKey, X509Cert raCert) { this.raKey = Args.notNull(raKey, "raKey"); this.raCert = Args.notNull(raCert, "raCert"); } public PrivateKey getRaKey() { return raKey; } public X509Cert getRaCert() { return raCert; } }
6184b8e09846536e25b48a8364c9e7c7bb38e940
9cd59689fefb92454ad858f2d0d6a29ee5c20f4c
/easy/common/src/androidTest/java/com/easy/common/date/DateUtilsTest.java
0af717e00ee22891758c391d3232ff0b73db7274
[ "Apache-2.0" ]
permissive
sb3h/easy
49b1cd21b34862361f8ee569f6f4d795fa4b59c9
2c3eb046af5e27e55d27999f2c13b7852081ad54
refs/heads/master
2021-01-18T08:17:06.993360
2016-08-03T08:41:05
2016-08-03T08:41:05
null
0
0
null
null
null
null
UTF-8
Java
false
false
4,500
java
package com.easy.common.date; import android.test.AndroidTestCase; import com.easy.common.LogCatUtils; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; public class DateUtilsTest extends AndroidTestCase { private static final String LOG_CLASS_NAME = "【DateUtilsTest】"; public void testGetAgeByBirthday() { String time1 = "2010-11-20"; String time2 = "2010/01/10"; String time3 = "2010-07-04 12:10"; String time4 = "2010~10~11"; LogCatUtils.log(LOG_CLASS_NAME + "(testGetAgeByBirthday)" + String.valueOf(DateUtils.getAgeByBirthday(time1))); LogCatUtils.log(LOG_CLASS_NAME + "(testGetAgeByBirthday)" + String.valueOf(DateUtils.getAgeByBirthday(time2))); LogCatUtils.log(LOG_CLASS_NAME + "(testGetAgeByBirthday)" + String.valueOf(DateUtils.getAgeByBirthday(time3))); assertEquals(-1, DateUtils.getAgeByBirthday(time4)); } public void testGetShortDateFormat() { String time1 = "2016-06-30 11:20"; String time2 = "2015/01/22 10:31"; long time3 = new Date().getTime(); String time4 = "2013-10-11"; LogCatUtils.log(LOG_CLASS_NAME + "(testGetShortDateFormat)" + DateUtils.getShortDateFormat(time1)); LogCatUtils.log(LOG_CLASS_NAME + "(testGetShortDateFormat)" + DateUtils.getShortDateFormat(time2)); LogCatUtils.log(LOG_CLASS_NAME + "(testGetShortDateFormat)" + DateUtils.getShortDateFormat(time3)); assertNull("解析是会出错的", DateUtils.getShortDateFormat(time4)); } public void testParseTime() { // parseTime和getSimpleDateFormat配套使用才正确 Object parseResult1 = DateUtils.parseTime("2010-11-21 10:08", "yyyy-MM-dd", null); Object parseResult2 = DateUtils.parseTime("2010-11-21 10:08", "yyyy-MM-dd HH:mm", null); Object parseResult3 = DateUtils.parseTime("2010-11-21", "yyyy-MM-dd HH:mm", null); LogCatUtils.log(LOG_CLASS_NAME + "(testParseTime)" + parseResult1.toString()); LogCatUtils.log(LOG_CLASS_NAME + "(testParseTime)" + parseResult2.toString()); assertNull("解析是会出错的", parseResult3); Date date = new Date("2010/11/21 10:08"); LogCatUtils.log(LOG_CLASS_NAME + "(testParseTime)" + date.toString()); LogCatUtils.log(LOG_CLASS_NAME + "(testParseTime)" + DateUtils.getSimpleDateFormat("yyyy-MM-dd HH:mm").format(date)); LogCatUtils.log(LOG_CLASS_NAME + "(testParseTime)" + DateUtils.getSimpleDateFormat("yyyy-MM-dd HH:mm").format((Date) parseResult2)); LogCatUtils.log(LOG_CLASS_NAME + "(testParseTime)" + String.valueOf(date.getTime())); LogCatUtils.log(LOG_CLASS_NAME + "(testParseTime)" + String.valueOf(((Date) parseResult2).getTime())); } public void testGetSimpleDateFormat() { String format = "yyyy-MM-dd HH:mm"; Date date = new Date(); SimpleDateFormat dateFormat1 = new SimpleDateFormat(format); SimpleDateFormat dateFormat2 = DateUtils.getSimpleDateFormat(format); LogCatUtils.log(LOG_CLASS_NAME + "(testGetSimpleDateFormat)" + dateFormat1.format(date)); LogCatUtils.log(LOG_CLASS_NAME + "(testGetSimpleDateFormat)" + dateFormat2.format(date)); } public void testGetCalendar() { // Calendar calendar = Calendar.getInstance(); Calendar calendar = DateUtils.getCalendar(); calendar.setTime(new Date()); int year = calendar.get(Calendar.YEAR); int month = calendar.get(Calendar.MONTH) + 1; int dayOfMonth = calendar.get(Calendar.DAY_OF_MONTH); int hourOfDay = calendar.get(Calendar.HOUR_OF_DAY); int minute = calendar.get(Calendar.MINUTE); LogCatUtils.log(LOG_CLASS_NAME + "(testGetCalendar)" + year + "-" + month + "-" + dayOfMonth + " " + hourOfDay + ":" + minute); } public void testIsLeapYear() { int year1 = 2010; int year2 = 2004; LogCatUtils.log(LOG_CLASS_NAME + "(testIsLeapYear)" + DateUtils.isLeapYear(year1)); LogCatUtils.log(LOG_CLASS_NAME + "(testIsLeapYear)" + DateUtils.isLeapYear(year2)); } }
ea8436d7829ff9513a1bacbd5b6f73d99e564349
1ff65599329bc3958cdb1f356a31fbf14a16ae56
/src/com/demo/HeadLessBrowser.java
1a1e010c2bf1803d2b2d6159ed55acd3e7e83b83
[]
no_license
shilpareddy92/DemoProject
6eb3dc7e34ef585b378cd25933ce6c120baf2866
9f63ddf949737dcae7a5c0ae5ddd2e3a67a1db22
refs/heads/master
2020-06-12T13:12:24.759497
2019-10-04T10:26:49
2019-10-04T10:26:49
194,309,926
0
0
null
null
null
null
UTF-8
Java
false
false
956
java
package com.demo; import java.util.concurrent.TimeUnit; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.htmlunit.HtmlUnitDriver; //////NOT SUITABLE FOR MOUSEMOVEMENT////////////// //////////HEADLESS AND GHOST DRIVER///////////// /////////VERT FAST//// public class HeadLessBrowser { public static void main(String[] args) { WebDriver driver = new HtmlUnitDriver(); driver.get("https://www.facebook.com/"); System.out.println(driver.getCurrentUrl()); System.out.println(driver.getTitle()); driver.manage().window().maximize(); driver.manage().deleteAllCookies(); driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); driver.findElement(By.name("email")).sendKeys("shilpa"); driver.findElement(By.name("pass")).sendKeys("reddy"); System.out.println(driver.getCurrentUrl()); System.out.println(driver.getTitle()); } }
a636803999c75184beaaf9dfda42bc9968bae400
6ff346b4086ecdb77dfead7e26a0a951b4dc3ef3
/core/src/org/xendra/controls/MessageServerDialog.java
a5ff3024b36401a3d8b7718eab7f053064a3a486
[]
no_license
xapiens/Xendra
02ce123adb3e986325431f06b710b9b5c7c8aadf
b63d72d2319eca3f1c6cc67d05fac29ad8f6ef9a
refs/heads/master
2023-05-25T11:23:05.879161
2023-05-23T04:27:12
2023-05-23T04:27:12
101,092,524
0
5
null
null
null
null
UTF-8
Java
false
false
32,659
java
package org.xendra.controls; import java.awt.BorderLayout; import java.awt.GridLayout; import java.awt.Insets; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import java.io.ByteArrayInputStream; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import javax.imageio.ImageIO; import javax.swing.AbstractAction; import javax.swing.BorderFactory; import javax.swing.DefaultCellEditor; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JComponent; import javax.swing.JDialog; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.KeyStroke; import javax.swing.SwingConstants; import javax.swing.border.EmptyBorder; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; import okhttp3.FormBody; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.RequestBody; import okhttp3.Response; import org.columba.core.base.SwingWorker; import org.columba.core.gui.base.ButtonWithMnemonic; import org.columba.core.gui.base.SingleSideEtchedBorder; import org.columba.core.resourceloader.GlobalResourceLoader; import org.columba.core.xml.XMLCoreParser; import org.compiere.apps.AEnv; import org.compiere.apps.AGlassPane; import org.compiere.apps.search.Find; import org.compiere.grid.ed.VHeaderRenderer; import org.compiere.minigrid.CheckRenderer; import org.compiere.model.GridField; import org.compiere.model.GridTab; import org.compiere.model.GridWindow; import org.compiere.model.GridWindowVO; import org.compiere.model.MQuery; import org.compiere.model.MTab; import org.compiere.model.MWindow; import org.compiere.model.Query; import org.compiere.model.persistence.X_AD_Table; import org.compiere.model.persistence.X_A_Machine; import org.compiere.model.reference.REF_ServerType; import org.compiere.swing.CCheckBox; import org.compiere.util.DisplayType; import org.compiere.util.Env; import org.compiere.util.KeyNamePair; import org.jdom.Document; import org.jdom.Element; import org.jdom.input.SAXBuilder; import org.xendra.Constants; import org.xendra.api.XendrianServer; import org.xendra.swing.LED; import com.jgoodies.forms.factories.FormFactory; import com.jgoodies.forms.layout.ColumnSpec; import com.jgoodies.forms.layout.FormLayout; import com.jgoodies.forms.layout.RowSpec; import javax.swing.JTable; import javax.swing.table.AbstractTableModel; import javax.swing.table.TableCellRenderer; import javax.swing.table.TableColumn; import javax.swing.table.TableModel; import javax.swing.JScrollPane; import java.awt.Component; import java.awt.Dimension; import javax.swing.ListSelectionModel; import javax.swing.JTabbedPane; import net.miginfocom.swing.MigLayout; public class MessageServerDialog extends JDialog implements ActionListener, ListSelectionListener { private static final String SOURCEQMACHINE = "SOURCEMACHINE"; private static final String SYNCMACHINE = "SYNCMACHINE"; private static final String TARGETQMACHINE = "TQM"; private static final String TARGETRMACHINE = "TRM"; private Object[][] data; private String[] colNames = new String[] { "name", "md5", "count", "count delta", "depth", "depth delta", "last updated", "active"}; private String[] rcolNames = new String[] { "id","TableName", "filter","last updated","active"}; private Object[][] rdata; private X_A_Machine m_machine; private LED led = new LED(); private KeyNamePair m_vp; private Integer webport = 0; private Integer m_port; private JLabel lblTable = new JLabel("source"); private JButton btnsourceQueue; private JButton btnTargetQueue; private JButton btnSynchronize; private ButtonWithMnemonic okButton; private ButtonWithMnemonic cancelButton; private JTable queuelist; private JScrollPane scrollPane; private JTabbedPane tabbedPane; private JLabel lblMessage; private JPanel replicationPanel; private JScrollPane scrollPane_1; private JTable replicationlist; private JButton btnTargetReplication; private AGlassPane m_glassPane; private JFrame waitpanel; private JLabel rmessage; private JPanel panel_1; private JButton btnreplication; private X_A_Machine machinesync = Env.getMachine(); private X_A_Machine machinesreplicationtarget = null; private X_A_Machine machinequeuetarget = null; private ImageIcon pcIcon; private JLabel lblDestination; private JPanel panel; private JLabel lblDestination_1; private ButtonColumn buttonColumn; private AbstractAction filter; int m_curWindowNo = Env.createWindowNo (this); // Timing: ca. 1.5 sec JFrame m_frame; public MessageServerDialog(KeyNamePair vp) { m_frame = Env.getFrame(this); setModal(true); Components(); m_vp = vp; Initialize(); if (led.getState() == LED.OFF) CheckQueueSourceMachine(); pack(); setLocationRelativeTo(null); setVisible(true); } private void loaddata() { Document doc = new XendrianServer().setMachineName(m_machine).setServlet("replication").setAction("list").getDocument(); //String url = String.format("http:/%s:%s/replication?action=list", m_machine.getName(), webport); //OkHttpClient client = new OkHttpClient(); //Request request = new Request.Builder().url(url).build(); try { //Response response = client.newCall(request).execute(); //String result = response.body().string(); //InputStream s = new ByteArrayInputStream(result.getBytes(StandardCharsets.UTF_8)); //Document doc = XMLCoreParser.retrieveDocument(s); try { Element root = doc.getRootElement(); List<Element> items = new ArrayList<Element>(); List list = root.getChildren(); for (int i = 0; i < list.size(); i++) { Element item = (Element) list.get(i); items.add(item); } int i = 0; rdata = new Object[items.size()][5]; for (Element item:items) { //rdata[i][0] = rdata[i][0] = false; Integer uid = Integer.valueOf(item.getAttributeValue(X_AD_Table.COLUMNNAME_AD_Table_ID).toString()); String name = item.getAttributeValue(X_AD_Table.COLUMNNAME_Name).toString(); KeyNamePair kp = new KeyNamePair(uid, name); rdata[i][1] = kp; rdata[i][2] = ""; rdata[i][3] = item.getAttributeValue(Constants.COLUMNNAME_Updated); rdata[i][4] = item.getAttributeValue(Constants.COLUMNNAME_IsActive); i++; } replicationlist.setModel(createModelReplication()); replicationlist.getTableHeader().setResizingAllowed(true); replicationlist.getTableHeader().setDefaultRenderer(new HeaderRenderer()); replicationlist.getColumnModel().getColumn(0).setPreferredWidth(50); TableColumn tc = replicationlist.getColumnModel().getColumn(0); tc.setCellRenderer(new CheckRenderer()); CCheckBox check = new CCheckBox(); check.setMargin(new Insets(0,0,0,0)); check.setHorizontalAlignment(SwingConstants.CENTER); tc.setCellEditor(new DefaultCellEditor(check)); tc.setHeaderRenderer(new VHeaderRenderer(DisplayType.YesNo)); replicationlist.getColumnModel().getColumn(1).setPreferredWidth(100); filter = new AbstractAction() { public void actionPerformed(ActionEvent e) { int r = replicationlist.getSelectedRow(); KeyNamePair kp = (KeyNamePair) replicationlist.getValueAt(r, 1); X_AD_Table table = new Query(Env.getCtx(), X_AD_Table.Table_Name, "TableName = ?", null) .setParameters(kp.getName()).first(); if (table != null) { List<MTab> mTabs = new Query(Env.getCtx(), MTab.Table_Name, "AD_Table_ID = ?", null) .setParameters(table.getAD_Table_ID()).list(); MWindow window = new Query(Env.getCtx(), MWindow.Table_Name, "AD_Window_ID = ?", null) .setParameters(mTabs.get(0).getAD_Window_ID()).first(); if (window != null) { int AD_Window_ID = window.getAD_Window_ID(); GridWindowVO wVO = AEnv.getMWindowVO (m_curWindowNo, AD_Window_ID, 0); if (wVO != null) { GridTab m_mTab = null; GridWindow m_mWindow = new GridWindow (wVO); int count = m_mWindow.getTabCount(); for (int i=0; i < count; i ++) { if (m_mTab == null) { for (MTab mTab:mTabs) { if (mTab.getAD_Tab_ID() == m_mWindow.getTab(i).getAD_Tab_ID()) { m_mTab = m_mWindow.getTab(i); break; } } } } String where = ""; //GridField[] findFields = m_mTab.getFields(); GridField[] findFields = GridField.createFields(Env.getCtx(), m_curWindowNo, 0, m_mTab.getAD_Tab_ID()); Find find = new Find (m_frame, m_curWindowNo, m_mTab.getName(), m_mTab.getAD_Tab_ID(), m_mTab.getAD_Table_ID(), table.getTableName(), where, findFields, 10); // no query below 10 MQuery query = find.getQuery(); String sqlquery = ""; if (query != null) sqlquery = query.getWhereClause(); find.dispose(); find = null; replicationlist.setValueAt(sqlquery, r, 2); //replicationlist.setValueAt(r, 1); } } } } }; buttonColumn = new ButtonColumn(replicationlist, filter, 2); replicationlist.getColumnModel().getColumn(3).setPreferredWidth(50); replicationlist.getColumnModel().getColumn(4).setPreferredWidth(50); } catch (Exception e) { e.printStackTrace(); } } catch (Exception ex) { ex.printStackTrace(); } } private void Components() { m_glassPane = new AGlassPane(); setGlassPane(m_glassPane); getContentPane().setLayout(new BorderLayout()); tabbedPane = new JTabbedPane(JTabbedPane.TOP); panel = new JPanel(); getContentPane().add(panel, BorderLayout.NORTH); panel.setLayout(new FormLayout(new ColumnSpec[] { FormFactory.DEFAULT_COLSPEC, FormFactory.DEFAULT_COLSPEC, FormFactory.RELATED_GAP_COLSPEC, FormFactory.DEFAULT_COLSPEC, FormFactory.RELATED_GAP_COLSPEC, ColumnSpec.decode("max(37dlu;default)"), FormFactory.RELATED_GAP_COLSPEC, ColumnSpec.decode("default:grow"),}, new RowSpec[] { RowSpec.decode("22dlu"),})); getContentPane().add(tabbedPane, BorderLayout.CENTER); JPanel queuePanel = new JPanel(); tabbedPane.addTab("Queue", null, queuePanel, null); queuePanel.setLayout(new FormLayout(new ColumnSpec[] { FormFactory.RELATED_GAP_COLSPEC, FormFactory.DEFAULT_COLSPEC, FormFactory.RELATED_GAP_COLSPEC, ColumnSpec.decode("max(26dlu;default)"), FormFactory.RELATED_GAP_COLSPEC, ColumnSpec.decode("max(39dlu;default)"), FormFactory.RELATED_GAP_COLSPEC, ColumnSpec.decode("max(35dlu;default)"), FormFactory.RELATED_GAP_COLSPEC, ColumnSpec.decode("max(41dlu;default):grow"), FormFactory.RELATED_GAP_COLSPEC, ColumnSpec.decode("max(10dlu;default)"),}, new RowSpec[] { FormFactory.RELATED_GAP_ROWSPEC, FormFactory.DEFAULT_ROWSPEC, FormFactory.RELATED_GAP_ROWSPEC, RowSpec.decode("max(91dlu;min):grow"), FormFactory.RELATED_GAP_ROWSPEC, FormFactory.DEFAULT_ROWSPEC,})); try { pcIcon = new ImageIcon(ImageIO.read(new File(Env.getResource("org.columba.core", "computer.png")))); } catch (Exception e) {}; queuelist = new JTable(); queuelist.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); queuelist.getSelectionModel().addListSelectionListener(this); lblDestination = new JLabel("destination"); queuePanel.add(lblDestination, "4, 2"); try { pcIcon = new ImageIcon(ImageIO.read(new File(Env.getResource("org.columba.core", "computer.png")))); } catch (Exception e) {}; panel.add(led, "2, 1"); led.setState(LED.OFF); panel.add(lblTable, "4, 1"); btnsourceQueue = new JButton(); panel.add(btnsourceQueue, "6, 1"); btnsourceQueue.setIcon(pcIcon); btnsourceQueue.addActionListener(this); btnsourceQueue.setActionCommand(SOURCEQMACHINE); btnTargetQueue = new JButton(); btnTargetQueue.setIcon(pcIcon); btnTargetQueue.setEnabled(false); btnTargetQueue.addActionListener(this); btnTargetQueue.setActionCommand(TARGETQMACHINE); queuePanel.add(btnTargetQueue, "6, 2"); btnSynchronize = new JButton(); queuePanel.add(btnSynchronize, "8, 2"); ImageIcon queueIcon = null; try { queueIcon = new ImageIcon(ImageIO.read(new File(Env.getResource("org.columba.core", "queue.png")))); } catch (Exception e) {} btnSynchronize.setHorizontalAlignment(SwingConstants.LEADING); btnSynchronize.setIcon(queueIcon); btnSynchronize.addActionListener(this); btnSynchronize.setActionCommand("sincro"); btnSynchronize.setEnabled(false); scrollPane = new JScrollPane(queuelist); queuePanel.add(scrollPane, "4, 4, 8, 1, fill, fill"); lblMessage = new JLabel(""); queuePanel.add(lblMessage, "4, 6, 7, 1"); JPanel bottomPanel = new JPanel(); bottomPanel.setBorder(new SingleSideEtchedBorder(SwingConstants.TOP)); getContentPane().add(bottomPanel, BorderLayout.SOUTH); bottomPanel.setLayout(new BorderLayout(0, 0)); JPanel buttonPanel = new JPanel(); buttonPanel.setBorder(new EmptyBorder(12, 12, 12, 12)); buttonPanel.setLayout(new GridLayout(1, 3, 6, 0)); okButton = new ButtonWithMnemonic(GlobalResourceLoader.getString("org.columba.core.i18n.dialog", "global", "ok")); //$NON-NLS-1$ //$NON-NLS-2$ okButton.setActionCommand("OK"); //$NON-NLS-1$ okButton.addActionListener(this); buttonPanel.add(okButton); cancelButton = new ButtonWithMnemonic(GlobalResourceLoader.getString("org.columba.core.i18n.dialog", "global", "cancel")); //$NON-NLS-1$ //$NON-NLS-2$ cancelButton.setActionCommand("CANCEL"); //$NON-NLS-1$ cancelButton.addActionListener(this); buttonPanel.add(cancelButton); getRootPane().registerKeyboardAction(this, "CANCEL", //$NON-NLS-1$ KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), JComponent.WHEN_IN_FOCUSED_WINDOW); // bottomPanel.add(buttonPanel, BorderLayout.EAST); // replicationPanel = new JPanel(); tabbedPane.addTab("Replication", null, replicationPanel, null); replicationPanel.setLayout(new FormLayout(new ColumnSpec[] { FormFactory.RELATED_GAP_COLSPEC, FormFactory.DEFAULT_COLSPEC, FormFactory.RELATED_GAP_COLSPEC, ColumnSpec.decode("max(45dlu;default)"), FormFactory.RELATED_GAP_COLSPEC, ColumnSpec.decode("default:grow"), FormFactory.RELATED_GAP_COLSPEC, FormFactory.DEFAULT_COLSPEC, FormFactory.RELATED_GAP_COLSPEC, ColumnSpec.decode("max(104dlu;default):grow"), FormFactory.RELATED_GAP_COLSPEC, ColumnSpec.decode("max(10dlu;default)"),}, new RowSpec[] { FormFactory.RELATED_GAP_ROWSPEC, FormFactory.DEFAULT_ROWSPEC, FormFactory.RELATED_GAP_ROWSPEC, RowSpec.decode("max(91dlu;min):grow"), FormFactory.RELATED_GAP_ROWSPEC, FormFactory.DEFAULT_ROWSPEC, FormFactory.RELATED_GAP_ROWSPEC, RowSpec.decode("default:grow"),})); replicationlist = new JTable(); replicationlist.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); replicationlist.getSelectionModel().addListSelectionListener(this); btnTargetReplication = new JButton(); btnTargetReplication.setActionCommand(TARGETRMACHINE); btnTargetReplication.setEnabled(false); btnTargetReplication.addActionListener(this); btnTargetReplication.setIcon(pcIcon); lblDestination_1 = new JLabel("origen"); replicationPanel.add(lblDestination_1, "4, 2"); replicationPanel.add(btnTargetReplication, "6, 2"); btnreplication = new JButton("Replicar "); btnreplication.addActionListener(this); btnreplication.setActionCommand("replication"); btnreplication.setIcon(queueIcon); replicationPanel.add(btnreplication, "8, 2"); btnreplication.setEnabled(false); scrollPane_1 = new JScrollPane(replicationlist); replicationPanel.add(scrollPane_1, "4, 4, 7, 1, fill, top"); rmessage = new JLabel(""); replicationPanel.add(rmessage, "4, 6, 7, 3"); panel_1 = new JPanel(); replicationPanel.add(panel_1, "4, 8, 7, 1, fill, fill"); panel_1.setLayout(new MigLayout("", "[117px][]", "[25px]")); } public TableModel createModelReplication() { return new AbstractTableModel() { public int getColumnCount() { return rcolNames.length; } public int getRowCount() { return rdata.length; } public String getColumnName(int col) { return rcolNames[col]; } public Object getValueAt(int row, int col) { return rdata[row][col]; } public Class<? extends Object> getColumnClass(int c) { Object value = getValueAt(0, c); return (value != null) ? value.getClass() : ImageIcon.class; } /* * Don't need to implement this method unless your table's * editable. */ public boolean isCellEditable(int row, int col) { if (col == 0 || col == 2) return true; return false; } /* * Don't need to implement this method unless your table's data * can change. */ public void setValueAt(Object value, int row, int col) { rdata[row][col] = value; fireTableCellUpdated(row, col); } }; } @SuppressWarnings("serial") public TableModel createModelQueue() { return new AbstractTableModel() { public int getColumnCount() { return colNames.length; } public int getRowCount() { return data.length; } public String getColumnName(int col) { return colNames[col]; } public Object getValueAt(int row, int col) { return data[row][col]; } public Class<? extends Object> getColumnClass(int c) { Object value = getValueAt(0, c); return (value != null) ? value.getClass() : ImageIcon.class; } /* * Don't need to implement this method unless your table's * editable. */ public boolean isCellEditable(int row, int col) { return col == 0; } /* * Don't need to implement this method unless your table's data * can change. */ public void setValueAt(Object value, int row, int col) { data[row][col] = value; fireTableCellUpdated(row, col); } }; } public void Initialize() { m_machine = new Query(Env.getCtx(), X_A_Machine.Table_Name, "A_Machine_ID = ?", null) .setParameters(m_vp.getKey()).first(); if (m_machine != null) { //btnRunNow.setText(String.format("get info from %s",m_machine.getName())); HashMap props = Env.getServerProperties(m_machine.getA_Machine_ID(), REF_ServerType.WebServer); webport = 0; if (props.containsKey("port")) { webport = Integer.valueOf(props.get("port").toString()); } props = Env.getServerProperties(m_machine.getA_Machine_ID(), REF_ServerType.MessageServer); m_port = 0; if (props.containsKey("port")) m_port = Integer.valueOf((String) props.get("port")); } } @Override public void actionPerformed(ActionEvent e) { if (e.getActionCommand().equals(SOURCEQMACHINE)) { CheckQueueSourceMachine(); } else if (e.getActionCommand().equals(TARGETQMACHINE)) { CheckQueueTargetMachine(); } else if (e.getActionCommand().equals("sincro")) { DoSyncro(); } else if (e.getActionCommand().equals(TARGETRMACHINE)) { CheckReplicationTargetMachine(); } else if (e.getActionCommand().equals("replication")) { replication(); } else if (e.getActionCommand().equals("CANCEL")) { //$NON-NLS-1$ setVisible(false); } else if (e.getActionCommand().equals("OK")) { setVisible(false); } } private void showWaitPanel() { if (waitpanel == null) { waitpanel = new JFrame(); waitpanel.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE); waitpanel.setUndecorated(true); waitpanel.setPreferredSize(new Dimension(200,200)); waitpanel.setAlwaysOnTop(true); waitpanel.setSize(new Dimension(300,200)); m_glassPane = new AGlassPane(); waitpanel.setGlassPane(m_glassPane); waitpanel.setLocationRelativeTo(null); waitpanel.setVisible(true); } else { waitpanel.setVisible(true); } m_glassPane.setBusyTimer(10000000); System.out.println("show"); } private void DoSyncro() { showWaitPanel(); TaskDoSynchro tsk = new TaskDoSynchro(); tsk.start(); } private void CheckQueueSourceMachine() { showWaitPanel(); TaskCheckSourceMachine tsk = new TaskCheckSourceMachine(); tsk.start(); } private void CheckQueueTargetMachine() { PickMachineDialog dlg = new PickMachineDialog(machinequeuetarget); machinequeuetarget = dlg.getMachine(); if (machinequeuetarget != null) { showWaitPanel(); TaskCheckQueueTarget tsk = new TaskCheckQueueTarget(); tsk.start(); } } public void CheckReplicationTargetMachine() { PickMachineDialog dlg = new PickMachineDialog(machinesreplicationtarget); machinesreplicationtarget = dlg.getMachine(); if (machinesreplicationtarget != null) { TaskCheckReplication tsk = new TaskCheckReplication(machinesreplicationtarget); tsk.start(); } } //private void checkreplication(X_A_Machine m) { // showWaitPanel(); // TaskCheckReplication tsk = new TaskCheckReplication(m); // tsk.start(); //} @Override public void valueChanged(ListSelectionEvent ev) { if (ev.getValueIsAdjusting()) return; if (queuelist.getSelectedRow() != -1 && machinequeuetarget != null) { btnSynchronize.setEnabled(true); } } public void replication() { if (machinesreplicationtarget != null) { showWaitPanel(); TaskReplication tsk = new TaskReplication(); tsk.start(); } } class HeaderRenderer extends JLabel implements TableCellRenderer { public HeaderRenderer() { setBorder(BorderFactory.createEtchedBorder()); } @Override public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { setText(value.toString()); return this; } } class TaskReplication extends SwingWorker { public TaskReplication() { // machinesreplicationtarget } public Object construct() { m_glassPane.setMessage(String.format("%s hacia %s", machinesreplicationtarget.getName(), m_machine.getName())); int port = 0; HashMap props = Env.getServerProperties(machinesreplicationtarget.getA_Machine_ID(), REF_ServerType.WebServer); if (props.containsKey("port")) { port = Integer.valueOf(props.get("port").toString()); } int count = replicationlist.getModel().getRowCount(); String msg = String.format("<replication destination=\"%s\">",m_machine.getName()); HashMap<String, String> tables = new HashMap<String, String>(); for (int i=0; i < count; i++) { Boolean selected = (Boolean) replicationlist.getValueAt(i, 0); if (selected) { String where = (String) replicationlist.getValueAt(i, 2); KeyNamePair kp = (KeyNamePair) replicationlist.getValueAt(i, 1); X_AD_Table table = new Query(Env.getCtx(), X_AD_Table.Table_Name, "AD_Table_ID = ?", null) .setParameters(kp.getKey()).first(); tables.put(table.getTableName(), where); } } Iterator<String> it = tables.keySet().iterator(); while (it.hasNext()) { String table = it.next(); String query = tables.get(table); msg += String.format("<table name=\"%s\" query=\"%s\"/>",table, query); } msg += "</replication>"; String url = String.format("http:/%s:%s/replication", machinesreplicationtarget.getName(), port); OkHttpClient client = new OkHttpClient(); RequestBody formBody = new FormBody.Builder() .add("message", msg) .build(); Request request = new Request.Builder() .url(url) .post(formBody) .build(); msg = ""; it = tables.keySet().iterator(); while (it.hasNext()) { String table = it.next(); if (msg.length() > 0) msg += ","; msg += String.format("%s",table); } rmessage.setText(String.format("replica tables %s from %s to %s", msg, machinesreplicationtarget.getName(), m_machine.getName())); try { Response response = client.newCall(request).execute(); // Do something with the response. } catch (IOException e) { e.printStackTrace(); } return ""; } /* * Executed in event dispatching thread */ @Override public void finished() { m_glassPane.setBusyTimer(0); waitpanel.setVisible(false); } } class TaskCheckQueueTarget extends SwingWorker { public TaskCheckQueueTarget() {} public Object construct() { btnTargetQueue.setText(""); btnSynchronize.setEnabled(false); m_glassPane.setMessage(String.format("Checking %s", machinequeuetarget.getName())); int port = 0; HashMap props = Env.getServerProperties(machinequeuetarget.getA_Machine_ID(), REF_ServerType.WebServer); if (props.containsKey("port")) { port = Integer.valueOf(props.get("port").toString()); } //String url = String.format("http://%s:%s/monitor?JMS=status", machinequeuetarget.getName(), port); String url = String.format("http:/%s:%s/replication?action=status", machinequeuetarget.getName(), port); Document doc = getDocument(url); if (doc != null) { Element root = doc.getRootElement(); String status = root.getText(); if (status.equals("alive")) { btnTargetQueue.setText(machinequeuetarget.getName()); if (queuelist.getSelectedRow() != -1) { btnSynchronize.setEnabled(true); } } else { machinequeuetarget = null; } } else { machinequeuetarget = null; } return ""; } /* * Executed in event dispatching thread */ @Override public void finished() { m_glassPane.setBusyTimer(0); waitpanel.setVisible(false); } } //btnTargetReplication.setText(machinesreplicationtarget.getName()); //checkreplication(machinesreplicationtarget); class TaskCheckReplication extends SwingWorker { X_A_Machine machine; public TaskCheckReplication(X_A_Machine m) { machine = m; } public Object construct() { showWaitPanel(); btnTargetReplication.setText(""); machinesreplicationtarget = null; int port = 0; HashMap props = Env.getServerProperties(machine.getA_Machine_ID(), REF_ServerType.WebServer); if (props.containsKey("port")) { port = Integer.valueOf(props.get("port").toString()); } m_glassPane.setMessage(String.format("Status %s:%s...", machine.getName(), port)); btnreplication.setEnabled(false); String url = String.format("http:/%s:%s/replication?action=status", machine.getName(), port); Document doc = getDocument(url); if (doc != null) { Element root = doc.getRootElement(); String status = root.getText(); if (status.equals("alive")) { btnreplication.setEnabled(true); btnTargetReplication.setEnabled(true); btnTargetReplication.setText(machine.getName()); machinesreplicationtarget = machine; } } return ""; } /* * Executed in event dispatching thread */ @Override public void finished() { m_glassPane.setBusyTimer(0); waitpanel.setVisible(false); } } private Document getDocument(String url) { Document doc = null; try { OkHttpClient client = new OkHttpClient(); Request request = new Request.Builder().url(url).build(); Response response = client.newCall(request).execute(); String result = response.body().string(); SAXBuilder builder = new SAXBuilder(); InputStream stream = new ByteArrayInputStream(result.getBytes("UTF-8")); doc = builder.build(stream); } catch (Exception e) {} return doc; } class TaskCheckSourceMachine extends SwingWorker { public TaskCheckSourceMachine() {} public Object construct() { led.setState(LED.RED); btnsourceQueue.setText(""); btnTargetQueue.setEnabled(false); btnTargetReplication.setEnabled(false); btnSynchronize.setEnabled(false); m_glassPane.setMessage("Status..."); String url = String.format("http:/%s:%s/replication?action=status", m_machine.getName(), webport); Document doc = getDocument(url); if (doc != null) { Element root = doc.getRootElement(); String status = root.getText(); if (status.equals("alive")) { loaddata(); led.setState(LED.GREEN); btnsourceQueue.setText(m_machine.getName()); btnTargetQueue.setEnabled(true); btnTargetReplication.setEnabled(true); //url = String.format("http://%s:%s/monitor?JMS=snapshot",m_machine.getName(), webport); url = String.format("http:/%s:%s/replication?action=snapshot", m_machine.getName(), webport); doc = getDocument(url); try { root = doc.getRootElement(); List<Element> items = new ArrayList<Element>(); List list = root.getChildren(); for (int i = 0; i < list.size(); i++) { Element item = (Element) list.get(i); items.add(item); } int i = 0; data = new Object[items.size()][8]; for (Element item:items) { data[i][0] = item.getAttributeValue("name"); data[i][1] = item.getAttributeValue("md5"); data[i][2] = item.getAttributeValue("count"); data[i][3] = item.getAttributeValue("countdelta"); data[i][4] = item.getAttributeValue("depth"); data[i][5] = item.getAttributeValue("depthdelta"); data[i][6] = item.getAttributeValue("lastupdated"); data[i][7] = item.getAttributeValue("active"); i++; } queuelist.setModel(createModelQueue()); queuelist.getTableHeader().setResizingAllowed(true); queuelist.getTableHeader().setDefaultRenderer(new HeaderRenderer()); queuelist.getColumnModel().getColumn(0).setPreferredWidth(50); queuelist.getColumnModel().getColumn(1).setPreferredWidth(50); queuelist.getColumnModel().getColumn(2).setPreferredWidth(15); queuelist.getColumnModel().getColumn(3).setPreferredWidth(15); queuelist.getColumnModel().getColumn(4).setPreferredWidth(15); queuelist.getColumnModel().getColumn(5).setPreferredWidth(15); queuelist.getColumnModel().getColumn(6).setPreferredWidth(15); queuelist.getColumnModel().getColumn(7).setPreferredWidth(15); } catch (Exception e) { e.printStackTrace(); } } } return ""; } /* * Executed in event dispatching thread */ @Override public void finished() { m_glassPane.setBusyTimer(0); waitpanel.setVisible(false); } } class TaskDoSynchro extends SwingWorker { public TaskDoSynchro() { } public Object construct() { m_glassPane.setMessage("Synchronized..."); String queuename = (String) queuelist.getValueAt(queuelist.getSelectedRow(), 0); String md5 = ""; int port = 0; HashMap props = Env.getServerProperties(machinequeuetarget.getA_Machine_ID(), REF_ServerType.WebServer); if (props.containsKey("port")) { port = Integer.valueOf(props.get("port").toString()); } String url = String.format("http://%s:%s/replication?action=checksum&type=queue&name=%s",machinequeuetarget.getName(), port, queuename); Document doc = getDocument(url); if (doc != null) { Element root = doc.getRootElement(); md5 = root.getText(); } url = String.format("http://%s:%s/replication?action=synchro&queuename=%s&md5=%s&machine=%s",m_machine.getName(), webport, queuename,md5,machinequeuetarget.getName()); doc = getDocument(url); if (doc != null) { Element root = doc.getRootElement(); Element e = root.getChild("queue"); String remotequeuename = e.getAttributeValue("name"); String remotemd5 = e.getAttributeValue("md5"); String msg = e.getAttributeValue("status"); // if (remotequeuename.compareTo(queuename) != 0) { url = String.format("http://%s:%s/replication?action=createqueue&queuename=%s&md5=%s", machinequeuetarget.getName(), port, remotequeuename,remotemd5); doc = getDocument(url); if (doc != null) { root = doc.getRootElement(); String status = root.getText(); if (status.equals("created")) { url = String.format("http://%s:%s/replication?action=synchro&queuename=%s&md5=%s&machine=%s&queueremote=%s",m_machine.getName(), webport, queuename,remotemd5,machinequeuetarget.getName(), remotequeuename); doc = getDocument(url); if (doc != null) { root = doc.getRootElement(); e = root.getChild("queue"); msg = e.getAttributeValue("status"); } } } } lblMessage.setText(msg); } return ""; } /* * Executed in event dispatching thread */ @Override public void finished() { m_glassPane.setBusyTimer(0); waitpanel.setVisible(false); } } }
7361458ecc23128087c8a22db146786da648e683
f48debdb4983c7c133ad02a03282233f19922390
/src/test/java/com/adriano/usuario/usuariointelipost/UsuarioIntelipostApplicationTests.java
6ada2829f8f310200e75084591dea35b0616f762
[]
no_license
adrianoribeiro/usuario-intelipost
48c815cf9eeae225660b9a69b60519ddaa48d582
17b1c08dc479247f2366a926d43b4ebe3193abff
refs/heads/master
2020-03-21T00:12:11.234313
2018-06-19T11:47:54
2018-06-19T11:47:54
137,881,435
0
0
null
null
null
null
UTF-8
Java
false
false
365
java
package com.adriano.usuario.usuariointelipost; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) @SpringBootTest public class UsuarioIntelipostApplicationTests { @Test public void contextLoads() { } }
dd45d2414eb15b809ad1e92abbd81ccf58202f7d
dec482dcb3fff0ed34a8e0fb591fa06a2837b4f6
/taotao_common/src/main/java/com/utils/HttpClientUtil.java
594a12cc446fd1937a37bcab60cca940d7ba2a24
[]
no_license
jerrylisri/taotao_parent
90770ad26b2322b5c46da6a190964db975230280
4483272738ebbad02a64b97adebfcf1b1818baf3
refs/heads/master
2021-05-10T08:07:41.886747
2018-02-02T12:47:48
2018-02-02T12:48:06
118,876,365
0
0
null
null
null
null
UTF-8
Java
false
false
3,721
java
package com.utils; import java.io.IOException; import java.net.URI; import java.util.ArrayList; import java.util.List; import java.util.Map; import org.apache.http.NameValuePair; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.utils.URIBuilder; import org.apache.http.entity.ContentType; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.message.BasicNameValuePair; import org.apache.http.util.EntityUtils; public class HttpClientUtil { public static String doGet(String url, Map<String, String> param) { // 创建Httpclient对象 CloseableHttpClient httpclient = HttpClients.createDefault(); String resultString = ""; CloseableHttpResponse response = null; try { // 创建uri URIBuilder builder = new URIBuilder(url); if (param != null) { for (String key : param.keySet()) { builder.addParameter(key, param.get(key)); } } URI uri = builder.build(); // 创建http GET请求 HttpGet httpGet = new HttpGet(uri); // 执行请求 response = httpclient.execute(httpGet); // 判断返回状态是否为200 if (response.getStatusLine().getStatusCode() == 200) { resultString = EntityUtils.toString(response.getEntity(), "UTF-8"); } } catch (Exception e) { e.printStackTrace(); } finally { try { if (response != null) { response.close(); } httpclient.close(); } catch (IOException e) { e.printStackTrace(); } } return resultString; } public static String doGet(String url) { return doGet(url, null); } public static String doPost(String url, Map<String, String> param) { // 创建Httpclient对象 CloseableHttpClient httpClient = HttpClients.createDefault(); CloseableHttpResponse response = null; String resultString = ""; try { // 创建Http Post请求 HttpPost httpPost = new HttpPost(url); // 创建参数列表 if (param != null) { List<NameValuePair> paramList = new ArrayList<>(); for (String key : param.keySet()) { paramList.add(new BasicNameValuePair(key, param.get(key))); } // 模拟表单 UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList); httpPost.setEntity(entity); } // 执行http请求 response = httpClient.execute(httpPost); resultString = EntityUtils.toString(response.getEntity(), "utf-8"); } catch (Exception e) { e.printStackTrace(); } finally { try { response.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return resultString; } public static String doPost(String url) { return doPost(url, null); } public static String doPostJson(String url, String json) { // 创建Httpclient对象 CloseableHttpClient httpClient = HttpClients.createDefault(); CloseableHttpResponse response = null; String resultString = ""; try { // 创建Http Post请求 HttpPost httpPost = new HttpPost(url); // 创建请求内容 StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON); httpPost.setEntity(entity); // 执行http请求 response = httpClient.execute(httpPost); resultString = EntityUtils.toString(response.getEntity(), "utf-8"); } catch (Exception e) { e.printStackTrace(); } finally { try { response.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return resultString; } }
116a4c59c1e98d3460f6bd34b91496bd58a6e49c
b1d5edc216b8a5f62fa21afe1c10a8832b8d93ad
/app/src/main/java/master/imd/ufrn/br/carusepattern/getbehavior/util/MockReadings.java
b626882fe2f7a254936bbfd9a1182df3a5efa046
[]
no_license
cephasax/CarUsePattern
23ddbbba975b003e1f108f677857b207a5b508ee
1535fe08b021adc5db6fb387fc6059faa68fb33a
refs/heads/master
2020-03-21T08:40:30.415104
2018-06-29T22:41:40
2018-06-29T22:41:40
138,358,138
0
0
null
null
null
null
UTF-8
Java
false
false
1,644
java
package master.imd.ufrn.br.carusepattern.getbehavior.util; import java.util.ArrayList; import java.util.Calendar; import master.imd.ufrn.br.carusepattern.getbehavior.domain.ReadingFromCar; import static master.imd.ufrn.br.carusepattern.getbehavior.util.DoubleUtils.randomDouble; public class MockReadings { public static ArrayList<ReadingFromCar> createReadings(){ ArrayList<ReadingFromCar> readings = new ArrayList<ReadingFromCar>(); ArrayList<String> placas = new ArrayList<String>(); placas.add("MTC-4052"); placas.add("IET-5682"); placas.add("JZC-6601"); placas.add("MZF-6638"); placas.add("KIZ-5481"); placas.add("MPJ-8698"); placas.add("KFE-0204"); placas.add("KGM-5852"); placas.add("LZH-2182"); placas.add("LWI-2246"); for(String s: placas) { Calendar c = Calendar.getInstance(); ReadingFromCar rfc = new ReadingFromCar(s, DateParser.dateToString(c.getTime())); rfc.setEngineCoolantTemp(randomDouble()); rfc.setEngineLoad(randomDouble()); rfc.setEngineRpm(randomDouble()); rfc.setIntakeManifoldPressure(randomDouble()); rfc.setMaf(randomDouble()); rfc.setSpeed(randomDouble()); rfc.setShortTermFuelTrimBank1(randomDouble()); rfc.setThrottlePos(randomDouble()); rfc.setTimingAdvance(randomDouble()); //MOCK ids rfc.setIdReadingFromCar(0); rfc.getElement().setIdElement(0); readings.add(rfc); } return readings; } }
8387c0fb61c37071775d82486a54c52988f1cf85
3c5442b492bb1a1ae6e99a3c5fd82055fac426f1
/src/main/java/com/common/BaseModel.java
e345a13e1c110bf009f6c8c6ea56ecaa5a0b50c7
[]
no_license
lysix/mybatis-plus-code-generate
014b34e7508c5f82d86f0a956f956a39c7d69d92
50017f3cbc4c9867595ec777cd77a8f3d229dcf3
refs/heads/develop
2022-12-27T04:16:20.191556
2020-01-06T07:56:27
2020-01-06T07:56:27
210,746,301
2
4
null
2022-12-10T03:44:33
2019-09-25T03:19:27
Java
UTF-8
Java
false
false
259
java
package com.common; import com.baomidou.mybatisplus.extension.activerecord.Model; /** * @author zhanghaichao * @ClassName: ModelBase * @ProjectName dcp * @date 2019/10/1211:17 */ public abstract class BaseModel<T extends Model<?>> extends Model<T> { }
f7cde0c6db0a1df4823abbab85b600fc717ac013
a04fdf4c0be8c60dfe532863107c2fd1281727b4
/Java.Collections/src/main/java/Java/Collections/List/ExemploList.java
684771c1f046b0d978768c71ce7498336ff3366b
[]
no_license
MarcusVSRDev/Capgemini
047da9bc5a5ca8191432f376789d8946c8532cd1
2bbd5a17907f54eb78160026d7b799b67c4176c6
refs/heads/main
2023-07-19T16:29:58.050584
2021-09-21T22:21:40
2021-09-21T22:21:40
400,924,671
1
0
null
null
null
null
UTF-8
Java
false
false
2,291
java
package Java.Collections.List; import java.lang.reflect.Array; import java.util.*; public class ExemploList { public static void main(String[] args) { //List<Double> notas = new ArrayList<>(Arrays.asList(7d, 8.5, 9.3, 5d, 7d, 0d, 3.6)); System.out.println("Crie uma lista e adicione sete notas"); List<Double> notas = new ArrayList<Double>(); notas.add(7.0); notas.add(8.5); notas.add(9.3); notas.add(5d); notas.add(7d); notas.add(0d); notas.add(3.6); System.out.println(notas.toString()); System.out.println("Exiba a posição da nota 5: " + notas.indexOf(5d)); System.out.println("Adicione na lista a nota 8.0 na posição 4: "); notas.add(4, 8d); System.out.println("Substitua a nota 5.0 pela nota 6.0: "); notas.set(notas.indexOf(5.0), 6d); System.out.println(notas.toString()); System.out.println("Confira se a nota 5.0 está na lista: " + notas.contains(5.0)); System.out.println("Exiba todas as notas na ordem em que foram informadas: "); //for (Double nota: notas) System.out.println(nota); System.out.println("Exiba a terceira nota adicionada: " + notas.get(2)); System.out.println("EXiba a menor nota: " + Collections.min(notas)); System.out.println("EXiba a maior nota: " + Collections.max(notas)); Iterator<Double> iterator = notas.iterator(); Double soma = 0d; while(iterator.hasNext()){ Double next = iterator.next(); soma += next; } System.out.println("Exiba a soma dos valores: " + soma); System.out.println("Exiba a média das notas: " + (soma/notas.size())); System.out.println("Remova a nota 0: "); notas.remove(0d); System.out.println(notas); System.out.println("Remova a nota na posição 0: "); notas.remove(0); System.out.println(notas); System.out.println("Remova as notas menor que 7 "); notas.removeIf(next -> next < 7); System.out.println(notas); System.out.println("Apague toda a lista"); notas.clear(); System.out.println("Confira se a lista está vazia: " + notas.isEmpty()); } }
e1f4a599f6df62a1b65696334be6f0591079b487
eabebb52b03b6d2397154d13db2f3ce484dad27f
/balance/src/main/java/com/jdc/balance/utils/StringUtils.java
d0de33b357a596dac47c2f19727c77f041e965d5
[ "MIT" ]
permissive
minlwin/java-web
94574458e4af987a98aadda653a14477c216bed4
543def887ff051ca69a62da1b9bf20229d208cff
refs/heads/main
2022-02-17T20:37:44.108354
2022-01-24T15:29:06
2022-01-24T15:29:06
28,694,888
8
4
null
null
null
null
UTF-8
Java
false
false
350
java
package com.jdc.balance.utils; import java.text.DecimalFormat; public class StringUtils { private static final DecimalFormat INT_FMT = new DecimalFormat("#,##0"); public static boolean isEmpty(String string) { return null == string || string.isEmpty(); } public static String formatNumber(int data) { return INT_FMT.format(data); } }
bfe3c9e1e9f4c65c9fdfc50a5b80be4efd6e9ba4
b780c6d51def4f6631535d5751fc2b1bc40072c7
/generated_patches/mybatis-3/mc/2021-02-26T12:38:49.193/125.java
a6402539f376056f1fcb95c4a47278299e24ac21
[]
no_license
FranciscoRibeiro/bugswarm-case-studies
95fad7a9b3d78fcdd2d3941741163ad73e439826
b2fb9136c3dcdd218b80db39a8a1365bf0842607
refs/heads/master
2023-07-08T05:27:27.592054
2021-08-19T17:27:54
2021-08-19T17:27:54
null
0
0
null
null
null
null
UTF-8
Java
false
false
25,615
java
package org.apache.ibatis.builder.annotation; import java.io.IOException; import java.io.InputStream; import java.lang.annotation.Annotation; import java.lang.reflect.Array; import java.lang.reflect.GenericArrayType; import java.lang.reflect.Method; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Set; import org.apache.ibatis.annotations.Arg; import org.apache.ibatis.annotations.CacheNamespace; import org.apache.ibatis.annotations.CacheNamespaceRef; import org.apache.ibatis.annotations.Case; import org.apache.ibatis.annotations.ConstructorArgs; import org.apache.ibatis.annotations.Delete; import org.apache.ibatis.annotations.DeleteProvider; import org.apache.ibatis.annotations.Insert; import org.apache.ibatis.annotations.InsertProvider; import org.apache.ibatis.annotations.Lang; import org.apache.ibatis.annotations.MapKey; import org.apache.ibatis.annotations.Options; import org.apache.ibatis.annotations.Result; import org.apache.ibatis.annotations.ResultMap; import org.apache.ibatis.annotations.ResultType; import org.apache.ibatis.annotations.Results; import org.apache.ibatis.annotations.Select; import org.apache.ibatis.annotations.SelectKey; import org.apache.ibatis.annotations.SelectProvider; import org.apache.ibatis.annotations.TypeDiscriminator; import org.apache.ibatis.annotations.Update; import org.apache.ibatis.annotations.UpdateProvider; import org.apache.ibatis.binding.BindingException; import org.apache.ibatis.binding.MapperMethod.ParamMap; import org.apache.ibatis.builder.BuilderException; import org.apache.ibatis.builder.IncompleteElementException; import org.apache.ibatis.builder.MapperBuilderAssistant; import org.apache.ibatis.builder.xml.XMLMapperBuilder; import org.apache.ibatis.executor.keygen.Jdbc3KeyGenerator; import org.apache.ibatis.executor.keygen.KeyGenerator; import org.apache.ibatis.executor.keygen.NoKeyGenerator; import org.apache.ibatis.executor.keygen.SelectKeyGenerator; import org.apache.ibatis.io.Resources; import org.apache.ibatis.mapping.Discriminator; import org.apache.ibatis.mapping.FetchType; import org.apache.ibatis.mapping.MappedStatement; import org.apache.ibatis.mapping.ResultFlag; import org.apache.ibatis.mapping.ResultMapping; import org.apache.ibatis.mapping.ResultSetType; import org.apache.ibatis.mapping.SqlCommandType; import org.apache.ibatis.mapping.SqlSource; import org.apache.ibatis.mapping.StatementType; import org.apache.ibatis.scripting.LanguageDriver; import org.apache.ibatis.session.Configuration; import org.apache.ibatis.session.ResultHandler; import org.apache.ibatis.session.RowBounds; import org.apache.ibatis.type.JdbcType; import org.apache.ibatis.type.TypeHandler; import org.apache.ibatis.type.UnknownTypeHandler; public class MapperAnnotationBuilder { private final Set<Class<? extends Annotation>> sqlAnnotationTypes = new HashSet<Class<? extends Annotation>>(); private final Set<Class<? extends Annotation>> sqlProviderAnnotationTypes = new HashSet<Class<? extends Annotation>>(); private Configuration configuration; private MapperBuilderAssistant assistant; private Class<?> type; public MapperAnnotationBuilder(Configuration configuration, Class<?> type) { String resource = type.getName().replace('.', '/') + ".java (best guess)"; this.assistant = new MapperBuilderAssistant(configuration, resource); this.configuration = configuration; this.type = type; sqlAnnotationTypes.add(Select.class); sqlAnnotationTypes.add(Insert.class); sqlAnnotationTypes.add(Update.class); sqlAnnotationTypes.add(Delete.class); sqlProviderAnnotationTypes.add(SelectProvider.class); sqlProviderAnnotationTypes.add(InsertProvider.class); sqlProviderAnnotationTypes.add(UpdateProvider.class); sqlProviderAnnotationTypes.add(DeleteProvider.class); } public void parse() { String resource = type.toString(); if (!configuration.isResourceLoaded(resource)) { loadXmlResource(); configuration.addLoadedResource(resource); assistant.setCurrentNamespace(type.getName()); parseCache(); parseCacheRef(); Method[] methods = type.getMethods(); for (Method method : methods) { try { if (!method.isBridge()) { parseStatement(method); } } catch (IncompleteElementException e) { configuration.addIncompleteMethod(new MethodResolver(this, method)); } } } parsePendingMethods(); } private void parsePendingMethods() { Collection<MethodResolver> incompleteMethods = configuration.getIncompleteMethods(); synchronized (incompleteMethods) { Iterator<MethodResolver> iter = incompleteMethods.iterator(); while (iter.hasNext()) { try { iter.next().resolve(); iter.remove(); } catch (IncompleteElementException e) { } } } } private void loadXmlResource() { if (!configuration.isResourceLoaded("namespace:" + type.getName())) { String xmlResource = type.getName().replace('.', '/') + ".xml"; InputStream inputStream = null; try { inputStream = Resources.getResourceAsStream(type.getClassLoader(), xmlResource); } catch (IOException e) { } if (inputStream != null) { XMLMapperBuilder xmlParser = new XMLMapperBuilder(inputStream, assistant.getConfiguration(), xmlResource, configuration.getSqlFragments(), type.getName()); xmlParser.parse(); } } } private void parseCache() { CacheNamespace cacheDomain = type.getAnnotation(CacheNamespace.class); if (cacheDomain != null) { Integer size = cacheDomain.size() == 0 ? null : cacheDomain.size(); Long flushInterval = cacheDomain.flushInterval() == 0 ? null : cacheDomain.flushInterval(); assistant.useNewCache(cacheDomain.implementation(), cacheDomain.eviction(), flushInterval, size, cacheDomain.readWrite(), cacheDomain.blocking(), null); } } private void parseCacheRef() { CacheNamespaceRef cacheDomainRef = type.getAnnotation(CacheNamespaceRef.class); if (cacheDomainRef != null) { assistant.useCacheRef(cacheDomainRef.value().getName()); } } private String parseResultMap(Method method) { Class<?> returnType = getReturnType(method); ConstructorArgs args = method.getAnnotation(ConstructorArgs.class); Results results = method.getAnnotation(Results.class); TypeDiscriminator typeDiscriminator = method.getAnnotation(TypeDiscriminator.class); String resultMapId = generateResultMapName(method); applyResultMap(resultMapId, returnType, argsIf(args), resultsIf(results), typeDiscriminator); return resultMapId; } private String generateResultMapName(Method method) { Results results = method.getAnnotation(Results.class); if (results != null && !results.id().isEmpty()) { return type.getName() + "." + results.id(); } StringBuilder suffix = new StringBuilder(); for (Class<?> c : method.getParameterTypes()) { suffix.append("-"); suffix.append(c.getSimpleName()); } if (suffix.length() < 1) { suffix.append("-void"); } return type.getName() + "." + method.getName() + suffix; } private void applyResultMap(String resultMapId, Class<?> returnType, Arg[] args, Result[] results, TypeDiscriminator discriminator) { List<ResultMapping> resultMappings = new ArrayList<ResultMapping>(); applyConstructorArgs(args, returnType, resultMappings); applyResults(results, returnType, resultMappings); Discriminator disc = applyDiscriminator(resultMapId, returnType, discriminator); // TODO add AutoMappingBehaviour assistant.addResultMap(resultMapId, returnType, null, disc, resultMappings, null); createDiscriminatorResultMaps(resultMapId, returnType, discriminator); } private void createDiscriminatorResultMaps(String resultMapId, Class<?> resultType, TypeDiscriminator discriminator) { if (discriminator != null) { for (Case c : discriminator.cases()) { String caseResultMapId = resultMapId + "-" + c.value(); List<ResultMapping> resultMappings = new ArrayList<ResultMapping>(); // issue #136 applyConstructorArgs(c.constructArgs(), resultType, resultMappings); applyResults(c.results(), resultType, resultMappings); // TODO add AutoMappingBehaviour assistant.addResultMap(caseResultMapId, c.type(), resultMapId, null, resultMappings, null); } } } private Discriminator applyDiscriminator(String resultMapId, Class<?> resultType, TypeDiscriminator discriminator) { if (discriminator != null) { String column = discriminator.column(); Class<?> javaType = discriminator.javaType() == void.class ? String.class : discriminator.javaType(); JdbcType jdbcType = discriminator.jdbcType() == JdbcType.UNDEFINED ? null : discriminator.jdbcType(); Class<? extends TypeHandler<?>> typeHandler = discriminator.typeHandler() == UnknownTypeHandler.class ? null : discriminator.typeHandler(); Case[] cases = discriminator.cases(); Map<String, String> discriminatorMap = new HashMap<String, String>(); for (Case c : cases) { String value = c.value(); String caseResultMapId = resultMapId + "-" + value; discriminatorMap.put(value, caseResultMapId); } return assistant.buildDiscriminator(resultType, column, javaType, jdbcType, typeHandler, discriminatorMap); } return null; } void parseStatement(Method method) { Class<?> parameterTypeClass = getParameterType(method); LanguageDriver languageDriver = getLanguageDriver(method); SqlSource sqlSource = getSqlSourceFromAnnotations(method, parameterTypeClass, StatementType); if (sqlSource != null) { Options options = method.getAnnotation(Options.class); final String mappedStatementId = type.getName() + "." + method.getName(); Integer fetchSize = null; Integer timeout = null; StatementType statementType = StatementType.PREPARED; ResultSetType resultSetType = ResultSetType.FORWARD_ONLY; SqlCommandType sqlCommandType = getSqlCommandType(method); boolean isSelect = sqlCommandType == SqlCommandType.SELECT; boolean flushCache = !isSelect; boolean useCache = isSelect; KeyGenerator keyGenerator; String keyProperty = "id"; String keyColumn = null; if (SqlCommandType.INSERT.equals(sqlCommandType) || SqlCommandType.UPDATE.equals(sqlCommandType)) { // first check for SelectKey annotation - that overrides everything else SelectKey selectKey = method.getAnnotation(SelectKey.class); if (selectKey != null) { keyGenerator = handleSelectKeyAnnotation(selectKey, mappedStatementId, getParameterType(method), languageDriver); keyProperty = selectKey.keyProperty(); } else if (options == null) { keyGenerator = configuration.isUseGeneratedKeys() ? new Jdbc3KeyGenerator() : new NoKeyGenerator(); } else { keyGenerator = options.useGeneratedKeys() ? new Jdbc3KeyGenerator() : new NoKeyGenerator(); keyProperty = options.keyProperty(); keyColumn = options.keyColumn(); } } else { keyGenerator = new NoKeyGenerator(); } if (options != null) { flushCache = options.flushCache(); useCache = options.useCache(); //issue #348 fetchSize = options.fetchSize() > -1 || options.fetchSize() == Integer.MIN_VALUE ? options.fetchSize() : null; timeout = options.timeout() > -1 ? options.timeout() : null; statementType = options.statementType(); resultSetType = options.resultSetType(); } String resultMapId = null; ResultMap resultMapAnnotation = method.getAnnotation(ResultMap.class); if (resultMapAnnotation != null) { String[] resultMaps = resultMapAnnotation.value(); StringBuilder sb = new StringBuilder(); for (String resultMap : resultMaps) { if (sb.length() > 0) { sb.append(","); } sb.append(resultMap); } resultMapId = sb.toString(); } else if (isSelect) { resultMapId = parseResultMap(method); } final Select select = method.getAnnotation(Select.class); assistant.addMappedStatement(mappedStatementId, sqlSource, statementType, sqlCommandType, fetchSize, timeout, null, parameterTypeClass, resultMapId, getReturnType(method), resultSetType, flushCache, useCache, false, keyGenerator, keyProperty, keyColumn, null, languageDriver, select != null ? nullOrEmpty(options.resultSets()) : null); } } private LanguageDriver getLanguageDriver(Method method) { Lang lang = method.getAnnotation(Lang.class); Class<?> langClass = null; if (lang != null) { langClass = lang.value(); } return assistant.getLanguageDriver(langClass); } private Class<?> getParameterType(Method method) { Class<?> parameterType = null; Class<?>[] parameterTypes = method.getParameterTypes(); for (int i = 0; i < parameterTypes.length; i++) { if (!RowBounds.class.isAssignableFrom(parameterTypes[i]) && !ResultHandler.class.isAssignableFrom(parameterTypes[i])) { if (parameterType == null) { parameterType = parameterTypes[i]; } else { // issue #135 parameterType = ParamMap.class; } } } return parameterType; } private Class<?> getReturnType(Method method) { Class<?> returnType = method.getReturnType(); if (void.class.equals(returnType)) { ResultType rt = method.getAnnotation(ResultType.class); if (rt != null) { returnType = rt.value(); } } else if (Collection.class.isAssignableFrom(returnType)) { Type returnTypeParameter = method.getGenericReturnType(); if (returnTypeParameter instanceof ParameterizedType) { Type[] actualTypeArguments = ((ParameterizedType) returnTypeParameter).getActualTypeArguments(); if (actualTypeArguments != null && actualTypeArguments.length == 1) { returnTypeParameter = actualTypeArguments[0]; if (returnTypeParameter instanceof Class) { returnType = (Class<?>) returnTypeParameter; } else if (returnTypeParameter instanceof ParameterizedType) { // (issue #443) actual type can be a also a parameterized type returnType = (Class<?>) ((ParameterizedType) returnTypeParameter).getRawType(); } else if (returnTypeParameter instanceof GenericArrayType) { Class<?> componentType = (Class<?>) ((GenericArrayType) returnTypeParameter).getGenericComponentType(); // (issue #525) support List<byte[]> returnType = Array.newInstance(componentType, 0).getClass(); } } } } else if (method.isAnnotationPresent(MapKey.class) && Map.class.isAssignableFrom(returnType)) { // (issue 504) Do not look into Maps if there is not MapKey annotation Type returnTypeParameter = method.getGenericReturnType(); if (returnTypeParameter instanceof ParameterizedType) { Type[] actualTypeArguments = ((ParameterizedType) returnTypeParameter).getActualTypeArguments(); if (actualTypeArguments != null && actualTypeArguments.length == 2) { returnTypeParameter = actualTypeArguments[1]; if (returnTypeParameter instanceof Class) { returnType = (Class<?>) returnTypeParameter; } else if (returnTypeParameter instanceof ParameterizedType) { // (issue 443) actual type can be a also a parameterized type returnType = (Class<?>) ((ParameterizedType) returnTypeParameter).getRawType(); } } } } return returnType; } private SqlSource getSqlSourceFromAnnotations(Method method, Class<?> parameterType, LanguageDriver languageDriver) { try { Class<? extends Annotation> sqlAnnotationType = getSqlAnnotationType(method); Class<? extends Annotation> sqlProviderAnnotationType = getSqlProviderAnnotationType(method); if (sqlAnnotationType != null) { if (sqlProviderAnnotationType != null) { throw new BindingException("You cannot supply both a static SQL and SqlProvider to method named " + method.getName()); } Annotation sqlAnnotation = method.getAnnotation(sqlAnnotationType); final String[] strings = (String[]) sqlAnnotation.getClass().getMethod("value").invoke(sqlAnnotation); return buildSqlSourceFromStrings(strings, parameterType, languageDriver); } else if (sqlProviderAnnotationType != null) { Annotation sqlProviderAnnotation = method.getAnnotation(sqlProviderAnnotationType); return new ProviderSqlSource(assistant.getConfiguration(), sqlProviderAnnotation); } return null; } catch (Exception e) { throw new BuilderException("Could not find value method on SQL annotation. Cause: " + e, e); } } private SqlSource buildSqlSourceFromStrings(String[] strings, Class<?> parameterTypeClass, LanguageDriver languageDriver) { final StringBuilder sql = new StringBuilder(); for (String fragment : strings) { sql.append(fragment); sql.append(" "); } return languageDriver.createSqlSource(configuration, sql.toString().trim(), parameterTypeClass); } private SqlCommandType getSqlCommandType(Method method) { Class<? extends Annotation> type = getSqlAnnotationType(method); if (type == null) { type = getSqlProviderAnnotationType(method); if (type == null) { return SqlCommandType.UNKNOWN; } if (type == SelectProvider.class) { type = Select.class; } else if (type == InsertProvider.class) { type = Insert.class; } else if (type == UpdateProvider.class) { type = Update.class; } else if (type == DeleteProvider.class) { type = Delete.class; } } return SqlCommandType.valueOf(type.getSimpleName().toUpperCase(Locale.ENGLISH)); } private Class<? extends Annotation> getSqlAnnotationType(Method method) { return chooseAnnotationType(method, sqlAnnotationTypes); } private Class<? extends Annotation> getSqlProviderAnnotationType(Method method) { return chooseAnnotationType(method, sqlProviderAnnotationTypes); } private Class<? extends Annotation> chooseAnnotationType(Method method, Set<Class<? extends Annotation>> types) { for (Class<? extends Annotation> type : types) { Annotation annotation = method.getAnnotation(type); if (annotation != null) { return type; } } return null; } private void applyResults(Result[] results, Class<?> resultType, List<ResultMapping> resultMappings) { for (Result result : results) { List<ResultFlag> flags = new ArrayList<ResultFlag>(); if (result.id()) { flags.add(ResultFlag.ID); } ResultMapping resultMapping = assistant.buildResultMapping(resultType, nullOrEmpty(result.property()), nullOrEmpty(result.column()), result.javaType() == void.class ? null : result.javaType(), result.jdbcType() == JdbcType.UNDEFINED ? null : result.jdbcType(), hasNestedSelect(result) ? nestedSelectId(result) : null, null, null, null, result.typeHandler() == UnknownTypeHandler.class ? null : result.typeHandler(), flags, null, null, isLazy(result)); resultMappings.add(resultMapping); } } private String nestedSelectId(Result result) { String nestedSelect = result.one().select(); if (nestedSelect.length() < 1) { nestedSelect = result.many().select(); } if (!nestedSelect.contains(".")) { nestedSelect = type.getName() + "." + nestedSelect; } return nestedSelect; } private boolean isLazy(Result result) { boolean isLazy = configuration.isLazyLoadingEnabled(); if (result.one().select().length() > 0 && FetchType.DEFAULT != result.one().fetchType()) { isLazy = (result.one().fetchType() == FetchType.LAZY); } else if (result.many().select().length() > 0 && FetchType.DEFAULT != result.many().fetchType()) { isLazy = (result.many().fetchType() == FetchType.LAZY); } return isLazy; } private boolean hasNestedSelect(Result result) { if (result.one().select().length() > 0 && result.many().select().length() > 0) { throw new BuilderException("Cannot use both @One and @Many annotations in the same @Result"); } return result.one().select().length() > 0 || result.many().select().length() > 0; } private void applyConstructorArgs(Arg[] args, Class<?> resultType, List<ResultMapping> resultMappings) { for (Arg arg : args) { List<ResultFlag> flags = new ArrayList<ResultFlag>(); flags.add(ResultFlag.CONSTRUCTOR); if (arg.id()) { flags.add(ResultFlag.ID); } ResultMapping resultMapping = assistant.buildResultMapping(resultType, null, nullOrEmpty(arg.column()), arg.javaType() == void.class ? null : arg.javaType(), arg.jdbcType() == JdbcType.UNDEFINED ? null : arg.jdbcType(), nullOrEmpty(arg.select()), nullOrEmpty(arg.resultMap()), null, null, arg.typeHandler() == UnknownTypeHandler.class ? null : arg.typeHandler(), flags, null, null, false); resultMappings.add(resultMapping); } } private String nullOrEmpty(String value) { return value == null || value.trim().length() == 0 ? null : value; } private Result[] resultsIf(Results results) { return results == null ? new Result[0] : results.value(); } private Arg[] argsIf(ConstructorArgs args) { return args == null ? new Arg[0] : args.value(); } private KeyGenerator handleSelectKeyAnnotation(SelectKey selectKeyAnnotation, String baseStatementId, Class<?> parameterTypeClass, LanguageDriver languageDriver) { String id = baseStatementId + SelectKeyGenerator.SELECT_KEY_SUFFIX; Class<?> resultTypeClass = selectKeyAnnotation.resultType(); StatementType statementType = selectKeyAnnotation.statementType(); String keyProperty = selectKeyAnnotation.keyProperty(); String keyColumn = selectKeyAnnotation.keyColumn(); boolean executeBefore = selectKeyAnnotation.before(); // defaults boolean useCache = false; KeyGenerator keyGenerator = new NoKeyGenerator(); Integer fetchSize = null; Integer timeout = null; boolean flushCache = false; String parameterMap = null; String resultMap = null; ResultSetType resultSetTypeEnum = null; SqlSource sqlSource = buildSqlSourceFromStrings(selectKeyAnnotation.statement(), parameterTypeClass, languageDriver); SqlCommandType sqlCommandType = SqlCommandType.SELECT; assistant.addMappedStatement(id, sqlSource, statementType, sqlCommandType, fetchSize, timeout, parameterMap, parameterTypeClass, resultMap, resultTypeClass, resultSetTypeEnum, flushCache, useCache, false, keyGenerator, keyProperty, keyColumn, null, languageDriver, null); id = assistant.applyCurrentNamespace(id, false); MappedStatement keyStatement = configuration.getMappedStatement(id, false); SelectKeyGenerator answer = new SelectKeyGenerator(keyStatement, executeBefore); configuration.addKeyGenerator(id, answer); return answer; } }
37e288a0777318b972772ab7021e09405f721c6d
cb1bca30868ce143ed0198d4002680c1be786ccc
/src/main/java/com/bookstore/servlets/SignIn.java
59b1629ce83c02bf839321d968aac4ec21c182aa
[]
no_license
MaxYaro/YaroshenkoWeb
ea4520857d061902d76f241bc861f60d179f8dae
ce3f3e1689bb7d205be045d8fa0915f3a9aceb15
refs/heads/master
2022-12-28T07:30:53.251666
2020-05-29T00:56:34
2020-05-29T00:56:34
267,728,641
0
0
null
2020-10-13T22:23:54
2020-05-29T00:40:42
Java
UTF-8
Java
false
false
1,275
java
package com.bookstore.servlets; import java.io.IOException; import java.util.ArrayList; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import com.bookstore.db.Users; import com.bookstore.operationsdb.SelectUsers; public class SignIn extends HttpServlet { private static final long serialVersionUID = 1L; protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String login = request.getParameter("login"); String password = request.getParameter("password"); SelectUsers selectUsers = new SelectUsers(); ArrayList<Users> users = selectUsers.getUsersbyLogin(login); HttpSession session = request.getSession(); try { if (users.size() > 0) { if (password.equals(users.get(0).getPassword())) { session.setAttribute("loginSession", login); response.sendRedirect("/bookstore/SuccesfulSignIn"); } else { response.sendRedirect("/bookstore/WrongLoginOrPassword"); } } else { response.sendRedirect("/bookstore/WrongLoginOrPassword"); } } catch (Exception e) { System.out.println(e); } } }
1d8cbd52b3e0deebbe761d72ef6d71d01b9e147a
7da3f7e63fc9c02295af692ad3f43b221108e216
/src/com/xz/calculate/MainActivity.java
b436686d77f47225400f8d6738886c2811ac4610
[]
no_license
zhumingmin/calculate
c28c29ced4e30969162330415ab91a6fd80b4a6a
4a8d6b574cf785297ce78fa59a09744fe5d5e4be
refs/heads/master
2021-01-19T05:05:46.349160
2016-07-08T01:11:53
2016-07-08T01:11:53
62,814,237
1
0
null
null
null
null
UTF-8
Java
false
false
9,643
java
package com.xz.calculate; import android.app.Activity; import android.os.Bundle; import android.view.View; import android.view.Window; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; public class MainActivity extends Activity { private Button bt_mc, bt_m1, bt_m2, bt_mr, bt_ac, bt_jiajian, bt_chu, bt_cheng, bt_jian, bt_jia, bt_9, bt_8, bt_7, bt_6, bt_5, bt_4, bt_3, bt_2, bt_1, bt_0, bt_dian, bt_delete, bt_dengyu; private TextView tv_a, tv_fangfa, tv_b, tv_dengyuhao, tv_result; private String fangfa = null; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.activity_main); initView(); delete(); button(); } private void button() { // TODO Auto-generated method stub bt_0.setOnClickListener(new Button.OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub if (tv_a.getText() == "") { tv_a.setText(tv_a.getText().toString() + "0"); } else if (tv_fangfa.getText() == "") { tv_a.setText(tv_a.getText().toString() + "0"); } else { tv_b.setText(tv_b.getText().toString() + "0"); } } }); bt_1.setOnClickListener(new Button.OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub if (tv_a.getText() == "") { tv_a.setText(tv_a.getText().toString() + "1"); } else if (tv_fangfa.getText() == "") { tv_a.setText(tv_a.getText().toString() + "1"); } else { tv_b.setText(tv_b.getText().toString() + "1"); } } }); bt_2.setOnClickListener(new Button.OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub if (tv_a.getText() == "") { tv_a.setText(tv_a.getText().toString() + "2"); } else if (tv_fangfa.getText() == "") { tv_a.setText(tv_a.getText().toString() + "2"); } else { tv_b.setText(tv_b.getText().toString() + "2"); } } }); bt_3.setOnClickListener(new Button.OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub if (tv_a.getText() == "") { tv_a.setText(tv_a.getText().toString() + "3"); } else if (tv_fangfa.getText() == "") { tv_a.setText(tv_a.getText().toString() + "3"); } else { tv_b.setText(tv_b.getText().toString() + "3"); } } }); bt_4.setOnClickListener(new Button.OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub if (tv_a.getText() == "") { tv_a.setText(tv_a.getText().toString() + "4"); } else if (tv_fangfa.getText() == "") { tv_a.setText(tv_a.getText().toString() + "4"); } else { tv_b.setText(tv_b.getText().toString() + "4"); } } }); bt_5.setOnClickListener(new Button.OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub if (tv_a.getText() == "") { tv_a.setText(tv_a.getText().toString() + "5"); } else if (tv_fangfa.getText() == "") { tv_a.setText(tv_a.getText().toString() + "5"); } else { tv_b.setText(tv_b.getText().toString() + "5"); } } }); bt_6.setOnClickListener(new Button.OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub if (tv_a.getText() == "") { tv_a.setText(tv_a.getText().toString() + "6"); } else if (tv_fangfa.getText() == "") { tv_a.setText(tv_a.getText().toString() + "6"); } else { tv_b.setText(tv_b.getText().toString() + "6"); } } }); bt_7.setOnClickListener(new Button.OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub if (tv_a.getText() == "") { tv_a.setText(tv_a.getText().toString() + "7"); } else if (tv_fangfa.getText() == "") { tv_a.setText(tv_a.getText().toString() + "7"); } else { tv_b.setText(tv_b.getText().toString() + "7"); } } }); bt_8.setOnClickListener(new Button.OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub if (tv_a.getText() == "") { tv_a.setText(tv_a.getText().toString() + "8"); } else if (tv_fangfa.getText() == "") { tv_a.setText(tv_a.getText().toString() + "8"); } else { tv_b.setText(tv_b.getText().toString() + "8"); } } }); bt_9.setOnClickListener(new Button.OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub if (tv_a.getText() == "") { tv_a.setText(tv_a.getText().toString() + "9"); } else if (tv_fangfa.getText() == "") { tv_a.setText(tv_a.getText().toString() + "9"); } else { tv_b.setText(tv_b.getText().toString() + "9"); } } }); bt_jia.setOnClickListener(new Button.OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub tv_fangfa.setText("+"); fangfa = "+"; } }); bt_jian.setOnClickListener(new Button.OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub tv_fangfa.setText("-"); fangfa = "-"; } }); bt_cheng.setOnClickListener(new Button.OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub tv_fangfa.setText("×"); fangfa = "×"; } }); bt_chu.setOnClickListener(new Button.OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub tv_fangfa.setText("÷"); fangfa = "÷"; } }); bt_dian.setOnClickListener(new Button.OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub if (tv_fangfa.getText() == "") { tv_a.setText(tv_a.getText().toString() + "."); } else { tv_b.setText(tv_b.getText().toString() + "."); } } }); bt_dengyu.setOnClickListener(new Button.OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub tv_dengyuhao.setText("="); switch (fangfa) { case "+": { Double a, b, c; if (tv_b.getText() != "") { a = Double.parseDouble(tv_a.getText().toString()); b = Double.parseDouble(tv_b.getText().toString()); c = a + b; String d = Double.toString(c); tv_result.setText(d); } else { tv_result.setText("erro"); } break; } case "-": { Double a, b, c; if (tv_b.getText() != "") { a = Double.parseDouble(tv_a.getText().toString()); b = Double.parseDouble(tv_b.getText().toString()); c = a - b; String d = Double.toString(c); tv_result.setText(d); } else { tv_result.setText("erro"); } break; } case "×": { Double a, b, c; if (tv_b.getText() != "") { a = Double.parseDouble(tv_a.getText().toString()); b = Double.parseDouble(tv_b.getText().toString()); c = a * b; String d = Double.toString(c); tv_result.setText(d); } else { tv_result.setText("erro"); } break; } case "÷": { Double a, b, c; if (tv_b.getText().toString() == "0" || tv_b.getText() == "") { DisplayToast("除数不可为0"); tv_result.setText("erro"); } else { a = Double.parseDouble(tv_a.getText().toString()); b = Double.parseDouble(tv_b.getText().toString()); c = a / b; String d = Double.toString(c); tv_result.setText(d); } break; } } } }); } private void delete() { // TODO Auto-generated method stub bt_delete.setOnClickListener(new Button.OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub tv_a.setText(""); tv_fangfa.setText(""); tv_b.setText(""); tv_dengyuhao.setText(""); tv_result.setText(""); } }); } private void initView() { // TODO Auto-generated method stub tv_a = (TextView) findViewById(R.id.tv_a); tv_fangfa = (TextView) findViewById(R.id.tv_fangfa); tv_b = (TextView) findViewById(R.id.tv_b); tv_dengyuhao = (TextView) findViewById(R.id.tv_dengyuhao); tv_result = (TextView) findViewById(R.id.tv_result); bt_mc = (Button) findViewById(R.id.bt_mc); bt_m1 = (Button) findViewById(R.id.bt_m1); bt_m2 = (Button) findViewById(R.id.bt_m2); bt_mr = (Button) findViewById(R.id.bt_mr); bt_ac = (Button) findViewById(R.id.bt_ac); bt_jiajian = (Button) findViewById(R.id.bt_jiajian); bt_chu = (Button) findViewById(R.id.bt_chu); bt_cheng = (Button) findViewById(R.id.bt_cheng); bt_jian = (Button) findViewById(R.id.bt_jian); bt_jia = (Button) findViewById(R.id.bt_jia); bt_9 = (Button) findViewById(R.id.bt_9); bt_8 = (Button) findViewById(R.id.bt_8); bt_7 = (Button) findViewById(R.id.bt_7); bt_6 = (Button) findViewById(R.id.bt_6); bt_5 = (Button) findViewById(R.id.bt_5); bt_4 = (Button) findViewById(R.id.bt_4); bt_3 = (Button) findViewById(R.id.bt_3); bt_2 = (Button) findViewById(R.id.bt_2); bt_1 = (Button) findViewById(R.id.bt_1); bt_0 = (Button) findViewById(R.id.bt_0); bt_dian = (Button) findViewById(R.id.bt_dian); bt_delete = (Button) findViewById(R.id.bt_delete); bt_dengyu = (Button) findViewById(R.id.bt_dengyu); } private void DisplayToast(String string) { // TODO Auto-generated method stub Toast.makeText(this, string, Toast.LENGTH_SHORT).show(); } }
752c6333894dad670fcffe7f85ba40387834e800
78bcabbf50d6daf269334778a4b131402bef6d5c
/src/main/java/com/learnings/practise/problems/binary_search_tree/InOrderPredecessor.java
b10d7a8f62459011a7ab0806dfa446d00728f8d0
[]
no_license
Personal-Learnings/CodeIsLife
760aa7bde789736311b1e7623d6555a497eefcdb
2696e4a43011ed2574726c7bab957ef142e1d240
refs/heads/master
2020-07-28T16:23:11.265077
2020-03-12T23:00:41
2020-03-12T23:00:41
209,463,763
1
0
null
null
null
null
UTF-8
Java
false
false
5,572
java
package com.learnings.practise.problems.binary_search_tree; public class InOrderPredecessor<T> { private Integer findInOrderPredecessor(Node<T> tree, T data) throws Exception { Node<T> foundNode = search(tree, data); if(null == foundNode) { throw new Exception(String.format("Node %s Not Found.", data)); } else { if(null == foundNode.getLeftNode()) { Integer predecessor = null; Node<T> iteratorNode = tree; while(!iteratorNode.getData().equals(foundNode.getData())) { if((Integer) iteratorNode.getData() < (Integer) foundNode.getData()) { predecessor = (Integer) iteratorNode.getData(); iteratorNode = iteratorNode.getRightNode(); } else { iteratorNode = iteratorNode.getLeftNode(); } } if(predecessor == null) { throw new Exception(String.format("Predecessor Node Not Found as Node %s is the Least Node in the Tree.", data)); } return predecessor; } else { return (Integer) getMax(foundNode.getLeftNode(), foundNode.getLeftNode()); } } } private T getMax(Node<T> parentNode, Node<T> currentNode) { if(currentNode == null) return parentNode.getData(); return getMax(currentNode, currentNode.getRightNode()); } private Node<T> search(Node<T> currentNode, T data) { if(currentNode == null) return null; else if(currentNode.getData().equals(data)) { return currentNode; } else if((Integer) currentNode.getData() > (Integer) data) { return search(currentNode.getLeftNode(), data); } else { return search(currentNode.getRightNode(), data); } } public static void main(String[] args) throws Exception { Node<Integer> tree = setupAndGetData(); InOrderPredecessor<Integer> inOrderPredecessor = new InOrderPredecessor<>(); try { inOrderPredecessor.findInOrderPredecessor(tree, 100); } catch (Exception e) { System.out.println(e.getMessage()); } System.out.println("Inorder Predecessor of 19 is: " + inOrderPredecessor.findInOrderPredecessor(tree, 19)); System.out.println("Inorder Predecessor of 5 is: " + inOrderPredecessor.findInOrderPredecessor(tree, 5)); System.out.println("Inorder Predecessor of 7 is: " + inOrderPredecessor.findInOrderPredecessor(tree, 7)); System.out.println("Inorder Predecessor of 12 is: " + inOrderPredecessor.findInOrderPredecessor(tree, 12)); System.out.println("Inorder Predecessor of 16 is: " + inOrderPredecessor.findInOrderPredecessor(tree, 16)); System.out.println("Inorder Predecessor of 10 is: " + inOrderPredecessor.findInOrderPredecessor(tree, 10)); System.out.println("Inorder Predecessor of 13 is: " + inOrderPredecessor.findInOrderPredecessor(tree, 13)); System.out.println("Inorder Predecessor of 42 is: " + inOrderPredecessor.findInOrderPredecessor(tree, 42)); try { inOrderPredecessor.findInOrderPredecessor(tree, 3); } catch (Exception e) { System.out.println(e.getMessage()); } } private static Node<Integer> setupAndGetData() { Node<Integer> treeLeft = new Node<>( new Node<>( new Node<>(new Node<>(null, 3, null), 4, null ), 5, new Node<>( new Node<>( new Node<>(null, 6, null), 7, null ), 8, null ) ), 9, new Node<>( new Node<>(null, 10, null), 11, new Node<>(null, 12, null)) ); Node<Integer> treeRight = new Node<>( new Node<>( new Node<>( new Node<>(null, 14, null), 15, null ), 16, null ), 19, new Node<>( null, 27, new Node<>( null, 32, new Node<>(null, 42, null) ))); return new Node<>( treeLeft, 13, treeRight ); } private static class Node<T> { private T data; private Node<T> leftNode; private Node<T> rightNode; Node(Node<T> leftNode, T element, Node<T> rightNode) { this.leftNode = leftNode; this.data = element; this.rightNode = rightNode; } T getData() { return data; } Node<T> getLeftNode() { return leftNode; } Node<T> getRightNode() { return rightNode; } } }
42b5ad40829c57518331df361fa43ea446f565b0
b890395690103043c3a36f6e6f1fd9dc19e39eb7
/app/src/main/java/android/example/bmicalculator/MainActivity.java
d8c3197100c4976fb5a99cfdb7306fa24de3ba82
[]
no_license
ihyaet/BMICalculator
011aaa1b1d07a6f8fa12b876cf91e593f9459e5b
cfa95be2e257c22a7caf123c0583f5b1451dc8c9
refs/heads/master
2020-09-09T06:06:14.528729
2019-11-13T04:07:08
2019-11-13T04:07:08
221,369,586
0
0
null
null
null
null
UTF-8
Java
false
false
1,496
java
package android.example.bmicalculator; import androidx.appcompat.app.AppCompatActivity; import android.app.ActionBar; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.util.Log; import android.view.View; import android.view.Window; import android.view.WindowManager; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); /* View decorView = getWindow().getDecorView(); // Hide the status bar. int uiOptions = View.SYSTEM_UI_FLAG_FULLSCREEN; decorView.setSystemUiVisibility(uiOptions); // Remember that you should never show the action bar if the // status bar is hidden, so hide that too if necessary. ActionBar actionBar = getActionBar(); actionBar.hide();*/ } public void bukaAct2(View view) { Intent intent = new Intent(MainActivity.this, SecondActivity.class); startActivity(intent); } public void clickIG(View view) { String url = "https://instagram.com/ihyaet"; Uri webpage = Uri.parse(url); Intent intent = new Intent(Intent.ACTION_VIEW, webpage); if (intent.resolveActivity(getPackageManager()) != null) { startActivity(intent); } else { Log.d("ImplicitIntents", "Can't handle this intent!"); } } }
03353ee80a7a531b3576384a4b2e6a98f24545ce
5fb8bc38bca5d6d7d3301f337f32da2a90c3fa13
/src/test/java/unitTesting/UnitTestParametrized.java
ce1f445d9b20eed59544d5e319f6131b11647a86
[]
no_license
baur100/a10
c0bf42b9db9457aed6cb2180edefeb1f75b83c0f
c646b6e09199ba144fced29aa6b374709111e63e
refs/heads/main
2023-04-06T07:59:41.118813
2021-04-14T02:28:14
2021-04-14T02:28:14
335,495,750
0
0
null
2021-03-20T20:23:39
2021-02-03T03:26:29
Java
UTF-8
Java
false
false
729
java
package unitTesting; import org.testng.Assert; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import tickets.CalculateTicketPrice; public class UnitTestParametrized { @DataProvider (name = "testData") public Object[][] getTestData(){ return new Object[][]{ {1,1000,0.0}, {5,1000,500.0}, {29,1000,1000.0}, {75,1000,800.0} }; } @Test(dataProvider = "testData") public void calculateTicketPrice(int age, int fare, double price){ CalculateTicketPrice person = new CalculateTicketPrice(fare,age); double result = person.getPrice(); Assert.assertEquals(price,result); } }
d870cfab0c4dc5257ea8e70e4e59dec723495cad
e594842f49ffde8d4c4558e0533949aeab3a4e77
/src/main/java/com/ocelot/mod/game/core/level/tile/ConnectedTile.java
8af351896e33b70a5b509f102d990ee4cda7d9d7
[]
no_license
Ocelot5836/SuperMarioWorldApplication
dfcc98b1af8c79e441f8e1a9d086cf3c1489526f
62abe057c3dda74ac32f08d7b341cfbc1ff618ac
refs/heads/master
2021-04-26T21:47:59.960202
2018-11-15T05:51:02
2018-11-15T05:51:02
124,160,876
4
2
null
2018-03-07T21:20:27
2018-03-07T01:28:28
Java
UTF-8
Java
false
false
6,092
java
package com.ocelot.mod.game.core.level.tile; import com.ocelot.mod.game.core.gfx.Sprite; import com.ocelot.mod.game.core.level.TileMap; import com.ocelot.mod.game.core.level.tile.property.PropertyString; import com.ocelot.mod.game.core.level.tile.property.TileStateContainer; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.Gui; import net.minecraft.util.ResourceLocation; /** * <em><b>Copyright (c) 2018 Ocelot5836.</b></em> * * <br> * </br> * * Allows a tile's sprite to link with those around them that are the same tile. * * @author Ocelot5836 */ public class ConnectedTile extends BasicTile { /** The tile connections */ public static final PropertyString CONNECTIONS = PropertyString.create("connections", "000000000"); protected Sprite[] sprites; protected ConnectedTile(String unlocalizedName) { super(unlocalizedName); } public ConnectedTile(String unlocalizedName, ResourceLocation sheet, int u, int v, int textureWidth, int textureHeight) { this(unlocalizedName, sheet, u, v, textureWidth, textureHeight, 16); } public ConnectedTile(String unlocalizedName, ResourceLocation sheet, int u, int v, int textureWidth, int textureHeight, int tileSize) { super(unlocalizedName); this.sprites = new Sprite[13]; for (int x = 0; x < 3; x++) { for (int y = 0; y < 3; y++) { sprites[x + y * 3] = new Sprite(sheet, u + x * tileSize, v + y * tileSize, tileSize, tileSize, textureWidth, textureHeight); } } for (int i = 0; i < 4; i++) { sprites[i + 9] = new Sprite(sheet, u + (i % 2) * tileSize, v + (i / 2) * tileSize + tileSize * 3, tileSize, tileSize, textureWidth, textureHeight); } } @Override public TileStateContainer modifyContainer(int x, int y, TileMap tileMap, TileStateContainer container) { String value = container.getValue(CONNECTIONS); if (value != null && value.length() == 9) { StringBuilder connections = new StringBuilder(); for (int i = 0; i < 9; i++) { int xx = i % 3; int yy = i / 3; int tileX = x + xx - 1; int tileY = y + yy - 1; connections.append(this.canConnectTo(tileX, tileY, tileMap) ? 1 : 0); } container.setValue(CONNECTIONS, connections.toString()); } return container; } public boolean canConnectTo(int x, int y, TileMap tileMap) { Tile tile = tileMap.getTile(x, y); return tile == this || tile == Tile.VOID; } @Override public void render(double x, double y, TileMap tileMap, Gui gui, Minecraft mc, int mouseX, int mouseY, float partialTicks) { // if (getValue(UP) != null && getValue(DOWN) != null && getValue(LEFT) != null && getValue(RIGHT) != null) { // boolean up = (boolean) getValue(UP); // boolean down = (boolean) getValue(DOWN); // boolean left = (boolean) getValue(LEFT); // boolean right = (boolean) getValue(RIGHT); // // if (up && down) { // if (left && right) { // sprites[4].render(x, y, 16, 16); // } else if (left) { // sprites[5].render(x, y, 16, 16); // } else if (right) { // sprites[3].render(x, y, 16, 16); // } // } else if (up) { // if (left && right) { // sprites[7].render(x, y, 16, 16); // } else if (left) { // sprites[8].render(x, y, 16, 16); // } else if (right) { // sprites[6].render(x, y, 16, 16); // } // } else if (down) { // if (left && right) { // sprites[1].render(x, y, 16, 16); // } else if (left) { // sprites[2].render(x, y, 16, 16); // } else if (right) { // sprites[0].render(x, y, 16, 16); // } // } else { // sprites[1].render(x, y, 16, 16); // } // } else { // sprites[1].render(x, y, 16, 16); // } String value = getValue(CONNECTIONS); if (value != null && value.length() == 9) { boolean upLeft = (value.charAt(0) + "").equalsIgnoreCase("1"); boolean up = (value.charAt(1) + "").equalsIgnoreCase("1"); boolean upRight = (value.charAt(2) + "").equalsIgnoreCase("1"); boolean left = (value.charAt(3) + "").equalsIgnoreCase("1"); boolean right = (value.charAt(5) + "").equalsIgnoreCase("1"); boolean downLeft = (value.charAt(6) + "").equalsIgnoreCase("1"); boolean down = (value.charAt(7) + "").equalsIgnoreCase("1"); boolean downRight = (value.charAt(8) + "").equalsIgnoreCase("1"); if (up && down) { if (left && right) { if (upLeft && upRight) { if (downLeft && downRight) { sprites[4].render(x, y, 16, 16); } else if (downLeft) { sprites[9].render(x, y, 16, 16); } else if (downRight) { sprites[10].render(x, y, 16, 16); } else { sprites[4].render(x, y, 16, 16); } } else if (upLeft) { sprites[11].render(x, y, 16, 16); } else if (upRight) { sprites[12].render(x, y, 16, 16); } else { sprites[4].render(x, y, 16, 16); } } else if (left) { sprites[5].render(x, y, 16, 16); } else if (right) { sprites[3].render(x, y, 16, 16); } else { sprites[4].render(x, y, 16, 16); } } else if (up) { if (left && right) { if (upLeft && upRight) { sprites[7].render(x, y, 16, 16); } else if (upLeft) { sprites[11].render(x, y, 16, 16); } else if (upRight) { sprites[12].render(x, y, 16, 16); } else { sprites[7].render(x, y, 16, 16); } } else if (left) { sprites[8].render(x, y, 16, 16); } else if (right) { sprites[6].render(x, y, 16, 16); } else { sprites[7].render(x, y, 16, 16); } } else if (down) { if (left && right) { sprites[1].render(x, y, 16, 16); } else if (left) { sprites[2].render(x, y, 16, 16); } else if (right) { sprites[0].render(x, y, 16, 16); } else { sprites[1].render(x, y, 16, 16); } } else { sprites[1].render(x, y, 16, 16); } } else { sprites[1].render(x, y, 16, 16); } } @Override public TileStateContainer createContainer() { return new TileStateContainer(this, CONNECTIONS); } }
94d8a3bb844567961b7e7204a2a694d936929745
5c0fc978e096fd9b442b583c75e65297ce6badb8
/src/main/java/com/_37coins/bcJsonRpc/pojo/Vin.java
686a65be9b69ccfcd4672c53bafa60bf6324c6d3
[]
no_license
hernss/SocialSendApiRest
6a9db0deff6be8364f59248e049b683ebeada132
9f255d4ef3f7570152a44076ef4ae96e5972dc70
refs/heads/master
2020-03-07T15:13:00.892344
2018-04-11T20:55:01
2018-04-11T20:55:01
127,548,555
0
0
null
null
null
null
UTF-8
Java
false
false
1,738
java
package com._37coins.bcJsonRpc.pojo; import java.math.BigDecimal; public class Vin { /*"vin" : [ { "coinbase" : "039cd9020101", "sequence" : 4294967295 } ], */ /* * { "txid" : "755258f2c0233ed6e503597551ee5ae7cd45d2884cbdade476e7e044d4ec50b4", "vout" : 1, "scriptSig" : { "asm" : "3045022100e35212c225f54a927359888964ac505022bd17038bfd4a79f335570aada95549022049da0d79c6dbe6396f87c302b38391cc88ff0620b08ad6a6eace6f65ff8e2eb801 02d29abd37b099eaeef5db8e7e980aad2242ffce391b3b00fa61e8f001bfb48d22", "hex" : "483045022100e35212c225f54a927359888964ac505022bd17038bfd4a79f335570aada95549022049da0d79c6dbe6396f87c302b38391cc88ff0620b08ad6a6eace6f65ff8e2eb8012102d29abd37b099eaeef5db8e7e980aad2242ffce391b3b00fa61e8f001bfb48d22" }, "sequence" : 4294967295 } */ private String coinbase; private BigDecimal sequence; private long vout; private String txid; private ScriptPubKey scriptSig; public String getCoinbase() { return coinbase; } public void setCoinbase(String coinbase) { this.coinbase = coinbase; } public BigDecimal getSequence() { return sequence; } public void setSequence(BigDecimal sequence) { this.sequence = sequence; } public long getVout() { return vout; } public void setVout(long vout) { this.vout = vout; } public String getTxid() { return txid; } public void setTxid(String txid) { this.txid = txid; } public ScriptPubKey getScriptSig() { return scriptSig; } public void setScriptSig(ScriptPubKey scriptSig) { this.scriptSig = scriptSig; } }
bbac88c1e83c4f81a303c5b89f3a377a96b8f4cf
7585bbcfad09b1236d00f0d62cd0109b9b27e706
/lishiMobile/src/main/java/com/lis99/mobile/club/model/ClubMainListModel.java
a47e3367385d93d3474bc2637b9e11937a366816
[]
no_license
xiaxiao1/Lis99Test
d7c943e25456bf341b43cd9da1a67bfe29fc55b2
43c3b2bb0b53dcee80d990a7ef8b5de44b5e9144
refs/heads/master
2020-06-30T23:44:50.990863
2016-11-21T09:41:37
2016-11-21T09:41:37
74,347,642
0
0
null
null
null
null
UTF-8
Java
false
false
359
java
package com.lis99.mobile.club.model; /** * Created by yy on 15/8/4. */ public class ClubMainListModel extends BaseModel { //状态标识 public int type; public int id; public String image; public String title; public String topic_title; public int topic_id; /**是否同城:0否,1是*/ public int is_samecity; }
a4368b861b7ac1b92cd95450f302c551b3c1048a
6e34771b226ed10b2f08b45b404eb60e8a86e415
/src/test/java/com/hogwarts/contact/Department.java
a42a8a2c14b0a93a81b3dba6cfd51ad994e0ff1a
[]
no_license
dabaoting/wechat-web-test
0acc6527f63ab3a615f6ae67a8be4a2b27f17427
5cddb9c0f3c44a5213932135934f09b7714b4261
refs/heads/master
2023-01-20T01:13:24.911322
2020-11-28T03:17:23
2020-11-28T03:17:23
313,651,269
0
0
null
null
null
null
UTF-8
Java
false
false
460
java
package com.hogwarts.contact; import java.util.List; public class Department { private String name; private List<Member> members; public String getName() { return name; } public List<Member> getMembers() { return members; } public void setName(String name) { this.name = name; } public void setMembers(List<Member> members) { this.members = members; } }
e5d7b5bf2ab364cfeea0a3e8a45f77b73849c915
ae84bd8aae7e5f9fa6f0c8657a8398ebe001fe4f
/app/src/androidTest/java/com/example/android/parkit/ExampleInstrumentedTest.java
d778c1b12ca5cfe59b76a102de5ba51263383082
[]
no_license
hsp98/ParkIt
b66de0d1abd33d9b159a8f11b2df2408a149ab6e
723b4a04fcf07160c098921bd8c0b3b5866dae30
refs/heads/master
2023-01-14T04:10:38.850774
2020-11-03T16:35:54
2020-11-03T16:35:54
178,289,497
1
0
null
null
null
null
UTF-8
Java
false
false
736
java
package com.example.android.parkit; import android.content.Context; import android.support.test.InstrumentationRegistry; import android.support.test.runner.AndroidJUnit4; import org.junit.Test; import org.junit.runner.RunWith; import static org.junit.Assert.*; /** * Instrumented test, which will execute on an Android device. * * @see <a href="http://d.android.com/tools/testing">Testing documentation</a> */ @RunWith(AndroidJUnit4.class) public class ExampleInstrumentedTest { @Test public void useAppContext() { // Context of the app under test. Context appContext = InstrumentationRegistry.getTargetContext(); assertEquals("com.example.android.parkit", appContext.getPackageName()); } }
07372f68d7ea7166552f7412285319df867c9940
4d87bca2b78d8d146b0442e621de24d23d8cfc15
/ExceptionHandlingLib/src/perennialbank/excpt/EmailAct.java
a96890e9d4ecabad62926cf83201acae0c5d8e7c
[]
no_license
pranoti22/ExceptionHandlingLib
62d7e15c35a5c8c667e83a9b904e1f5f2077d961
0eb4b0e826503ee5c17afb893221e0a472bd5df2
refs/heads/main
2023-03-28T21:39:06.810416
2021-04-08T10:24:07
2021-04-08T10:24:07
345,881,690
0
0
null
null
null
null
UTF-8
Java
false
false
1,496
java
package perennialbank.excpt; import java.util.Map; import java.util.Properties; import javax.mail.Authenticator; import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.PasswordAuthentication; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; public class EmailAct implements Actions { public String performAction(Map<String, String> act) { Properties prop=new Properties(); prop.put("mail.smtp.auth","true"); prop.put("mail.smtp.starttls.enable","true"); prop.put("mail.smtp.host","smtp.gmail.com"); prop.put("mail.smtp.port","587");//465 String Accountemail=act.get("from"); String recipent=act.get("to"); String pwd=act.get("pwd"); Session sec=Session.getInstance(prop, new Authenticator(){ protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(Accountemail,pwd); } }); //Message msg= prepareMsg(sec,Accountemail,recipent); try { Message msg=new MimeMessage(sec); msg.setFrom(new InternetAddress(Accountemail)); msg.setRecipient(Message.RecipientType.TO, new InternetAddress(recipent)); msg.setSubject(act.get("subject")); msg.setText("error occured"); Transport.send(msg); } catch (MessagingException e) { // TODO Auto-generated catch block e.printStackTrace(); } return "mail sent!"; } }
0011cbb3d5b9a29f4b3d7da30c4ec4a0c5b559fa
b0f83d81a6d1b1d2caea42706f0362d7eb11bd15
/core/src/com/teratorns/objects/TeratornsLogoObject.java
f0a415aa1dae2cbdcc61708290ca0c516f435268
[]
no_license
tlimao/teratorns
a4eb5a432de55d20a7ce787d3914ab400a08b586
554db10293e34bf9d35c486f23347a970d872a49
refs/heads/master
2021-03-12T23:02:27.338754
2015-06-17T16:04:16
2015-06-17T16:04:16
23,495,174
0
0
null
2015-06-17T16:04:17
2014-08-30T15:58:52
Java
UTF-8
Java
false
false
2,340
java
package com.teratorns.objects; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.glutils.ShapeRenderer.ShapeType; import com.badlogic.gdx.math.Rectangle; import com.badlogic.gdx.math.Vector2; import com.teratorns.assets.AssetsLoader; import com.teratorns.game.GameRenderer; import com.teratorns.interaction.Interactor; /** This a example */ public class TeratornsLogoObject extends GameObject implements Interactor<Rectangle> { private Rectangle interactionRect; public TeratornsLogoObject(float x, float y) { super(x, y); /* you need to adjust the dimensions (Width & Height) of the object * in proportion to the size of the corresponding sprite */ height = ((float) AssetsLoader.instance.teratorns.getRegionHeight()) / AssetsLoader.instance.teratorns.getRegionWidth(); interactionRect = new Rectangle(x, y, width, height); } @Override public boolean isTouched(Rectangle obj) { if (interactionRect.overlaps(obj)) { AssetsLoader.instance.click.play(5f); return true; } else { return false; } } @Override public void drawInteractor() { GameRenderer.instance.shapeRenderer.begin(ShapeType.Line); GameRenderer.instance.shapeRenderer.setColor(Color.CYAN); GameRenderer.instance.shapeRenderer.rect(interactionRect.x, interactionRect.y, interactionRect.width, interactionRect.height); GameRenderer.instance.shapeRenderer.end(); } @Override public void update() { // TODO Auto-generated method stub } @Override public void setPosition(float x, float y) { /* Remember that by moving the the rectangle of interaction (interactRect) * should follow the movement */ super.setPosition(x, y); interactionRect.setPosition(x, y); } @Override public void setPosition(Vector2 pos) { super.setPosition(pos); interactionRect.setPosition(pos); } @Override public void draw() { GameRenderer.instance.spriteRenderer.draw(AssetsLoader.instance.teratorns, position.x , position.y , width /2 , height /2 , width , height , 1 , 1 , rotation); } @Override public void setScale(float scl) { super.setScale(scl); interactionRect.setSize(width, height); } }
38d4162856665c64d3bf629ac13c492118c0f4db
3b4009b067a4605fa11d014c5aed96768bdea960
/webView_buildingAWebBrowser/src/sample/Main.java
b4dc8f28ee33fd6a446e38d97def930282ea81f1
[]
no_license
viking736/JavaFX-mini-projects
02dee63ddcbe69a8216f6d0b93971891b5a50c2c
2d0e5d51e1112b849e135f2f64bbb61f63d0029f
refs/heads/main
2023-06-05T20:29:03.657145
2021-07-02T12:08:25
2021-07-02T12:08:25
380,532,666
0
0
null
null
null
null
UTF-8
Java
false
false
608
java
package sample; import javafx.application.Application; import javafx.fxml.FXMLLoader; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.stage.Stage; public class Main extends Application { @Override public void start(Stage primaryStage) throws Exception{ Parent root = FXMLLoader.load(getClass().getResource("sample.fxml")); Scene scene = new Scene(root, 600, 400); primaryStage.setTitle("Hello World"); primaryStage.setScene(scene); primaryStage.show(); } public static void main(String[] args) { launch(args); } }
62739018205bf5bfb60037a967439d34abc1ca19
92defe9a6cfb711df61df190bf8804ef82993742
/engine/src/main/java/com/agiletec/aps/system/common/entity/loader/ExtraAttributeRolesWrapper.java
aafded2c8007295e0fed306973b1dc7c7ec949d3
[]
no_license
DevBrandon/entando-core
e6ffeddd0d76ff5f3694e96834a313764c20a739
4d1f88b372d4b0ef604fdde2aa929eef3de0e6b2
refs/heads/master
2020-12-26T01:13:58.694861
2014-12-01T17:18:43
2014-12-01T17:18:43
null
0
0
null
null
null
null
UTF-8
Java
false
false
2,452
java
/* * * Copyright 2013 Entando S.r.l. (http://www.entando.com) All rights reserved. * * This file is part of Entando software. * Entando is a free software; * You can redistribute it and/or modify it * under the terms of the GNU General Public License (GPL) as published by the Free Software Foundation; version 2. * * See the file License for the specific language governing permissions * and limitations under the License * * * * Copyright 2013 Entando S.r.l. (http://www.entando.com) All rights reserved. * */ package com.agiletec.aps.system.common.entity.loader; import java.util.ArrayList; import java.util.List; import java.util.Map; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.agiletec.aps.system.common.IManager; import com.agiletec.aps.system.common.entity.IEntityManager; import com.agiletec.aps.system.common.entity.model.attribute.AttributeRole; import com.agiletec.aps.system.common.entity.parse.AttributeRoleDOM; import com.agiletec.aps.system.exception.ApsSystemException; /** * The Wrapper Class of the extra attribute roles. * @author E.Santoboni */ public class ExtraAttributeRolesWrapper extends AbstractExtraAttributeSupportObject { private static final Logger _logger = LoggerFactory.getLogger(ExtraAttributeRolesWrapper.class); public void executeLoading(Map<String, AttributeRole> collectionToFill, IEntityManager entityManager) throws ApsSystemException { String managerName = ((IManager) entityManager).getName(); if (!managerName.equals(super.getEntityManagerNameDest())) { return; } AttributeRoleDOM dom = new AttributeRoleDOM(); try { String xml = super.extractXml(); Map<String, AttributeRole> attributeRoles = dom.extractRoles(xml, this.getDefsFilePath()); List<AttributeRole> roles = new ArrayList<AttributeRole>(attributeRoles.values()); for (int i = 0; i < roles.size(); i++) { AttributeRole role = roles.get(i); if (collectionToFill.containsKey(role.getName())) { _logger.warn("You can't override existing attribute role : {} - {}", role.getName(), role.getDescription()); } else { collectionToFill.put(role.getName(), role); _logger.info("Added new attribute role : {} - {}",role.getName(), role.getDescription()); } } } catch (Throwable t) { //ApsSystemUtils.logThrowable(t, this, "executeLoading", "Error loading extra attribute Roles"); _logger.error("Error loading extra attribute Roles", t); } } }
8b56bf3e8be2e57663437559c8ff3789a55221b1
a1a11ccd0d9938aa762bb9c01ddd1427f0e4deb4
/main_module/src/main/java/org/cryse/novelreader/model/NovelSyncBookShelfModel.java
5a75f05051681d29616f2a492b263ca69ee98055
[ "Apache-2.0" ]
permissive
crysehillmes/smoothnovelreader
e27177e583ddedd918320afe4136fca023911b56
13afe386fcc687603525724b2e5e4a91c67bd88a
refs/heads/master
2020-09-16T11:14:34.608290
2016-08-18T14:29:07
2016-08-19T05:49:10
65,994,022
9
1
null
null
null
null
UTF-8
Java
false
false
2,212
java
package org.cryse.novelreader.model; import android.os.Parcel; import android.os.Parcelable; public class NovelSyncBookShelfModel implements Parcelable { private String id; private String lastChapterId; private String lastChapterTitle; private String lastUpdate; public NovelSyncBookShelfModel(String id, String lastChapterId, String lastChapterTitle, String lastUpdate) { this.id = id; this.lastChapterId = lastChapterId; this.lastChapterTitle = lastChapterTitle; this.lastUpdate = lastUpdate; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getLastChapterId() { return lastChapterId; } public void setLastChapterId(String lastChapterId) { this.lastChapterId = lastChapterId; } public String getLastChapterTitle() { return lastChapterTitle; } public void setLastChapterTitle(String lastChapterTitle) { this.lastChapterTitle = lastChapterTitle; } public String getLastUpdate() { return lastUpdate; } public void setLastUpdate(String lastUpdate) { this.lastUpdate = lastUpdate; } public NovelSyncBookShelfModel() { } @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeString(this.id); dest.writeString(this.lastChapterId); dest.writeString(this.lastChapterTitle); dest.writeString(this.lastUpdate); } protected NovelSyncBookShelfModel(Parcel in) { this.id = in.readString(); this.lastChapterId = in.readString(); this.lastChapterTitle = in.readString(); this.lastUpdate = in.readString(); } public static final Creator<NovelSyncBookShelfModel> CREATOR = new Creator<NovelSyncBookShelfModel>() { public NovelSyncBookShelfModel createFromParcel(Parcel source) { return new NovelSyncBookShelfModel(source); } public NovelSyncBookShelfModel[] newArray(int size) { return new NovelSyncBookShelfModel[size]; } }; }
6f58e1754fab84195d91254b38a0ba1aa68b6e93
d57777f9324258a940c8cb6c99017adc7431ebe9
/assignment3.java
4afd9a6f70d43716eaf29276fa78da20beba46a0
[]
no_license
kritika1922/m2
8800487aa1e360cdd0584e6dfcfd05cc1480371a
98881aa2ea9df8f6097a800a6fc80063b5a9bf5d
refs/heads/master
2023-08-22T17:34:45.530099
2021-10-06T13:26:02
2021-10-06T13:26:02
413,770,915
0
0
null
null
null
null
UTF-8
Java
false
false
1,419
java
import java.io.File; import java.io.IOException; import java.util.Scanner; import MyProject.*; class Assignment3 { public static void main(String args[]) throws IOException { Scanner sc = new Scanner(System.in); System.out.println("Enter Whatever you want"); System.out.println("Add\nDelete\nSearch"); System.out.println("==============="); String s = sc.nextLine(); System.out.println("+++++++++++++"); switch (s) { case "Add": System.out.println("Enter EmployeId,Name,Email,Age And Date of birth"); String id = sc.nextLine(); String name = sc.nextLine(); String email = sc.nextLine(); String age = sc.nextLine(); String date = sc.nextLine(); Add a = new Add(); a.add(id, name, email, age, date); break; case "Delete": System.out.println("Enter the String you wish to delete "); String lineToRemove = sc.nextLine(); Delete d = new Delete(); d.delete(lineToRemove); break; case "Search": System.out.println("Search String\nSort File\nWhich Direction"); System.out.println("==============="); String type = sc.nextLine(); System.out.println("+++++++++++++"); switch (type) { case "Search String": System.out.println("Enter the String you wish to search "); String se = sc.nextLine(); Search sea = new Search(); sea.search(se); break; case "Sort File": Sort so=new Sort(); so.sort(); } } } }
27108404aa2efe98b178b093828f9f30934d3366
83c5ee93112cf2d505f5db329df50e300e132661
/springcore/src/main/java/com/bharath/spring/springcore/shoppingcart/ShoppingCart.java
f62c5911abbb3d850d078e100938bd9eeda5ab20
[]
no_license
Pygator/UdemySpringEasySteps
b393e02ee5704d102fb76c3d0f07bd9416a7ce16
c9463c766ce2cfad88234f065f91fcca94b45e9c
refs/heads/master
2020-03-17T22:55:17.582187
2018-05-29T03:18:01
2018-05-29T03:18:01
134,023,663
0
1
null
null
null
null
UTF-8
Java
false
false
391
java
package com.bharath.spring.springcore.shoppingcart; import java.util.Set; public class ShoppingCart { private Item item; public Item getItem() { return item; } public void setItem(Item item) { this.item = item; } @Override public String toString() { return "ShoppingCart{" + "item=" + item + '}'; } }
a1868d012b829f86936d902445e3562dcc2a644f
c513cef0467db2f49556c310b02c31f775b96bfe
/sjjh/sjjh-provider/src/main/java/nju/software/sjjh/webservice/IexportdtsService.java
60c8ffdb37d8d153c5984050a6078caca0de80e5
[]
no_license
lr12/sjjh
2b51ae0a2e0e3bc581207bd06f74dcdfed7502c8
061668048e3149711067724aceef2c46dc965c2d
refs/heads/master
2021-01-19T21:51:48.011449
2017-05-23T07:37:16
2017-05-23T07:37:16
88,716,247
2
0
null
null
null
null
UTF-8
Java
false
false
1,008
java
package nju.software.sjjh.webservice; public interface IexportdtsService { /** * 导出法庭信息 * @param xml * @return */ public String exportFTXX(String xml); /** * 导出人员信息 * @param xml * @return */ public String exportRYXX(String xml); /** * 导出开庭信息 * @param xml * @return */ public String exportKTXX(String xml); /** * 导出案件经办信息 * @param xml * @return */ public String exportAJJBXX(String xml); /** * 导出当事人信息 * @param xml * @return */ public String exportDSRXX(String xml); /** * 导出审判组织成员信息 * @param xml * @return */ public String exportSPZZCYXX(String xml); /** * 回写笔录信息接口 * @param xml * @return */ public String updateTrialInfo(String xml); /** * 获取庭审录像接口 * @param xml * @return */ public String getCaseVod(String xml); /** * 测试 * @return */ public String sayHello(String xml); }
164732f01d47ded1309872e9c8b5a8c41b1b4573
021f5ec9986225b25638a13b9b9b70df2ce38263
/src/test/java/edu/berkeley/compbio/sequtils/sequencereader/fasta/FastaParserTest.java
760c873745db5d754549565e2c8b86912bb96588
[ "Apache-2.0" ]
permissive
davidsoergel/sequtils
473eb9746b8545698903fceb8ab994419282c18d
5571a5790bfbb5de8aebfe6ed926e38b33ac6939
refs/heads/master
2021-01-01T15:31:48.329165
2014-07-06T05:11:14
2014-07-06T05:11:14
21,191,317
1
0
null
null
null
null
UTF-8
Java
false
false
8,890
java
/* * Copyright (c) 2007-2013 David Soergel <[email protected]> * Licensed under the Apache License, Version 2.0 * http://www.apache.org/licenses/LICENSE-2.0 */ package edu.berkeley.compbio.sequtils.sequencereader.fasta; import com.davidsoergel.dsutils.math.MersenneTwisterFast; import edu.berkeley.compbio.sequtils.NotEnoughSequenceException; import edu.berkeley.compbio.sequtils.SequenceFragmentMetadata; import org.apache.log4j.Logger; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import java.io.File; import java.io.IOException; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.net.URL; /** * @author <a href="mailto:[email protected]">David Soergel</a> * @version $Id: FastaParserTest.java 999 2009-06-23 03:00:18Z soergel $ */ public class FastaParserTest { private static final Logger logger = Logger.getLogger(FastaParserTest.class); // ------------------------------ FIELDS ------------------------------ String seq; FastaParser fp; FastaFileSet fs; File theDirectory; // -------------------------- OTHER METHODS -------------------------- @Test public void currentPositionIsInHeaderWorksCorrectly() throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, IOException { // trick to test private method final Method checkCurrentPositionIsValidSequence = FastaParser.class.getDeclaredMethod("checkCurrentPositionIsValidSequence"); checkCurrentPositionIsValidSequence.setAccessible(true); expectPositionValid(checkCurrentPositionIsValidSequence, 0, false); expectPositionValid(checkCurrentPositionIsValidSequence, 7, false); expectPositionValid(checkCurrentPositionIsValidSequence, 35, false); expectPositionValid(checkCurrentPositionIsValidSequence, 36, false); expectPositionValid(checkCurrentPositionIsValidSequence, 37, true); expectPositionValid(checkCurrentPositionIsValidSequence, 37, true); expectPositionValid(checkCurrentPositionIsValidSequence, 50, true); expectPositionValid(checkCurrentPositionIsValidSequence, 500, true); expectPositionValid(checkCurrentPositionIsValidSequence, 5000, false); } private void expectPositionValid(Method checkCurrentPositionIsValidSequence, int position, boolean validExpected) throws IOException { fp.seek(position); try { checkCurrentPositionIsValidSequence.invoke(fp); } catch (IllegalAccessException e) { logger.error("Error", e); assert false; } catch (InvocationTargetException e) { assert !validExpected; return; } assert validExpected; } @Test public void headersAreReadCorrectly() throws Exception { seq = fp.next().getSequenceName(); assert seq.equals("testgenome.1.1"); } @Test public void headersAreReadCorrectlyAcrossFiles() throws Exception { seq = fp.next().getSequenceName(); assert seq.equals("testgenome.1.1"); seq = fp.next().getSequenceName(); assert seq.equals("testgenome.1.2"); seq = fp.next().getSequenceName(); assert seq.equals("testgenome.2.1"); seq = fp.next().getSequenceName(); assert seq.equals("testgenome.2.2"); } @Test public void positionSeekWorksCorrectly() throws Exception { fp.seek(50); assertPosition50(); } private void assertPosition50() throws Exception { byte b; b = fp.read(); assert b == 'G'; b = fp.read(); assert b == 'G'; b = fp.read(); assert b == 'T'; b = fp.read(); assert b == 'G'; b = fp.read(); assert b == 'G'; } @Test(expectedExceptions = NotEnoughSequenceException.class) public void readingEndOfSectionAtEOFProducesNotEnoughSequenceException() throws IOException, NotEnoughSequenceException { fp.next(); fp.seek(fp.next()); for (int i = 0; i < 2000; i++) { fp.read(); } } @Test(expectedExceptions = NotEnoughSequenceException.class) public void readingEndOfSectionAtNextHeaderProducesNotEnoughSequenceException() throws IOException, NotEnoughSequenceException { fp.seek(fp.next()); for (int i = 0; i < 2000; i++) { fp.read(); } } @Test(expectedExceptions = NotEnoughSequenceException.class) public void requestingTooManySectionsProducesNotEnoughSequenceException() throws IOException, NotEnoughSequenceException { fp.next(); fp.next(); fp.next(); fp.next(); fp.next(); } @Test public void resetWorksCorrectly() throws Exception { fp.seek(50); assertPosition50(); fp.reset(); seq = fp.next().getSequenceName(); //System.out.println(seq); assert seq.equals("testgenome.1.1"); assertSection1p1(); } private void assertSection1p1() throws Exception { byte b; b = fp.read(); assert b == 'G'; b = fp.read(); assert b == 'C'; b = fp.read(); assert b == 'A'; b = fp.read(); assert b == 'A'; b = fp.read(); assert b == 'C'; } @Test public void resetWorksCorrectlyAcrossFiles() throws Exception { fp.next(); fp.seek(fp.next()); fp.seek(fp.next()); assertSection2p1(); fp.reset(); seq = fp.next().getSequenceName(); //System.out.println(seq); assert seq.equals("testgenome.1.1"); } private void assertSection2p1() throws Exception { byte b; b = fp.read(); assert b == 'C'; b = fp.read(); assert b == 'T'; b = fp.read(); assert b == 'G'; b = fp.read(); assert b == 'G'; b = fp.read(); assert b == 'T'; } @Test public void sectionSeekWorksCorrectlyAcrossFiles() throws Exception { SequenceFragmentMetadata section1p1 = fp.next(); fp.next(); SequenceFragmentMetadata section2p1 = fp.next(); fp.seek(section2p1); assertSection2p1(); fp.seek(section1p1); assertSection1p1(); } @Test public void sequenceIsProvidedCorrectlyAcrossFiles() throws Exception { fp.seek(fp.next()); assertSection1p1(); } @BeforeMethod public void setUp() throws Exception { MersenneTwisterFast.init(); // Map<String, Object> props = new HashMap<String, Object>(); //props.setProperty("msensr.windowscan.writeshortwindows", "1"); //props.setProperty("msensr.ktrie.smoothfactor", "2"); //props.setProperty("msensr.ktrie.smoothtype", "sampleSizeBased"); // HierarchicalTypedPropertyNode n = PropertyConsumerClassParser.parseRootContextClass(StubSequenceFragmentIterator.class); // MapToHierarchicalTypedPropertyNodeAdapter.mergeInto(n, props); // stubSequenceFragmentIteratorFactory = new PropertyConsumerFactory<StubSequenceFragmentIterator>(n); URL url = ClassLoader.getSystemResource("Test_Genome"); theDirectory = new File(url.getPath()); //theDirectory = new File("src/test/data/Test_Genome/"); fs = new FastaFileSet(theDirectory); logger.info("Loading test genome: " + theDirectory.getAbsolutePath() + " " + theDirectory.exists()); fp = new FastaParser(fs, true); logger.info("Got FastaParser: " + fp.getTotalSequence()); } /* @Test public void checkValidWorksCorrectly() throws Exception { FastaParser fp; FastaFileSet fs; File theDirectory = new File("src/test/data/Test_Genome/"); fs = new FastaFileSet(theDirectory); fp = new FastaParser(fs); fp.seek(0); //System.out.println("Start..."); try { fp.checkCurrentPositionIsValidSequence(); assert false; } catch (NotEnoughSequenceException e) { // Good } fp.seek(3); try { fp.checkCurrentPositionIsValidSequence(); assert false; } catch (NotEnoughSequenceException e) { // Good } fp.seek(100); fp.checkCurrentPositionIsValidSequence(); }*/ }
5be3911af74bfa7dbc232cc46b16b391c7a98a41
d0774b87c73ec59cdac85766a8f4776664a639bf
/app/src/main/java/com/bilibili/video/indicator/ViewPagerIndicatorHelper.java
0aec8585c0c03638c570f31d7e8db124ef1b7b6b
[]
no_license
whiteyen/Video
44a5ce762783b4ea591ed35e27b422e1b2966292
cefb8fda7dc8d0670aa0ed790cc5cf3ecc623839
refs/heads/master
2020-12-30T05:32:54.442153
2020-02-18T14:22:24
2020-02-18T14:22:24
238,877,396
0
0
null
null
null
null
UTF-8
Java
false
false
6,705
java
package com.bilibili.video.indicator; import android.support.v4.view.ViewPager; import android.util.SparseArray; import android.util.SparseBooleanArray; public class ViewPagerIndicatorHelper { private IPagerTitle mScrollListener; private int mCurrentIndex; private int mLastIndex; private float mLastPositionOffsetSum; private int mTotalCount; private int mScrollState = ViewPager.SCROLL_STATE_IDLE; private SparseArray<Float> mLeavePercents = new SparseArray<>(); private SparseBooleanArray mDeSelectedItems = new SparseBooleanArray(); public ViewPagerIndicatorHelper(){ } public void setScrollListener(IPagerTitle listener){ mScrollListener = listener; } public void onPageScrolled(int position, float positionOffset, float positionPixel){ float currentPositionOffsetSum = position + positionOffset; boolean isLeftToRight = currentPositionOffsetSum>mLastPositionOffsetSum; int safePosition = getSafeIndex(position); //不是就绪状态时 if(mScrollState != ViewPager.SCROLL_STATE_IDLE){ int enterIndex,leaveIndex; float enterPercent,leavePercent; if(isLeftToRight){ enterIndex = getSafeIndex(position+1); enterPercent = positionOffset; leaveIndex = safePosition; leavePercent = positionOffset; }else{ enterIndex = safePosition; enterPercent = 1.0f - positionOffset; leaveIndex = getSafeIndex(safePosition + 1); leavePercent = 1.0f - positionOffset; } for(int i = 0;i<mTotalCount;i++){ if(i==enterIndex || i==leaveIndex){ continue; } Float leavedPercent = mLeavePercents.get(i,0.0f); if(leavedPercent != 1.0f){ mScrollListener.onLeave(i,mTotalCount,1.0f,isLeftToRight); mLeavePercents.put(i,1.0f); } } if(enterIndex == leaveIndex){ if(enterIndex == mTotalCount-1 && (mLeavePercents.get(enterIndex,0.0f) !=0.0f) && enterPercent==0.0f&&isLeftToRight){ boolean disPatchEnterEvent = (mScrollState == ViewPager.SCROLL_STATE_DRAGGING) || enterIndex == mCurrentIndex; if(disPatchEnterEvent){ mScrollListener.onEnter(enterIndex,mTotalCount,1.0f,true); mLeavePercents.put(enterIndex,0.0f); } } return; } if(1.0f - mLeavePercents.get(enterIndex,0.0f) != enterPercent){ boolean disPatchEnterEvent = mScrollState == ViewPager.SCROLL_STATE_DRAGGING || enterIndex == mCurrentIndex; if(disPatchEnterEvent){ mScrollListener.onEnter(enterIndex,mTotalCount,enterPercent,isLeftToRight); mLeavePercents.put(enterIndex,1.0f - enterIndex); } } if(mLeavePercents.get(leaveIndex,0.0f)!= leavePercent){ if(isLeftToRight && leaveIndex == getSafeIndex(mCurrentIndex) && leavePercent == 0.0f){ boolean disPatchEnterEvent = mScrollState == ViewPager.SCROLL_STATE_DRAGGING|| mCurrentIndex == leaveIndex; if(disPatchEnterEvent){ mScrollListener.onEnter(leaveIndex,mTotalCount,1.0f,true); mLeavePercents.put(leaveIndex,0.0f); }else { boolean disPatchLeaveEvent = mScrollState == ViewPager.SCROLL_STATE_DRAGGING || leaveIndex == mLastIndex ||(leaveIndex == mCurrentIndex-1)&& mLeavePercents.get(leaveIndex,0.0f)!=1.0f ||(leaveIndex == mCurrentIndex+1)&& mLeavePercents.get(leaveIndex,0.0f)!=1.0f; if(disPatchLeaveEvent){ mScrollListener.onLeave(leaveIndex,mTotalCount,leavePercent,isLeftToRight); } } } } //滚动状态时 else{ for (int i = 0;i<mTotalCount ;i++){ if(i==mCurrentIndex){ continue; } boolean deSelected = mDeSelectedItems.get(i); if(!deSelected){ mScrollListener.onDisSelected(i,mTotalCount); } Float leavedPercnet = mLeavePercents.get(i,0.0f); if(leavedPercnet != 1.0f){ mScrollListener.onLeave(i,mTotalCount,1.0f,isLeftToRight); mLeavePercents.put(i,1.0f); } } mScrollListener.onEnter(mCurrentIndex,mTotalCount,1.0f,false); mLeavePercents.put(mCurrentIndex,0.0f); mScrollListener.onSelected(mCurrentIndex,mTotalCount); mDeSelectedItems.put(mCurrentIndex,false); } mLastPositionOffsetSum = currentPositionOffsetSum; } } private int getSafeIndex(int position) { return Math.max(Math.min(position,mTotalCount-1),0); } public void onPageSelected(int position){ int currentIndex = setCurrentIndex(position); if(mScrollListener!=null){ mScrollListener.onSelected(mCurrentIndex,mTotalCount); mDeSelectedItems.put(mCurrentIndex,false); for(int i=0,j = mTotalCount;i<j;i++){ if(i==mCurrentIndex){ continue; } boolean disSelected = mDeSelectedItems.get(i); if(!disSelected){ mScrollListener.onDisSelected(i,mTotalCount); mDeSelectedItems.put(i,true); } } } } public void onPageScrollStateChanged(int scrollState){ mScrollState = scrollState; } public void setTotalCount(int totalCount){ mTotalCount = totalCount; } public int getSctollState(){ return mScrollState; } public int getTotalCount(){ return mTotalCount; } public int getCurrentIndex(){ return mCurrentIndex; } private int setCurrentIndex(int index) { mLastIndex = mCurrentIndex; mCurrentIndex = getSafeIndex(index); return mCurrentIndex; } }
[ "https://gitee.com/Isshiki_yen/201727010317_tan_xueyuan.git" ]
https://gitee.com/Isshiki_yen/201727010317_tan_xueyuan.git
4df560bbc0e428a09ba0b7b80a249090b2571942
c2820ab14e71fb8ceed367e136833ba05a00fc8e
/src/org/xmpp/android/contact/roster/Group.java
d6f608986d88fdf3dda0d4b602cb9d3a98e19a6c
[]
no_license
emdete/XmppAndroidService
814b950f09c2b427e4aa8e7793f594a3ec7605e6
b18f835194fed6d47e263b53e7f36e6e6e30d42c
refs/heads/master
2021-01-23T00:34:07.834243
2014-02-21T17:11:44
2014-02-21T17:11:44
17,064,563
1
0
null
null
null
null
UTF-8
Java
false
false
659
java
package org.xmpp.android.contact.roster; import org.xmpp.android.shared.stanzas.BaseStanza; import org.xmpp.android.shared.stanzas.XmppStanza; public class Group extends BaseStanza { public static final StanzaType TYPE = new StanzaType("group", "jabber:iq:roster"); public Group(XmppStanza stanza) { super(stanza); assert TYPE.equals(stanza.getStanzaType()); } public static void register() { XmppStanza.register(TYPE, Group.class); } public String getName() { return stanza.getSubText(); } @Override public String toString() { return "Group { "+getName()+" }"; } @Override public StanzaType getStanzaType() { return TYPE; } }
a03efe3ee04107483f22837b4ebd672e4deaad78
e2cc9800d3bcceaad141d3215efe1690940c59d7
/ny_Card/app/src/main/java/com/example/ny_card/MartActivity.java
8dbd5212fb7f27a426635c3d0451546d0e807adb
[]
no_license
yura970804/Capstone
244a2d7130439928f78b52e603007a41f944ad26
64e20ac6541562eb2c9c79438ed376c2a0e35f7c
refs/heads/master
2023-02-14T17:52:26.146566
2021-01-18T08:53:09
2021-01-18T08:53:09
null
0
0
null
null
null
null
UTF-8
Java
false
false
60
java
package com.example.ny_card; public class MartActivity { }
59fbbf3edf694cabfd6dcca962a64af6b2e6f79d
0a9878cadcfa7901044fb441bf7d8efac87a8f97
/src/main/java/inPractice/chapter12/BoundedBuffer.java
35c69f24f2c7d8939d1243b85db4373192580bbe
[]
no_license
lastFeng/JavaConcurrentPractice
56b18479490351145aaee8a69e6991023a530e6f
755486a55411681d133ff0eb85885d5d87466791
refs/heads/main
2023-06-17T08:52:27.611033
2021-07-12T07:28:09
2021-07-12T07:28:09
366,572,650
0
0
null
null
null
null
UTF-8
Java
false
false
1,443
java
package inPractice.chapter12; import inPractice.annotation.GuardedBy; import inPractice.annotation.ThreadSafe; import java.util.concurrent.Semaphore; @ThreadSafe public class BoundedBuffer<E> { private final Semaphore availableItems, availableSpaces; @GuardedBy("this") private final E[] items; @GuardedBy("this") private int putPosition = 0, takePosition = 0; public BoundedBuffer(int capacity) { availableItems = new Semaphore(0); availableSpaces = new Semaphore(capacity); items = (E[]) new Object[capacity]; } public boolean isEmpty() { return availableItems.availablePermits() == 0; } public boolean isFull() { return availableSpaces.availablePermits() == 0; } public void put(E x) throws InterruptedException { availableSpaces.acquire(); doInsert(x); availableItems.release(); } public E take() throws InterruptedException { availableItems.acquire(); E item = doExtract(); availableSpaces.release(); return item; } private synchronized void doInsert(E x) { int i = putPosition; items[i] = x; putPosition = (++i == items.length) ? 0 : i; } private synchronized E doExtract() { int i = takePosition; E x = items[i]; items[i] = null; takePosition = (++i == items.length) ? 0 : i; return x; } }
424b226d76297e73d40309de07be39706a78c5ac
e3387e23d63425de08e1bd4b4d4eb4ea4e8e4e57
/src/main/java/br/com/alura/store/model/CategoryId.java
a323bc681602528898b776dc27942aea261aef4f
[]
no_license
Gilmardealcantara/jpa
1d0bcf739588fc79483dae3884c914c09709266c
34bb3ab2a1dc4a9545c4e277ea2fd9ee41d881ae
refs/heads/main
2023-06-14T14:41:30.371125
2021-07-19T03:28:02
2021-07-19T03:28:02
387,324,617
0
0
null
null
null
null
UTF-8
Java
false
false
618
java
package br.com.alura.store.model; import javax.persistence.Embeddable; import java.io.Serializable; @Embeddable public class CategoryId implements Serializable { private String name; private String type; public CategoryId(String name, String type) { this.name = name; this.type = type; } public CategoryId() { } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getType() { return type; } public void setType(String type) { this.type = type; } }
2ba3624e4c3247f47887b6de4809a1147cdc033f
6570761ebcdc48f900ada1e219888417da93f406
/minhaLojaDeGamesSecurity/src/main/java/com/minhaLojaDeGames/minhaLojaDeGames/seguranca/BasicSecurityConfig.java
ff138a1daa34fd9dbab340fabd9ba3280ec9bd9d
[]
no_license
djan-domingues/AtividadesSpring
a66394a81b41272bc3143df9dd21ef61d5244311
8a871bbe32f1f0eebf900f78037305004d9151f7
refs/heads/master
2023-06-26T19:30:38.524820
2021-07-30T19:15:22
2021-07-30T19:15:22
379,696,694
0
0
null
null
null
null
UTF-8
Java
false
false
1,663
java
package com.minhaLojaDeGames.minhaLojaDeGames.seguranca; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.config.http.SessionCreationPolicy; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder; @EnableWebSecurity public class BasicSecurityConfig extends WebSecurityConfigurerAdapter{ @Autowired private UserDetailsService userDetailsService; @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.userDetailsService(userDetailsService); } @Bean public PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests() .antMatchers("/usuarios/logar").permitAll() .antMatchers("/usuarios/cadastrar").permitAll() .anyRequest().authenticated() .and().httpBasic() .and().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS) .and().cors() .and().csrf().disable(); } }
6f31ece2f4d849cb63123103608ef4216088da1a
d5f322967da9cd030fc2dbb4de3023cca5eba8ae
/king/src/main/java/com/king/service/IEnvironmentService.java
567576b52f1f2e6dd4d54c51d037e06c5bd9cfb1
[]
no_license
myouj/king
aca71310549c5b11ea04803f4ec2666a41491284
747fb2240b94cb692eb0e6998cc9e0790dd7f3f2
refs/heads/master
2020-04-07T11:39:36.526938
2018-12-07T08:08:25
2018-12-07T08:08:25
158,335,302
0
0
null
null
null
null
UTF-8
Java
false
false
297
java
package com.king.service; import com.king.utils.ResultInfo; /** * @author M_youj E-mail: [email protected] * @version 创建时间:2018年12月5日 上午9:07:38 * Describe: */ public interface IEnvironmentService { ResultInfo selectAllEnvironment(int page, int rows); }
c17f23bab65e65ece4761acf0669caba881aeee3
c39fdf70886060060fd5ab2dcdf09a1e59325279
/FileFormatException.java
74191067a82b8f71b4c62204c56eb66746b78ba7
[]
no_license
Elijah-Gabriel/Movie-Database
1293cb5d4a6947076f8a19d112c118ee3686d6d1
e5f068240d5a9f42f6edb8eb5c516c4378261b82
refs/heads/master
2020-03-23T16:53:00.880230
2018-07-21T17:06:05
2018-07-21T17:06:05
141,831,760
0
0
null
null
null
null
UTF-8
Java
false
false
273
java
public class FileFormatException extends Exception{ public FileFormatException() //default constructor for error message { super("Line not formatted correctly, skipped"); //error message to print out } public FileFormatException(String aMsg) { super(aMsg); } }
dfb840288058dc868042e301c60bd05eaea960ed
bcf7ff26896faaad4aa9c9961e7de2fe1be78f3a
/src/test/FancyMessage.java
01189a1d1b21b93d30d3340a890ab3f62cb2e5ae
[]
no_license
db483/test
ab6077486fe25f4983e69965dba4683da1255e05
241431bb696e980278e9c47dbdd3fd160bd11140
refs/heads/master
2016-08-11T12:39:38.993614
2016-01-26T15:22:56
2016-01-26T15:26:14
50,424,802
0
0
null
2016-02-02T17:16:17
2016-01-26T11:37:05
Java
UTF-8
Java
false
false
254
java
package test; public class FancyMessage extends Message { public FancyMessage(String message, String owner) { super(message, owner); } @Override public String toString() { return getOwner() + " sends you this message: " + getMessage(); } }
eb7e24f34537ed6d650e089fed4d0365ec17ec5b
c506e19d4ad6311a90c9afd227e36155ae79d14e
/lab3/src/main/java/problem2/Soldier.java
5850d4c7cd6c5e9fbe527ae609881e8d4db0c933
[]
no_license
CheukTsai/cs5004_ood
57d55a171e910bf3eb5f6be1d3224b476cfc236c
767e236b1e2c1afe00ca0998a6e9bf6f19d8dd81
refs/heads/main
2023-08-31T21:37:40.711763
2021-10-23T21:24:20
2021-10-23T21:24:20
420,525,669
1
0
null
null
null
null
UTF-8
Java
false
false
1,212
java
package problem2; /** * A abstract class Soldier that inherits from its parent class of Piece. */ public abstract class Soldier extends Piece{ private static final Integer MAX_STAMINA = 100; private static final Integer MIN_STAMINA = 0; private Double stamina; /** * Constructs a Soldier * @param name - Name, name of the piece * @param age - Integer, age of the piece * @param stamina - Double, stamina of the piece */ public Soldier(Name name, Integer age, Double stamina) { super(name, age); this.stamina = stamina; checkStamina(); } /** * Increase stamina * @param extraStamina - Double, extra stamina */ public void addStamina(Double extraStamina){ stamina += extraStamina; checkStamina(); } /** * Decrease stamina * @param extraStamina - Double, extra stamina */ public void removeStamina(Double extraStamina){ stamina -= extraStamina; checkStamina(); } /** * Check if stamina is legal * @exception - thrown when stamina is illegal */ void checkStamina(){ if(stamina < MIN_STAMINA || stamina > MAX_STAMINA) throw new IllegalArgumentException("Stamina should be between 0 and 100"); } }
823c464bf1c10fde2b77ad75cece8055d2408a2a
cf532637f18524369d4f4d2c3b2bebc836d068ec
/app-sample/src/main/java/io/noties/markwon/app/samples/latex/LatexDarkSample.java
06f2ca8d45602ac8e85eb81ba5a7252848c05ed9
[ "Apache-2.0" ]
permissive
bastienleonard/Markwon
2a0006b4bcea14fe7ae5d8e046e4e3b66c0fb137
82cb42813a96d28a90fbf670a1ef093781df04bb
refs/heads/master
2023-01-25T03:46:23.852648
2020-11-11T23:06:49
2020-11-11T23:06:49
316,166,587
0
0
Apache-2.0
2020-11-26T08:25:54
2020-11-26T08:25:54
null
UTF-8
Java
false
false
1,149
java
package io.noties.markwon.app.samples.latex; import io.noties.markwon.Markwon; import io.noties.markwon.app.sample.Tags; import io.noties.markwon.app.sample.ui.MarkwonTextViewSample; import io.noties.markwon.ext.latex.JLatexMathPlugin; import io.noties.markwon.sample.annotations.MarkwonArtifact; import io.noties.markwon.sample.annotations.MarkwonSampleInfo; @MarkwonSampleInfo( id = "20200701094225", title = "LaTeX dark", description = "LaTeX automatically uses `TextView` text color " + "if not configured explicitly", artifacts = MarkwonArtifact.EXT_LATEX, tags = Tags.rendering ) public class LatexDarkSample extends MarkwonTextViewSample { @Override public void render() { scrollView.setBackgroundColor(0xFF000000); textView.setTextColor(0xFFffffff); final String md = "" + "# LaTeX\n" + "$$\n" + "\\int \\frac{1}{x} dx = \\ln \\left| x \\right| + C\n" + "$$\n" + "text color is taken from text"; final Markwon markwon = Markwon.builder(context) .usePlugin(JLatexMathPlugin.create(textView.getTextSize())) .build(); markwon.setMarkdown(textView, md); } }
24fb280875cd9dbc9de58fd03f6802ebb9af35d2
0e18b3b6f4acc082a364f815281fd0cc09cd8561
/Samsung/B17244.java
37fc925db51377ab616256898453d393546e7903
[]
no_license
ChanWoongLee/Algorithm
6b6b2d0dfc52ecad657ae494f0665612c0dba24e
5a5fbe1681094a2061edab1ee56e7cfd3600febe
refs/heads/master
2021-08-01T17:42:15.867289
2021-07-27T14:47:24
2021-07-27T14:47:24
245,803,824
1
0
null
null
null
null
UHC
Java
false
false
3,278
java
package Samsung; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Arrays; import java.util.LinkedList; import java.util.Queue; public class B17244 { // 1시 20 분 시작!!! static int N, M; static int[][] map; static int[] dr = { -1, 1, 0, 0 }; static int[] dc = { 0, 0, -1, 1 }; static boolean[] visit; static int[] temp; static ArrayList<Object> ar; static Object start = null; static Object end = null; static int answer = Integer.MAX_VALUE; // 내 생각을 조심하자!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!111 // 항상 최적이 최적이 아님을 // 모든 경우의수를 세는 쪽으로 가자@@@@@@@@@@@@@@@@@@@@@@@@@ public static void main(String[] args) throws IOException { BufferedReader bf = new BufferedReader(new InputStreamReader(System.in)); String[] str = bf.readLine().split(" "); M = Integer.parseInt(str[0]); N = Integer.parseInt(str[1]); map = new int[N][M]; int object = 3; ar = new ArrayList<>(); for (int i = 0; i < N; i++) { str = bf.readLine().split(""); for (int j = 0; j < M; j++) { if (str[j].equals("S")) { start = new Object(i, j, 1, 0); map[i][j] = 1; } else if (str[j].equals("E")) { map[i][j] = 2; end = new Object(i, j, 2, 0); } else if (str[j].equals("X")) { ar.add(new Object(i, j, object, 0)); map[i][j] = object++; } else if (str[j].equals("#")) map[i][j] = -1; else map[i][j] = 0; } } visit = new boolean[object - 3]; temp = new int[object - 3]; recur(0); System.out.println(answer); } static void recur(int index) { if (index == visit.length) { int res = bfs(); if (res == -1) return; answer = res < answer ? res : answer; return; } for (int i = 0; i < visit.length; i++) { if (visit[i]) continue; temp[index] = i; visit[i] = true; recur(index + 1); visit[i] = false; } } static int bfs() { ArrayList<Object> target = new ArrayList<>(); for (int i = 0; i < ar.size(); i++) { target.add(ar.get(temp[i])); } target.add(end); boolean[][] visit = new boolean[N][M]; visit[start.r][start.c] = true; Queue<Object> q = new LinkedList<Object>(); q.add(start); int index = 0; int result = 0; while (!q.isEmpty()) { Object now = q.poll(); for (int move = 0; move < 4; move++) { int nextR = now.r + dr[move]; int nextC = now.c + dc[move]; if (nextR >= N || nextR < 0 || nextC >= M || nextC < 0) continue; if (map[nextR][nextC] == -1 || visit[nextR][nextC]) continue; if (map[nextR][nextC] == target.get(index).num) { result += now.cnt + 1; visit = new boolean[N][M]; visit[nextR][nextC] = true; q = new LinkedList<Object>(); q.add(new Object(nextR, nextC, map[nextR][nextC], 0)); index++; if (result >= answer) return -1; break; } visit[nextR][nextC] = true; q.add(new Object(nextR, nextC, now.num, now.cnt + 1)); } if (index == target.size()) return result; } return result; } } class Object { int r, c, num, cnt; public Object(int r, int c, int num, int cnt) { this.r = r; this.c = c; this.num = num; this.cnt = cnt; } }
e0d277d015677a46e20cd58aeabf945cdbf75310
b27bfe9db8f0c7e5ca9377397b23ef2ef27d4ddc
/morozov/syntax/errors/QuestionMarkIsNotExpectedHere.java
a784ab921bd1548ab415fc2bf08a00fc752ca647
[]
no_license
Morozov2012/actor-prolog-java-library
85fe97eb6a37709d742f4ab06b29d0718c7269c3
5a7e2011ac2152278b8ebae3dfb2da4d925619a3
refs/heads/master
2021-01-20T15:39:14.173431
2019-12-13T13:09:01
2019-12-13T13:09:01
7,780,078
5
3
null
null
null
null
UTF-8
Java
false
false
200
java
// (c) 2019 IRE RAS Alexei A. Morozov package morozov.syntax.errors; public class QuestionMarkIsNotExpectedHere extends ParserError { public QuestionMarkIsNotExpectedHere(int p) { super(p); } }
442a4aa76d61b8123f82ae7e4d22fdbd0add1eb8
947ad90c8b8c4262e7fe041759d911403a4dac05
/PNF_HW2/src/Components/myFilter/MyFilter.java
bf5957f325a88bb2a1ef2f5a2d45c0e64dc8580c
[]
no_license
kingchan223/Pipe_Filter
dcb80ac62d2ea325cc3e0c5ee95d621442198d4e
d2ce22e2f4726c6a61bc934a4c5879e2d831e5b3
refs/heads/master
2023-08-29T13:46:11.576003
2021-11-09T12:58:49
2021-11-09T12:58:49
423,501,142
0
0
null
null
null
null
UTF-8
Java
false
false
1,079
java
package Components.myFilter; import Framework.CommonFilterImpl; import utils.DefaultUtil; import utils.UtilImpl; import java.io.IOException; import java.util.List; public class MyFilter extends CommonFilterImpl { DefaultUtil utils = new UtilImpl(); @Override public void specificComputationForFilter() throws IOException { List<String> requiredId = List.of(new String[]{"23456"}); int idx = 0; byte[] buffer = new byte[80]; int byte_read = 0; while(true) { while(byte_read != '\n' && byte_read != -1) { byte_read = in.read(); if(byte_read != -1 && byte_read != 13 && byte_read != 10) buffer[idx++] = (byte)byte_read; } byte[] buffer2 = new byte[idx]; System.arraycopy(buffer, 0, buffer2, 0, idx); byte[] filtered = utils.addCompulsory("EE", requiredId, buffer2); for (byte b : filtered) out.write((char) b); if (byte_read == -1) return; idx = 0; byte_read = '\0'; } } }
[ "--global" ]
--global
9796af7e735af5f88e4163039c613d7e7cf2d17e
89efe58164140bd5f535f8873e0954beaed59477
/src/main/java/kr/or/initspring/dto/commons/CollegeDTO.java
be3fb8c28b4764c02404413e806e26a1aff0dc34
[]
no_license
kown8447/ProjectSSS
ed06891e6675307fe0296cec9efb1684bf98511c
fb3ec52361cca9a486dcdefb5e6690db6e8b64eb
refs/heads/master
2020-08-03T15:41:49.802077
2016-12-13T08:16:54
2016-12-13T08:16:54
73,536,054
0
0
null
null
null
null
UTF-8
Java
false
false
1,521
java
/* * @Class : CollegeDTO * @Date : 2016.11.19 * @Author : 권기엽 * @Desc : 단과대학 정보를 관리하는 DTO */ package kr.or.initspring.dto.commons; public class CollegeDTO { private String college_code; //단과대학 코드 private String professor_code; //교수번호 private String office_code; //사무실 코드 private String college_name; //단과대학 이름 private String college_description; //단과대학 설명 public String getCollege_code() { return college_code; } public void setCollege_code(String college_code) { this.college_code = college_code; } public String getProfessor_code() { return professor_code; } public void setProfessor_code(String professor_code) { this.professor_code = professor_code; } public String getOffice_code() { return office_code; } public void setOffice_code(String office_code) { this.office_code = office_code; } public String getCollege_name() { return college_name; } public void setCollege_name(String college_name) { this.college_name = college_name; } public String getCollege_description() { return college_description; } public void setCollege_description(String college_description) { this.college_description = college_description; } @Override public String toString() { return "CollegeDTO [college_code=" + college_code + ", professor_code=" + professor_code + ", office_code=" + office_code + ", college_name=" + college_name + ", college_description=" + college_description + "]"; } }
407a82d9ac44fcacebdd50afdceaca289626620a
786bfc635cf9d233e9ce9508cd2c0b88cb6e78ec
/dk.dtu.imm.esculapauml.gui.topcased/src/dk/dtu/imm/esculapauml/gui/topcased/commands/EsculapaCommand.java
7966948c0b0bc0241dc76c7c1e4c29795cdc2eae
[]
no_license
piotr-puczynski/esculapa-uml
eafbede835776aa738eb75e44ebacf31740e99b1
07a2f020fd713aa0d5fe160efbcee3e057bcfb37
refs/heads/master
2021-01-21T22:26:42.914199
2012-09-16T10:22:58
2012-09-16T10:22:58
34,077,485
0
0
null
null
null
null
UTF-8
Java
false
false
2,968
java
/****************************************************************************** * Copyright (c) 2011, 2012 Piotr J. Puczynski (DTU Informatics). * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Piotr J. Puczynski (DTU Informatics) - initial API and implementation * ****************************************************************************/ package dk.dtu.imm.esculapauml.gui.topcased.commands; import org.eclipse.emf.common.util.EList; import org.eclipse.emf.ecore.resource.Resource; import org.eclipse.gef.commands.Command; import org.eclipse.uml2.uml.Interaction; import org.topcased.modeler.editor.Modeler; import dk.dtu.imm.esculapauml.core.checkers.UseCaseChecker; import dk.dtu.imm.esculapauml.gui.topcased.extenders.InteractionExtender; import dk.dtu.imm.esculapauml.gui.topcased.fixers.InteractionOrderFixer; import dk.dtu.imm.esculapauml.gui.topcased.observer.SimulationObserver; import dk.dtu.imm.esculapauml.gui.topcased.utils.GuiUtils; import dk.dtu.imm.esculapauml.gui.topcased.utils.TopcasedMarkerHelper; /** * The main consistency checking command. * * @author Piotr J. Puczynski * */ public class EsculapaCommand extends Command { private EList<Interaction> interactions; private Resource res; private Modeler modeler; /** * */ public EsculapaCommand(Resource res, Modeler modeler, EList<Interaction> interactions) { super(); this.interactions = interactions; this.res = res; this.modeler = modeler; } /** * @see org.eclipse.gef.commands.Command#execute() */ @Override public void execute() { redo(); } /** * @see org.eclipse.gef.commands.Command#redo() */ @Override public void redo() { TopcasedMarkerHelper.deleteMarkers(res); for (Interaction interaction : interactions) { InteractionOrderFixer fixer = new InteractionOrderFixer(modeler, interaction); fixer.fix(); if (fixer.hadFixedErrors()) { GuiUtils.showInfo("Interaction '" + interaction.getLabel() + "' had order of messages in diagram inconsistent with the order in the model. The model was fixed before checking.", modeler); } UseCaseChecker checker = new UseCaseChecker(interaction); checker.getSystemState().getSimObservers().addListener(new SimulationObserver(modeler)); checker.check(); InteractionExtender ie = new InteractionExtender(modeler, checker.getCheckedObject()); ie.extend(); TopcasedMarkerHelper.createMarkers(checker.getDiagnostics(), res); } modeler.refreshOutline(); modeler.refreshActiveDiagram(); } /* * (non-Javadoc) * * @see org.eclipse.gef.commands.Command#canUndo() */ @Override public boolean canUndo() { return false; } }
df269a9637b83a95cd77a5d00dda20fee56c3c24
8af1164bac943cef64e41bae312223c3c0e38114
/results-java/elastic--elasticsearch/2cc97a0d3ed2a9276378e2a6462942deab04a1fb/after/RecoverySettingsTests.java
64040decdb95941cc9c4e16e549938ee0e7cded5
[]
no_license
fracz/refactor-extractor
3ae45c97cc63f26d5cb8b92003b12f74cc9973a9
dd5e82bfcc376e74a99e18c2bf54c95676914272
refs/heads/master
2021-01-19T06:50:08.211003
2018-11-30T13:00:57
2018-11-30T13:00:57
87,353,478
0
0
null
null
null
null
UTF-8
Java
false
false
7,164
java
/* * Licensed to Elasticsearch under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch licenses this file to you under * the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.elasticsearch.recovery; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.unit.ByteSizeUnit; import org.elasticsearch.indices.recovery.RecoverySettings; import org.elasticsearch.test.ESSingleNodeTestCase; import java.util.concurrent.TimeUnit; public class RecoverySettingsTests extends ESSingleNodeTestCase { @Override protected boolean resetNodeAfterTest() { return true; } public void testAllSettingsAreDynamicallyUpdatable() { innerTestSettings(RecoverySettings.INDICES_RECOVERY_FILE_CHUNK_SIZE, randomIntBetween(1, 200), ByteSizeUnit.BYTES, new Validator() { @Override public void validate(RecoverySettings recoverySettings, int expectedValue) { assertEquals(expectedValue, recoverySettings.fileChunkSize().bytesAsInt()); } }); innerTestSettings(RecoverySettings.INDICES_RECOVERY_TRANSLOG_OPS, randomIntBetween(1, 200), new Validator() { @Override public void validate(RecoverySettings recoverySettings, int expectedValue) { assertEquals(expectedValue, recoverySettings.translogOps()); } }); innerTestSettings(RecoverySettings.INDICES_RECOVERY_TRANSLOG_SIZE, randomIntBetween(1, 200), ByteSizeUnit.BYTES, new Validator() { @Override public void validate(RecoverySettings recoverySettings, int expectedValue) { assertEquals(expectedValue, recoverySettings.translogSize().bytesAsInt()); } }); innerTestSettings(RecoverySettings.INDICES_RECOVERY_CONCURRENT_STREAMS, randomIntBetween(1, 200), new Validator() { @Override public void validate(RecoverySettings recoverySettings, int expectedValue) { assertEquals(expectedValue, recoverySettings.concurrentStreamPool().getMaximumPoolSize()); } }); innerTestSettings(RecoverySettings.INDICES_RECOVERY_CONCURRENT_SMALL_FILE_STREAMS, randomIntBetween(1, 200), new Validator() { @Override public void validate(RecoverySettings recoverySettings, int expectedValue) { assertEquals(expectedValue, recoverySettings.concurrentSmallFileStreamPool().getMaximumPoolSize()); } }); innerTestSettings(RecoverySettings.INDICES_RECOVERY_MAX_BYTES_PER_SEC, 0, new Validator() { @Override public void validate(RecoverySettings recoverySettings, int expectedValue) { assertEquals(null, recoverySettings.rateLimiter()); } }); innerTestSettings(RecoverySettings.INDICES_RECOVERY_RETRY_DELAY_STATE_SYNC, randomIntBetween(1, 200), TimeUnit.MILLISECONDS, new Validator() { @Override public void validate(RecoverySettings recoverySettings, int expectedValue) { assertEquals(expectedValue, recoverySettings.retryDelayStateSync().millis()); } }); innerTestSettings(RecoverySettings.INDICES_RECOVERY_RETRY_DELAY_NETWORK, randomIntBetween(1, 200), TimeUnit.MILLISECONDS, new Validator() { @Override public void validate(RecoverySettings recoverySettings, int expectedValue) { assertEquals(expectedValue, recoverySettings.retryDelayNetwork().millis()); } }); innerTestSettings(RecoverySettings.INDICES_RECOVERY_ACTIVITY_TIMEOUT, randomIntBetween(1, 200), TimeUnit.MILLISECONDS, new Validator() { @Override public void validate(RecoverySettings recoverySettings, int expectedValue) { assertEquals(expectedValue, recoverySettings.activityTimeout().millis()); } }); innerTestSettings(RecoverySettings.INDICES_RECOVERY_INTERNAL_ACTION_TIMEOUT, randomIntBetween(1, 200), TimeUnit.MILLISECONDS, new Validator() { @Override public void validate(RecoverySettings recoverySettings, int expectedValue) { assertEquals(expectedValue, recoverySettings.internalActionTimeout().millis()); } }); innerTestSettings(RecoverySettings.INDICES_RECOVERY_INTERNAL_LONG_ACTION_TIMEOUT, randomIntBetween(1, 200), TimeUnit.MILLISECONDS, new Validator() { @Override public void validate(RecoverySettings recoverySettings, int expectedValue) { assertEquals(expectedValue, recoverySettings.internalActionLongTimeout().millis()); } }); innerTestSettings(RecoverySettings.INDICES_RECOVERY_COMPRESS, false, new Validator() { @Override public void validate(RecoverySettings recoverySettings, boolean expectedValue) { assertEquals(expectedValue, recoverySettings.compress()); } }); } private static class Validator { public void validate(RecoverySettings recoverySettings, int expectedValue) { } public void validate(RecoverySettings recoverySettings, boolean expectedValue) { } } private void innerTestSettings(String key, int newValue, Validator validator) { client().admin().cluster().prepareUpdateSettings().setTransientSettings(Settings.builder().put(key, newValue)).get(); validator.validate(getInstanceFromNode(RecoverySettings.class), newValue); } private void innerTestSettings(String key, int newValue, TimeUnit timeUnit, Validator validator) { client().admin().cluster().prepareUpdateSettings().setTransientSettings(Settings.builder().put(key, newValue, timeUnit)).get(); validator.validate(getInstanceFromNode(RecoverySettings.class), newValue); } private void innerTestSettings(String key, int newValue, ByteSizeUnit byteSizeUnit, Validator validator) { client().admin().cluster().prepareUpdateSettings().setTransientSettings(Settings.builder().put(key, newValue, byteSizeUnit)).get(); validator.validate(getInstanceFromNode(RecoverySettings.class), newValue); } private void innerTestSettings(String key, boolean newValue, Validator validator) { client().admin().cluster().prepareUpdateSettings().setTransientSettings(Settings.builder().put(key, newValue)).get(); validator.validate(getInstanceFromNode(RecoverySettings.class), newValue); } }
a3d59a28d8d63df57fd1158fdbe99aab8fe3e722
5456502f97627278cbd6e16d002d50f1de3da7bb
/android_webview/javatests/src/org/chromium/android_webview/test/AwContentsClientVisitedHistoryTest.java
94e341efa3e91be3ea843f7c16dc563fa63e8e28
[ "BSD-3-Clause" ]
permissive
TrellixVulnTeam/Chromium_7C66
72d108a413909eb3bd36c73a6c2f98de1573b6e5
c8649ab2a0f5a747369ed50351209a42f59672ee
refs/heads/master
2023-03-16T12:51:40.231959
2017-12-20T10:38:26
2017-12-20T10:38:26
null
0
0
null
null
null
null
UTF-8
Java
false
false
6,310
java
// Copyright 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package org.chromium.android_webview.test; import android.test.suitebuilder.annotation.SmallTest; import android.webkit.ValueCallback; import org.chromium.android_webview.AwContents; import org.chromium.android_webview.test.TestAwContentsClient.DoUpdateVisitedHistoryHelper; import org.chromium.base.test.util.CallbackHelper; import org.chromium.base.test.util.Feature; import org.chromium.net.test.util.TestWebServer; /** * Tests for AwContentsClient.getVisitedHistory and AwContents.doUpdateVisitedHistory callbacks. */ public class AwContentsClientVisitedHistoryTest extends AwTestBase { private static class GetVisitedHistoryHelper extends CallbackHelper { private ValueCallback<String[]> mCallback; private boolean mSaveCallback = false; public ValueCallback<String[]> getCallback() { assert getCallCount() > 0; return mCallback; } public void setSaveCallback(boolean value) { mSaveCallback = value; } public void notifyCalled(ValueCallback<String[]> callback) { if (mSaveCallback) { mCallback = callback; } notifyCalled(); } } private static class VisitedHistoryTestAwContentsClient extends TestAwContentsClient { private GetVisitedHistoryHelper mGetVisitedHistoryHelper; public VisitedHistoryTestAwContentsClient() { mGetVisitedHistoryHelper = new GetVisitedHistoryHelper(); } public GetVisitedHistoryHelper getGetVisitedHistoryHelper() { return mGetVisitedHistoryHelper; } @Override public void getVisitedHistory(ValueCallback<String[]> callback) { getGetVisitedHistoryHelper().notifyCalled(callback); } } private VisitedHistoryTestAwContentsClient mContentsClient = new VisitedHistoryTestAwContentsClient(); @Feature({"AndroidWebView"}) @SmallTest public void testUpdateVisitedHistoryCallback() throws Throwable { AwTestContainerView testView = createAwTestContainerViewOnMainSync(mContentsClient); AwContents awContents = testView.getAwContents(); final String path = "/testUpdateVisitedHistoryCallback.html"; final String html = "testUpdateVisitedHistoryCallback"; TestWebServer webServer = TestWebServer.start(); try { final String pageUrl = webServer.setResponse(path, html, null); final DoUpdateVisitedHistoryHelper doUpdateVisitedHistoryHelper = mContentsClient.getDoUpdateVisitedHistoryHelper(); int callCount = doUpdateVisitedHistoryHelper.getCallCount(); loadUrlAsync(awContents, pageUrl); doUpdateVisitedHistoryHelper.waitForCallback(callCount); assertEquals(pageUrl, doUpdateVisitedHistoryHelper.getUrl()); assertEquals(false, doUpdateVisitedHistoryHelper.getIsReload()); // Reload callCount = doUpdateVisitedHistoryHelper.getCallCount(); loadUrlAsync(awContents, pageUrl); doUpdateVisitedHistoryHelper.waitForCallback(callCount); assertEquals(pageUrl, doUpdateVisitedHistoryHelper.getUrl()); assertEquals(true, doUpdateVisitedHistoryHelper.getIsReload()); } finally { webServer.shutdown(); } } @Feature({"AndroidWebView"}) @SmallTest public void testGetVisitedHistoryExerciseCodePath() throws Throwable { // Due to security/privacy restrictions around the :visited css property, it is not // possible test this end to end without using the flaky and brittle capturing picture of // the web page. So we are doing the next best thing, exercising all the code paths. final GetVisitedHistoryHelper visitedHistoryHelper = mContentsClient.getGetVisitedHistoryHelper(); final int callCount = visitedHistoryHelper.getCallCount(); visitedHistoryHelper.setSaveCallback(true); AwTestContainerView testView = createAwTestContainerViewOnMainSync(mContentsClient); AwContents awContents = testView.getAwContents(); final String path = "/testGetVisitedHistoryExerciseCodePath.html"; final String visitedLinks[] = {"http://foo.com", "http://bar.com", null}; final String html = "<a src=\"http://foo.com\">foo</a><a src=\"http://bar.com\">bar</a>"; TestWebServer webServer = TestWebServer.start(); try { final String pageUrl = webServer.setResponse(path, html, null); loadUrlSync(awContents, mContentsClient.getOnPageFinishedHelper(), pageUrl); visitedHistoryHelper.waitForCallback(callCount); assertNotNull(visitedHistoryHelper.getCallback()); visitedHistoryHelper.getCallback().onReceiveValue(visitedLinks); visitedHistoryHelper.getCallback().onReceiveValue(null); loadUrlSync(awContents, mContentsClient.getOnPageFinishedHelper(), pageUrl); } finally { webServer.shutdown(); } } @Feature({"AndroidWebView"}) @SmallTest public void testGetVisitedHistoryCallbackAfterDestroy() throws Throwable { GetVisitedHistoryHelper visitedHistoryHelper = mContentsClient.getGetVisitedHistoryHelper(); visitedHistoryHelper.setSaveCallback(true); final int callCount = visitedHistoryHelper.getCallCount(); AwTestContainerView testView = createAwTestContainerViewOnMainSync(mContentsClient); AwContents awContents = testView.getAwContents(); loadUrlAsync(awContents, "about:blank"); visitedHistoryHelper.waitForCallback(callCount); assertNotNull(visitedHistoryHelper.getCallback()); destroyAwContentsOnMainSync(awContents); visitedHistoryHelper.getCallback().onReceiveValue(new String[] {"abc.def"}); visitedHistoryHelper.getCallback().onReceiveValue(null); } }
51f9735ade6b5b2393bfde9e169c5f55866666e9
3d39c8c6d66f402e40e03f610d0dbcc4a3b3fac1
/src/com/jagex/rt4/lights/LightRenderer.java
4e4dcde24f82b29b1c3debbd8c0940ac042df240
[]
no_license
95thcobra/508-HD
f1add7e3865e24ed65e7d0340e78c014a031afe1
c0e1899487a90b3b022a81f4e84645f2bcaef1c0
refs/heads/master
2020-03-28T19:41:09.993251
2018-04-17T21:48:30
2018-04-17T21:48:30
null
0
0
null
null
null
null
UTF-8
Java
false
false
5,784
java
/* Class130 - Decompiled by JODE * Visit http://jode.sourceforge.net/ */ package com.jagex.rt4.lights; import java.nio.ByteBuffer; import javax.media.opengl.GL; import com.jagex.io.Buffer; import com.jagex.link.HashTable; import com.jagex.rt4.Class14_Sub1; import com.jagex.rt4.RT4GL; import com.jagex.rt4.VertexBuffer; import rs.JunkTex; public class LightRenderer { public byte[] aByteArray2141; public byte[] aByteArray2145; public byte[] aByteArray2146; public ByteBuffer aByteBuffer2139; public ByteBuffer aByteBuffer2147; public VertexBuffer aClass29_2137; public VertexBuffer aClass29_2142; public HashTable aClass55_2138; public int anInt2140; public int anInt2144; public int anInt2151; public int anInt2152; public int[] anIntArray2143; public int[] anIntArray2148; public int[] anIntArray2149; public int[] anIntArray2150; public void init() { Buffer class14_sub10 = new Buffer(anInt2152 * 4); Buffer class14_sub10_0_ = new Buffer(anInt2140 * 16); if (RT4GL.usingBigEndian) { for (int i = 0; i < anInt2140; i++) { class14_sub10_0_.method809(aByteArray2145[i]); class14_sub10_0_.method809(aByteArray2141[i]); class14_sub10_0_.method809(aByteArray2146[i]); class14_sub10_0_.method809(255); class14_sub10_0_.putFloatAsInt((float) anIntArray2143[i]); class14_sub10_0_.putFloatAsInt((float) anIntArray2148[i]); class14_sub10_0_.putFloatAsInt((float) anIntArray2150[i]); } for (int i = 0; i < anInt2152; i++) class14_sub10.method803(anIntArray2149[i], 107); } else { for (int i = 0; i < anInt2140; i++) { class14_sub10_0_.method809(aByteArray2145[i]); class14_sub10_0_.method809(aByteArray2141[i]); class14_sub10_0_.method809(aByteArray2146[i]); class14_sub10_0_.method809(255); class14_sub10_0_.putFloatAsLEInt((float) anIntArray2143[i], 24671); class14_sub10_0_.putFloatAsLEInt((float) anIntArray2148[i], 24671); class14_sub10_0_.putFloatAsLEInt((float) anIntArray2150[i], 24671); } for (int i = 0; i < anInt2152; i++) class14_sub10.method825(-99, anIntArray2149[i]); } if (RT4GL.vertexBufferAsObject) { aClass29_2137 = new VertexBuffer(); ByteBuffer bytebuffer = ByteBuffer.wrap(class14_sub10_0_.payload); aClass29_2137._setArrayData(bytebuffer); aClass29_2142 = new VertexBuffer(); bytebuffer = ByteBuffer.wrap(class14_sub10.payload); aClass29_2142.setElementData(bytebuffer); } else { aByteBuffer2147 = ByteBuffer.allocateDirect(class14_sub10_0_.position); aByteBuffer2147.put(class14_sub10_0_.payload); aByteBuffer2147.flip(); aByteBuffer2139 = ByteBuffer.allocateDirect(class14_sub10.position); aByteBuffer2139.put(class14_sub10.payload); aByteBuffer2139.flip(); } anIntArray2143 = null; anIntArray2148 = null; anIntArray2150 = null; aByteArray2145 = null; aByteArray2141 = null; aByteArray2146 = null; anIntArray2149 = null; aClass55_2138 = null; } public void render() { GL gl = RT4GL.gl; if (RT4GL.vertexBufferAsObject) { aClass29_2137.bindArray(); gl.glInterleavedArrays(10787, 16, 0L); RT4GL.aBoolean2027 = false; aClass29_2142.method1055(); gl.glDrawElements(4, anInt2152, 5125, 0L); } else { if (RT4GL.vertexBufferAsObject) { gl.glBindBufferARB(34962, 0); gl.glBindBufferARB(34963, 0); } gl.glInterleavedArrays(10787, 16, aByteBuffer2147); RT4GL.aBoolean2027 = false; gl.glDrawElements(4, anInt2152, 5125, aByteBuffer2139); } } public int method1769(Light light, int i, int i_1_, int i_2_, float f, float f_3_, float f_4_) { long l = 0L; if ((i & 0x7f) == 0 || (i_2_ & 0x7f) == 0) { l = (long) (i + (i_2_ << 16)); Class14_Sub1 class14_sub1 = (Class14_Sub1) aClass55_2138.get(l); if (class14_sub1 != null) return class14_sub1.anInt2714; } int i_5_ = light.anInt1122; float f_6_ = (float) (light.param1 - i); float f_7_ = (float) (light.param2 - i_1_); float f_8_ = (float) (light.param3 - i_2_); float f_9_ = (float) Math.sqrt((double) (f_6_ * f_6_ + f_7_ * f_7_ + f_8_ * f_8_)); float f_10_ = 1.0F / f_9_; f_6_ *= f_10_; f_7_ *= f_10_; f_8_ *= f_10_; float f_11_ = f_9_ / (float) ((light.anInt1120 << 7) + 64); float f_12_ = 1.0F - f_11_ * f_11_; if (f_12_ < 0.0F) f_12_ = 0.0F; float f_13_ = f_6_ * f + f_7_ * f_3_ + f_8_ * f_4_; if (f_13_ < 0.0F) f_13_ = 0.0F; float f_14_ = f_13_ * f_12_ * 2.0F; if (f_14_ > 1.0F) f_14_ = 1.0F; int i_15_ = (int) (f_14_ * (float) (i_5_ >> 16 & 0xff)); if (i_15_ > 255) i_15_ = 255; int i_16_ = (int) (f_14_ * (float) (i_5_ >> 8 & 0xff)); if (i_16_ > 255) i_16_ = 255; int i_17_ = (int) (f_14_ * (float) (i_5_ & 0xff)); if (i_17_ > 255) i_17_ = 255; aByteArray2145[anInt2140] = (byte) i_15_; aByteArray2141[anInt2140] = (byte) i_16_; aByteArray2146[anInt2140] = (byte) i_17_; anIntArray2143[anInt2140] = i; anIntArray2148[anInt2140] = i_1_; anIntArray2150[anInt2140] = i_2_; aClass55_2138.put(l, new Class14_Sub1(anInt2140)); return anInt2140++; } public void method1770(int[] is) { for (int i = 1; i < is.length - 1; i++) { anIntArray2149[anInt2152++] = is[0]; anIntArray2149[anInt2152++] = is[i]; anIntArray2149[anInt2152++] = is[i + 1]; } } public void method1771() { anIntArray2149 = new int[anInt2144]; anIntArray2143 = new int[anInt2151]; anIntArray2148 = new int[anInt2151]; anIntArray2150 = new int[anInt2151]; aByteArray2145 = new byte[anInt2151]; aByteArray2141 = new byte[anInt2151]; aByteArray2146 = new byte[anInt2151]; aClass55_2138 = new HashTable(JunkTex.method653(anInt2151)); } }
fda8223c2fa32db47144fb161b442a74766215c8
65423f57d25e34d9440bf894584b92be29946825
/target/generated-sources/xjc/com/clincab/web/app/eutils/jaxb/e2br3/COCTMT970000UVAuthorization3.java
a4ce4222e2b4f8e96b05d74bd1a9a403fa539b06
[]
no_license
kunalcabcsi/toolsr3
0b518cfa6813a88a921299ab8b8b5d6cbbd362fe
5071990dc2325bc74c34a3383792ad5448dee1b0
refs/heads/master
2021-08-31T04:20:23.924815
2017-12-20T09:25:33
2017-12-20T09:25:33
114,867,895
0
0
null
null
null
null
UTF-8
Java
false
false
5,868
java
// // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.11 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2017.12.20 at 02:30:39 PM IST // package com.clincab.web.app.eutils.jaxb.e2br3; import java.util.ArrayList; import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for COCT_MT970000UV.Authorization3 complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="COCT_MT970000UV.Authorization3"&gt; * &lt;complexContent&gt; * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"&gt; * &lt;sequence&gt; * &lt;group ref="{urn:hl7-org:v3}InfrastructureRootElements"/&gt; * &lt;element name="contractEvent" type="{urn:hl7-org:v3}COCT_MT970000UV.ContractEvent"/&gt; * &lt;/sequence&gt; * &lt;attGroup ref="{urn:hl7-org:v3}InfrastructureRootAttributes"/&gt; * &lt;attribute name="nullFlavor" type="{urn:hl7-org:v3}NullFlavor" /&gt; * &lt;attribute name="typeCode" use="required" type="{urn:hl7-org:v3}ActRelationshipAuthorizedBy" /&gt; * &lt;/restriction&gt; * &lt;/complexContent&gt; * &lt;/complexType&gt; * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "COCT_MT970000UV.Authorization3", propOrder = { "realmCode", "typeId", "templateId", "contractEvent" }) public class COCTMT970000UVAuthorization3 { protected List<CS> realmCode; protected II typeId; protected List<II> templateId; @XmlElement(required = true, nillable = true) protected COCTMT970000UVContractEvent contractEvent; @XmlAttribute(name = "nullFlavor") protected NullFlavor nullFlavor; @XmlAttribute(name = "typeCode", required = true) protected ActRelationshipAuthorizedBy typeCode; /** * Gets the value of the realmCode property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the realmCode property. * * <p> * For example, to add a new item, do as follows: * <pre> * getRealmCode().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link CS } * * */ public List<CS> getRealmCode() { if (realmCode == null) { realmCode = new ArrayList<CS>(); } return this.realmCode; } /** * Gets the value of the typeId property. * * @return * possible object is * {@link II } * */ public II getTypeId() { return typeId; } /** * Sets the value of the typeId property. * * @param value * allowed object is * {@link II } * */ public void setTypeId(II value) { this.typeId = value; } /** * Gets the value of the templateId property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the templateId property. * * <p> * For example, to add a new item, do as follows: * <pre> * getTemplateId().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link II } * * */ public List<II> getTemplateId() { if (templateId == null) { templateId = new ArrayList<II>(); } return this.templateId; } /** * Gets the value of the contractEvent property. * * @return * possible object is * {@link COCTMT970000UVContractEvent } * */ public COCTMT970000UVContractEvent getContractEvent() { return contractEvent; } /** * Sets the value of the contractEvent property. * * @param value * allowed object is * {@link COCTMT970000UVContractEvent } * */ public void setContractEvent(COCTMT970000UVContractEvent value) { this.contractEvent = value; } /** * Gets the value of the nullFlavor property. * * @return * possible object is * {@link NullFlavor } * */ public NullFlavor getNullFlavor() { return nullFlavor; } /** * Sets the value of the nullFlavor property. * * @param value * allowed object is * {@link NullFlavor } * */ public void setNullFlavor(NullFlavor value) { this.nullFlavor = value; } /** * Gets the value of the typeCode property. * * @return * possible object is * {@link ActRelationshipAuthorizedBy } * */ public ActRelationshipAuthorizedBy getTypeCode() { return typeCode; } /** * Sets the value of the typeCode property. * * @param value * allowed object is * {@link ActRelationshipAuthorizedBy } * */ public void setTypeCode(ActRelationshipAuthorizedBy value) { this.typeCode = value; } }
4d36905543e1071775cb8619ad9af34206f95d61
85465b318c5f38e32f52792b6be3ce06063e9b32
/Code/src/www/learnjava/garfield/ch30/HomeWorkTest.java
b4827d7bf9c6f90255006761a91bd7ca588b9687
[]
no_license
Garfield-0927/LearnJava
dee0c20cd80948c73b6ba6eca26ca754366521c4
92d4d9c46c2d61f04d3397bc8a3a93483f709d09
refs/heads/master
2023-05-04T23:26:36.836449
2021-05-27T15:12:39
2021-05-27T15:12:39
367,068,028
1
0
null
null
null
null
UTF-8
Java
false
false
6,077
java
/** * @author:Garfield * @date :Created in 2021/5/27 20:30 */ package www.learnjava.garfield.ch30; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class HomeWorkTest { } class Holder { private int data = 0; public int getData() { return data; } public synchronized void inc(int amount) { int newValue = data + amount; try { System.out.println("IncThread sleep"); Thread.sleep(5000); System.out.println("IncThread awake"); } catch (InterruptedException e) { } data = newValue; } public void dec(int amount) { int newValue = data - amount; try { System.out.println("DecThread"); Thread.sleep(1); } catch (InterruptedException e) { } data = newValue; } public static void main(String[] args) { ExecutorService es = Executors.newCachedThreadPool(); Holder holder = new Holder(); int incAmount = 10, decAmount = 5, loops = 100; Runnable incTask = () -> holder.inc(incAmount); Runnable decTask = () -> holder.dec(decAmount); for (int i = 0; i < loops; i++) { es.execute(incTask); es.execute(decTask); } es.shutdown(); while (!es.isTerminated()) { } } } class Test2_3 { private static Object lockObject = new Object(); /** * \* 计数器 */ public static class Counter { private int count = 0; public int getCount() { return count; } public void inc() { synchronized (lockObject) { int temp = count + 1; try { Thread.sleep(5); } catch (InterruptedException e) { } count = temp; } } public void dec() { synchronized (lockObject) { int temp = count - 1; try { Thread.sleep(5); } catch (InterruptedException e) { } count = temp; } } } public static void main(String[] args) { ExecutorService es = Executors.newCachedThreadPool(); Counter counter1 = new Counter(); Counter counter2 = new Counter(); int loops1 = 10, loops2 = 5; Runnable incTask = () -> counter1.inc(); Runnable decTask = () -> counter2.dec(); for (int i = 0; i < loops1; i++) { es.execute(incTask); } for (int i = 0; i < loops2; i++) { es.execute(decTask); } es.shutdown(); while (!es.isTerminated()) { } } } class Test2_4 { public static class Resource { private int value = 0; public int sum(int amount) { int newValue = value + amount; try { Thread.sleep(5); } catch (InterruptedException e) { } return newValue; } public int sub(int amount) { int newValue = value - amount; try { Thread.sleep(5); } catch (InterruptedException e) { } return newValue; } } public static void main(String[] args) { ExecutorService es = Executors.newCachedThreadPool(); Resource r = new Resource(); int loops1 = 10, loops2 = 5, amount = 5; Runnable sumTask = () -> r.sum(amount); Runnable subTask = () -> r.sub(amount); for (int i = 0; i < loops1; i++) { es.execute(sumTask); } for (int i = 0; i < loops2; i++) { es.execute(subTask); } es.shutdown(); while (!es.isTerminated()) { } } } class Test2_5 { public static class Resource { private static int value = 0; public static int getValue() { return value; } public static void inc(int amount) { synchronized (Resource.class) { int newValue = value + amount; try { Thread.sleep(5); } catch (InterruptedException e) { } value = newValue; } } public synchronized static void dec(int amount) { int newValue = value - amount; try { Thread.sleep(2); } catch (InterruptedException e) { } value = newValue; } } public static void main(String[] args) { ExecutorService es = Executors.newCachedThreadPool(); int incAmount = 10, decAmount = 5, loops = 100; Resource r1 = new Resource(); Resource r2 = new Resource(); Runnable incTask = () -> r1.inc(incAmount); Runnable decTask = () -> r2.dec(decAmount); for (int i = 0; i < loops; i++) { es.execute(incTask); es.execute(decTask); } es.shutdown(); while (!es.isTerminated()) { } } } //class p3 { // public static void main(String[] args) { // Thread t1 = new T1(); // Thread t2 = new T2(); // Thread t3 = new T3(); // // try { // t1.start(); // t1.join(); // } catch (InterruptedException e) { // e.printStackTrace(); // } // // try { // t2.start(); // t2.join(); // } catch (InterruptedException e) { // e.printStackTrace(); // } // // try { // t3.start(); // t3.join(); // } catch (InterruptedException e) { // e.printStackTrace(); // } // } //}
d804ca4dfec3d16243d9f02212df1caff6b55829
3ea826fd5b18aa0747841712fb8c35d5bfac3323
/app/src/main/java/com/example/gauravpc/mis/temples.java
f0b1c4c81992d15f4ff5639536c595125fa0a478
[]
no_license
gaurav4ever/Mis-Project
b727cd81b97b2e2bc73515d7c6f0add2dca00f0c
f86820970e82268feb2b280c09c6b67aa055b3a5
refs/heads/master
2021-01-20T07:38:09.004769
2017-05-02T11:05:47
2017-05-02T11:05:47
90,023,862
0
0
null
null
null
null
UTF-8
Java
false
false
8,001
java
package com.example.gauravpc.mis; import android.Manifest; import android.app.ProgressDialog; import android.content.Context; import android.content.Intent; import android.content.pm.PackageManager; import android.content.res.AssetManager; import android.graphics.Typeface; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.net.Uri; import android.os.AsyncTask; import android.os.Bundle; import android.support.design.widget.FloatingActionButton; import android.support.design.widget.Snackbar; import android.support.v4.app.ActivityCompat; import android.support.v4.widget.DrawerLayout; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.ImageView; import android.widget.ListView; import android.widget.RelativeLayout; import android.widget.TextView; import android.widget.Toast; import com.nostra13.universalimageloader.core.DisplayImageOptions; import com.nostra13.universalimageloader.core.ImageLoader; import com.nostra13.universalimageloader.core.ImageLoaderConfiguration; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.List; import java.util.Locale; public class temples extends AppCompatActivity { ListView listView; Typeface typeface; RelativeLayout r; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_temples); Context context = getApplicationContext(); AssetManager am = context.getApplicationContext().getAssets(); typeface = Typeface.createFromAsset(am, String.format(Locale.US, "fonts/%s", "lato.ttf")); TextView t=(TextView)findViewById(R.id.headerText); t.setTypeface(typeface); ImageView backImage=(ImageView)findViewById(R.id.back); backImage.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Log.d("back", "pressed"); onBackPressed(); } }); DisplayImageOptions defaultOptions = new DisplayImageOptions.Builder() .cacheInMemory(true).cacheOnDisk(true).build(); ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(getApplicationContext()) .defaultDisplayImageOptions(defaultOptions).build(); ImageLoader.getInstance().init(config); listView=(ListView)findViewById(R.id.templesList); listView.setVisibility(View.GONE); r=(RelativeLayout)findViewById(R.id.loadingLayout); r.setVisibility(View.VISIBLE); boolean check=isNetworkAvailable(); if(check==true) { new JSONTask().execute("https://gauravpersonal.herokuapp.com/api/mis/all"); } else{ Toast.makeText(getApplicationContext(), "Please Check Your Internet Connection", Toast.LENGTH_SHORT).show(); } } private boolean isNetworkAvailable() { ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo(); return activeNetworkInfo != null && activeNetworkInfo.isConnected(); } public class JSONTask extends AsyncTask<String, String, List<TempleModel>> { @Override protected void onPreExecute() { super.onPreExecute(); } @Override protected List<TempleModel> doInBackground(String... params) { HttpURLConnection connection = null; BufferedReader reader = null; try { URL url = new URL(params[0]); connection = (HttpURLConnection) url.openConnection(); connection.connect(); InputStream stream = connection.getInputStream(); reader = new BufferedReader(new InputStreamReader(stream)); StringBuffer buffer = new StringBuffer(); String line = ""; while ((line = reader.readLine()) != null) { buffer.append(line); } String finalJson = buffer.toString(); JSONObject parentObject = new JSONObject(finalJson); JSONArray parentArray = parentObject.getJSONArray("all"); List<TempleModel> templeModelList = new ArrayList<>(); for (int i = 0; i < parentArray.length(); i++) { JSONObject finalObject = parentArray.getJSONObject(i); TempleModel templeModel = new TempleModel(); templeModel.setName(finalObject.getString("temple_name")); templeModel.setImg(finalObject.getString("img")); templeModel.setDesc(finalObject.getString("desc")); templeModelList.add(templeModel); } return templeModelList; } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (JSONException e) { e.printStackTrace(); } finally { if (connection != null) { connection.disconnect(); } try { if (reader != null) { reader.close(); } } catch (IOException e) { e.printStackTrace(); } } return null; } @Override protected void onPostExecute(List<TempleModel> TempleModels) { super.onPostExecute(TempleModels); r.setVisibility(View.GONE); listView.setVisibility(View.VISIBLE); TemplesAdapter templesAdapter = new TemplesAdapter(getApplicationContext(), R.layout.row_temple, TempleModels); listView.setAdapter(templesAdapter); } } public class TemplesAdapter extends ArrayAdapter { public List<TempleModel> TempleModelList; private int resource; private LayoutInflater inflater; public TemplesAdapter(Context context, int resource, List<TempleModel> objects) { super(context, resource,objects); TempleModelList=objects; this.resource=resource; inflater=(LayoutInflater)getSystemService(LAYOUT_INFLATER_SERVICE); } @Override public View getView(final int position, View convertView, ViewGroup parent) { if(convertView==null){ convertView=inflater.inflate(R.layout.row_temple,null); } TextView temple_nameText,descText; temple_nameText=(TextView)convertView.findViewById(R.id.temple_name); descText=(TextView)convertView.findViewById(R.id.desc); temple_nameText.setText(TempleModelList.get(position).getName()); temple_nameText.setTypeface(typeface); descText.setText(TempleModelList.get(position).getDesc()); descText.setTypeface(typeface); ImageView img=(ImageView)convertView.findViewById(R.id.img); ImageLoader.getInstance().displayImage(TempleModelList.get(position).getImg(),img); return convertView; } } @Override public void onBackPressed() { super.onBackPressed(); } }
[ "gaurav sharma" ]
gaurav sharma
2716f5434de75b647c620b3d8e7fc3509fc0dbac
a1ccd86b65a9875411bac7c5ad8a607dd977581f
/src/likou/company/bytedance/string/ReverseWords.java
4b96733ed07d5f912e71c06f6a5e8c8fb97d4ccd
[]
no_license
wp518cookie/leetcode
2b48549494f43ba666ca9b08b43e8815a2826455
c12839693a0931ec6365621a4c3df28eb60c9941
refs/heads/master
2023-05-30T20:26:32.814839
2021-06-22T07:59:15
2021-06-22T07:59:15
73,679,492
0
0
null
null
null
null
UTF-8
Java
false
false
3,354
java
package likou.company.bytedance.string; import java.util.ArrayDeque; import java.util.Deque; /** * @author wuping * @date 2020-06-29 * https://leetcode-cn.com/explore/featured/card/bytedance/242/string/1011/ * 给定一个字符串,逐个翻转字符串中的每个单词。 * * * * 示例 1: * * 输入: "the sky is blue" * 输出: "blue is sky the" * 示例 2: * * 输入: " hello world! " * 输出: "world! hello" * 解释: 输入字符串可以在前面或者后面包含多余的空格,但是反转后的字符不能包括。 * 示例 3: * * 输入: "a good example" * 输出: "example good a" * 解释: 如果两个单词间有多余的空格,将反转后单词间的空格减少到只含一个。 * * * 说明: * 无空格字符构成一个单词。 * 输入字符串可以在前面或者后面包含多余的空格,但是反转后的字符不能包括。 * 如果两个单词间有多余的空格,将反转后单词间的空格减少到只含一个。 */ public class ReverseWords { public static void main(String[] args) { String t = "a good example"; System.out.println(new ReverseWords().reverseWords(t)); } public String reverseWords(String s) { if (s ==null || s.length() == 0) { return s; } s = s.trim(); if (s.length() == 0) { return ""; } int start = -1; Deque<Character> deque = new ArrayDeque<>(); for (int i = 0; i < s.length(); i++) { char t = s.charAt(i); if (t != ' ') { if (start < 0) { start = i; } if (i == s.length() - 1) { int cur = i; while (start >= 0 && cur >= start) { deque.addFirst(s.charAt(cur--)); } } } else { if (start < 0) { continue; } int cur = i - 1; while (start >= 0 && cur >= start) { deque.addFirst(s.charAt(cur--)); } deque.addFirst(' '); start = -1; } } if (deque.peekFirst() == ' ') { deque.removeFirst(); } StringBuilder sb = new StringBuilder(); while (deque.size() > 0) { sb.append(deque.removeFirst()); } return sb.toString(); } // public String reverseWords(String s) { // if (s == null || s.length() == 0) { // return s; // } // s = s.trim(); // if (s.length() == 0) { // return s; // } // StringBuilder temp = new StringBuilder(); // for (int i = 0; i < s.length(); i++) { // if (s.charAt(i) == ' ' && s.charAt(i - 1) == ' ') { // continue; // } // temp.append(s.charAt(i)); // } // // 涉及正则表达式,很慢 // String[] arr = temp.toString().split(" "); // StringBuilder sb = new StringBuilder(); // for (int i = arr.length - 1; i >= 0; i--) { // sb.append(arr[i]); // if (i != 0) { // sb.append(" "); // } // } // return sb.toString(); // } }
3dbcbc08a00fb059d6bd17107ebb6d748b1aca59
94138ba86d0dbf80b387064064d1d86269e927a1
/group04/844028312/four/min-jvm/src/com/coderising/jvm/test/ClassFileloaderTest.java
6c617b54ce05a1fa457c311f9c549362deff9b96
[]
no_license
DonaldY/coding2017
2aa69b8a2c2990b0c0e02c04f50eef6cbeb60d42
0e0c386007ef710cfc90340cbbc4e901e660f01c
refs/heads/master
2021-01-17T20:14:47.101234
2017-06-01T00:19:19
2017-06-01T00:19:19
84,141,024
2
28
null
2017-06-01T00:19:20
2017-03-07T01:45:12
Java
UTF-8
Java
false
false
1,944
java
package com.coderising.jvm.test; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import com.coderising.jvm.loader.ClassFileLoader; public class ClassFileloaderTest { static String path1 = "F:\\workspace\\min-jvm\\bin"; static String path2 = "C:\temp"; @Before public void setUp() throws Exception { } @After public void tearDown() throws Exception { } @Test public void testClassPath(){ ClassFileLoader loader = new ClassFileLoader(); loader.addClassPath(path1); loader.addClassPath(path2); String clzPath = loader.getClassPath(); Assert.assertEquals(path1+";"+path2,clzPath); } @Test public void testClassFileLength() { ClassFileLoader loader = new ClassFileLoader(); loader.addClassPath(path1); String className = "com.coderising.jvm.test.EmployeeV1"; byte[] byteCodes = loader.readBinaryCode(className); int i=byteCodes.length; // 注意:这个字节数可能和你的JVM版本有关系, 你可以看看编译好的类到底有多大 Assert.assertEquals(2048, byteCodes.length); } @Test public void testMagicNumber(){ ClassFileLoader loader = new ClassFileLoader(); loader.addClassPath(path1); String className = "com.coderising.jvm.test.EmployeeV1"; byte[] byteCodes = loader.readBinaryCode(className); byte[] codes = new byte[]{byteCodes[0],byteCodes[1],byteCodes[2],byteCodes[3]}; String acctualValue = this.byteToHexString(codes); Assert.assertEquals("cafebabe", acctualValue); } private String byteToHexString(byte[] codes ){ StringBuffer buffer = new StringBuffer(); for(int i=0;i<codes.length;i++){ byte b = codes[i]; int value = b & 0xFF; String strHex = Integer.toHexString(value); if(strHex.length()< 2){ strHex = "0" + strHex; } buffer.append(strHex); } return buffer.toString(); } }
d49261bab54738e6511c0b9daef317557e838c9f
416443403df54fb750644332ec0544aba0d88f0b
/Java/BulbSwitcher.java
1413b9f5ca7f8d44cb9d0a3c012a160df783057c
[]
no_license
Xiao-Ma/leetcode
b52fd469e5fdfccc93d932d3dd72f833570060af
b286956215a100cbb461271ebb28417f57fba2df
refs/heads/master
2021-01-18T22:56:05.267815
2016-04-07T03:18:54
2016-04-07T03:18:54
31,341,771
1
0
null
null
null
null
UTF-8
Java
false
false
560
java
/** * @author: Xiao * LeetCode: bulb switcher * Description: There are n bulbs that are initially off. You first turn on all * the bulbs. Then, you turn off every second bulb. On the third * round, you toggle every third bulb (turning on if it's off or * turning off if it's on). For the nth round, you only toggle the * last bulb. Find how many bulbs are on after n rounds. */ public class BulbSwitcher { public int bulbSwitch(int n) { return (int)Math.floor(Math.sqrt(n)); } }
2c54b39c708d806826e3df94927818a297b03ca0
fcaedb149d7e08058110aa9744e65c8e1f6137d5
/app/src/main/java/sepm/englishgo/ChooseLevel.java
e069ffd52cf9b65386f07a156592c4bbccfed63b
[]
no_license
JamesToan/EnglishGO-master
b381c9d083c129aa60ba1eba05828987141d87be
dd214c6f134742ea0af36cdb55eb089dd7baac3a
refs/heads/master
2020-04-11T08:34:14.449100
2018-12-13T14:05:56
2018-12-13T14:05:56
161,648,037
0
0
null
null
null
null
UTF-8
Java
false
false
2,295
java
package sepm.englishgo; import android.content.Intent; import android.graphics.drawable.Drawable; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Button; public class ChooseLevel extends AppCompatActivity { public static int LEVEL; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.choose_level); Button btn1 = (Button)findViewById(R.id.level1); btn1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { LEVEL = 1; openChallenge(v); } }); Button btn2 = (Button)findViewById(R.id.level2); btn2.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { LEVEL = 2; openChallenge(v); } }); Button btn3 = (Button)findViewById(R.id.level3); btn3.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { LEVEL = 3; openChallenge(v); } }); final Button back = findViewById(R.id.levelBackButton); final Drawable before = getResources().getDrawable(R.drawable.back_before); back.setBackground(before); final Drawable after = getResources().getDrawable(R.drawable.back_after); back.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { back.setBackground(after); Intent changeView = new Intent( ChooseLevel.this, ChooseTopic.class); startActivity(changeView); } }); } protected void onStop() { super.onStop(); final Button back = findViewById(R.id.levelBackButton); final Drawable before = getResources().getDrawable(R.drawable.back_before); back.setBackground(before); } public void openChallenge(View view){ Intent changeView = new Intent( ChooseLevel.this, Challenge.class); startActivity(changeView); } }
21e98767c5004344c233418e537412b3cce30ed3
8400d1db5d29ab3f150949854600eee8b9d4fa49
/src/Offer/push_and_pop_sequence_of_stack.java
b6f956c6d6fa28ef9f6c6d15608b10d8aede7e66
[]
no_license
DozzzeN/leetcode
9664e6f332cd7ee08f10eabb0f9793a5253ee8fa
d6540c1df56348e94981237ff89c1738409b3613
refs/heads/master
2020-08-01T10:50:13.282254
2020-06-13T07:43:50
2020-06-13T07:43:50
210,971,594
0
0
null
null
null
null
GB18030
Java
false
false
1,566
java
package Offer; import java.util.Stack; //https://www.nowcoder.com/practice/d77d11405cc7470d82554cb392585106?tpId=13&tqId=11174&tPage=2&rp=2&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking //输入两个整数序列,第一个序列表示栈的压入顺序,请判断第二个序列是否可能为该栈的弹出顺序。假设压入栈的所有数字均不相等。例如序列1,2,3,4,5是某栈的压入顺序,序列4,5,3,2,1是该压栈序列对应的一个弹出序列,但4,3,5,1,2就不可能是该压栈序列的弹出序列。(注意:这两个序列的长度是相等的) public class push_and_pop_sequence_of_stack { public static void main(String[] args) { System.out.println(new push_and_pop_sequence_of_stack.Solution().IsPopOrder( new int[]{1, 2, 3, 4, 5}, // new int[]{4, 5, 3, 2, 1} new int[]{4, 3, 5, 1, 2} // new int[]{3, 5, 4, 2, 1} )); } public static class Solution { public boolean IsPopOrder(int[] pushA, int[] popA) { if (popA.length == 0 || popA.length != pushA.length) return false; Stack<Integer> stack = new Stack<>(); for (int pushIndex = 0, popIndex = 0; pushIndex < pushA.length; pushIndex++) { stack.push(pushA[pushIndex]); while (!stack.isEmpty() && stack.peek() == popA[popIndex]) { stack.pop(); popIndex++; } } return stack.isEmpty(); } } }
2993f5b821e2924ce2b1239f8f60aacb63e93367
dcce0cded9398c5915bffbb5e4f20946e6abddda
/Person.java
2585cd942d94bfec45c6957ba8a1c0b7e7b81e50
[]
no_license
widyapangestutians/praktikum10-widya
ac3717c78f3aac7b0d369f0665b296dc9ff28087
b06fd2f806d90220749f4a3fae2bd05c9285ad4f
refs/heads/master
2020-04-14T20:47:50.246160
2019-01-04T12:55:38
2019-01-04T12:55:38
164,107,122
0
0
null
null
null
null
UTF-8
Java
false
false
1,030
java
/* * 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 Praktikum10; /** * * @author widya */ public class Person { protected String name; protected String address; /** * Default constructor */ public Person(){ System.out.println("Inside Person:Custructor"); name = ""; address = ""; } /** * Constructor dengan dua parameter */ public Person( String vname, String vaddress){ this.name = vname; this.address = vaddress; } /** * Method accessor */ public String getName(){ return name; } public String getAddress(){ return address; } public void setName(String vname){ this.name = vname; } public void setAddress(String vaddress){ this.address = vaddress; } }
ea335bcfd7276bb0b9a2dce881a1b74c1804ddcd
a4424fdc2a740e47d72f39ec1f6ebdb7b564f274
/src/test/java/com/parallelstack/rsearch/RsearchApiTest.java
bef86e0aef3884df2418e6b36a9239d9a9b231e0
[]
no_license
ParallelStack/rsearch-sdk-java
62460f100ee74e81f5a0741b73055846dc3d9f74
ea2464fbca73b32ec55f8dd99cf708afb634c2c1
refs/heads/master
2021-09-09T01:57:20.224090
2018-03-13T08:19:04
2018-03-13T08:19:04
110,425,362
0
0
null
null
null
null
UTF-8
Java
false
false
11,577
java
/* * ParallelStack RSearch API * REST API Specification for ParallelStack RSearch API * * OpenAPI spec version: 1.3.0 * Contact: [email protected] * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. */ package com.parallelstack.rsearch; import com.parallelstack.ApiException; import com.parallelstack.rsearch.model.AlgorithmFailure; import com.parallelstack.rsearch.model.AlgorithmSimilarDocsQuery; import com.parallelstack.rsearch.model.AlgorithmSuccess; import com.parallelstack.rsearch.model.CreateDocTypeFailure; import com.parallelstack.rsearch.model.CreateDocTypeSuccess; import com.parallelstack.rsearch.model.CreateDocumentFailure; import com.parallelstack.rsearch.model.CreateDocumentSuccess; import com.parallelstack.rsearch.model.CreateIndexFailure; import com.parallelstack.rsearch.model.CreateIndexSuccess; import com.parallelstack.rsearch.model.DeleteDocumentFailure; import com.parallelstack.rsearch.model.DeleteDocumentSuccess; import com.parallelstack.rsearch.model.DeleteIndexFailure; import com.parallelstack.rsearch.model.DeleteIndexSuccess; import com.parallelstack.rsearch.model.Document; import com.parallelstack.rsearch.model.DocumentType; import com.parallelstack.rsearch.model.GetDocTypeFailure; import com.parallelstack.rsearch.model.GetDocTypeSuccess; import com.parallelstack.rsearch.model.GetDocTypesFailure; import com.parallelstack.rsearch.model.GetDocTypesSuccess; import com.parallelstack.rsearch.model.GetDocumentFailure; import com.parallelstack.rsearch.model.GetDocumentSuccess; import com.parallelstack.rsearch.model.GetIndexFailure; import com.parallelstack.rsearch.model.GetIndexSuccess; import com.parallelstack.rsearch.model.GetIndexesFailure; import com.parallelstack.rsearch.model.GetIndexesSuccess; import com.parallelstack.rsearch.model.IndexesSearchQuery; import com.parallelstack.rsearch.model.IndexesSuggestQuery; import com.parallelstack.rsearch.model.SearchFailure; import com.parallelstack.rsearch.model.SearchQuery; import com.parallelstack.rsearch.model.SearchSuccess; import com.parallelstack.rsearch.model.SuggestFailure; import com.parallelstack.rsearch.model.SuggestQuery; import com.parallelstack.rsearch.model.SuggestSuccess; import org.junit.Test; import org.junit.Ignore; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * API tests for RsearchApi */ @Ignore public class RsearchApiTest { private final RsearchApi api = new RsearchApi(); /** * * * Creates &#x60;doc_id&#x60; in &#x60;doc_type_name&#x60; for &#x60;index_name&#x60; * * @throws ApiException * if the Api call fails */ @Test public void addDocumentTest() throws ApiException { String indexName = null; String docTypeName = null; String docId = null; Document documentDetails = null; CreateDocumentSuccess response = api.addDocument(indexName, docTypeName, docId, documentDetails); // TODO: test validations } /** * * * Creates specific &#x60;document_type&#x60; in &#x60;index_name&#x60; with specified parameters. You should define the parameters correctly as per the getting started guide, else getting the right structure might be an issue. * * @throws ApiException * if the Api call fails */ @Test public void addDocumentTypeTest() throws ApiException { String indexName = null; String docTypeName = null; DocumentType docTypeDetails = null; CreateDocTypeSuccess response = api.addDocumentType(indexName, docTypeName, docTypeDetails); // TODO: test validations } /** * * * Creates &#x60;a new index&#x60;. * * @throws ApiException * if the Api call fails */ @Test public void addIndexTest() throws ApiException { String indexName = null; CreateIndexSuccess response = api.addIndex(indexName); // TODO: test validations } /** * * * Deletes &#x60;doc_id&#x60; in &#x60;doc_type_name&#x60; for &#x60;index_name&#x60; * * @throws ApiException * if the Api call fails */ @Test public void deleteDocumentTest() throws ApiException { String indexName = null; String docTypeName = null; String docId = null; DeleteDocumentSuccess response = api.deleteDocument(indexName, docTypeName, docId); // TODO: test validations } /** * * * Deletes &#x60;an index&#x60; {index_name} * * @throws ApiException * if the Api call fails */ @Test public void deleteIndexTest() throws ApiException { String indexName = null; DeleteIndexSuccess response = api.deleteIndex(indexName); // TODO: test validations } /** * * * Gets Suggestions from &#x60;doc_type_name&#x60; in &#x60;index_name&#x60; based on body params. Please ensure you refer the getting started guides, to get the format of the query right. * * @throws ApiException * if the Api call fails */ @Test public void getAdvancedDocTypeSuggestResultsTest() throws ApiException { String indexName = null; String docTypeName = null; SuggestQuery suggest = null; SuggestSuccess response = api.getAdvancedDocTypeSuggestResults(indexName, docTypeName, suggest); // TODO: test validations } /** * * * Gets Suggestions in &#x60;index_name&#x60; limited by the request body fields * * @throws ApiException * if the Api call fails */ @Test public void getAdvancedIndexSuggestResultsTest() throws ApiException { String indexName = null; SuggestQuery search = null; SuggestSuccess response = api.getAdvancedIndexSuggestResults(indexName, search); // TODO: test validations } /** * * * Advanced Search across multiple indexes specified as a part of the search criteria. Please ensure you refer the getting started guides, to get the format of the query right. * * @throws ApiException * if the Api call fails */ @Test public void getAdvancedMultiIndexSearchResultsTest() throws ApiException { IndexesSearchQuery search = null; SearchSuccess response = api.getAdvancedMultiIndexSearchResults(search); // TODO: test validations } /** * * * Gets Suggestions across multiple indexes. Please ensure you refer the getting started guides, to get the format of the query right. * * @throws ApiException * if the Api call fails */ @Test public void getAdvancedMultiIndexSuggestResultsTest() throws ApiException { IndexesSuggestQuery suggest = null; SuggestSuccess response = api.getAdvancedMultiIndexSuggestResults(suggest); // TODO: test validations } /** * * * Advanced Search which gets all documents in &#x60;index_name&#x60; for provided search criteria. Please ensure you refer the getting started guides, to get the format of the query right. * * @throws ApiException * if the Api call fails */ @Test public void getAdvancedSearchResultsTest() throws ApiException { String indexName = null; String docTypeName = null; SearchQuery search = null; SearchSuccess response = api.getAdvancedSearchResults(indexName, docTypeName, search); // TODO: test validations } /** * * * Gets &#x60;All document_types&#x60; present in &#x60;index_name&#x60; * * @throws ApiException * if the Api call fails */ @Test public void getAllDocumentTypesTest() throws ApiException { String indexName = null; GetDocTypesSuccess response = api.getAllDocumentTypes(indexName); // TODO: test validations } /** * * * Fetches &#x60;All indexes&#x60; that the user has. Not recommended to be used in production code, as there isn&#39;t that big a Use case for listing all indexes! * * @throws ApiException * if the Api call fails */ @Test public void getAllIndexesTest() throws ApiException { GetIndexesSuccess response = api.getAllIndexes(); // TODO: test validations } /** * * * Basic Search which gets all documents in &#x60;index_name&#x60; for provided search criteria * * @throws ApiException * if the Api call fails */ @Test public void getBasicSearchResultsTest() throws ApiException { String indexName = null; String q = null; SearchSuccess response = api.getBasicSearchResults(indexName, q); // TODO: test validations } /** * * * Gets Suggestions from &#x60;doc_type_name&#x60; in &#x60;index_name&#x60;. Please ensure you refer the getting started guides, to get the format of the query right. * * @throws ApiException * if the Api call fails */ @Test public void getDocTypeSuggestResultsTest() throws ApiException { String indexName = null; String docTypeName = null; String q = null; SuggestSuccess response = api.getDocTypeSuggestResults(indexName, docTypeName, q); // TODO: test validations } /** * * * Fetches the document referenced by &#x60;doc_id&#x60; in &#x60;doc_type_name&#x60; for &#x60;index_name&#x60; * * @throws ApiException * if the Api call fails */ @Test public void getDocumentTest() throws ApiException { String indexName = null; String docTypeName = null; String docId = null; GetDocumentSuccess response = api.getDocument(indexName, docTypeName, docId); // TODO: test validations } /** * * * Checks whether &#x60;document_type&#x60; in &#x60;index_name&#x60; exists * * @throws ApiException * if the Api call fails */ @Test public void getDocumentTypeTest() throws ApiException { String indexName = null; String docTypeName = null; GetDocTypeSuccess response = api.getDocumentType(indexName, docTypeName); // TODO: test validations } /** * * * Checks whether &#x60;a particular index&#x60; {index_name} exists * * @throws ApiException * if the Api call fails */ @Test public void getIndexTest() throws ApiException { String indexName = null; GetIndexSuccess response = api.getIndex(indexName); // TODO: test validations } /** * * * Returns Similar Documents based on the provided document(s) details. Please ensure you refer the getting started guides, to get the format of the query right. * * @throws ApiException * if the Api call fails */ @Test public void getSimilarDocsResultsTest() throws ApiException { AlgorithmSimilarDocsQuery algorithm = null; AlgorithmSuccess response = api.getSimilarDocsResults(algorithm); // TODO: test validations } }
84087f9510498a3f076bd282b1a04bc09c121221
19ea7b8fa26c4f0762b23a2b9b64d9c30c081342
/src/test/java/pruebasTest.java
75114d658acd2fff62f91454a99909973829cd43
[]
no_license
sachone/travisProyect
043f9be43fab4012e13c19693048d415b949df13
96396723bfc2c424a5c45c04e8f35ce0f31b6574
refs/heads/master
2021-01-25T06:06:13.356793
2015-01-19T14:16:19
2015-01-19T14:16:19
29,356,036
0
0
null
null
null
null
UTF-8
Java
false
false
1,196
java
/* * 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. */ import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; /** * * @author al037542 */ public class pruebasTest { public pruebasTest() { } @BeforeClass public static void setUpClass() { } @AfterClass public static void tearDownClass() { } @Before public void setUp() { } @After public void tearDown() { } /** * Test of multiplicacion method, of class pruebas. */ @Test public void testMultiplicacion() { System.out.println("multiplicacion"); Integer numero1 = 5; Integer numero2 = 5; pruebas instance = new pruebas(); Integer expResult = 25; Integer result = instance.multiplicacion(numero1, numero2); assertEquals(expResult, result); // TODO review the generated test code and remove the default call to fail. } }
[ "al037542@s09-pc16" ]
al037542@s09-pc16
503bb4c1aad539ff17658400d75f6ff899a234ac
42503a9dc7f8f8eaf7324514105395bebf0a70cb
/b-common/src/main/java/com/balabala/utils/JwtUtils.java
a28d92e16946f484d6b60ee9b35d3768591d4a77
[]
no_license
XiaoLingShuShu/BALABALA
45d003efed8775128f29fbdd38cf17d72f4d3441
4bdeaa414b1714f85066ede3ed9d49ceb492596d
refs/heads/master
2022-12-02T02:11:50.636950
2022-11-17T02:30:56
2022-11-17T02:30:56
242,712,337
6
0
null
2022-11-17T02:30:57
2020-02-24T10:55:47
Java
UTF-8
Java
false
false
3,484
java
package com.balabala.utils; import com.balabala.auth.Payload; import io.jsonwebtoken.Claims; import io.jsonwebtoken.Jws; import io.jsonwebtoken.Jwts; import io.jsonwebtoken.SignatureAlgorithm; import org.joda.time.DateTime; import java.security.PrivateKey; import java.security.PublicKey; import java.util.Base64; import java.util.UUID; /** * @ProjectName: BALABALA * @Package: com.balabala.utils * @ClassName: JwtUtils * @Author: Administrator * @Description: ${description} * @Date: 2020/2/7 16:14 * @Version: 1.0 */ public class JwtUtils { private static final String JWT_PAYLOAD_USER_KEY = "user"; /** * 私钥加密token * * @param userInfo 载荷中的数据 * @param privateKey 私钥 * @param expire 过期时间,单位分钟 * @return JWT */ public static String generateTokenExpireInMinutes(Object userInfo, PrivateKey privateKey, int expire) { return Jwts.builder() .claim(JWT_PAYLOAD_USER_KEY, JsonUtils.toString(userInfo)) .setId(createJTI()) .setExpiration(DateTime.now().plusMinutes(expire).toDate()) .signWith(privateKey, SignatureAlgorithm.RS256) .compact(); } /** * 私钥加密token * * @param userInfo 载荷中的数据 * @param privateKey 私钥 * @param expire 过期时间,单位秒 * @return JWT */ public static String generateTokenExpireInSeconds(Object userInfo, PrivateKey privateKey, int expire) { return Jwts.builder() .claim(JWT_PAYLOAD_USER_KEY, JsonUtils.toString(userInfo)) .setId(createJTI()) .setExpiration(DateTime.now().plusSeconds(expire).toDate()) .signWith(privateKey, SignatureAlgorithm.RS256) .compact(); } /** * 公钥解析token * * @param token 用户请求中的token * @param publicKey 公钥 * @return Jws<Claims> */ private static Jws<Claims> parserToken(String token, PublicKey publicKey) { return Jwts.parser().setSigningKey(publicKey).parseClaimsJws(token); } private static String createJTI() { return new String(Base64.getEncoder().encode(UUID.randomUUID().toString().getBytes())); } /** * 获取token中的用户信息 * * @param token 用户请求中的令牌 * @param publicKey 公钥 * @return 用户信息 */ public static <T> Payload<T> getInfoFromToken(String token, PublicKey publicKey, Class<T> userType) { Jws<Claims> claimsJws = parserToken(token, publicKey); Claims body = claimsJws.getBody(); Payload<T> claims = new Payload<>(); claims.setId(body.getId()); claims.setUserInfo(JsonUtils.toBean(body.get(JWT_PAYLOAD_USER_KEY).toString(), userType)); claims.setExpiration(body.getExpiration()); return claims; } /** * 获取token中的载荷信息 * * @param token 用户请求中的令牌 * @param publicKey 公钥 * @return 用户信息 */ public static <T> Payload<T> getInfoFromToken(String token, PublicKey publicKey) { Jws<Claims> claimsJws = parserToken(token, publicKey); Claims body = claimsJws.getBody(); Payload<T> claims = new Payload<>(); claims.setId(body.getId()); claims.setExpiration(body.getExpiration()); return claims; } }
[ "cxl1207" ]
cxl1207
d76e26c82f9172ab68f6a1f6ca169d3b759f4bd9
e4012103ed80df46e2ffa9219d837816842d91c3
/build/tmp/expandedArchives/forge-1.15.2-31.2.21_mapped_snapshot_20200620-1.15.1-sources.jar_d3963c278627a7c46a4708e9daeaa27e/net/minecraft/item/ItemStack.java
567633d61ec7394e11a95bc9213645ac57b0aa88
[]
no_license
TheCowKingmoo/ShaftDriller
befe3a8721b4c150a93063fe03d3d3d995881a83
2cf25cddd41af33c2b73877099f489d3db02ae1a
refs/heads/master
2022-11-16T08:54:46.250506
2020-07-16T23:51:39
2020-07-16T23:51:39
null
0
0
null
null
null
null
UTF-8
Java
false
false
39,429
java
package net.minecraft.item; import com.google.common.collect.HashMultimap; import com.google.common.collect.Lists; import com.google.common.collect.Multimap; import com.google.gson.JsonParseException; import com.mojang.brigadier.StringReader; import com.mojang.brigadier.exceptions.CommandSyntaxException; import java.text.DecimalFormat; import java.text.DecimalFormatSymbols; import java.util.Collection; import java.util.List; import java.util.Locale; import java.util.Objects; import java.util.Random; import java.util.Map.Entry; import java.util.function.Consumer; import java.util.function.Predicate; import java.util.stream.Collectors; import javax.annotation.Nullable; import net.minecraft.advancements.CriteriaTriggers; import net.minecraft.block.Block; import net.minecraft.block.BlockState; import net.minecraft.client.util.ITooltipFlag; import net.minecraft.command.arguments.BlockPredicateArgument; import net.minecraft.command.arguments.BlockStateParser; import net.minecraft.enchantment.Enchantment; import net.minecraft.enchantment.EnchantmentHelper; import net.minecraft.enchantment.Enchantments; import net.minecraft.enchantment.UnbreakingEnchantment; import net.minecraft.entity.CreatureAttribute; import net.minecraft.entity.Entity; import net.minecraft.entity.LivingEntity; import net.minecraft.entity.SharedMonsterAttributes; import net.minecraft.entity.ai.attributes.AttributeModifier; import net.minecraft.entity.item.ItemFrameEntity; import net.minecraft.entity.player.PlayerEntity; import net.minecraft.entity.player.ServerPlayerEntity; import net.minecraft.inventory.EquipmentSlotType; import net.minecraft.nbt.CompoundNBT; import net.minecraft.nbt.INBT; import net.minecraft.nbt.ListNBT; import net.minecraft.stats.Stats; import net.minecraft.tags.BlockTags; import net.minecraft.tags.NetworkTagManager; import net.minecraft.tags.Tag; import net.minecraft.util.ActionResult; import net.minecraft.util.ActionResultType; import net.minecraft.util.CachedBlockInfo; import net.minecraft.util.Hand; import net.minecraft.util.IItemProvider; import net.minecraft.util.ResourceLocation; import net.minecraft.util.SoundEvent; import net.minecraft.util.math.BlockPos; import net.minecraft.util.registry.Registry; import net.minecraft.util.text.ITextComponent; import net.minecraft.util.text.StringTextComponent; import net.minecraft.util.text.Style; import net.minecraft.util.text.TextComponentUtils; import net.minecraft.util.text.TextFormatting; import net.minecraft.util.text.TranslationTextComponent; import net.minecraft.util.text.event.HoverEvent; import net.minecraft.world.World; import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.api.distmarker.OnlyIn; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; public final class ItemStack extends net.minecraftforge.common.capabilities.CapabilityProvider<ItemStack> implements net.minecraftforge.common.extensions.IForgeItemStack { private static final Logger LOGGER = LogManager.getLogger(); public static final ItemStack EMPTY = new ItemStack((Item)null); public static final DecimalFormat DECIMALFORMAT = createAttributeModifierDecimalFormat(); private int count; private int animationsToGo; @Deprecated private final Item item; private CompoundNBT tag; private boolean isEmpty; private ItemFrameEntity itemFrame; private CachedBlockInfo canDestroyCacheBlock; private boolean canDestroyCacheResult; private CachedBlockInfo canPlaceOnCacheBlock; private boolean canPlaceOnCacheResult; private net.minecraftforge.registries.IRegistryDelegate<Item> delegate; private CompoundNBT capNBT; private static DecimalFormat createAttributeModifierDecimalFormat() { DecimalFormat decimalformat = new DecimalFormat("#.##"); decimalformat.setDecimalFormatSymbols(DecimalFormatSymbols.getInstance(Locale.ROOT)); return decimalformat; } public ItemStack(IItemProvider itemIn) { this(itemIn, 1); } public ItemStack(IItemProvider itemIn, int count) { this(itemIn, count, null); } public ItemStack(IItemProvider itemIn, int count, @Nullable CompoundNBT capNBT) { super(ItemStack.class); this.capNBT = capNBT; this.item = itemIn == null ? null : itemIn.asItem(); this.count = count; if (this.item != null && this.item.isDamageable()) { this.setDamage(this.getDamage()); } this.updateEmptyState(); this.forgeInit(); } private void updateEmptyState() { this.isEmpty = false; this.isEmpty = this.isEmpty(); } private ItemStack(CompoundNBT compound) { super(ItemStack.class); this.capNBT = compound.contains("ForgeCaps") ? compound.getCompound("ForgeCaps") : null; this.item = Registry.ITEM.getOrDefault(new ResourceLocation(compound.getString("id"))); this.count = compound.getByte("Count"); if (compound.contains("tag", 10)) { this.tag = compound.getCompound("tag"); this.getItem().updateItemStackNBT(compound); } if (this.getItem().isDamageable()) { this.setDamage(this.getDamage()); } this.updateEmptyState(); this.forgeInit(); } public static ItemStack read(CompoundNBT compound) { try { return new ItemStack(compound); } catch (RuntimeException runtimeexception) { LOGGER.debug("Tried to load invalid item: {}", compound, runtimeexception); return EMPTY; } } public boolean isEmpty() { if (this == EMPTY) { return true; } else if (this.getItemRaw() != null && this.getItemRaw() != Items.AIR) { return this.count <= 0; } else { return true; } } /** * Splits off a stack of the given amount of this stack and reduces this stack by the amount. */ public ItemStack split(int amount) { int i = Math.min(amount, this.count); ItemStack itemstack = this.copy(); itemstack.setCount(i); this.shrink(i); return itemstack; } /** * Returns the object corresponding to the stack. */ public Item getItem() { return this.isEmpty || this.delegate == null ? Items.AIR : this.delegate.get(); } public ActionResultType onItemUse(ItemUseContext context) { if (!context.world.isRemote) return net.minecraftforge.common.ForgeHooks.onPlaceItemIntoWorld(context); return onItemUse(context, (c) -> getItem().onItemUse(context)); } public ActionResultType onItemUseFirst(ItemUseContext context) { return onItemUse(context, (c) -> getItem().onItemUseFirst(this, context)); } private ActionResultType onItemUse(ItemUseContext context, java.util.function.Function<ItemUseContext, ActionResultType> callback) { PlayerEntity playerentity = context.getPlayer(); BlockPos blockpos = context.getPos(); CachedBlockInfo cachedblockinfo = new CachedBlockInfo(context.getWorld(), blockpos, false); if (playerentity != null && !playerentity.abilities.allowEdit && !this.canPlaceOn(context.getWorld().getTags(), cachedblockinfo)) { return ActionResultType.PASS; } else { Item item = this.getItem(); ActionResultType actionresulttype = callback.apply(context); if (playerentity != null && actionresulttype == ActionResultType.SUCCESS) { playerentity.addStat(Stats.ITEM_USED.get(item)); } return actionresulttype; } } public float getDestroySpeed(BlockState blockIn) { return this.getItem().getDestroySpeed(this, blockIn); } /** * Called whenr the item stack is equipped and right clicked. Replaces the item stack with the return value. */ public ActionResult<ItemStack> useItemRightClick(World worldIn, PlayerEntity playerIn, Hand hand) { return this.getItem().onItemRightClick(worldIn, playerIn, hand); } /** * Called when the item in use count reach 0, e.g. item food eaten. Return the new ItemStack. Args : world, entity */ public ItemStack onItemUseFinish(World worldIn, LivingEntity entityLiving) { return this.getItem().onItemUseFinish(this, worldIn, entityLiving); } /** * Write the stack fields to a NBT object. Return the new NBT object. */ public CompoundNBT write(CompoundNBT nbt) { ResourceLocation resourcelocation = Registry.ITEM.getKey(this.getItem()); nbt.putString("id", resourcelocation == null ? "minecraft:air" : resourcelocation.toString()); nbt.putByte("Count", (byte)this.count); if (this.tag != null) { nbt.put("tag", this.tag.copy()); } CompoundNBT cnbt = this.serializeCaps(); if (cnbt != null && !cnbt.isEmpty()) { nbt.put("ForgeCaps", cnbt); } return nbt; } /** * Returns maximum size of the stack. */ public int getMaxStackSize() { return this.getItem().getItemStackLimit(this); } /** * Returns true if the ItemStack can hold 2 or more units of the item. */ public boolean isStackable() { return this.getMaxStackSize() > 1 && (!this.isDamageable() || !this.isDamaged()); } /** * true if this itemStack is damageable */ public boolean isDamageable() { if (!this.isEmpty && this.getItem().getMaxDamage(this) > 0) { CompoundNBT compoundnbt = this.getTag(); return compoundnbt == null || !compoundnbt.getBoolean("Unbreakable"); } else { return false; } } /** * returns true when a damageable item is damaged */ public boolean isDamaged() { return this.isDamageable() && getItem().isDamaged(this); } public int getDamage() { return this.getItem().getDamage(this); } public void setDamage(int damage) { this.getItem().setDamage(this, damage); } /** * Returns the max damage an item in the stack can take. */ public int getMaxDamage() { return this.getItem().getMaxDamage(this); } /** * Attempts to damage the ItemStack with par1 amount of damage, If the ItemStack has the Unbreaking enchantment there * is a chance for each point of damage to be negated. Returns true if it takes more damage than getMaxDamage(). * Returns false otherwise or if the ItemStack can't be damaged or if all points of damage are negated. */ public boolean attemptDamageItem(int amount, Random rand, @Nullable ServerPlayerEntity damager) { if (!this.isDamageable()) { return false; } else { if (amount > 0) { int i = EnchantmentHelper.getEnchantmentLevel(Enchantments.UNBREAKING, this); int j = 0; for(int k = 0; i > 0 && k < amount; ++k) { if (UnbreakingEnchantment.negateDamage(this, i, rand)) { ++j; } } amount -= j; if (amount <= 0) { return false; } } if (damager != null && amount != 0) { CriteriaTriggers.ITEM_DURABILITY_CHANGED.trigger(damager, this, this.getDamage() + amount); } int l = this.getDamage() + amount; this.setDamage(l); return l >= this.getMaxDamage(); } } public <T extends LivingEntity> void damageItem(int amount, T entityIn, Consumer<T> onBroken) { if (!entityIn.world.isRemote && (!(entityIn instanceof PlayerEntity) || !((PlayerEntity)entityIn).abilities.isCreativeMode)) { if (this.isDamageable()) { amount = this.getItem().damageItem(this, amount, entityIn, onBroken); if (this.attemptDamageItem(amount, entityIn.getRNG(), entityIn instanceof ServerPlayerEntity ? (ServerPlayerEntity)entityIn : null)) { onBroken.accept(entityIn); Item item = this.getItem(); this.shrink(1); if (entityIn instanceof PlayerEntity) { ((PlayerEntity)entityIn).addStat(Stats.ITEM_BROKEN.get(item)); } this.setDamage(0); } } } } /** * Calls the delegated method to the Item to damage the incoming Entity, and if necessary, triggers a stats increase. */ public void hitEntity(LivingEntity entityIn, PlayerEntity playerIn) { Item item = this.getItem(); if (item.hitEntity(this, entityIn, playerIn)) { playerIn.addStat(Stats.ITEM_USED.get(item)); } } /** * Called when a Block is destroyed using this ItemStack */ public void onBlockDestroyed(World worldIn, BlockState blockIn, BlockPos pos, PlayerEntity playerIn) { Item item = this.getItem(); if (item.onBlockDestroyed(this, worldIn, blockIn, pos, playerIn)) { playerIn.addStat(Stats.ITEM_USED.get(item)); } } /** * Check whether the given Block can be harvested using this ItemStack. */ public boolean canHarvestBlock(BlockState blockIn) { return this.getItem().canHarvestBlock(this, blockIn); } public boolean interactWithEntity(PlayerEntity playerIn, LivingEntity entityIn, Hand hand) { return this.getItem().itemInteractionForEntity(this, playerIn, entityIn, hand); } /** * Returns a new stack with the same properties. */ public ItemStack copy() { if (this.isEmpty()) { return EMPTY; } else { ItemStack itemstack = new ItemStack(this.getItem(), this.count, this.serializeCaps()); itemstack.setAnimationsToGo(this.getAnimationsToGo()); if (this.tag != null) { itemstack.tag = this.tag.copy(); } return itemstack; } } public static boolean areItemStackTagsEqual(ItemStack stackA, ItemStack stackB) { if (stackA.isEmpty() && stackB.isEmpty()) { return true; } else if (!stackA.isEmpty() && !stackB.isEmpty()) { if (stackA.tag == null && stackB.tag != null) { return false; } else { return (stackA.tag == null || stackA.tag.equals(stackB.tag)) && stackA.areCapsCompatible(stackB); } } else { return false; } } /** * compares ItemStack argument1 with ItemStack argument2; returns true if both ItemStacks are equal */ public static boolean areItemStacksEqual(ItemStack stackA, ItemStack stackB) { if (stackA.isEmpty() && stackB.isEmpty()) { return true; } else { return !stackA.isEmpty() && !stackB.isEmpty() ? stackA.isItemStackEqual(stackB) : false; } } /** * compares ItemStack argument to the instance ItemStack; returns true if both ItemStacks are equal */ private boolean isItemStackEqual(ItemStack other) { if (this.count != other.count) { return false; } else if (this.getItem() != other.getItem()) { return false; } else if (this.tag == null && other.tag != null) { return false; } else { return (this.tag == null || this.tag.equals(other.tag)) && this.areCapsCompatible(other); } } /** * Compares Item and damage value of the two stacks */ public static boolean areItemsEqual(ItemStack stackA, ItemStack stackB) { if (stackA == stackB) { return true; } else { return !stackA.isEmpty() && !stackB.isEmpty() ? stackA.isItemEqual(stackB) : false; } } public static boolean areItemsEqualIgnoreDurability(ItemStack stackA, ItemStack stackB) { if (stackA == stackB) { return true; } else { return !stackA.isEmpty() && !stackB.isEmpty() ? stackA.isItemEqualIgnoreDurability(stackB) : false; } } /** * compares ItemStack argument to the instance ItemStack; returns true if the Items contained in both ItemStacks are * equal */ public boolean isItemEqual(ItemStack other) { return !other.isEmpty() && this.getItem() == other.getItem(); } public boolean isItemEqualIgnoreDurability(ItemStack stack) { if (!this.isDamageable()) { return this.isItemEqual(stack); } else { return !stack.isEmpty() && this.getItem() == stack.getItem(); } } public String getTranslationKey() { return this.getItem().getTranslationKey(this); } public String toString() { return this.count + " " + this.getItem(); } /** * Called each tick as long the ItemStack in on player inventory. Used to progress the pickup animation and update * maps. */ public void inventoryTick(World worldIn, Entity entityIn, int inventorySlot, boolean isCurrentItem) { if (this.animationsToGo > 0) { --this.animationsToGo; } if (this.getItem() != null) { this.getItem().inventoryTick(this, worldIn, entityIn, inventorySlot, isCurrentItem); } } public void onCrafting(World worldIn, PlayerEntity playerIn, int amount) { playerIn.addStat(Stats.ITEM_CRAFTED.get(this.getItem()), amount); this.getItem().onCreated(this, worldIn, playerIn); } public int getUseDuration() { return this.getItem().getUseDuration(this); } public UseAction getUseAction() { return this.getItem().getUseAction(this); } /** * Called when the player releases the use item button. */ public void onPlayerStoppedUsing(World worldIn, LivingEntity entityLiving, int timeLeft) { this.getItem().onPlayerStoppedUsing(this, worldIn, entityLiving, timeLeft); } public boolean isCrossbowStack() { return this.getItem().isCrossbow(this); } /** * Returns true if the ItemStack has an NBTTagCompound. Currently used to store enchantments. */ public boolean hasTag() { return !this.isEmpty && this.tag != null && !this.tag.isEmpty(); } @Nullable public CompoundNBT getTag() { return this.tag; } public CompoundNBT getOrCreateTag() { if (this.tag == null) { this.setTag(new CompoundNBT()); } return this.tag; } public CompoundNBT getOrCreateChildTag(String key) { if (this.tag != null && this.tag.contains(key, 10)) { return this.tag.getCompound(key); } else { CompoundNBT compoundnbt = new CompoundNBT(); this.setTagInfo(key, compoundnbt); return compoundnbt; } } /** * Get an NBTTagCompound from this stack's NBT data. */ @Nullable public CompoundNBT getChildTag(String key) { return this.tag != null && this.tag.contains(key, 10) ? this.tag.getCompound(key) : null; } public void removeChildTag(String p_196083_1_) { if (this.tag != null && this.tag.contains(p_196083_1_)) { this.tag.remove(p_196083_1_); if (this.tag.isEmpty()) { this.tag = null; } } } public ListNBT getEnchantmentTagList() { return this.tag != null ? this.tag.getList("Enchantments", 10) : new ListNBT(); } /** * Assigns a NBTTagCompound to the ItemStack, minecraft validates that only non-stackable items can have it. */ public void setTag(@Nullable CompoundNBT nbt) { this.tag = nbt; if (this.getItem().isDamageable()) { this.setDamage(this.getDamage()); } } public ITextComponent getDisplayName() { CompoundNBT compoundnbt = this.getChildTag("display"); if (compoundnbt != null && compoundnbt.contains("Name", 8)) { try { ITextComponent itextcomponent = ITextComponent.Serializer.fromJson(compoundnbt.getString("Name")); if (itextcomponent != null) { return itextcomponent; } compoundnbt.remove("Name"); } catch (JsonParseException var3) { compoundnbt.remove("Name"); } } return this.getItem().getDisplayName(this); } public ItemStack setDisplayName(@Nullable ITextComponent name) { CompoundNBT compoundnbt = this.getOrCreateChildTag("display"); if (name != null) { compoundnbt.putString("Name", ITextComponent.Serializer.toJson(name)); } else { compoundnbt.remove("Name"); } return this; } /** * Clear any custom name set for this ItemStack */ public void clearCustomName() { CompoundNBT compoundnbt = this.getChildTag("display"); if (compoundnbt != null) { compoundnbt.remove("Name"); if (compoundnbt.isEmpty()) { this.removeChildTag("display"); } } if (this.tag != null && this.tag.isEmpty()) { this.tag = null; } } /** * Returns true if the itemstack has a display name */ public boolean hasDisplayName() { CompoundNBT compoundnbt = this.getChildTag("display"); return compoundnbt != null && compoundnbt.contains("Name", 8); } /** * Return a list of strings containing information about the item */ @OnlyIn(Dist.CLIENT) public List<ITextComponent> getTooltip(@Nullable PlayerEntity playerIn, ITooltipFlag advanced) { List<ITextComponent> list = Lists.newArrayList(); ITextComponent itextcomponent = (new StringTextComponent("")).appendSibling(this.getDisplayName()).applyTextStyle(this.getRarity().color); if (this.hasDisplayName()) { itextcomponent.applyTextStyle(TextFormatting.ITALIC); } list.add(itextcomponent); if (!advanced.isAdvanced() && !this.hasDisplayName() && this.getItem() == Items.FILLED_MAP) { list.add((new StringTextComponent("#" + FilledMapItem.getMapId(this))).applyTextStyle(TextFormatting.GRAY)); } int i = 0; if (this.hasTag() && this.tag.contains("HideFlags", 99)) { i = this.tag.getInt("HideFlags"); } if ((i & 32) == 0) { this.getItem().addInformation(this, playerIn == null ? null : playerIn.world, list, advanced); } if (this.hasTag()) { if ((i & 1) == 0) { addEnchantmentTooltips(list, this.getEnchantmentTagList()); } if (this.tag.contains("display", 10)) { CompoundNBT compoundnbt = this.tag.getCompound("display"); if (compoundnbt.contains("color", 3)) { if (advanced.isAdvanced()) { list.add((new TranslationTextComponent("item.color", String.format("#%06X", compoundnbt.getInt("color")))).applyTextStyle(TextFormatting.GRAY)); } else { list.add((new TranslationTextComponent("item.dyed")).applyTextStyles(new TextFormatting[]{TextFormatting.GRAY, TextFormatting.ITALIC})); } } if (compoundnbt.getTagId("Lore") == 9) { ListNBT listnbt = compoundnbt.getList("Lore", 8); for(int j = 0; j < listnbt.size(); ++j) { String s = listnbt.getString(j); try { ITextComponent itextcomponent1 = ITextComponent.Serializer.fromJson(s); if (itextcomponent1 != null) { list.add(TextComponentUtils.mergeStyles(itextcomponent1, (new Style()).setColor(TextFormatting.DARK_PURPLE).setItalic(true))); } } catch (JsonParseException var19) { compoundnbt.remove("Lore"); } } } } } for(EquipmentSlotType equipmentslottype : EquipmentSlotType.values()) { Multimap<String, AttributeModifier> multimap = this.getAttributeModifiers(equipmentslottype); if (!multimap.isEmpty() && (i & 2) == 0) { list.add(new StringTextComponent("")); list.add((new TranslationTextComponent("item.modifiers." + equipmentslottype.getName())).applyTextStyle(TextFormatting.GRAY)); for(Entry<String, AttributeModifier> entry : multimap.entries()) { AttributeModifier attributemodifier = entry.getValue(); double d0 = attributemodifier.getAmount(); boolean flag = false; if (playerIn != null) { if (attributemodifier.getID() == Item.ATTACK_DAMAGE_MODIFIER) { d0 = d0 + playerIn.getAttribute(SharedMonsterAttributes.ATTACK_DAMAGE).getBaseValue(); d0 = d0 + (double)EnchantmentHelper.getModifierForCreature(this, CreatureAttribute.UNDEFINED); flag = true; } else if (attributemodifier.getID() == Item.ATTACK_SPEED_MODIFIER) { d0 += playerIn.getAttribute(SharedMonsterAttributes.ATTACK_SPEED).getBaseValue(); flag = true; } } double d1; if (attributemodifier.getOperation() != AttributeModifier.Operation.MULTIPLY_BASE && attributemodifier.getOperation() != AttributeModifier.Operation.MULTIPLY_TOTAL) { d1 = d0; } else { d1 = d0 * 100.0D; } if (flag) { list.add((new StringTextComponent(" ")).appendSibling(new TranslationTextComponent("attribute.modifier.equals." + attributemodifier.getOperation().getId(), DECIMALFORMAT.format(d1), new TranslationTextComponent("attribute.name." + (String)entry.getKey()))).applyTextStyle(TextFormatting.DARK_GREEN)); } else if (d0 > 0.0D) { list.add((new TranslationTextComponent("attribute.modifier.plus." + attributemodifier.getOperation().getId(), DECIMALFORMAT.format(d1), new TranslationTextComponent("attribute.name." + (String)entry.getKey()))).applyTextStyle(TextFormatting.BLUE)); } else if (d0 < 0.0D) { d1 = d1 * -1.0D; list.add((new TranslationTextComponent("attribute.modifier.take." + attributemodifier.getOperation().getId(), DECIMALFORMAT.format(d1), new TranslationTextComponent("attribute.name." + (String)entry.getKey()))).applyTextStyle(TextFormatting.RED)); } } } } if (this.hasTag() && this.getTag().getBoolean("Unbreakable") && (i & 4) == 0) { list.add((new TranslationTextComponent("item.unbreakable")).applyTextStyle(TextFormatting.BLUE)); } if (this.hasTag() && this.tag.contains("CanDestroy", 9) && (i & 8) == 0) { ListNBT listnbt1 = this.tag.getList("CanDestroy", 8); if (!listnbt1.isEmpty()) { list.add(new StringTextComponent("")); list.add((new TranslationTextComponent("item.canBreak")).applyTextStyle(TextFormatting.GRAY)); for(int k = 0; k < listnbt1.size(); ++k) { list.addAll(getPlacementTooltip(listnbt1.getString(k))); } } } if (this.hasTag() && this.tag.contains("CanPlaceOn", 9) && (i & 16) == 0) { ListNBT listnbt2 = this.tag.getList("CanPlaceOn", 8); if (!listnbt2.isEmpty()) { list.add(new StringTextComponent("")); list.add((new TranslationTextComponent("item.canPlace")).applyTextStyle(TextFormatting.GRAY)); for(int l = 0; l < listnbt2.size(); ++l) { list.addAll(getPlacementTooltip(listnbt2.getString(l))); } } } if (advanced.isAdvanced()) { if (this.isDamaged()) { list.add(new TranslationTextComponent("item.durability", this.getMaxDamage() - this.getDamage(), this.getMaxDamage())); } list.add((new StringTextComponent(Registry.ITEM.getKey(this.getItem()).toString())).applyTextStyle(TextFormatting.DARK_GRAY)); if (this.hasTag()) { list.add((new TranslationTextComponent("item.nbt_tags", this.getTag().keySet().size())).applyTextStyle(TextFormatting.DARK_GRAY)); } } net.minecraftforge.event.ForgeEventFactory.onItemTooltip(this, playerIn, list, advanced); return list; } @OnlyIn(Dist.CLIENT) public static void addEnchantmentTooltips(List<ITextComponent> p_222120_0_, ListNBT p_222120_1_) { for(int i = 0; i < p_222120_1_.size(); ++i) { CompoundNBT compoundnbt = p_222120_1_.getCompound(i); Registry.ENCHANTMENT.getValue(ResourceLocation.tryCreate(compoundnbt.getString("id"))).ifPresent((p_222123_2_) -> { p_222120_0_.add(p_222123_2_.getDisplayName(compoundnbt.getInt("lvl"))); }); } } @OnlyIn(Dist.CLIENT) private static Collection<ITextComponent> getPlacementTooltip(String stateString) { try { BlockStateParser blockstateparser = (new BlockStateParser(new StringReader(stateString), true)).parse(true); BlockState blockstate = blockstateparser.getState(); ResourceLocation resourcelocation = blockstateparser.getTag(); boolean flag = blockstate != null; boolean flag1 = resourcelocation != null; if (flag || flag1) { if (flag) { return Lists.newArrayList(blockstate.getBlock().getNameTextComponent().applyTextStyle(TextFormatting.DARK_GRAY)); } Tag<Block> tag = BlockTags.getCollection().get(resourcelocation); if (tag != null) { Collection<Block> collection = tag.getAllElements(); if (!collection.isEmpty()) { return collection.stream().map(Block::getNameTextComponent).map((p_222119_0_) -> { return p_222119_0_.applyTextStyle(TextFormatting.DARK_GRAY); }).collect(Collectors.toList()); } } } } catch (CommandSyntaxException var8) { ; } return Lists.newArrayList((new StringTextComponent("missingno")).applyTextStyle(TextFormatting.DARK_GRAY)); } public boolean hasEffect() { return this.getItem().hasEffect(this); } public Rarity getRarity() { return this.getItem().getRarity(this); } /** * True if it is a tool and has no enchantments to begin with */ public boolean isEnchantable() { if (!this.getItem().isEnchantable(this)) { return false; } else { return !this.isEnchanted(); } } /** * Adds an enchantment with a desired level on the ItemStack. */ public void addEnchantment(Enchantment ench, int level) { this.getOrCreateTag(); if (!this.tag.contains("Enchantments", 9)) { this.tag.put("Enchantments", new ListNBT()); } ListNBT listnbt = this.tag.getList("Enchantments", 10); CompoundNBT compoundnbt = new CompoundNBT(); compoundnbt.putString("id", String.valueOf((Object)Registry.ENCHANTMENT.getKey(ench))); compoundnbt.putShort("lvl", (short)((byte)level)); listnbt.add(compoundnbt); } /** * True if the item has enchantment data */ public boolean isEnchanted() { if (this.tag != null && this.tag.contains("Enchantments", 9)) { return !this.tag.getList("Enchantments", 10).isEmpty(); } else { return false; } } public void setTagInfo(String key, INBT value) { this.getOrCreateTag().put(key, value); } /** * Return whether this stack is on an item frame. */ public boolean isOnItemFrame() { return this.itemFrame != null; } /** * Set the item frame this stack is on. */ public void setItemFrame(@Nullable ItemFrameEntity frame) { this.itemFrame = frame; } /** * Return the item frame this stack is on. Returns null if not on an item frame. */ @Nullable public ItemFrameEntity getItemFrame() { return this.isEmpty ? null : this.itemFrame; } /** * Get this stack's repair cost, or 0 if no repair cost is defined. */ public int getRepairCost() { return this.hasTag() && this.tag.contains("RepairCost", 3) ? this.tag.getInt("RepairCost") : 0; } /** * Set this stack's repair cost. */ public void setRepairCost(int cost) { this.getOrCreateTag().putInt("RepairCost", cost); } /** * Gets the attribute modifiers for this ItemStack. * Will check for an NBT tag list containing modifiers for the stack. */ public Multimap<String, AttributeModifier> getAttributeModifiers(EquipmentSlotType equipmentSlot) { Multimap<String, AttributeModifier> multimap; if (this.hasTag() && this.tag.contains("AttributeModifiers", 9)) { multimap = HashMultimap.create(); ListNBT listnbt = this.tag.getList("AttributeModifiers", 10); for(int i = 0; i < listnbt.size(); ++i) { CompoundNBT compoundnbt = listnbt.getCompound(i); AttributeModifier attributemodifier = SharedMonsterAttributes.readAttributeModifier(compoundnbt); if (attributemodifier != null && (!compoundnbt.contains("Slot", 8) || compoundnbt.getString("Slot").equals(equipmentSlot.getName())) && attributemodifier.getID().getLeastSignificantBits() != 0L && attributemodifier.getID().getMostSignificantBits() != 0L) { multimap.put(compoundnbt.getString("AttributeName"), attributemodifier); } } } else { multimap = this.getItem().getAttributeModifiers(equipmentSlot, this); } multimap.values().forEach((p_226631_0_) -> { p_226631_0_.setSaved(false); }); return multimap; } public void addAttributeModifier(String attributeName, AttributeModifier modifier, @Nullable EquipmentSlotType equipmentSlot) { this.getOrCreateTag(); if (!this.tag.contains("AttributeModifiers", 9)) { this.tag.put("AttributeModifiers", new ListNBT()); } ListNBT listnbt = this.tag.getList("AttributeModifiers", 10); CompoundNBT compoundnbt = SharedMonsterAttributes.writeAttributeModifier(modifier); compoundnbt.putString("AttributeName", attributeName); if (equipmentSlot != null) { compoundnbt.putString("Slot", equipmentSlot.getName()); } listnbt.add(compoundnbt); } /** * Get a ChatComponent for this Item's display name that shows this Item on hover */ public ITextComponent getTextComponent() { ITextComponent itextcomponent = (new StringTextComponent("")).appendSibling(this.getDisplayName()); if (this.hasDisplayName()) { itextcomponent.applyTextStyle(TextFormatting.ITALIC); } ITextComponent itextcomponent1 = TextComponentUtils.wrapInSquareBrackets(itextcomponent); if (!this.isEmpty) { CompoundNBT compoundnbt = this.write(new CompoundNBT()); itextcomponent1.applyTextStyle(this.getRarity().color).applyTextStyle((p_226632_1_) -> { p_226632_1_.setHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_ITEM, new StringTextComponent(compoundnbt.toString()))); }); } return itextcomponent1; } private static boolean isStateAndTileEntityEqual(CachedBlockInfo p_206846_0_, @Nullable CachedBlockInfo p_206846_1_) { if (p_206846_1_ != null && p_206846_0_.getBlockState() == p_206846_1_.getBlockState()) { if (p_206846_0_.getTileEntity() == null && p_206846_1_.getTileEntity() == null) { return true; } else { return p_206846_0_.getTileEntity() != null && p_206846_1_.getTileEntity() != null ? Objects.equals(p_206846_0_.getTileEntity().write(new CompoundNBT()), p_206846_1_.getTileEntity().write(new CompoundNBT())) : false; } } else { return false; } } public boolean canDestroy(NetworkTagManager p_206848_1_, CachedBlockInfo p_206848_2_) { if (isStateAndTileEntityEqual(p_206848_2_, this.canDestroyCacheBlock)) { return this.canDestroyCacheResult; } else { this.canDestroyCacheBlock = p_206848_2_; if (this.hasTag() && this.tag.contains("CanDestroy", 9)) { ListNBT listnbt = this.tag.getList("CanDestroy", 8); for(int i = 0; i < listnbt.size(); ++i) { String s = listnbt.getString(i); try { Predicate<CachedBlockInfo> predicate = BlockPredicateArgument.blockPredicate().parse(new StringReader(s)).create(p_206848_1_); if (predicate.test(p_206848_2_)) { this.canDestroyCacheResult = true; return true; } } catch (CommandSyntaxException var7) { ; } } } this.canDestroyCacheResult = false; return false; } } public boolean canPlaceOn(NetworkTagManager p_206847_1_, CachedBlockInfo p_206847_2_) { if (isStateAndTileEntityEqual(p_206847_2_, this.canPlaceOnCacheBlock)) { return this.canPlaceOnCacheResult; } else { this.canPlaceOnCacheBlock = p_206847_2_; if (this.hasTag() && this.tag.contains("CanPlaceOn", 9)) { ListNBT listnbt = this.tag.getList("CanPlaceOn", 8); for(int i = 0; i < listnbt.size(); ++i) { String s = listnbt.getString(i); try { Predicate<CachedBlockInfo> predicate = BlockPredicateArgument.blockPredicate().parse(new StringReader(s)).create(p_206847_1_); if (predicate.test(p_206847_2_)) { this.canPlaceOnCacheResult = true; return true; } } catch (CommandSyntaxException var7) { ; } } } this.canPlaceOnCacheResult = false; return false; } } public int getAnimationsToGo() { return this.animationsToGo; } public void setAnimationsToGo(int animations) { this.animationsToGo = animations; } public int getCount() { return this.isEmpty ? 0 : this.count; } public void setCount(int count) { this.count = count; this.updateEmptyState(); } public void grow(int count) { this.setCount(this.count + count); } public void shrink(int count) { this.grow(-count); } /** * Called as the stack is being used by an entity. */ public void onItemUsed(World worldIn, LivingEntity livingEntityIn, int countIn) { this.getItem().onUse(worldIn, livingEntityIn, this, countIn); } public boolean isFood() { return this.getItem().isFood(); } // FORGE START public void deserializeNBT(CompoundNBT nbt) { final ItemStack itemStack = ItemStack.read(nbt); getStack().setTag(itemStack.getTag()); if (itemStack.capNBT != null) deserializeCaps(itemStack.capNBT); } /** * Set up forge's ItemStack additions. */ private void forgeInit() { Item item = getItemRaw(); if (item != null) { this.delegate = item.delegate; net.minecraftforge.common.capabilities.ICapabilityProvider provider = item.initCapabilities(this, this.capNBT); this.gatherCapabilities(provider); if (this.capNBT != null) deserializeCaps(this.capNBT); } } /** * Internal call to get the actual item, not the delegate. * In all other methods, FML replaces calls to this.item with the item delegate. */ @Nullable private Item getItemRaw() { return this.item; } public SoundEvent getDrinkSound() { return this.getItem().getDrinkSound(); } public SoundEvent getEatSound() { return this.getItem().getEatSound(); } }
60a70ecf8afdabcd165c1db0ef0fb414e80c7ef5
f62b938e7e8510ee6868005035d5955d22a39802
/src/test/java/com/tts/ItemsSpringBoot/ItemsSpringBootTests.java
fbf05e5b0d22b05d06fd0f34e6f4082cbc8c8a16
[ "MIT" ]
permissive
HajarAlhassan/SpringBoot-Items
49df447c923401c0d94d53733ae2b54b0d4520b6
bfdfdaa09939177beb4d29297f2b3b1058f2045d
refs/heads/main
2023-05-01T05:33:21.273025
2021-05-14T02:22:31
2021-05-14T02:22:31
367,219,417
0
0
null
null
null
null
UTF-8
Java
false
false
213
java
package com.tts.ItemsSpringBoot; import org.junit.jupiter.api.Test; import org.springframework.boot.test.context.SpringBootTest; @SpringBootTest class ItemsSpringBootTests { @Test void contextLoads() { } }
f35610a955cec593269726f95c143453c233f4ae
2e924b045959e20a7ae5a286f794e8609664c68c
/BibliotecaApp/src/cl/inacap/bibliotecaApp/controller/RegistrarController.java
aff939e232ef5654a7d9e38ab8267773306ade65
[]
no_license
constanzaB72/biblioteca
40e79d29e3cef73027b1f52f39188b70664eb1c9
4d2cb82fc21ee3e764d9529c983ac43a540fe813
refs/heads/main
2023-06-29T11:44:51.652477
2021-07-28T17:18:20
2021-07-28T17:18:20
377,364,486
0
0
null
null
null
null
ISO-8859-3
Java
false
false
6,776
java
package cl.inacap.bibliotecaApp.controller; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.sql.SQLIntegrityConstraintViolationException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.List; import javax.swing.DefaultListModel; import javax.swing.JOptionPane; import cl.inacap.bibliotecaApp.frames.RegistrarFrame; import cl.inacap.bibliotecaModel.dao.ClientesDAO; import cl.inacap.bibliotecaModel.dao.TrabajadoresDAO; import cl.inacap.bibliotecaModel.dto.Cliente; import cl.inacap.bibliotecaModel.dto.Trabajador; import cl.inacap.bibliotecaModel.utils.Generador; public class RegistrarController { private RegistrarFrame registrarFrame; private Generador generador = new Generador(); private TrabajadoresDAO trabajadoresDAO = new TrabajadoresDAO(); private ClientesDAO clientesDAO = new ClientesDAO(); public RegistrarController() { registrarFrame = new RegistrarFrame(); registrarFrame.getRdbtnTrabajador().setSelected(true); registrarFrame.setVisible(true); registrarFrame.addConfirmaRegistrar(new RegistrarListener()); registrarFrame.addAgregarDireccion(new DireccionListener()); registrarFrame.addAgregarCorreos(new CorreosListener()); registrarFrame.addAgregarTelefonos(new TelefonosListener()); } class RegistrarListener implements ActionListener { public void actionPerformed(ActionEvent e) { String nombre = registrarFrame.getTxtNombreIngresar().getText(); String apellidoP = registrarFrame.getTxtApellidoPaRegistrar().getText(); String apellidoM = registrarFrame.getTxtApellidoMaRegistrar().getText(); String rut = registrarFrame.getTxtRutRegistrar().getText(); SimpleDateFormat dateFormat = new SimpleDateFormat( registrarFrame.getDataNacimiento().getDateFormatString()); List<String> errores = new ArrayList<String>(); String fechaContrato=""; String fechaNac=""; if (registrarFrame.getRdbtnCliente().isSelected()) { try { fechaNac = dateFormat.format(registrarFrame.getDataNacimiento().getDate()); } catch (Exception exc) { System.out.println(exc); errores.add("Ingrese Fecha de Nacimiento para Cliente"); } } if (registrarFrame.getRdbtnTrabajador().isSelected()) { try { fechaContrato = dateFormat.format(registrarFrame.getDataContrato().getDate()); } catch (Exception exc) { System.out.println(exc); errores.add("Ingrese Fecha de Contrato para Trabajador"); } } String password = registrarFrame.getTextPassword().getText(); List<String> correos = traerLista((DefaultListModel<String>) registrarFrame.getListaCorreos().getModel()); List<String> telefonos = traerLista( (DefaultListModel<String>) registrarFrame.getListaTelefonos().getModel()); List<String> Direcciones = traerLista( (DefaultListModel<String>) registrarFrame.getListaDireccion().getModel()); if (nombre.isEmpty()) { errores.add("Debe ingresar nombre"); } if (apellidoP.isEmpty()) { errores.add("Debe ingresar apellido paterno"); } /* * private RutUtils rutUtils=new RutUtils(); * * String valido = * rutUtils.validarRut(registrarFrame.getTxtRutRegistrar().getText()); if * (valido.equals("Valido")) { * * * } */ if (telefonos.size() == 0) { errores.add("Debe ingresar al menos un numero de teléfono"); } if (correos.size() == 0) { errores.add("Debe ingresar al menos un correo electrónico"); } if (Direcciones.size() == 0) { errores.add("Debe ingresar al menos una dirección"); } if (errores.size() == 0) { if (registrarFrame.getRdbtnTrabajador().isSelected()) { System.out.println("entraif registrar"); Trabajador trabajador = new Trabajador(); trabajador.setNombre(nombre); trabajador.setApellidoPa(apellidoP); trabajador.setApellidoMa(apellidoM); trabajador.setRut(rut); trabajador.setFechaContrato(fechaContrato); trabajador.setPassword(password); try { trabajadoresDAO.insertTrabajador(trabajador, telefonos, correos, Direcciones); } catch (Exception ex) { JOptionPane.showMessageDialog(registrarFrame, "usuario ya registrado", "ERROR", JOptionPane.ERROR_MESSAGE); } } else { System.out.println("entra else registrar"); Cliente cliente = new Cliente(); cliente.setRut(rut); cliente.setNombre(nombre); cliente.setApellidoPa(apellidoP); cliente.setApellidoMa(apellidoM); cliente.setFechaNacimiento(fechaNac); cliente.setPassword(password); try { clientesDAO.insertCliente(cliente, telefonos, correos, Direcciones); } catch (Exception ex) { JOptionPane.showMessageDialog(registrarFrame, "usuario ya registrado", "ERROR", JOptionPane.ERROR_MESSAGE); } } } else { String mostrarError = ""; for (String error : errores) { mostrarError = mostrarError + "-" + error + "\n"; } JOptionPane.showMessageDialog(registrarFrame, mostrarError, "ERROR", JOptionPane.ERROR_MESSAGE); } } } class DireccionListener implements ActionListener { @SuppressWarnings("unchecked") public void actionPerformed(ActionEvent e) { DefaultListModel<String> DireccionModel = (DefaultListModel<String>) registrarFrame.getListaDireccion() .getModel(); DireccionModel.addElement(registrarFrame.getTxtDireccionRegistrar().getText()); registrarFrame.getListaDireccion().setModel(DireccionModel); registrarFrame.getTxtDireccionRegistrar().setText(""); registrarFrame.getListaDireccion().repaint(); } } class CorreosListener implements ActionListener { public void actionPerformed(ActionEvent e) { System.out.println("entra correo"); DefaultListModel<String> correoModel = (DefaultListModel<String>) registrarFrame.getListaCorreos() .getModel(); correoModel.addElement(registrarFrame.getTxtCorreoRegistrar().getText()); registrarFrame.getListaCorreos().setModel(correoModel); registrarFrame.getTxtCorreoRegistrar().setText(""); System.out.println("entra correo fin"); } } class TelefonosListener implements ActionListener { public void actionPerformed(ActionEvent e) { DefaultListModel<String> telefonoModel = (DefaultListModel<String>) registrarFrame.getListaTelefonos() .getModel(); telefonoModel.addElement(registrarFrame.getTxtTelefonoRegistrar().getText()); registrarFrame.getListaTelefonos().setModel(telefonoModel); registrarFrame.getTxtTelefonoRegistrar().setText(""); } } private List<String> traerLista(DefaultListModel<String> lista) { List<String> listaString = new ArrayList<String>(); for (int i = 0; i < lista.getSize(); i++) { listaString.add(lista.getElementAt(i)); } return listaString; } }
7b95a0b29935c0b08e3691d475ea2381ed3d3df4
cc7c5aa4792efbce1fa825218599637e0693834a
/api/target/generated-sources/openapi/src/main/java/io/reflectoring/api/ApiUtil.java
4cc505397a9fc89c2571ee2f51521f3e52d12ca2
[]
no_license
TomaszReda/testapi
155b3d56f2ceb88be7c432ba267ed2bdc802b5a4
4643a666704f162bb621224e5bcfef0e81255554
refs/heads/master
2023-03-16T13:24:49.384448
2021-03-11T20:59:33
2021-03-11T20:59:33
346,825,715
0
0
null
null
null
null
UTF-8
Java
false
false
641
java
package io.reflectoring.api; import org.springframework.web.context.request.NativeWebRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; public class ApiUtil { public static void setExampleResponse(NativeWebRequest req, String contentType, String example) { try { HttpServletResponse res = req.getNativeResponse(HttpServletResponse.class); res.setCharacterEncoding("UTF-8"); res.addHeader("Content-Type", contentType); res.getWriter().print(example); } catch (IOException e) { throw new RuntimeException(e); } } }
9ca2f752ed58b40b8b8ddb62d983456874b4f4cf
3cb795e3c307db7696205a7ea642505b2ce9001f
/app/src/androidTest/java/com/kurkov/p0801_handler/ApplicationTest.java
5c62c89ced675c4bbe20c07e97a33ea54106c721
[]
no_license
kurkov/P0801_Handler
35aaf516ce8d510428ea8661e9ff0d87813ed5df
c24de75ec05120499e1f37d4d489c7f659b68b6e
refs/heads/master
2021-01-22T09:04:15.592912
2015-09-22T09:47:45
2015-09-22T09:47:45
42,925,465
0
0
null
null
null
null
UTF-8
Java
false
false
355
java
package com.kurkov.p0801_handler; import android.app.Application; import android.test.ApplicationTestCase; /** * <a href="http://d.android.com/tools/testing/testing_android.html">Testing Fundamentals</a> */ public class ApplicationTest extends ApplicationTestCase<Application> { public ApplicationTest() { super(Application.class); } }