blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
4
410
content_id
stringlengths
40
40
detected_licenses
sequencelengths
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
sequencelengths
1
1
author_id
stringlengths
0
313
262065434b1e34d7ce52606f7af93a412df9bd1a
f868d40cdcd152b199f5c5fc82c56bca2f3e646d
/MortgageOriginationRestService/src/main/java/com/jpmorgan/awm/pb/mortgageorigination/response/UserDetailsResponse.java
8bf4d144a1b2fecafc5a2b4ee5affc5cfd2249bd
[]
no_license
los2016org/LoanOriginationSystem
6493a7c7550c9a5213ed80aabd938de4dc133455
1e0f506cd84fbf0b5fafedb496b64c7e10fd83ed
refs/heads/master
2020-05-20T18:31:42.153215
2016-04-30T04:49:51
2016-04-30T04:49:51
55,230,727
0
1
null
2016-04-28T11:20:35
2016-04-01T12:25:12
Java
UTF-8
Java
false
false
475
java
package com.jpmorgan.awm.pb.mortgageorigination.response; import com.myorg.losmodel.model.LOSResponse; import com.myorg.losmodel.model.User; public class UserDetailsResponse { private User user; private LOSResponse response; public LOSResponse getResponse() { return response; } public void setResponse(LOSResponse response) { this.response = response; } public User getUser() { return user; } public void setUser(User user) { this.user = user; } }
fc3c8986b895e0e472c33123759208e723e214ea
35dedc76ed04fea5ccfca8e929453da7366d78d2
/app/src/main/java/com/zmt/boxin/NetworkThread/IdentifyThread.java
867d63e23d86cd54ffee21dc2aa9d9b7d78bb6bb
[]
no_license
xiyouZmt/XiyouScore
2dd296e01f097c80098df02348549abaef789d6b
22bca25240cf081ea85b36e1e11de3ef9a5be4df
refs/heads/master
2020-05-21T22:34:15.697718
2017-05-31T13:07:05
2017-05-31T13:07:05
64,858,143
4
0
null
null
null
null
UTF-8
Java
false
false
1,011
java
package com.zmt.boxin.NetworkThread; import android.os.Handler; import com.zmt.boxin.Application.App; import com.zmt.boxin.Utils.OkHttpUtils; /** * Created by Dangelo on 2016/9/4. */ public class IdentifyThread implements Runnable { private String url; private Handler handler; private App app; public IdentifyThread(String url, Handler handler, App app) { this.url = url; this.handler = handler; this.app = app; } @Override public void run() { OkHttpUtils okHttpUtils = new OkHttpUtils(url); String result = okHttpUtils.getCheckCode(); switch (result){ case "error" : handler.sendEmptyMessage(0x333); break; case "can not find cookie" : handler.sendEmptyMessage(0x222); break; default : handler.sendEmptyMessage(0x001); app.getUser().setCookie(result); break; } } }
8315ef05135799cbe2b63623fa1494ce85223b66
9b18528c073feae60c19b34b0cef567fae80f04a
/src/main/java/com/cg/addressbook/service/imp/AddressBookServiceImp.java
f1aa8f4934a7317bea38ee9b47b2cf520d33d2c3
[]
no_license
Avnish986/AddressBookProject
153d96af9f0ed970c99d932f492ee8526b3065fe
c09b50097f89a111da39a59bc979acd4d56ee2ee
refs/heads/master
2022-12-31T05:19:18.554483
2020-10-21T03:45:45
2020-10-21T03:45:45
300,214,906
0
0
null
2020-10-01T13:08:32
2020-10-01T09:04:37
Java
UTF-8
Java
false
false
3,157
java
package com.cg.addressbook.service.imp; import com.cg.addressbook.dto.AddressBook; import com.cg.addressbook.dto.PersonContact; import com.cg.addressbook.exception.ContactException; import com.cg.addressbook.service.AddressBookService; import com.cg.addressbook.service.PersonService; import java.util.*; public class AddressBookServiceImp implements AddressBookService { private AddressBook addressBook; private PersonService personService; private Scanner sc; public AddressBookServiceImp(Scanner sc) { this.sc = sc; } public void showOptions(AddressBook addressBook){ this.addressBook = addressBook; personService = new PersonServiceImp(this.sc); while(true) { System.out.println("Option For Address Book"); System.out.println("1.) Find A Person"); System.out.println("2.) Create A Person"); System.out.println("3.) Update A Person"); System.out.println("4.) Delete A Person"); System.out.println("5.) View all Persons storted by Names"); System.out.println("6.) View all Persons storted by City"); System.out.println("7.) View all Persons storted by State"); System.out.println("8.) View all Persons storted by Zip"); System.out.println("9.) Exit"); int option = sc.nextInt(); switch(option) { case 1: findAPerson(); //display(); break; case 2: PersonContact person = new PersonContact(); createAPerson(); display(); break; case 3: updateAPerson(); break; case 4: deleteAPerson(); break; case 5: List<PersonContact> contact1 = new ArrayList<PersonContact>(); contact1=addressBook.showContact(); for(PersonContact i : contact1) { System.out.println(i); } break; case 6: System.out.println(addressBook.sortCity()); break; case 7: System.out.println(addressBook.sortState()); break; case 8: System.out.println(addressBook.sortZip()); break; case 9: return; default: System.out.println("Invalid Input"); break; } } } @Override public void findAPerson() { System.out.println("Enter Person Name"); Scanner d = new Scanner(System.in); String name = d.nextLine(); personService.displayPerson(addressBook.isPerson(name)); } public void createAPerson(){ try { addressBook.addContact(personService.createPerson()); } catch (ContactException e) { e.printStackTrace(); } } public void display() { addressBook.getAddressBook(); } @Override public void updateAPerson() { System.out.println("Enter Person Name"); String name = sc.next(); PersonContact person = addressBook.isPerson(name); if(Objects.nonNull(person)) { personService.updatePerson(person); return; } System.out.println("Person Not Found"); } @Override public void deleteAPerson() { System.out.println("Enter Person Name"); String name = sc.next(); PersonContact person = addressBook.isPerson(name); if(Objects.nonNull(person)){ addressBook.deletePerson(name); return; } System.out.println("Person Not Found"); } @Override public AddressBook createAddressBook(String name) { AddressBook addressBook= new AddressBook(name); return addressBook; } }
742d4e907843a50bafa9ed78f5599ad41b074406
55eb407ff4d54421e2e1326e36777bed20cfedee
/application/AnlegenController.java
8154bcadd3376af71c6317498e958aa9aa831b37
[]
no_license
paphill/zeiterfassung
bf0ce04a54e74988d03a1bcd372ea613636e9c7b
bc7a182099dc9ca8e2c795c675460b03c71397de
refs/heads/master
2020-05-23T02:02:15.876026
2019-05-28T10:53:53
2019-05-28T10:53:53
186,594,741
0
0
null
null
null
null
ISO-8859-1
Java
false
false
8,918
java
package application; import javafx.collections.*; import javafx.fxml.*; import javafx.scene.control.*; import javafx.scene.control.Alert.AlertType; import javafx.scene.control.cell.PropertyValueFactory; import javafx.scene.input.MouseEvent; import java.util.*; import java.net.URL; public class AnlegenController implements Initializable{ ProjektDAO project = new ProjektDAODBImpl(); MitarbeiterDAO mitarbeiter = new MitarbeiterDAODBImpl(); ObservableList<Mitarbeiter> mitarbeiterliste; ObservableList<Projekt> projektliste; @FXML private TextField eintragID; @FXML private TextField eintragProID; @FXML private TextField eintragVorname; @FXML private TextField eintragNachname; @FXML private TextField eintragBezeichnung; @FXML private TextField eintragAuftraggeber; @FXML private ChoiceBox<String> choiceTyp; @FXML private Button buttonLeeren; @FXML private Button buttonLoeschen; @FXML private Button buttonSpeichern; @FXML private Button buttonAbmelden; @FXML private TableColumn idcol; @FXML private TableColumn vorcol; @FXML private TableColumn nachcol; @FXML private TableColumn typcol; @FXML private TableColumn projidcol; @FXML private TableColumn bezcol; @FXML private TableColumn auftragcol; @FXML private Button mitarSpeichern; @FXML private Button mitarLeeren; @FXML private Button mitarLoeschen; @FXML private Button projSpeichern; @FXML private Button projLeeren; @FXML private Button projLoeschen; @FXML private TableView<Mitarbeiter> mitarbeiterview; @FXML private TableView<Projekt> projektview; @SuppressWarnings("unchecked") @Override public void initialize(URL url, ResourceBundle rb) { choiceTyp.getItems().add("Admin"); choiceTyp.getItems().add("Buchhaltung"); choiceTyp.getItems().add("Einkauf/Verkauf"); choiceTyp.getItems().add("Lagerhaltung"); idcol.setCellValueFactory(new PropertyValueFactory<Mitarbeiter, Integer>("id")); vorcol.setCellValueFactory(new PropertyValueFactory<Mitarbeiter, String>("vorname")); nachcol.setCellValueFactory(new PropertyValueFactory<Mitarbeiter, String>("nachname")); typcol.setCellValueFactory(new PropertyValueFactory<Mitarbeiter, String>("typ")); projidcol.setCellValueFactory(new PropertyValueFactory<Projekt, Integer>("id")); bezcol.setCellValueFactory(new PropertyValueFactory<Projekt, String>("name")); auftragcol.setCellValueFactory(new PropertyValueFactory<Projekt, String>("auftraggeber")); mitarbeiterliste = FXCollections.observableArrayList(mitarbeiter.getAllMitarbeiter()); projektliste = FXCollections.observableArrayList(project.getAllProjekt()); idcol.prefWidthProperty().bind(mitarbeiterview.widthProperty().multiply(0.09)); vorcol.prefWidthProperty().bind(mitarbeiterview.widthProperty().multiply(0.275)); nachcol.prefWidthProperty().bind(mitarbeiterview.widthProperty().multiply(0.275)); typcol.prefWidthProperty().bind(mitarbeiterview.widthProperty().multiply(0.35)); projidcol.prefWidthProperty().bind(mitarbeiterview.widthProperty().multiply(0.09)); bezcol.prefWidthProperty().bind(mitarbeiterview.widthProperty().multiply(0.45)); auftragcol.prefWidthProperty().bind(mitarbeiterview.widthProperty().multiply(0.45)); mitarbeiterview.setItems(mitarbeiterliste); projektview.setItems(projektliste); } @FXML public void mitarSpeichernClicked() { String vorname = String.valueOf(eintragVorname.getText()); String nachname = String.valueOf(eintragNachname.getText()); String typ = String.valueOf(choiceTyp.getValue()); if(eintragID.getLength() == 0) { Alert alert = new Alert(AlertType.INFORMATION); alert.setTitle("Information"); alert.setHeaderText("Bestätigung"); String s ="Mitarbeiter wurde erfolgreich hinzugefügt"; alert.setContentText(s); alert.show(); mitarbeiter.addMitarbeiter(vorname, nachname, typ); }else { Alert alert = new Alert(AlertType.INFORMATION); alert.setTitle("Information"); alert.setHeaderText("Bestätigung"); String s ="Mitarbeiter wurde erfolgreich aktualisiert"; alert.setContentText(s); alert.show(); int id = Integer.valueOf(eintragID.getText()); mitarbeiter.updateMitarbeiter(id, vorname, nachname, typ); } mitarbeiterliste = FXCollections.observableArrayList(mitarbeiter.getAllMitarbeiter()); mitarbeiterview.setItems(mitarbeiterliste); mitarLeerenSpeichern(); } @FXML public void mitarLeerenClicked() { Alert alert = new Alert(AlertType.INFORMATION); alert.setTitle("Information"); alert.setHeaderText("Entleeren"); String s ="Eingabefelder wurden geleert"; alert.setContentText(s); alert.show(); eintragID.setText(""); eintragVorname.setText(""); eintragNachname.setText(""); choiceTyp.getSelectionModel().clearSelection(); choiceTyp.setValue(null); } @FXML public void mitarLoeschenClicked() { Alert alert = new Alert(AlertType.CONFIRMATION); alert.setTitle("Information"); String s = "Bitte Löschen bestätigen"; alert.setContentText(s); Optional<ButtonType> result = alert.showAndWait(); if ((result.isPresent()) && (result.get() == ButtonType.OK)) { Mitarbeiter selectedItem = mitarbeiterview.getSelectionModel().getSelectedItem(); mitarbeiter.deleteMitarbeiter(selectedItem.getId()); mitarbeiterview.getItems().remove(selectedItem); } } @FXML public void mitarLeerenSpeichern() { eintragID.setText(""); eintragVorname.setText(""); eintragNachname.setText(""); choiceTyp.getSelectionModel().clearSelection(); choiceTyp.setValue(null); } @FXML public void projLeerenSpeichern() { eintragProID.setText(""); eintragBezeichnung.setText(""); eintragAuftraggeber.setText(""); } @FXML public void projSpeichernClicked() { String bezeichnung = String.valueOf(eintragBezeichnung.getText()); String auftrag = String.valueOf(eintragAuftraggeber.getText()); if(eintragProID.getLength() == 0) { Alert alert = new Alert(AlertType.INFORMATION); alert.setTitle("Information"); alert.setHeaderText("Bestätigung"); String s ="Projekt wurde erfolgreich hinzugefügt"; alert.setContentText(s); alert.show(); project.addProjekt(bezeichnung, auftrag); }else { Alert alert = new Alert(AlertType.INFORMATION); alert.setTitle("Information"); alert.setHeaderText("Bestätigung"); String s ="Projekt wurde erfolgreich aktualisiert"; alert.setContentText(s); alert.show(); int id = Integer.valueOf(eintragProID.getText()); project.updateProjekt(id, bezeichnung, auftrag); } projektliste = FXCollections.observableArrayList(project.getAllProjekt()); projektview.setItems(projektliste); projLeerenSpeichern(); } @FXML public void projLeerenClicked() { Alert alert = new Alert(AlertType.INFORMATION); alert.setTitle("Information"); alert.setHeaderText("Entleeren"); String s ="Eingabefelder wurden geleert"; alert.setContentText(s); alert.show(); eintragProID.setText(""); eintragBezeichnung.setText(""); eintragAuftraggeber.setText(""); } @FXML public void projLoeschenClicked() { Alert alert = new Alert(AlertType.CONFIRMATION); alert.setTitle("Information"); String s = "Bitte Löschen bestätigen"; alert.setContentText(s); Optional<ButtonType> result = alert.showAndWait(); if ((result.isPresent()) && (result.get() == ButtonType.OK)) { Projekt selectedItem = projektview.getSelectionModel().getSelectedItem(); project.deleteProjekt(selectedItem.getId()); projektview.getItems().remove(selectedItem); } } @FXML public void mitarbeiterviewClicked(MouseEvent event) { if (event.getClickCount() == 2) //Checking double click { Mitarbeiter abk = mitarbeiterview.getSelectionModel().getSelectedItem(); eintragID.setText(""+abk.getId()); eintragVorname.setText(abk.getVorname()); eintragNachname.setText(abk.getNachname()); choiceTyp.setValue(abk.getTyp()); } } @FXML public void projectviewClicked(MouseEvent event) { if (event.getClickCount() == 2) //Checking double click { Projekt abk = projektview.getSelectionModel().getSelectedItem(); eintragProID.setText(""+abk.getId()); eintragBezeichnung.setText(abk.getName()); eintragAuftraggeber.setText(abk.getAuftraggeber()); } } }
ed9bd0438b8dcf947fcbff745976afc7ca0180ad
10b0829d5480c4af1562d95f95cd69fde7514ab3
/java/src-test/com/toolsverse/etl/core/engine/EtlFactoryTest.java
c9766e00dacd42b076491d724fb5d05b6770d8c8
[]
no_license
huangfeng/toolsverse-etl-framework
9e4e3a3242af3f9058de8314ec692d1ba6c62b7b
140e066b4bf6d662f9a5dbac2652003c3430befd
refs/heads/master
2021-01-21T03:59:36.059934
2013-02-02T16:36:37
2013-02-02T16:36:37
null
0
0
null
null
null
null
UTF-8
Java
false
false
6,834
java
/* * EtlFactoryTest.java * * Copyright 2010-2012 Toolsverse. All rights reserved. Toolsverse * PROPRIETARY/CONFIDENTIAL. Use is subject to license terms. */ package com.toolsverse.etl.core.engine; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import org.junit.BeforeClass; import org.junit.Test; import com.toolsverse.config.SystemConfig; import com.toolsverse.etl.core.config.EtlConfig; import com.toolsverse.etl.core.util.EtlUtils; import com.toolsverse.etl.driver.Driver; import com.toolsverse.etl.driver.MockExtendedCallableDriver; import com.toolsverse.resource.TestResource; import com.toolsverse.util.TypedKeyValue; import com.toolsverse.util.Utils; /** * EtlFactoryTest * * @author Maksym Sherbinin * @version 2.0 * @since 1.0 */ public class EtlFactoryTest { private static final String DRIVER_CLASS_NAME = "com.toolsverse.etl.driver.MockExtendedCallableDriver"; private static final String SCENARIO_NAME = "test.xml"; @BeforeClass public static void setUp() { System.setProperty( SystemConfig.HOME_PATH_PROPERTY, SystemConfig.WORKING_PATH + TestResource.TEST_HOME_PATH.getValue()); SystemConfig.instance().setSystemProperty( SystemConfig.DEPLOYMENT_PROPERTY, SystemConfig.TEST_DEPLOYMENT); Utils.callAnyMethod(SystemConfig.instance(), "init"); } private Scenario getScenario(String scenarioFileName, int parseScope) throws Exception { EtlConfig etlConfig = new EtlConfig(); EtlFactory etlFactory = new EtlFactory(); Scenario scenario = etlFactory.getScenario(etlConfig, scenarioFileName, parseScope); return scenario; } private TypedKeyValue<EtlConfig, Scenario> getSettings( String scenarioFileName) throws Exception { EtlConfig etlConfig = new EtlConfig(); etlConfig.init(); EtlFactory etlFactory = new EtlFactory(); Scenario scenario = etlFactory.getScenario(etlConfig, scenarioFileName, EtlFactory.PARSE_ALL); return new TypedKeyValue<EtlConfig, Scenario>(etlConfig, scenario); } @Test public void testAssignVars() throws Exception { Scenario scenarioFrom = getScenario(SCENARIO_NAME, EtlFactory.PARSE_ALL); assertNotNull(scenarioFrom); Scenario scenarioTo = getScenario(SCENARIO_NAME, EtlFactory.PARSE_ALL); assertNotNull(scenarioTo); EtlUtils.substituteVars(scenarioFrom.getVariables()); scenarioFrom.assignVars(scenarioTo); assertNotNull(scenarioTo.getVariable("TEST_SUBST")); assertTrue("some value".equals(scenarioTo.getVariable("TEST_SUBST") .getValue())); } @Test public void testGetDriver() throws Exception { Scenario scenario = getScenario(SCENARIO_NAME, EtlFactory.PARSE_ALL); assertNotNull(scenario); EtlFactory etlFactory = new EtlFactory(); Driver driver = etlFactory.getDriver(scenario.getDriverClassName(), null, null); assertTrue(driver instanceof MockExtendedCallableDriver); assertTrue(driver.getCaseSensitive() == Driver.CASE_SENSITIVE_LOWER); } @Test public void testGetDriverClassName() throws Exception { Scenario scenario = getScenario(SCENARIO_NAME, EtlFactory.PARSE_ALL); assertNotNull(scenario); EtlFactory etlFactory = new EtlFactory(); assertTrue(DRIVER_CLASS_NAME.equals(etlFactory .getDriverClassName(scenario.getDriverClassName()))); } @Test public void testGetDrivers() throws Exception { TypedKeyValue<EtlConfig, Scenario> settings = getSettings(SCENARIO_NAME); EtlConfig config = settings.getKey(); Scenario scenario = settings.getValue(); assertNotNull(config); assertNotNull(scenario); assertNotNull(config.getDrivers()); assertTrue(config.getDrivers().size() > 0); } @Test public void testGetScenario() throws Exception { Scenario scenario = getScenario(SCENARIO_NAME, EtlFactory.PARSE_ALL); assertNotNull(scenario); assertNotNull(scenario.getId()); assertTrue(scenario.isReady()); assertTrue("This is a description".equals(scenario.getDescription())); assertNotNull(scenario.getVariables()); assertTrue(scenario.getVariables().size() > 0); assertNotNull(scenario.getSources()); assertTrue(scenario.getSources().size() > 0); assertNotNull(scenario.getDestinations()); assertTrue(scenario.getDestinations().size() > 0); Source source = scenario.getSources().get("PROPERTY"); assertNotNull(source); assertTrue(!Utils.isNothing(source.getSql())); assertNotNull(source.getTasks()); assertTrue(source.getTasks().size() > 0); Destination dest = scenario.getDestinations().get("CLOBS"); assertNotNull(dest); assertNotNull(dest.getVariables()); assertTrue(dest.getVariables().size() > 0); } @Test public void testIsReady() throws Exception { Scenario scenario = getScenario(SCENARIO_NAME, EtlFactory.PARSE_STRUCTURE_ONLY); assertNotNull(scenario); assertTrue(!scenario.isReady()); scenario = getScenario(SCENARIO_NAME, EtlFactory.PARSE_ALL); assertNotNull(scenario); assertTrue(scenario.isReady()); } @Test public void testSubstituteVars() throws Exception { Scenario scenario = getScenario(SCENARIO_NAME, EtlFactory.PARSE_ALL); assertNotNull(scenario); EtlUtils.substituteVars(scenario.getVariables()); assertNotNull(scenario.getVariable("TEST_SUBST")); assertTrue("some value".equals(scenario.getVariable("TEST_SUBST") .getValue())); } }
[ "[email protected]@687c8c9c-5067-5657-3508-d9a740e54cee" ]
[email protected]@687c8c9c-5067-5657-3508-d9a740e54cee
530669e2fa67bc7160e3f19be56c4fedd1f5d313
149adee1b50b128e4bac269e62554bcf68ee5191
/leetcode/DivideInteger.java
d577a2eb73887ab64430fa9c34b1470d8311e6fa
[]
no_license
hpn-codes/learn2code
ac22f129df8a60b8e5a46dd2abe74652309e83b1
fd4ceadc61b7cd293646ffdadefd20d759206f8a
refs/heads/master
2020-08-02T11:27:10.190041
2019-09-27T14:30:16
2019-09-27T14:30:16
211,335,219
0
0
null
null
null
null
UTF-8
Java
false
false
1,027
java
package leetcode; public class DivideInteger { public static void main(String[] args) { // TODO Auto-generated method stub System.out.println(divide(1,1)); } public static int divide(int dividend, int divisor) { Boolean isOutputPositive; if(dividend == 0) return 0; if((dividend <0 && divisor<0) || (dividend >0 && divisor>0)) isOutputPositive = true; else isOutputPositive = false; int pDivident, pDivisor; if(dividend<0) pDivident = dividend - dividend - dividend; else pDivident = dividend; if(divisor<0) pDivisor = divisor - divisor - divisor; else pDivisor = divisor; if(pDivident < pDivisor) return 0; if(pDivident == pDivisor) return 0; int q =0; while(pDivident >= pDivisor){ pDivident = pDivident - pDivisor; q++; } if(!isOutputPositive) q = q-q-q; return q; } }
5d93149fff8202b0c681b8b2ac981ef678da1b12
f3f00a3c8885dac8cb6b6330157e28c29e33d913
/lib.fast/src/main/java/com/sunday/common/utils/ViewUtils.java
f3d546e9bfc78b32d3068f0a29224c93dd4182d1
[]
no_license
WangZhouA/yunmama
91967ed72250646093df29d95c5873bf17d1d4cb
1b125f1bfdff1c6740ed1b46e1ac2e3e72f588eb
refs/heads/master
2020-03-30T19:29:45.732788
2018-10-04T09:13:07
2018-10-04T09:13:07
151,545,702
1
0
null
null
null
null
UTF-8
Java
false
false
384
java
package com.sunday.common.utils; import android.view.View; /** * 项目:智能控制 SmartLock */ public class ViewUtils { public static void addPadding(View view, int padding){ if(view == null)return; view.setPadding(view.getPaddingLeft()+padding, view.getPaddingTop()+padding, view.getPaddingRight()+padding, view.getPaddingBottom()+padding); } }
d2827cf40159ff82aa23981a14fe29de4789bb59
884d2901f9116c10465cbb103c04f2369ca7870a
/test/UnidadesProtossTest.java
1546c7c0b85721ced23208cb49c81e2e9287479d
[]
no_license
herniadlf/algo3
71e4b6c20af206bd13265b482f67f33fc9891f07
0a16a5f417f5f124b29e0fff16bd3dcfaacd521f
refs/heads/master
2021-01-10T10:43:31.216425
2015-06-29T20:10:35
2015-06-29T20:10:35
36,699,011
0
1
null
null
null
null
UTF-8
Java
false
false
13,069
java
package test; import org.junit.Assert; import org.junit.Test; import excepciones.ExcepcionConstruccionNoCorrespondiente; import excepciones.ExcepcionEdificioNoPuedeCrearUnidad; import excepciones.ExcepcionElementoFueraDelRangoDeAtaque; import excepciones.ExcepcionErrorPasoDeTurno; import excepciones.ExcepcionFinDeTurnoPorMaximoDeAtaques; import excepciones.ExcepcionLaUnidadNoPertenceATuTropa; import excepciones.ExcepcionNoHayLugarParaCrear; import excepciones.ExcepcionNoPudoColocarseEdificio; import excepciones.ExcepcionNoPuedeMoverseUnidad; import excepciones.ExcepcionPosicionInvalida; import excepciones.ExcepcionRecursoInsuficiente; import excepciones.ExcepcionSuperaLimenteDeArbolesPermitos; import excepciones.ExcepcionTamanioDelMapaInvalido; import excepciones.ExcepcionUnidadNoCorrespondiente; import excepciones.ExcepcionYaHayElementoEnLaPosicion; import src.AtaquesPermitidosPorTurno; import src.Juego; import src.Jugador; import src.construcciones.Acceso; import src.construcciones.Barraca; import src.construcciones.Creadora; import src.mapa.Mapa; import src.razas.Protoss; import src.razas.Terran; import src.unidades.*; public class UnidadesProtossTest{ private Jugador jugador; private Mapa mapa; @Test public void testZealotSeCreaCon60escudoY100deVida(){ Zealot zealot = new Zealot(); Assert.assertTrue((zealot.getVida().obtenerVida()) == 100); Assert.assertTrue((zealot.getEscudo().obtenerResistenciaActual()) == 60 ); } @Test public void testDragonSeCreaCon80escudoY100deVida(){ Dragon dragon = new Dragon(); Assert.assertTrue((dragon.getVida().obtenerVida()) == 100); Assert.assertTrue((dragon.getEscudo().obtenerResistenciaActual()) == 80 ); } @Test public void testScoutSeCreaCon100escudoY150deVida(){ Scout scout = new Scout(); Assert.assertTrue((scout.getVida().obtenerVida()) == 150); Assert.assertTrue((scout.getEscudo().obtenerResistenciaActual()) == 100 ); } @Test public void testAtacarZealotNuevoPorMarineSoloDaniaEscudo() throws ExcepcionNoPudoColocarseEdificio, ExcepcionPosicionInvalida, ExcepcionNoHayLugarParaCrear, ExcepcionYaHayElementoEnLaPosicion, ExcepcionEdificioNoPuedeCrearUnidad, ExcepcionErrorPasoDeTurno, ExcepcionSuperaLimenteDeArbolesPermitos, ExcepcionElementoFueraDelRangoDeAtaque, ExcepcionLaUnidadNoPertenceATuTropa, ExcepcionConstruccionNoCorrespondiente, ExcepcionRecursoInsuficiente, ExcepcionUnidadNoCorrespondiente, ExcepcionTamanioDelMapaInvalido, ExcepcionFinDeTurnoPorMaximoDeAtaques { Jugador jug1 = new Jugador ("carlos","rojo",new Terran()); jug1.setDinero(9999, 9999); Jugador jug2 = new Jugador ("williams", "azul", new Protoss()); Juego juego = new Juego(jug1, jug2, 100, 0); Mapa mapa = juego.getMapa(); AtaquesPermitidosPorTurno ataques = new AtaquesPermitidosPorTurno(); ataques.setJuego(juego); Creadora barraca = (Creadora) jug1.colocar(new Barraca(),mapa,5,5); Creadora acceso = (Creadora) jug2.colocar(new Acceso(), mapa, 8, 8); Unidad marine = new Marine(); barraca.colocarUnidad(marine, mapa); jug1.getUnidadesAlistadas().add(marine); marine.setAtaquesPermitidosPorTurno(ataques); Zealot zealot = new Zealot(); acceso.colocarUnidad(zealot, mapa); jug1.atacarCon(marine, zealot); Assert.assertTrue((zealot.getVida().obtenerVida()) == 100); Assert.assertTrue((zealot.getEscudo().obtenerResistenciaActual()) == 54 ); } @Test public void testZealotRecibeMultiplesAtaques () throws ExcepcionNoPudoColocarseEdificio, ExcepcionPosicionInvalida, ExcepcionNoHayLugarParaCrear, ExcepcionYaHayElementoEnLaPosicion, ExcepcionEdificioNoPuedeCrearUnidad, ExcepcionErrorPasoDeTurno, ExcepcionSuperaLimenteDeArbolesPermitos, ExcepcionElementoFueraDelRangoDeAtaque, ExcepcionLaUnidadNoPertenceATuTropa, ExcepcionConstruccionNoCorrespondiente, ExcepcionRecursoInsuficiente, ExcepcionUnidadNoCorrespondiente, ExcepcionTamanioDelMapaInvalido, ExcepcionFinDeTurnoPorMaximoDeAtaques { Jugador jugador1 = new Jugador ("carlos","rojo",new Terran()); Jugador jugador2 = new Jugador ("dean","azul",new Protoss()); Juego juego = new Juego(jugador1, jugador2, 100, 0); Mapa mapa = juego.getMapa(); jugador1.setDinero(99999, 99999); Creadora barraca = (Creadora) jugador1.colocar(new Barraca(), mapa, 5, 5); Creadora acceso = (Creadora) jugador2.colocar(new Acceso(), mapa, 2, 2); Unidad primerMarine = new Marine(); Unidad segundoMarine = new Marine(); Unidad tercerMarine = new Marine(); Unidad zealot = new Zealot(); AtaquesPermitidosPorTurno ataques = new AtaquesPermitidosPorTurno(); primerMarine.setAtaquesPermitidosPorTurno(ataques); segundoMarine.setAtaquesPermitidosPorTurno(ataques); tercerMarine.setAtaquesPermitidosPorTurno(ataques); ataques.setJuego(juego); barraca.colocarUnidad(primerMarine, mapa); barraca.colocarUnidad(segundoMarine, mapa); barraca.colocarUnidad(tercerMarine, mapa); jugador1.getUnidadesAlistadas().add(primerMarine); jugador1.getUnidadesAlistadas().add(segundoMarine); jugador1.getUnidadesAlistadas().add(tercerMarine); acceso.colocarUnidad(zealot, mapa); jugador1.atacarCon(primerMarine, zealot); jugador1.atacarCon(segundoMarine, zealot); jugador1.atacarCon(tercerMarine, zealot); Assert.assertTrue(zealot.getEscudo().obtenerResistenciaActual() == 42); } @Test public void testDestruccionDeDragon(){ Dragon dragon= new Dragon(); dragon.getVida().aumentarDanioARecibir(200); dragon.getVida().disminuirVidaPorDanio(); Assert.assertTrue(dragon.getVida().estaMuerto()); } @Test public void testAsesinatoDeProtosEliminacionDelMapa() throws ExcepcionNoPudoColocarseEdificio, ExcepcionPosicionInvalida, ExcepcionNoHayLugarParaCrear, ExcepcionYaHayElementoEnLaPosicion, ExcepcionEdificioNoPuedeCrearUnidad, ExcepcionErrorPasoDeTurno, ExcepcionSuperaLimenteDeArbolesPermitos, ExcepcionConstruccionNoCorrespondiente, ExcepcionRecursoInsuficiente, ExcepcionUnidadNoCorrespondiente, ExcepcionTamanioDelMapaInvalido { Jugador jugador1 = new Jugador ("carlos","rojo",new Protoss()); Jugador jugador2 = new Jugador ("dean","azul",new Protoss()); Juego juego = new Juego(jugador1, jugador2, 100, 0); Mapa mapa = juego.getMapa(); jugador1.setDinero(99999, 99999); Creadora acceso = (Creadora) jugador2.colocar(new Acceso(), mapa, 2, 2); Zealot zealot = new Zealot(); zealot.setJugador(jugador2); acceso.colocarUnidad(zealot, mapa); // El Zealot fue colocado en la posicion (1,3) Assert.assertTrue(mapa.obtenerContenidoEnPosicion(1, 3).getElementoEnTierra().getNombre()=="Zealot"); zealot.getVida().aumentarDanioARecibir(70); zealot.recibirDanio(); Assert.assertTrue(zealot.getVida().obtenerVida()==90); zealot.getVida().aumentarDanioARecibir(90); zealot.recibirDanio(); Assert.assertTrue(mapa.obtenerContenidoEnPosicion(1, 3).getElementoEnTierra().getNombre()=="Espacio Disponible"); } @Test (expected = ExcepcionElementoFueraDelRangoDeAtaque.class) public void unidadIntentaAtacarFueraDeSuAlcanceLanzaExcepcion() throws ExcepcionPosicionInvalida, ExcepcionYaHayElementoEnLaPosicion, ExcepcionSuperaLimenteDeArbolesPermitos, ExcepcionNoPudoColocarseEdificio, ExcepcionNoHayLugarParaCrear, ExcepcionEdificioNoPuedeCrearUnidad, ExcepcionErrorPasoDeTurno, ExcepcionElementoFueraDelRangoDeAtaque, ExcepcionLaUnidadNoPertenceATuTropa, ExcepcionConstruccionNoCorrespondiente, ExcepcionRecursoInsuficiente, ExcepcionUnidadNoCorrespondiente, ExcepcionTamanioDelMapaInvalido, ExcepcionFinDeTurnoPorMaximoDeAtaques{ Jugador jugador1 = new Jugador ("carlos","rojo",new Terran()); Jugador jugador2 = new Jugador ("dean","azul",new Protoss()); Juego juego = new Juego(jugador1, jugador2, 100, 0); Mapa mapa = juego.getMapa(); jugador1.setDinero(99999, 99999); Creadora barraca = (Creadora) jugador1.colocar(new Barraca(), mapa, 90, 90); Creadora acceso = (Creadora) jugador2.colocar(new Acceso(), mapa, 10, 10); Zealot zealot = new Zealot(); Marine marine = new Marine(); acceso.colocarUnidad(zealot, mapa); jugador2.getUnidadesAlistadas().add(zealot); barraca.colocarUnidad(marine, mapa); jugador2.atacarCon(zealot, marine); } @Test (expected = ExcepcionLaUnidadNoPertenceATuTropa.class) public void intentarAtacarConUnidadDelEnemigoLanzaExcepcion() throws ExcepcionPosicionInvalida, ExcepcionYaHayElementoEnLaPosicion, ExcepcionSuperaLimenteDeArbolesPermitos, ExcepcionNoPudoColocarseEdificio, ExcepcionNoHayLugarParaCrear, ExcepcionEdificioNoPuedeCrearUnidad, ExcepcionErrorPasoDeTurno, ExcepcionElementoFueraDelRangoDeAtaque, ExcepcionLaUnidadNoPertenceATuTropa, ExcepcionConstruccionNoCorrespondiente, ExcepcionRecursoInsuficiente, ExcepcionUnidadNoCorrespondiente, ExcepcionTamanioDelMapaInvalido, ExcepcionFinDeTurnoPorMaximoDeAtaques{ Jugador jugador1 = new Jugador ("carlos","rojo",new Terran()); Jugador jugador2 = new Jugador ("dean","azul",new Protoss()); Juego juego = new Juego(jugador1, jugador2, 100, 0); Mapa mapa = juego.getMapa(); jugador1.setDinero(99999, 99999); Creadora barraca = (Creadora) jugador1.colocar(new Barraca(), mapa, 90, 90); Creadora acceso = (Creadora) jugador2.colocar(new Acceso(), mapa, 10, 10); Zealot zealot = new Zealot(); Marine marine = new Marine(); acceso.colocarUnidad(zealot, mapa); jugador2.getUnidadesAlistadas().add(zealot); barraca.colocarUnidad(marine, mapa); jugador1.getUnidadesAlistadas().add(marine); jugador2.atacarCon(marine, zealot); } @Test (expected = ExcepcionUnidadNoCorrespondiente.class) public void intentarCrearUnidadConEdificioIncorrectoLanzaExcepcion() throws ExcepcionPosicionInvalida, ExcepcionNoHayLugarParaCrear, ExcepcionYaHayElementoEnLaPosicion, ExcepcionUnidadNoCorrespondiente, ExcepcionNoPudoColocarseEdificio, ExcepcionConstruccionNoCorrespondiente, ExcepcionRecursoInsuficiente, ExcepcionSuperaLimenteDeArbolesPermitos, ExcepcionTamanioDelMapaInvalido { Jugador jugador1 = new Jugador ("carlos","rojo",new Terran()); Jugador jugador2 = new Jugador ("dean","azul",new Protoss()); Juego juego = new Juego(jugador1, jugador2, 100, 0); Mapa mapa = juego.getMapa(); jugador1.setDinero(99999, 99999); Creadora barraca = (Creadora) jugador1.colocar(new Barraca(), mapa, 90, 90); Zealot zealot = new Zealot(); barraca.colocarUnidad(zealot, mapa); } @Test (expected = ExcepcionNoPuedeMoverseUnidad.class) public void moverUnidadAPosicionNoValidaLanzaExcepcion() throws ExcepcionNoPuedeMoverseUnidad, ExcepcionLaUnidadNoPertenceATuTropa, ExcepcionNoPudoColocarseEdificio, ExcepcionConstruccionNoCorrespondiente, ExcepcionRecursoInsuficiente, ExcepcionPosicionInvalida, ExcepcionYaHayElementoEnLaPosicion, ExcepcionSuperaLimenteDeArbolesPermitos, ExcepcionNoHayLugarParaCrear, ExcepcionUnidadNoCorrespondiente, ExcepcionTamanioDelMapaInvalido{ Jugador jugador1 = new Jugador ("carlos","rojo",new Protoss()); Jugador jugador2 = new Jugador ("dean","azul",new Protoss()); Juego juego = new Juego(jugador1, jugador2, 100, 0); Mapa mapa = juego.getMapa(); jugador1.setDinero(99999, 99999); Creadora acceso = (Creadora) jugador1.colocar(new Acceso(), mapa, 90, 90); Zealot zealot = new Zealot(); acceso.colocarUnidad(zealot, mapa); jugador1.getUnidadesAlistadas().add(zealot); jugador1.moverUnidadAPosicion(zealot, 101, 101); } @Test (expected = ExcepcionLaUnidadNoPertenceATuTropa.class ) public void intentarMoverUnidadDelEnemigoLanzaExcepcion() throws ExcepcionNoPuedeMoverseUnidad, ExcepcionLaUnidadNoPertenceATuTropa, ExcepcionNoPudoColocarseEdificio, ExcepcionConstruccionNoCorrespondiente, ExcepcionRecursoInsuficiente, ExcepcionPosicionInvalida, ExcepcionYaHayElementoEnLaPosicion, ExcepcionSuperaLimenteDeArbolesPermitos, ExcepcionNoHayLugarParaCrear, ExcepcionUnidadNoCorrespondiente, ExcepcionTamanioDelMapaInvalido{ Jugador jugador1 = new Jugador ("carlos","rojo",new Terran()); Jugador jugador2 = new Jugador ("dean","azul",new Protoss()); Juego juego = new Juego(jugador1, jugador2, 100, 0); Mapa mapa = juego.getMapa(); jugador1.setDinero(99999, 99999); Creadora barraca = (Creadora) jugador1.colocar(new Barraca(), mapa, 90, 90); Creadora acceso = (Creadora) jugador2.colocar(new Acceso(), mapa, 10, 10); Zealot zealot = new Zealot(); Marine marine = new Marine(); acceso.colocarUnidad(zealot, mapa); jugador2.getUnidadesAlistadas().add(zealot); barraca.colocarUnidad(marine, mapa); jugador1.getUnidadesAlistadas().add(marine); jugador1.moverUnidadAPosicion(zealot, 50, 50); } }
6ec881e34f51d36aeb1f67c2b6a9959a17c60316
370a710a4850d9465db60c85b4ed1e30a3c86740
/src/inputoutput/User.java
e09e6792683b0b411793316feec5c9cdcec94238
[]
no_license
KrutkoOleksii/Module09
2c1d6601d9ec2186d3b38b96d3d1f80e1b044418
29408e8fa86af9380abfc8b8f4c756dfe83ca5cf
refs/heads/master
2023-04-19T20:10:07.711362
2021-04-26T23:15:09
2021-04-26T23:15:09
361,383,809
0
0
null
null
null
null
UTF-8
Java
false
false
178
java
package inputoutput; public class User <N,A>{ private N name; private A age; public User(N name, A age) { this.name = name; this.age = age; } }
991482adf5d4bada8b0d19c93b016cb24407756e
21160010b22d0635f880d66aa2dbcf608b125361
/Struts2.1/src/ognl/OgnlBean.java
a9603d6f20456bd4a9c850292cf069b9ce030b8d
[]
no_license
Joker0077/JavaWeb
e7ed702330df23fc5a5c9d3bb1bbdac020236d11
920054c6ca343c74a15de793d0c17990c20d599b
refs/heads/master
2021-01-25T07:40:55.566834
2017-07-04T15:56:14
2017-07-04T15:56:14
93,652,974
0
0
null
null
null
null
UTF-8
Java
false
false
873
java
package ognl; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import lombok.Getter; import lombok.Setter; @Setter @Getter public class OgnlBean { public static final String staticProperty = "This is a static property!"; private String property = "This is a common property!"; private String[] array = { "Jack", "Rose", "Tom" }; private List<String> list = new ArrayList<String>(); private Map<String, String> map = new HashMap<String, String>(); public OgnlBean() { list.add("heifei"); list.add("beijing"); list.add("shanghai"); map.put("home", "111111"); map.put("office", "2222"); map.put("other", "333333"); } public String method() { return "This is a common method!"; } public static String staticMethod() { return "This is a static method"; } }
2bdc922497c66da13f9eba6492dbee2be4dbbd02
be32f80ab459779cd9707c09efb08b6d3284f91c
/app/src/main/java/com/bydesign/hmicontroller/model/SensorData.java
c967717b1236351fe88e5b6ab410d3826369cb5a
[]
no_license
Geeta-Singh/updated-HMI-code
b777c97f9e8903dfdb479eeab3e14daa3cde0835
5fdce201e2352e4fc67e29b9845031f223680a3e
refs/heads/master
2021-08-14T08:24:07.130497
2017-11-15T04:29:27
2017-11-15T04:29:27
110,782,573
0
0
null
null
null
null
UTF-8
Java
false
false
1,243
java
package com.bydesign.hmicontroller.model; import java.sql.Timestamp; /** * Created by Geeta on 1/18/2016. */ public class SensorData { Double Values; Timestamp Ts; String Status; String DiagnosticMsg; String Qcode; String Param; Double val[]; public Double[] getVal() { return val; } public String getParam() { return Param; } public void setParam(String param) { Param = param; } public void setVal(Double[] val) { this.val = val; } public String getQcode() { return Qcode; } public void setQcode(String qcode) { Qcode = qcode; } public Double getValues() { return Values; } public void setValues(Double values) { Values = values; } public Timestamp getTs() { return Ts; } public void setTs(Timestamp ts) { Ts = ts; } public String getStatus() { return Status; } public void setStatus(String status) { Status = status; } public String getDiagnosticMsg() { return DiagnosticMsg; } public void setDiagnosticMsg(String diagnosticMsg) { DiagnosticMsg = diagnosticMsg; } }
ebbc7a8a656cfc99d924533cae28d5c026c4d188
3f39994a6607249646cbb0453749b9fed0ac188f
/src/com/sjtu/contact/converter/DepartmentConverter.java
bfba71c3b05a428f7585e060fceb51e5e1bceed6
[]
no_license
RusonWong/Contact_Android
a8d6602306f6d2925bbf9668d59b0672a9ccee21
17dca35ca4aa40418c5a4d97c53ea5d65c0c59a2
refs/heads/master
2021-01-13T02:37:05.476477
2013-06-03T17:32:57
2013-06-03T17:32:57
null
0
0
null
null
null
null
UTF-8
Java
false
false
431
java
package com.sjtu.contact.converter; import java.util.Map; import com.sjtu.contact.pojo.Department; public class DepartmentConverter extends BaseConverter{ @Override protected Object toObj(Map objMap) { Department d = new Department(); d.setId(Integer.valueOf((String)objMap.get("id"))); d.setInstId(Integer.valueOf((String)objMap.get("instid"))); d.setName((String)objMap.get("name")); return d; } }
d651b4cef21babe6eb6f53e1e2b842dddc2d5f43
a449da9c20726e248cac6a2d698ce194d57ff85f
/src/model/IPlayer.java
06cc439b1c840183b0fcf7f1bace4aaf8f1c0585
[]
no_license
jonshippling/Mastermind
f8bffa0b5be7e9ea139f86ed459da7a4ebefa481
185943c7480520e5baf85950759e83f19b151142
refs/heads/master
2016-09-05T09:45:14.607206
2013-02-12T03:29:55
2013-02-12T03:29:55
null
0
0
null
null
null
null
UTF-8
Java
false
false
927
java
package model; /** * An Interface for the players of the game Mastermind * * @author Jonathon Shippling <[email protected]> * */ public interface IPlayer { public boolean waitIncrement(); public void setWaitTime(long amount); /** * Generates a code to be guessed by the code breaker, * Is only used by human players * * @return returns the color sequence selected */ public Color[] generateCode(); /** * Generates response to a guess made by the code breaker, * Is only used by human players * * @param guess created by the code breaker * @return a move representing the number of pegs the breaker had correct */ public void generateResponse(Move guess); /** * Creates a guess for the code * Used by both humans and computers * */ public Move guess(); /** * Returns the string name of the player, ie Human, Computer Difficulty X * */ public String getName(); }
c77893e7d146be8cfecf70abfd9c86eb82ab46fd
4e556215968bb326772eadee80b2c42e317d8cba
/Atividade01/src/benuthe/giovanni/Transacoes.java
6a1a2bfb78ce0e7999d827423015f8153a761689
[]
no_license
Gibenuthe/ecm251-2021
8d8d6662cc6f059778d176c8329bdc0ec80d8a98
08a4ed663247b2be950ea570bca67367d595d94f
refs/heads/main
2023-06-15T08:24:25.470617
2021-06-26T22:26:40
2021-06-26T22:26:40
341,176,307
0
0
null
null
null
null
UTF-8
Java
false
false
1,107
java
/* NOME: Giovanni Brandini Blanco Benuthe RA: 19.00043-0 */ package benuthe.giovanni; import java.util.Random; import static java.lang.Integer.parseInt; public class Transacoes { public static String gerarQrCode(int id, String nomeUsuario, double valor){ int r = getRandomNumberInRange(1000, 9999); String qrCode = String.join(";", id + "", nomeUsuario, valor+"", r+""); return qrCode; } // Pagamento pelo QR public static boolean transacao(Usuarios pagador, Usuarios recebedor, String qrCode){ // Separando o QR Code String[] dados = qrCode.split(";"); // Valida e transfere if (recebedor.getNome().equals(dados[1]) && recebedor.getC().getIdConta() == parseInt(dados[0])){ pagador.getC().transferirDinheiro(recebedor.getC(),Double.parseDouble(dados[2])); return true; } return false; } // Gerador de aleatorio private static int getRandomNumberInRange(int min, int max){ Random r = new Random(); return r.nextInt((max-min)+1) + min; } }
465440242f53a590a38a9da6d53fd9a8e47f0cc9
995f73d30450a6dce6bc7145d89344b4ad6e0622
/P40_HarmonyOS_2.0.0_Developer_Beta1/src/main/java/com/android/server/power/batterysaver/BatterySaverPolicy.java
43824ebfa71934c1edce0b818a8de0890b0c340f
[]
no_license
morningblu/HWFramework
0ceb02cbe42585d0169d9b6c4964a41b436039f5
672bb34094b8780806a10ba9b1d21036fd808b8e
refs/heads/master
2023-07-29T05:26:14.603817
2021-09-03T05:23:34
2021-09-03T05:23:34
null
0
0
null
null
null
null
UTF-8
Java
false
false
33,359
java
package com.android.server.power.batterysaver; import android.content.ContentResolver; import android.content.Context; import android.database.ContentObserver; import android.net.Uri; import android.os.BatterySaverPolicyConfig; import android.os.Handler; import android.os.PowerSaveState; import android.provider.Settings; import android.text.TextUtils; import android.util.ArrayMap; import android.util.KeyValueListParser; import android.util.Slog; import android.view.accessibility.AccessibilityManager; import com.android.internal.annotations.GuardedBy; import com.android.internal.annotations.VisibleForTesting; import com.android.internal.os.BackgroundThread; import com.android.internal.util.ConcurrentUtils; import com.android.server.power.batterysaver.BatterySaverPolicy; import java.io.PrintWriter; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Objects; public class BatterySaverPolicy extends ContentObserver { static final boolean DEBUG = false; private static final Policy DEFAULT_ADAPTIVE_POLICY = OFF_POLICY; private static final Policy DEFAULT_FULL_POLICY = new Policy(0.5f, true, true, true, false, true, true, true, true, true, false, false, true, true, true, new ArrayMap(), new ArrayMap(), true, true, 2); private static final String KEY_ACTIVATE_DATASAVER_DISABLED = "datasaver_disabled"; private static final String KEY_ACTIVATE_FIREWALL_DISABLED = "firewall_disabled"; private static final String KEY_ADJUST_BRIGHTNESS_DISABLED = "adjust_brightness_disabled"; private static final String KEY_ADJUST_BRIGHTNESS_FACTOR = "adjust_brightness_factor"; private static final String KEY_ADVERTISE_IS_ENABLED = "advertise_is_enabled"; private static final String KEY_ANIMATION_DISABLED = "animation_disabled"; private static final String KEY_AOD_DISABLED = "aod_disabled"; private static final String KEY_CPU_FREQ_INTERACTIVE = "cpufreq-i"; private static final String KEY_CPU_FREQ_NONINTERACTIVE = "cpufreq-n"; private static final String KEY_ENABLE_NIGHT_MODE = "enable_night_mode"; private static final String KEY_FORCE_ALL_APPS_STANDBY = "force_all_apps_standby"; private static final String KEY_FORCE_BACKGROUND_CHECK = "force_background_check"; private static final String KEY_FULLBACKUP_DEFERRED = "fullbackup_deferred"; private static final String KEY_GPS_MODE = "gps_mode"; private static final String KEY_KEYVALUE_DEFERRED = "keyvaluebackup_deferred"; private static final String KEY_LAUNCH_BOOST_DISABLED = "launch_boost_disabled"; private static final String KEY_OPTIONAL_SENSORS_DISABLED = "optional_sensors_disabled"; private static final String KEY_QUICK_DOZE_ENABLED = "quick_doze_enabled"; private static final String KEY_SOUNDTRIGGER_DISABLED = "soundtrigger_disabled"; private static final String KEY_VIBRATION_DISABLED = "vibration_disabled"; @VisibleForTesting static final Policy OFF_POLICY = new Policy(1.0f, false, false, false, false, false, false, false, false, false, false, false, false, false, false, new ArrayMap(), new ArrayMap(), false, false, 0); static final int POLICY_LEVEL_ADAPTIVE = 1; static final int POLICY_LEVEL_FULL = 2; static final int POLICY_LEVEL_OFF = 0; private static final String TAG = "BatterySaverPolicy"; @GuardedBy({"mLock"}) private boolean mAccessibilityEnabled; @GuardedBy({"mLock"}) private String mAdaptiveDeviceSpecificSettings; @GuardedBy({"mLock"}) private Policy mAdaptivePolicy; @GuardedBy({"mLock"}) private String mAdaptiveSettings; private final BatterySavingStats mBatterySavingStats; private final ContentResolver mContentResolver; private final Context mContext; @GuardedBy({"mLock"}) private Policy mDefaultAdaptivePolicy; @GuardedBy({"mLock"}) private String mDeviceSpecificSettings; @GuardedBy({"mLock"}) private String mDeviceSpecificSettingsSource; @GuardedBy({"mLock"}) private boolean mDisableVibrationEffective; @GuardedBy({"mLock"}) private String mEventLogKeys; @GuardedBy({"mLock"}) private Policy mFullPolicy = DEFAULT_FULL_POLICY; private final Handler mHandler; @GuardedBy({"mLock"}) private final List<BatterySaverPolicyListener> mListeners = new ArrayList(); private final Object mLock; @GuardedBy({"mLock"}) private int mPolicyLevel = 0; @GuardedBy({"mLock"}) private String mSettings; public interface BatterySaverPolicyListener { void onBatterySaverPolicyChanged(BatterySaverPolicy batterySaverPolicy); } @Retention(RetentionPolicy.SOURCE) @interface PolicyLevel { } public BatterySaverPolicy(Object lock, Context context, BatterySavingStats batterySavingStats) { super(BackgroundThread.getHandler()); Policy policy = DEFAULT_ADAPTIVE_POLICY; this.mDefaultAdaptivePolicy = policy; this.mAdaptivePolicy = policy; this.mLock = lock; this.mHandler = BackgroundThread.getHandler(); this.mContext = context; this.mContentResolver = context.getContentResolver(); this.mBatterySavingStats = batterySavingStats; } public void systemReady() { ConcurrentUtils.wtfIfLockHeld(TAG, this.mLock); this.mContentResolver.registerContentObserver(Settings.Global.getUriFor("battery_saver_constants"), false, this); this.mContentResolver.registerContentObserver(Settings.Global.getUriFor("battery_saver_device_specific_constants"), false, this); this.mContentResolver.registerContentObserver(Settings.Global.getUriFor("battery_saver_adaptive_constants"), false, this); this.mContentResolver.registerContentObserver(Settings.Global.getUriFor("battery_saver_adaptive_device_specific_constants"), false, this); AccessibilityManager acm = (AccessibilityManager) this.mContext.getSystemService(AccessibilityManager.class); acm.addAccessibilityStateChangeListener(new AccessibilityManager.AccessibilityStateChangeListener() { /* class com.android.server.power.batterysaver.$$Lambda$BatterySaverPolicy$rfw31Sb8JX1OVD2rGHGtCXyfop8 */ @Override // android.view.accessibility.AccessibilityManager.AccessibilityStateChangeListener public final void onAccessibilityStateChanged(boolean z) { BatterySaverPolicy.this.lambda$systemReady$0$BatterySaverPolicy(z); } }); boolean enabled = acm.isEnabled(); synchronized (this.mLock) { this.mAccessibilityEnabled = enabled; } onChange(true, null); } public /* synthetic */ void lambda$systemReady$0$BatterySaverPolicy(boolean enabled) { synchronized (this.mLock) { this.mAccessibilityEnabled = enabled; } refreshSettings(); } @VisibleForTesting public void addListener(BatterySaverPolicyListener listener) { synchronized (this.mLock) { this.mListeners.add(listener); } } /* access modifiers changed from: package-private */ @VisibleForTesting public String getGlobalSetting(String key) { return Settings.Global.getString(this.mContentResolver, key); } /* access modifiers changed from: package-private */ @VisibleForTesting public int getDeviceSpecificConfigResId() { return 17039784; } @Override // android.database.ContentObserver public void onChange(boolean selfChange, Uri uri) { refreshSettings(); } private void refreshSettings() { synchronized (this.mLock) { String setting = getGlobalSetting("battery_saver_constants"); String deviceSpecificSetting = getGlobalSetting("battery_saver_device_specific_constants"); this.mDeviceSpecificSettingsSource = "battery_saver_device_specific_constants"; if (TextUtils.isEmpty(deviceSpecificSetting) || "null".equals(deviceSpecificSetting)) { deviceSpecificSetting = this.mContext.getString(getDeviceSpecificConfigResId()); this.mDeviceSpecificSettingsSource = "(overlay)"; } if (updateConstantsLocked(setting, deviceSpecificSetting, getGlobalSetting("battery_saver_adaptive_constants"), getGlobalSetting("battery_saver_adaptive_device_specific_constants"))) { this.mHandler.post(new Runnable((BatterySaverPolicyListener[]) this.mListeners.toArray(new BatterySaverPolicyListener[0])) { /* class com.android.server.power.batterysaver.$$Lambda$BatterySaverPolicy$7awfvqpjaa389r6FVZsJX98cd8 */ private final /* synthetic */ BatterySaverPolicy.BatterySaverPolicyListener[] f$1; { this.f$1 = r2; } @Override // java.lang.Runnable public final void run() { BatterySaverPolicy.this.lambda$refreshSettings$1$BatterySaverPolicy(this.f$1); } }); } } } public /* synthetic */ void lambda$refreshSettings$1$BatterySaverPolicy(BatterySaverPolicyListener[] listeners) { for (BatterySaverPolicyListener listener : listeners) { listener.onBatterySaverPolicyChanged(this); } } /* access modifiers changed from: package-private */ @GuardedBy({"mLock"}) @VisibleForTesting public void updateConstantsLocked(String setting, String deviceSpecificSetting) { updateConstantsLocked(setting, deviceSpecificSetting, "", ""); } private boolean updateConstantsLocked(String setting, String deviceSpecificSetting, String adaptiveSetting, String adaptiveDeviceSpecificSetting) { String setting2 = TextUtils.emptyIfNull(setting); String deviceSpecificSetting2 = TextUtils.emptyIfNull(deviceSpecificSetting); String adaptiveSetting2 = TextUtils.emptyIfNull(adaptiveSetting); String adaptiveDeviceSpecificSetting2 = TextUtils.emptyIfNull(adaptiveDeviceSpecificSetting); if (setting2.equals(this.mSettings) && deviceSpecificSetting2.equals(this.mDeviceSpecificSettings) && adaptiveSetting2.equals(this.mAdaptiveSettings) && adaptiveDeviceSpecificSetting2.equals(this.mAdaptiveDeviceSpecificSettings)) { return false; } this.mSettings = setting2; this.mDeviceSpecificSettings = deviceSpecificSetting2; this.mAdaptiveSettings = adaptiveSetting2; this.mAdaptiveDeviceSpecificSettings = adaptiveDeviceSpecificSetting2; boolean changed = false; Policy newFullPolicy = Policy.fromSettings(setting2, deviceSpecificSetting2, DEFAULT_FULL_POLICY); if (this.mPolicyLevel == 2 && !this.mFullPolicy.equals(newFullPolicy)) { changed = true; } this.mFullPolicy = newFullPolicy; this.mDefaultAdaptivePolicy = Policy.fromSettings(adaptiveSetting2, adaptiveDeviceSpecificSetting2, DEFAULT_ADAPTIVE_POLICY); if (this.mPolicyLevel == 1 && !this.mAdaptivePolicy.equals(this.mDefaultAdaptivePolicy)) { changed = true; } this.mAdaptivePolicy = this.mDefaultAdaptivePolicy; updatePolicyDependenciesLocked(); return changed; } @GuardedBy({"mLock"}) private void updatePolicyDependenciesLocked() { Policy currPolicy = getCurrentPolicyLocked(); this.mDisableVibrationEffective = currPolicy.disableVibration && !this.mAccessibilityEnabled; StringBuilder sb = new StringBuilder(); if (currPolicy.forceAllAppsStandby) { sb.append("A"); } if (currPolicy.forceBackgroundCheck) { sb.append("B"); } if (this.mDisableVibrationEffective) { sb.append("v"); } if (currPolicy.disableAnimation) { sb.append("a"); } if (currPolicy.disableSoundTrigger) { sb.append("s"); } if (currPolicy.deferFullBackup) { sb.append("F"); } if (currPolicy.deferKeyValueBackup) { sb.append("K"); } if (currPolicy.enableFirewall) { sb.append("f"); } if (currPolicy.enableDataSaver) { sb.append("d"); } if (currPolicy.enableAdjustBrightness) { sb.append("b"); } if (currPolicy.disableLaunchBoost) { sb.append("l"); } if (currPolicy.disableOptionalSensors) { sb.append("S"); } if (currPolicy.disableAod) { sb.append("o"); } if (currPolicy.enableQuickDoze) { sb.append("q"); } sb.append(currPolicy.locationMode); this.mEventLogKeys = sb.toString(); } /* access modifiers changed from: package-private */ public static class Policy { public final float adjustBrightnessFactor; public final boolean advertiseIsEnabled; public final boolean deferFullBackup; public final boolean deferKeyValueBackup; public final boolean disableAnimation; public final boolean disableAod; public final boolean disableLaunchBoost; public final boolean disableOptionalSensors; public final boolean disableSoundTrigger; public final boolean disableVibration; public final boolean enableAdjustBrightness; public final boolean enableDataSaver; public final boolean enableFirewall; public final boolean enableNightMode; public final boolean enableQuickDoze; public final ArrayMap<String, String> filesForInteractive; public final ArrayMap<String, String> filesForNoninteractive; public final boolean forceAllAppsStandby; public final boolean forceBackgroundCheck; public final int locationMode; private final int mHashCode; Policy(float adjustBrightnessFactor2, boolean advertiseIsEnabled2, boolean deferFullBackup2, boolean deferKeyValueBackup2, boolean disableAnimation2, boolean disableAod2, boolean disableLaunchBoost2, boolean disableOptionalSensors2, boolean disableSoundTrigger2, boolean disableVibration2, boolean enableAdjustBrightness2, boolean enableDataSaver2, boolean enableFirewall2, boolean enableNightMode2, boolean enableQuickDoze2, ArrayMap<String, String> filesForInteractive2, ArrayMap<String, String> filesForNoninteractive2, boolean forceAllAppsStandby2, boolean forceBackgroundCheck2, int locationMode2) { char c; this.adjustBrightnessFactor = Math.min(1.0f, Math.max(0.0f, adjustBrightnessFactor2)); this.advertiseIsEnabled = advertiseIsEnabled2; this.deferFullBackup = deferFullBackup2; this.deferKeyValueBackup = deferKeyValueBackup2; this.disableAnimation = disableAnimation2; this.disableAod = disableAod2; this.disableLaunchBoost = disableLaunchBoost2; this.disableOptionalSensors = disableOptionalSensors2; this.disableSoundTrigger = disableSoundTrigger2; this.disableVibration = disableVibration2; this.enableAdjustBrightness = enableAdjustBrightness2; this.enableDataSaver = enableDataSaver2; this.enableFirewall = enableFirewall2; this.enableNightMode = enableNightMode2; this.enableQuickDoze = enableQuickDoze2; this.filesForInteractive = filesForInteractive2; this.filesForNoninteractive = filesForNoninteractive2; this.forceAllAppsStandby = forceAllAppsStandby2; this.forceBackgroundCheck = forceBackgroundCheck2; if (locationMode2 < 0 || 4 < locationMode2) { Slog.e(BatterySaverPolicy.TAG, "Invalid location mode: " + locationMode2); c = 0; this.locationMode = 0; } else { this.locationMode = locationMode2; c = 0; } Object[] objArr = new Object[20]; objArr[c] = Float.valueOf(adjustBrightnessFactor2); objArr[1] = Boolean.valueOf(advertiseIsEnabled2); objArr[2] = Boolean.valueOf(deferFullBackup2); objArr[3] = Boolean.valueOf(deferKeyValueBackup2); objArr[4] = Boolean.valueOf(disableAnimation2); objArr[5] = Boolean.valueOf(disableAod2); objArr[6] = Boolean.valueOf(disableLaunchBoost2); objArr[7] = Boolean.valueOf(disableOptionalSensors2); objArr[8] = Boolean.valueOf(disableSoundTrigger2); objArr[9] = Boolean.valueOf(disableVibration2); objArr[10] = Boolean.valueOf(enableAdjustBrightness2); objArr[11] = Boolean.valueOf(enableDataSaver2); objArr[12] = Boolean.valueOf(enableFirewall2); objArr[13] = Boolean.valueOf(enableNightMode2); objArr[14] = Boolean.valueOf(enableQuickDoze2); objArr[15] = filesForInteractive2; objArr[16] = filesForNoninteractive2; objArr[17] = Boolean.valueOf(forceAllAppsStandby2); objArr[18] = Boolean.valueOf(forceBackgroundCheck2); objArr[19] = Integer.valueOf(locationMode2); this.mHashCode = Objects.hash(objArr); } static Policy fromConfig(BatterySaverPolicyConfig config) { if (config == null) { Slog.e(BatterySaverPolicy.TAG, "Null config passed down to BatterySaverPolicy"); return BatterySaverPolicy.OFF_POLICY; } Map<String, String> deviceSpecificSettings = config.getDeviceSpecificSettings(); return new Policy(config.getAdjustBrightnessFactor(), config.getAdvertiseIsEnabled(), config.getDeferFullBackup(), config.getDeferKeyValueBackup(), config.getDisableAnimation(), config.getDisableAod(), config.getDisableLaunchBoost(), config.getDisableOptionalSensors(), config.getDisableSoundTrigger(), config.getDisableVibration(), config.getEnableAdjustBrightness(), config.getEnableDataSaver(), config.getEnableFirewall(), config.getEnableNightMode(), config.getEnableQuickDoze(), new CpuFrequencies().parseString(deviceSpecificSettings.getOrDefault(BatterySaverPolicy.KEY_CPU_FREQ_INTERACTIVE, "")).toSysFileMap(), new CpuFrequencies().parseString(deviceSpecificSettings.getOrDefault(BatterySaverPolicy.KEY_CPU_FREQ_NONINTERACTIVE, "")).toSysFileMap(), config.getForceAllAppsStandby(), config.getForceBackgroundCheck(), config.getLocationMode()); } static Policy fromSettings(String settings, String deviceSpecificSettings) { return fromSettings(settings, deviceSpecificSettings, BatterySaverPolicy.OFF_POLICY); } static Policy fromSettings(String settings, String deviceSpecificSettings, Policy defaultPolicy) { KeyValueListParser parser = new KeyValueListParser(','); String str = ""; try { parser.setString(deviceSpecificSettings == null ? str : deviceSpecificSettings); } catch (IllegalArgumentException e) { Slog.wtf(BatterySaverPolicy.TAG, "Bad device specific battery saver constants: " + deviceSpecificSettings); } String cpuFreqInteractive = parser.getString(BatterySaverPolicy.KEY_CPU_FREQ_INTERACTIVE, str); String cpuFreqNoninteractive = parser.getString(BatterySaverPolicy.KEY_CPU_FREQ_NONINTERACTIVE, str); if (settings != null) { str = settings; } try { parser.setString(str); } catch (IllegalArgumentException e2) { Slog.wtf(BatterySaverPolicy.TAG, "Bad battery saver constants: " + settings); } return new Policy(parser.getFloat(BatterySaverPolicy.KEY_ADJUST_BRIGHTNESS_FACTOR, defaultPolicy.adjustBrightnessFactor), parser.getBoolean(BatterySaverPolicy.KEY_ADVERTISE_IS_ENABLED, defaultPolicy.advertiseIsEnabled), parser.getBoolean(BatterySaverPolicy.KEY_FULLBACKUP_DEFERRED, defaultPolicy.deferFullBackup), parser.getBoolean(BatterySaverPolicy.KEY_KEYVALUE_DEFERRED, defaultPolicy.deferKeyValueBackup), parser.getBoolean(BatterySaverPolicy.KEY_ANIMATION_DISABLED, defaultPolicy.disableAnimation), parser.getBoolean(BatterySaverPolicy.KEY_AOD_DISABLED, defaultPolicy.disableAod), parser.getBoolean(BatterySaverPolicy.KEY_LAUNCH_BOOST_DISABLED, defaultPolicy.disableLaunchBoost), parser.getBoolean(BatterySaverPolicy.KEY_OPTIONAL_SENSORS_DISABLED, defaultPolicy.disableOptionalSensors), parser.getBoolean(BatterySaverPolicy.KEY_SOUNDTRIGGER_DISABLED, defaultPolicy.disableSoundTrigger), parser.getBoolean(BatterySaverPolicy.KEY_VIBRATION_DISABLED, defaultPolicy.disableVibration), !parser.getBoolean(BatterySaverPolicy.KEY_ADJUST_BRIGHTNESS_DISABLED, !defaultPolicy.enableAdjustBrightness), !parser.getBoolean(BatterySaverPolicy.KEY_ACTIVATE_DATASAVER_DISABLED, !defaultPolicy.enableDataSaver), !parser.getBoolean(BatterySaverPolicy.KEY_ACTIVATE_FIREWALL_DISABLED, !defaultPolicy.enableFirewall), parser.getBoolean(BatterySaverPolicy.KEY_ENABLE_NIGHT_MODE, defaultPolicy.enableNightMode), parser.getBoolean(BatterySaverPolicy.KEY_QUICK_DOZE_ENABLED, defaultPolicy.enableQuickDoze), new CpuFrequencies().parseString(cpuFreqInteractive).toSysFileMap(), new CpuFrequencies().parseString(cpuFreqNoninteractive).toSysFileMap(), parser.getBoolean(BatterySaverPolicy.KEY_FORCE_ALL_APPS_STANDBY, defaultPolicy.forceAllAppsStandby), parser.getBoolean(BatterySaverPolicy.KEY_FORCE_BACKGROUND_CHECK, defaultPolicy.forceBackgroundCheck), parser.getInt(BatterySaverPolicy.KEY_GPS_MODE, defaultPolicy.locationMode)); } public boolean equals(Object obj) { if (this == obj) { return true; } if (!(obj instanceof Policy)) { return false; } Policy other = (Policy) obj; if (Float.compare(other.adjustBrightnessFactor, this.adjustBrightnessFactor) == 0 && this.advertiseIsEnabled == other.advertiseIsEnabled && this.deferFullBackup == other.deferFullBackup && this.deferKeyValueBackup == other.deferKeyValueBackup && this.disableAnimation == other.disableAnimation && this.disableAod == other.disableAod && this.disableLaunchBoost == other.disableLaunchBoost && this.disableOptionalSensors == other.disableOptionalSensors && this.disableSoundTrigger == other.disableSoundTrigger && this.disableVibration == other.disableVibration && this.enableAdjustBrightness == other.enableAdjustBrightness && this.enableDataSaver == other.enableDataSaver && this.enableFirewall == other.enableFirewall && this.enableNightMode == other.enableNightMode && this.enableQuickDoze == other.enableQuickDoze && this.forceAllAppsStandby == other.forceAllAppsStandby && this.forceBackgroundCheck == other.forceBackgroundCheck && this.locationMode == other.locationMode && this.filesForInteractive.equals(other.filesForInteractive) && this.filesForNoninteractive.equals(other.filesForNoninteractive)) { return true; } return false; } public int hashCode() { return this.mHashCode; } } public PowerSaveState getBatterySaverPolicy(int type) { boolean isEnabled; synchronized (this.mLock) { Policy currPolicy = getCurrentPolicyLocked(); PowerSaveState.Builder builder = new PowerSaveState.Builder().setGlobalBatterySaverEnabled(currPolicy.advertiseIsEnabled); switch (type) { case 1: if (!currPolicy.advertiseIsEnabled) { if (currPolicy.locationMode == 0) { isEnabled = false; return builder.setBatterySaverEnabled(isEnabled).setLocationMode(currPolicy.locationMode).build(); } } isEnabled = true; return builder.setBatterySaverEnabled(isEnabled).setLocationMode(currPolicy.locationMode).build(); case 2: return builder.setBatterySaverEnabled(this.mDisableVibrationEffective).build(); case 3: return builder.setBatterySaverEnabled(currPolicy.disableAnimation).build(); case 4: return builder.setBatterySaverEnabled(currPolicy.deferFullBackup).build(); case 5: return builder.setBatterySaverEnabled(currPolicy.deferKeyValueBackup).build(); case 6: return builder.setBatterySaverEnabled(currPolicy.enableFirewall).build(); case 7: return builder.setBatterySaverEnabled(currPolicy.enableAdjustBrightness).setBrightnessFactor(currPolicy.adjustBrightnessFactor).build(); case 8: return builder.setBatterySaverEnabled(currPolicy.disableSoundTrigger).build(); case 9: default: return builder.setBatterySaverEnabled(currPolicy.advertiseIsEnabled).build(); case 10: return builder.setBatterySaverEnabled(currPolicy.enableDataSaver).build(); case 11: return builder.setBatterySaverEnabled(currPolicy.forceAllAppsStandby).build(); case 12: return builder.setBatterySaverEnabled(currPolicy.forceBackgroundCheck).build(); case 13: return builder.setBatterySaverEnabled(currPolicy.disableOptionalSensors).build(); case 14: return builder.setBatterySaverEnabled(currPolicy.disableAod).build(); case 15: return builder.setBatterySaverEnabled(currPolicy.enableQuickDoze).build(); case 16: return builder.setBatterySaverEnabled(currPolicy.enableNightMode).build(); } } } /* access modifiers changed from: package-private */ public boolean setPolicyLevel(int level) { synchronized (this.mLock) { if (this.mPolicyLevel == level) { return false; } if (level == 0 || level == 1 || level == 2) { this.mPolicyLevel = level; updatePolicyDependenciesLocked(); return true; } Slog.wtf(TAG, "setPolicyLevel invalid level given: " + level); return false; } } /* access modifiers changed from: package-private */ public boolean setAdaptivePolicyLocked(Policy p) { if (p == null) { Slog.wtf(TAG, "setAdaptivePolicy given null policy"); return false; } else if (this.mAdaptivePolicy.equals(p)) { return false; } else { this.mAdaptivePolicy = p; if (this.mPolicyLevel != 1) { return false; } updatePolicyDependenciesLocked(); return true; } } /* access modifiers changed from: package-private */ public boolean resetAdaptivePolicyLocked() { return setAdaptivePolicyLocked(this.mDefaultAdaptivePolicy); } private Policy getCurrentPolicyLocked() { int i = this.mPolicyLevel; if (i == 1) { return this.mAdaptivePolicy; } if (i != 2) { return OFF_POLICY; } return this.mFullPolicy; } public int getGpsMode() { int i; synchronized (this.mLock) { i = getCurrentPolicyLocked().locationMode; } return i; } public ArrayMap<String, String> getFileValues(boolean interactive) { ArrayMap<String, String> arrayMap; synchronized (this.mLock) { if (interactive) { arrayMap = getCurrentPolicyLocked().filesForInteractive; } else { arrayMap = getCurrentPolicyLocked().filesForNoninteractive; } } return arrayMap; } public boolean isLaunchBoostDisabled() { boolean z; synchronized (this.mLock) { z = getCurrentPolicyLocked().disableLaunchBoost; } return z; } /* access modifiers changed from: package-private */ public boolean shouldAdvertiseIsEnabled() { boolean z; synchronized (this.mLock) { z = getCurrentPolicyLocked().advertiseIsEnabled; } return z; } public String toEventLogString() { String str; synchronized (this.mLock) { str = this.mEventLogKeys; } return str; } public void dump(PrintWriter pw) { synchronized (this.mLock) { pw.println(); this.mBatterySavingStats.dump(pw, ""); pw.println(); pw.println("Battery saver policy (*NOTE* they only apply when battery saver is ON):"); pw.println(" Settings: battery_saver_constants"); pw.println(" value: " + this.mSettings); pw.println(" Settings: " + this.mDeviceSpecificSettingsSource); pw.println(" value: " + this.mDeviceSpecificSettings); pw.println(" Adaptive Settings: battery_saver_adaptive_constants"); pw.println(" value: " + this.mAdaptiveSettings); pw.println(" Adaptive Device Specific Settings: battery_saver_adaptive_device_specific_constants"); pw.println(" value: " + this.mAdaptiveDeviceSpecificSettings); pw.println(" mAccessibilityEnabled=" + this.mAccessibilityEnabled); pw.println(" mPolicyLevel=" + this.mPolicyLevel); dumpPolicyLocked(pw, " ", "full", this.mFullPolicy); dumpPolicyLocked(pw, " ", "default adaptive", this.mDefaultAdaptivePolicy); dumpPolicyLocked(pw, " ", "current adaptive", this.mAdaptivePolicy); } } private void dumpPolicyLocked(PrintWriter pw, String indent, String label, Policy p) { pw.println(); pw.print(indent); pw.println("Policy '" + label + "'"); pw.print(indent); pw.println(" advertise_is_enabled=" + p.advertiseIsEnabled); pw.print(indent); pw.println(" vibration_disabled:config=" + p.disableVibration); pw.print(indent); StringBuilder sb = new StringBuilder(); sb.append(" vibration_disabled:effective="); sb.append(p.disableVibration && !this.mAccessibilityEnabled); pw.println(sb.toString()); pw.print(indent); pw.println(" animation_disabled=" + p.disableAnimation); pw.print(indent); pw.println(" fullbackup_deferred=" + p.deferFullBackup); pw.print(indent); pw.println(" keyvaluebackup_deferred=" + p.deferKeyValueBackup); pw.print(indent); StringBuilder sb2 = new StringBuilder(); sb2.append(" firewall_disabled="); sb2.append(!p.enableFirewall); pw.println(sb2.toString()); pw.print(indent); StringBuilder sb3 = new StringBuilder(); sb3.append(" datasaver_disabled="); sb3.append(!p.enableDataSaver); pw.println(sb3.toString()); pw.print(indent); pw.println(" launch_boost_disabled=" + p.disableLaunchBoost); pw.println(" adjust_brightness_disabled=" + (p.enableAdjustBrightness ^ true)); pw.print(indent); pw.println(" adjust_brightness_factor=" + p.adjustBrightnessFactor); pw.print(indent); pw.println(" gps_mode=" + p.locationMode); pw.print(indent); pw.println(" force_all_apps_standby=" + p.forceAllAppsStandby); pw.print(indent); pw.println(" force_background_check=" + p.forceBackgroundCheck); pw.println(" optional_sensors_disabled=" + p.disableOptionalSensors); pw.print(indent); pw.println(" aod_disabled=" + p.disableAod); pw.print(indent); pw.println(" soundtrigger_disabled=" + p.disableSoundTrigger); pw.print(indent); pw.println(" quick_doze_enabled=" + p.enableQuickDoze); pw.print(indent); pw.println(" enable_night_mode=" + p.enableNightMode); pw.print(" Interactive File values:\n"); dumpMap(pw, " ", p.filesForInteractive); pw.println(); pw.print(" Noninteractive File values:\n"); dumpMap(pw, " ", p.filesForNoninteractive); } private void dumpMap(PrintWriter pw, String prefix, ArrayMap<String, String> map) { if (map != null) { int size = map.size(); for (int i = 0; i < size; i++) { pw.print(prefix); pw.print(map.keyAt(i)); pw.print(": '"); pw.print(map.valueAt(i)); pw.println("'"); } } } @VisibleForTesting public void setAccessibilityEnabledForTest(boolean enabled) { synchronized (this.mLock) { this.mAccessibilityEnabled = enabled; updatePolicyDependenciesLocked(); } } }
4de9faf17a3a0788297eb9e0f78640a1c7f2680c
9120b200ae2bdab0b781c316c20211b8d12312d9
/common-base-security/src/test/java/org/bremersee/security/core/AuthenticatedUserContextCallerTest.java
04ccb6c2e3088438517fdd4627401f65af077a05
[ "Apache-2.0" ]
permissive
designreuse/common-base
d1f83b4c3bff161357e0e2a293f1c87810d677c3
88ed2d64e1012fef09a3a1db5022f9a76917f689
refs/heads/master
2023-04-20T07:45:44.829089
2021-05-10T06:45:02
2021-05-10T06:45:02
null
0
0
null
null
null
null
UTF-8
Java
false
false
5,985
java
/* * Copyright 2020 the original 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.bremersee.security.core; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.Mockito.when; import java.util.Collection; import java.util.Collections; import java.util.Optional; import java.util.UUID; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.Mockito; import org.springframework.http.ResponseEntity; import org.springframework.security.core.Authentication; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.core.context.SecurityContextImpl; /** * The authenticated user context caller test. * * @author Christian Bremer */ class AuthenticatedUserContextCallerTest { private static final String userId = UUID.randomUUID().toString(); private static final String role = UUID.randomUUID().toString(); private static final String group = UUID.randomUUID().toString(); private static final UserContext expected = UserContext.newInstance( userId, Collections.singleton(role), Collections.singleton(group)); /** * Sets up. */ @BeforeEach void setUp() { SecurityContextHolder.clearContext(); Collection<GrantedAuthority> roles = Collections.singleton(new SimpleGrantedAuthority(role)); Authentication authentication = Mockito.mock(Authentication.class); when(authentication.isAuthenticated()).thenReturn(true); when(authentication.getName()).thenReturn(userId); when(authentication.getAuthorities()).then(invocation -> roles); SecurityContextHolder.setContext(new SecurityContextImpl(authentication)); } /** * Call with required user context. */ @Test void callWithRequiredUserContext() { UserContextCaller caller = new UserContextCaller( () -> Collections.singleton(group), UserContextCaller.FORBIDDEN_SUPPLIER); UserContext actual = caller .callWithRequiredUserContext(userContext -> serviceMethod(userContext, new Object())); assertNotNull(actual); assertEquals(expected, actual); caller = new UserContextCaller( auth -> Collections.singleton(group), UserContextCaller.FORBIDDEN_SUPPLIER); Optional<UserContext> optActual = caller .callWithRequiredUserContext(userContext -> optServiceMethod(userContext, new Object())); assertNotNull(optActual); assertTrue(optActual.isPresent()); assertEquals(expected, optActual.get()); } /** * Call with optional user context. */ @Test void callWithOptionalUserContext() { UserContextCaller caller = new UserContextCaller(() -> Collections.singleton(group)); UserContext actual = caller .callWithOptionalUserContext(userContext -> serviceMethod(userContext, new Object())); assertNotNull(actual); assertEquals(expected, actual); caller = new UserContextCaller(auth -> Collections.singleton(group)); Optional<UserContext> optActual = caller .callWithOptionalUserContext(userContext -> optServiceMethod(userContext, new Object())); assertNotNull(optActual); assertTrue(optActual.isPresent()); assertEquals(expected, optActual.get()); } /** * Response with required user context. */ @Test void responseWithRequiredUserContext() { UserContextCaller caller = new UserContextCaller(() -> Collections.singleton(group), null); ResponseEntity<UserContext> response = caller .responseWithRequiredUserContext(userContext -> serviceMethod(userContext, new Object())); assertNotNull(response); UserContext actual = response.getBody(); assertNotNull(actual); assertEquals(expected, actual); caller = new UserContextCaller(auth -> Collections.singleton(group), null); response = caller .responseWithRequiredUserContext( userContext -> optServiceMethod(userContext, new Object())); assertNotNull(response); actual = response.getBody(); assertNotNull(actual); assertEquals(expected, actual); } /** * Response with optional user context. */ @Test void responseWithOptionalUserContext() { UserContextCaller caller = new UserContextCaller(() -> Collections.singleton(group), null); ResponseEntity<UserContext> response = caller .responseWithOptionalUserContext(userContext -> serviceMethod(userContext, new Object())); assertNotNull(response); UserContext actual = response.getBody(); assertNotNull(actual); assertEquals(expected, actual); caller = new UserContextCaller(auth -> Collections.singleton(group), null); response = caller .responseWithOptionalUserContext( userContext -> optServiceMethod(userContext, new Object())); assertNotNull(response); actual = response.getBody(); assertNotNull(actual); assertEquals(expected, actual); } private UserContext serviceMethod(UserContext userContext, Object arg) { assertNotNull(arg); return userContext; } private Optional<UserContext> optServiceMethod(UserContext userContext, Object arg) { assertNotNull(arg); return Optional.of(userContext); } }
cd34e4eeb41b40bfed234cd8ed0d9d4c0da028dd
6d4bc939c8942d0ea29e58fffb0e742f1f53a12a
/VigenereCipher/VigenereBreaker.java
ef4554b097b7346911a606c692b96035933bcb85
[]
no_license
alana170/DukeCourseRepository
e28402512e1a8b27b82312291ca9afd1c09765d6
0cc40853dff45398a2e6b5fc466a9e2f4366d041
refs/heads/main
2023-01-18T21:20:51.214160
2020-11-24T18:57:18
2020-11-24T18:57:18
315,705,586
0
0
null
null
null
null
UTF-8
Java
false
false
7,065
java
import java.util.*; import edu.duke.*; import java.io.*; public class VigenereBreaker { public String sliceString(String message, int whichSlice, int totalSlices) { //REPLACE WITH YOUR CODE StringBuilder sb = new StringBuilder(); for(int i =0 ;i<=message.length(); i=i+totalSlices){ if(whichSlice+i+1 < message.length()) { String s = message.substring(whichSlice+i, whichSlice+i+1); sb.append(s); } } return sb.toString(); } public int[] tryKeyLength(String encrypted, int klength, char mostCommon) { int[] key = new int[klength]; String[] slices = new String[klength]; CaesarCracker cracker; for(int i=0; i<klength; i++){ slices[i]= sliceString(encrypted, i, klength); cracker = new CaesarCracker(mostCommon); key[i] = cracker.getKey(slices[i]); //int } return key; } public void getKeyFile(int KeyLength,char cm ){ FileResource fr = new FileResource(); String a = fr.asString(); int[] key = tryKeyLength(a,KeyLength, cm); for(int i = 0; i<key.length; i++){ //System.out.println(key[i]); } } public void breakVigenere () { /**WRITE YOUR CODE HERE FileResource fr = new FileResource(); String fileContent = fr.asString();**/ HashSet<String> dictionary= readDictionary(); // breakForLanguage(fileContent, dictionary); mostCommonCharIn(dictionary); // String d = vc.decrypt("Hhdiu LVXNEW uxh WKWVCEW, krg k wbbsqa si Mmwcjiqm"); // System.out.println(d); } public void tester4(){ FileResource fr = new FileResource(); String fileContent = fr.asString(); HashSet<String> dictionary= readDictionary(); int[] keys = tryKeyLength(fileContent, 38, 'e'); VigenereCipher vc = new VigenereCipher(keys); int count = countWords(vc.decrypt(fileContent), dictionary); System.out.println(count); } public HashSet<String> readDictionary() { HashSet<String> words = new HashSet<String>(); FileResource fr = new FileResource(); for (String s : fr.words()){ s = s.toLowerCase(); words.add(s); } return words; } public HashSet<String> NEWreadDictionary(File f ) { FileResource fr = new FileResource(f); HashSet<String> words = new HashSet<String>(); for (String s : fr.words()){ s = s.toLowerCase(); words.add(s); } return words; } public int countWords(String message,HashSet<String> dictionary){ int count = 0; String[] ewords = message.toLowerCase().split("\\W+"); for (int i = 0; i<ewords.length ; i++){ if(dictionary.contains(ewords[i])){ count++; } } return count; } public void breakForLanguage(String encrypted, HashSet<String>dictionary){ int maxVal = 0; int correctKeyL = 0 ; int [] keys; for (int i = 1 ; i<=100 ; i++){ keys = tryKeyLength(encrypted,i,'e'); VigenereCipher vc = new VigenereCipher(keys); int a =countWords(vc.decrypt(encrypted), dictionary); if ( maxVal < a ) { maxVal = a; correctKeyL = i; } } keys = tryKeyLength(encrypted, correctKeyL, 'e'); // loop keys String s = ""; String ks = ""; String alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; for(int i = 0 ; i<keys.length; i++){ ks = ks + ", " + keys[i] ; s = s + Character.toString(alphabet.charAt(keys[i])); } VigenereCipher vc = new VigenereCipher(keys); String decrypted = vc.decrypt(encrypted); System.out.println("Key Set: " + ks +" Key Word: "+ s) ; if (decrypted.length() < 100){ System.out.println("Key Length = " + correctKeyL+ " " +maxVal + " : " + vc.decrypt(encrypted)); } else System.out.println("Key Length = " + correctKeyL+ " " +maxVal + " : " + vc.decrypt(encrypted).substring(0,99)); } public void breakForLanguage2(String encrypted, HashSet<String>dictionary, char mostCommon){ int maxVal = 0; int correctKeyL = 0 ; int [] keys; for (int i = 1 ; i<=100 ; i++){ keys = tryKeyLength(encrypted,i,mostCommon); VigenereCipher vc = new VigenereCipher(keys); int a =countWords(vc.decrypt(encrypted), dictionary); if ( maxVal < a ) { maxVal = a; correctKeyL = i; } } keys = tryKeyLength(encrypted, correctKeyL, mostCommon); // loop keys String s = ""; String ks = ""; String alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; for(int i = 0 ; i<keys.length; i++){ ks = ks + ", " + keys[i] ; s = s + Character.toString(alphabet.charAt(keys[i])); } VigenereCipher vc = new VigenereCipher(keys); String decrypted = vc.decrypt(encrypted); System.out.println("Key Set: " + ks +" Key Word: "+ s) ; if (decrypted.length() < 100){ System.out.println("Key Length = " + correctKeyL+ " " +maxVal + " : " + vc.decrypt(encrypted)); } else System.out.println("Key Length = " + correctKeyL+ " " +maxVal + " : " + vc.decrypt(encrypted).substring(0,99)); } public char mostCommonCharIn(HashSet<String> dictionary){ HashMap<Character, Integer> charCount = new HashMap<Character, Integer>(); //dictionary = new HashSet<String>(); for (String words: dictionary) { // process each item in turn words = words.toLowerCase(); //System.out.println(words); for (char a : words.toCharArray()) { if(!charCount.containsKey(a)){ charCount.put(a,1); } else{ charCount.put(a,charCount.get(a) +1); } } } int max = 0; char maxChar = ' '; for (Character b: charCount.keySet()){ int i = charCount.get(b); //value if(max<i){ max= i; maxChar = b; } } System.out.println("Max Char = " + maxChar+ " It has a count of "+max); return maxChar; } public void breakForAllLangs(String encrypted,HashMap<String,HashSet<String>> lang){ for(String dictionary : lang.keySet()){ char common = mostCommonCharIn(lang.get(dictionary)); System.out.println("Selected Language is " + dictionary); breakForLanguage2(encrypted, lang.get(dictionary), common); System.out.println("------------------------------------------------------------------------------"); } } public void TESTER() { DirectoryResource dr = new DirectoryResource(); HashMap<String, HashSet<String>> hm= new HashMap<String, HashSet<String>>(); //String decrypted = ""; for (File f : dr.selectedFiles()){ String filename = f.getName(); System.out.println(filename); HashSet <String> dictionary = NEWreadDictionary(f); hm.put(filename, dictionary); } FileResource f = new FileResource(); String encrypt = f.asString();//content breakForAllLangs(encrypt, hm); } }
606ad6644f7246244e7e7557307a023f723a1022
ba6393e1b3140e10e8c6c7e1325acca9bfc869ff
/Reta-x/src/zigtraka/nfc/reta_x/ProductInformation.java
b2c1ae4772762cc5f449c8daf51fc78919bfa67e
[]
no_license
rishiwalanjkar/zigtraka
a9d8d9e7f2bbaf383ec3c30602ea2b4335c54c46
56a3ee48e620970b94008f152027d7bf7ef81594
refs/heads/master
2020-06-01T03:46:32.741720
2013-11-19T12:16:42
2013-11-19T12:16:42
null
0
0
null
null
null
null
UTF-8
Java
false
false
4,996
java
package zigtraka.nfc.reta_x; import java.util.Locale; import db.Access.DbForProductInformationActivity; import android.nfc.NfcAdapter; import android.nfc.Tag; import android.os.Bundle; import android.app.Activity; import android.content.Intent; import android.speech.tts.TextToSpeech; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.ImageButton; import android.widget.TextView; public class ProductInformation extends BaseActivity implements TextToSpeech.OnInitListener { String TagID, TagContents; String[] TagDetails; Bundle bundle; TextView ProductCode, ProductModel, Gemstone, Price, Carat, Cut, Type, Wear, MakingCharges; TextView Description, Welcome; Button back; ImageButton voice; TextToSpeech textToSpeech_Obj; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); textToSpeech_Obj = new TextToSpeech(getApplicationContext(), this); bundle = getIntent().getExtras(); if (bundle != null) { TagID = bundle.getString("TagID"); TagContents = bundle.getString("TagContents"); } if (NfcAdapter.ACTION_TECH_DISCOVERED.equals(getIntent().getAction())) ScanTag(getIntent()); // Welcome note....... Welcome = (TextView) findViewById(R.id.product_information_welcome); if (TagContents != null) Welcome.setText("Welcome To " + TagContents + " Store"); TagDetails = DbForProductInformationActivity.getTagDetails(TagID); ProductCode = (TextView) findViewById(R.id.product_information_product_code); ProductModel = (TextView) findViewById(R.id.product_information_product_model); Gemstone = (TextView) findViewById(R.id.product_information_gemestone); Price = (TextView) findViewById(R.id.product_information_price); Carat = (TextView) findViewById(R.id.product_information_carat); Cut = (TextView) findViewById(R.id.product_information_cut); Type = (TextView) findViewById(R.id.product_information_type); Wear = (TextView) findViewById(R.id.product_information_wear); MakingCharges = (TextView) findViewById(R.id.product_information_making_Charges); Description = (TextView) findViewById(R.id.product_information_description); if (TagDetails != null) { ProductCode.setText(TagDetails[7]); ProductModel.setText(TagDetails[4]); Gemstone.setText(TagDetails[8]); Price.setText(TagDetails[2]); Carat.setText(TagDetails[13]); Cut.setText(TagDetails[10]); Type.setText(TagDetails[11]); Wear.setText(TagDetails[12]); MakingCharges.setText(TagDetails[5]); Description.setText(TagDetails[9]); } back = (Button) findViewById(R.id.product_information_backbutton); back.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method textToSpeech_Obj.stop(); textToSpeech_Obj.shutdown(); finish(); } }); voice = (ImageButton) findViewById(R.id.product_information_imageButton); voice.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub textToSpeech_Obj.speak(Description.getText().toString(), TextToSpeech.QUEUE_FLUSH, null); } }); } public static String bin2hex(byte[] inarray) { // TODO Auto-generated method stub // parsing tagid to hex... int i, j, in; String[] hex = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F" }; String out = ""; for (j = 0; j < inarray.length; ++j) { in = (int) inarray[j] & 0xff; i = (in >> 4) & 0x0f; out += hex[i]; i = in & 0x0f; out += hex[i]; } return out; } @Override public void onInit(int status) { // TODO Auto-generated method stub if (status == TextToSpeech.SUCCESS) { textToSpeech_Obj.setSpeechRate((float) 0.6); int result = textToSpeech_Obj.setLanguage(Locale.UK); textToSpeech_Obj.speak("Welcome To " + TagContents + " Store", TextToSpeech.QUEUE_FLUSH, null); if (result == TextToSpeech.LANG_MISSING_DATA || result == TextToSpeech.LANG_NOT_SUPPORTED) { Log.e("error", "Language is not supported"); } } else { Log.e("error", "Failed to Initilize!"); } } @Override protected void onDestroy() { // TODO Auto-generated method stub super.onDestroy(); textToSpeech_Obj.stop(); textToSpeech_Obj.shutdown(); finish(); } public void ScanTag(Intent intent) { Tag detectedTag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG); TagID = ProductInformation.bin2hex(detectedTag.getId()).toString() .toLowerCase(); TagContents = GetProductInfo.readdata( GetProductInfo.getNdefMessages(intent)).toString(); } @Override protected int getResourceLayoutId() { // TODO Auto-generated method stub return R.layout.product_information; } }
b9083343bfec4e6fe53374f221bfaf37851895a7
e526a7434373d55a18aad4767044328315fec4b7
/src/com/shimne/zoopuweixin/common/PropertiesTool.java
746b8c60990ab12ce85bda8ccd193612851ec43f
[]
no_license
shimne/weixin
a6b79facd82d560cf05a21d4c28978866f9ca977
21cb10fd3add0409d4e49c1b3b72116c1c4cb98d
refs/heads/master
2020-08-05T15:07:02.709278
2016-09-07T00:53:02
2016-09-07T00:53:02
67,558,654
0
0
null
null
null
null
GB18030
Java
false
false
1,058
java
package com.shimne.zoopuweixin.common; import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.util.Properties; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class PropertiesTool { private static Logger log = LoggerFactory.getLogger(PropertiesTool.class); public static Properties properties; public void init(String filePath) { log.info("初始化相关属性开始。"); properties = new Properties(); File file = new File(filePath); if (file.isFile()) { InputStream is = null; try { is = new BufferedInputStream(new FileInputStream(file)); properties.load(is); } catch (IOException e) { e.printStackTrace(); } finally { try { if (is != null) { is.close(); } } catch (IOException e) { e.printStackTrace(); } } } log.info("初始化相关属性结束。"); } }
7d6ae721d03886dca07435cd3a101a6cfeb0ab3f
9e65827f57947ce2e6a45d2aa3eaa1b88ce69a56
/src/main/java/com/javafortesters/solution/staticClass.java
31c2bac4616f84f7160ec90037fa6f5ad2866e00
[ "MIT" ]
permissive
PramodKumarYadav/HackerRank
f520fc1182e17c08d9c4423c3e60222a60e3dac4
a01fd438308b6e61cf135132e6207a7798899521
refs/heads/master
2020-04-28T10:32:36.868334
2019-03-12T12:27:26
2019-03-12T12:27:26
175,205,045
0
0
null
null
null
null
UTF-8
Java
false
false
698
java
package com.javafortesters.solution; import java.util.Scanner; public class staticClass { static int B ; static int H ; static boolean flag = true ; static { Scanner scanner = new Scanner(System.in); B = scanner.nextInt(); scanner.nextLine(); H = scanner.nextInt(); scanner.close(); if((B<=0 || H<=0) || (B>100 || H>100) ){ flag = false; System.out.println("java.lang.Exception: Breadth and height must be positive"); } } public static void main(String[] args){ if(flag){ int area=B*H; System.out.print(area); } }//end of main }//end of class
ac6fa3402ec029a89acdec132effbf544f370222
655afe263978b704f6c76abb4ae1116db20efe0c
/Heap/TestHeap.java
89f6f45dbdedad7c4295ea8c7141e617c54e8fea
[]
no_license
antonykaavya/COM212
cbd4ecf2a934cf968c4fc9c40036d3479c0db156
9549479ef08f7b421001c3a4007f86e6c117c509
refs/heads/master
2020-03-23T03:34:03.654898
2019-01-09T00:47:03
2019-01-09T00:47:03
141,037,180
0
0
null
null
null
null
UTF-8
Java
false
false
1,229
java
/* Kaavya Antony COM 212 4/19/16 Programming Assignment 8: Test Code for Priority Queue/Heap */ public class TestHeap{ public static void main(String[] args){ Heap priorityQ = new Heap(); Node xNode = new Node("Jane", 123456789); Node yNode = new Node("Joe", 934567890); Node zNode = new Node("Jack", 223452234); Node kNode = new Node("Jill", 934567856); Node aNode = new Node("Abe", 123456788); Node bNode = new Node("Beth", 934567898); Node cNode = new Node("Chuck", 223452238); Node dNode = new Node("Dot", 934567858); Node mNode = new Node("Mike", 723452237); Node nNode = new Node("Nick", 734567857); Node oNode = new Node("Otis", 734562222); System.out.println("isEmptyHeap = " + priorityQ.isEmpty()); priorityQ.insert(xNode); priorityQ.insert(yNode); priorityQ.insert(zNode); priorityQ.insert(kNode); priorityQ.insert(aNode); priorityQ.insert(bNode); priorityQ.insert(cNode); priorityQ.insert(dNode); priorityQ.insert(mNode); priorityQ.insert(nNode); priorityQ.insert(oNode); System.out.println("isEmptyHeap = " + priorityQ.isEmpty()); priorityQ.printHeap(); System.out.println(); priorityQ.findMin(); priorityQ.deleteMin(); priorityQ.printHeap(); } }
d26c975e03814444b52c22a65f45618496381a1c
e5ac268d9e0ea031b96d7f41b67c70d63cb770dc
/src/main/java/com/github/hilcode/regex/internal/Program.java
317a85104f0ee8cb0992b027c1ca01d318fdb364
[]
no_license
hilcode/regex
2ac72c174bab195deec2e62c313186535129b129
1f12368b0e10b5af5ad8b152f6f2950d3a7c9f0c
refs/heads/master
2021-01-21T05:28:44.734036
2017-04-20T06:58:49
2017-04-20T06:58:49
83,191,230
0
0
null
null
null
null
UTF-8
Java
false
false
1,141
java
/* * Copyright (C) 2014 H.C. Wijbenga * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.hilcode.regex.internal; import static java.lang.String.format; import java.util.List; import com.google.common.collect.ImmutableList; public final class Program { public final ImmutableList<Instruction> instructions; public Program(final List<Instruction> instructions) { this.instructions = ImmutableList.copyOf(instructions); } public void print() { for (int i = 0; i < this.instructions.size(); i++) { System.out.println(format("%3d %s", Integer.valueOf(i), this.instructions.get(i))); } } }
50086e233af78cf17f06c259ad193204f411798a
7ffb15f77ed09b5308d870c72bf9a8e12a71f223
/MultiTenant_Prj/src/main/java/com/tekion/tenant/MultiTenant_Prj/controller/ModelController.java
660ed16fe07f40d6b4d87254dce614b3d3a534ac
[]
no_license
pvetrivel/Multitenant_Jan18
ee558c958f20153b11e1d1d14f132e5f75f284b3
eac58e98dcc5ce45e49d63fe3f5e6a4b253e00eb
refs/heads/master
2020-04-17T07:32:49.150160
2019-01-22T09:08:21
2019-01-22T09:08:21
166,374,249
0
0
null
2019-01-25T06:52:50
2019-01-18T08:52:10
Java
UTF-8
Java
false
false
2,195
java
package com.tekion.tenant.MultiTenant_Prj.controller; import java.sql.SQLException; import java.util.Random; import com.tekion.tenant.MultiTenant_Prj.repo.ModelRepo; import lombok.extern.slf4j.Slf4j; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import com.tekion.tenant.MultiTenant_Prj.model.Model; import org.springframework.beans.factory.annotation.Autowired; import com.tekion.tenant.MultiTenant_Prj.multiTenant.MultiTenantManager; @Slf4j @RestController @RequestMapping("/models") public class ModelController { @Autowired private ModelRepo modelService; private final MultiTenantManager tenantManager; @Autowired public ModelController(MultiTenantManager tenantManager) { //this.modelService = modelService; this.tenantManager = tenantManager; } // Get using tenant Id in an api call @GetMapping("/get/{tenantId}") public ResponseEntity<?> getAll(@PathVariable String tenantId) throws SQLException { setTenant(tenantId); return ResponseEntity.ok(modelService.findAll()); } // Post using tenant Id in an api call @PostMapping("/save/{tenantId}") public ResponseEntity<?> save(@RequestBody Model model, @PathVariable String tenantId) throws SQLException{ setTenant(tenantId); model.setTenant(tenantId); return ResponseEntity.ok(modelService.save(model)); } //Post by hashcode value @PostMapping("/create") public ResponseEntity<?> create(@RequestBody Model model) throws SQLException { String tenantId="tenant"+getTenantId(model); setTenant(tenantId); model.setTenant(tenantId); return ResponseEntity.ok(modelService.save(model)); } //Setting TenantId to Thread Local private void setTenant(String tenantId) throws SQLException { tenantManager.setCurrentTenant(tenantId); } // Used to create tenant Id using hashcode value private long getTenantId(Model model){ long id=Integer.toUnsignedLong(model.hashCode())%10; if(id==0){ Random rn = new Random(); id = rn.nextInt(9) + 1; } return id; } } //Try to get using Thread local value // @GetMapping("/collect") // public ResponseEntity<?> get() { // return ResponseEntity.ok(modelService.findAll()); // }
903d6d006bd3dca1b1c0a4bafe5715f7dec9e613
97b23af4d9042f57a64fc96d2846b72f1d7dc909
/AndroidStudioProjects/MovieDB-master/MovieDB-master/MovieDB/app/src/main/java/com/example/MovieDB/adapter/TrailersAdapter.java
603c62fb69c9a37765bec6f6d89ab9e7822ba1de
[]
no_license
cqrita/exampletest
4e1aa159118beeb6dea893f4528927cf6c26d16d
893d2de1d1c96d28e4490a5ca748c25656430c43
refs/heads/master
2023-02-25T13:48:55.020006
2021-02-04T08:45:21
2021-02-04T08:45:21
335,892,585
0
0
null
null
null
null
UTF-8
Java
false
false
2,942
java
package com.example.MovieDB.adapter; import android.content.Context; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.recyclerview.widget.RecyclerView; import com.example.MovieDB.R; import com.example.MovieDB.data.Trailer; import com.pierfrancescosoffritti.androidyoutubeplayer.core.player.YouTubePlayer; import com.pierfrancescosoffritti.androidyoutubeplayer.core.player.listeners.AbstractYouTubePlayerListener; import com.pierfrancescosoffritti.androidyoutubeplayer.core.player.views.YouTubePlayerView; import java.util.List; /** * @author Yassin Ajdi. */ public class TrailersAdapter extends RecyclerView.Adapter<TrailersAdapter.RecyclerViewHolders> { private List<Trailer> trailerList; public Context context; private YouTubePlayerView videoTrailerView; private com.pierfrancescosoffritti.androidyoutubeplayer.core.player.YouTubePlayer videoTrailer; public class RecyclerViewHolders extends RecyclerView.ViewHolder { public TextView trailerName; private String currentVideoId; public RecyclerViewHolders(View view) { super(view); videoTrailerView = view.findViewById(R.id.videoTrailer); trailerName =view.findViewById(R.id.trailerName); videoTrailerView.addYouTubePlayerListener(new AbstractYouTubePlayerListener() { public void onReady(@NonNull YouTubePlayer initializedYouTubePlayer) { videoTrailer = initializedYouTubePlayer; videoTrailer.cueVideo(currentVideoId, 0); } }); } void cueVideo(String videoId) { currentVideoId = videoId; if(videoTrailer == null) return; videoTrailer.cueVideo(videoId, 0); } } public TrailersAdapter(Context context, List<Trailer> trailerList) { this.trailerList = trailerList; this.context =context; } public void setTrailerList(List<Trailer> trailerList) { this.trailerList = trailerList; } @NonNull @Override public RecyclerViewHolders onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.trailer, parent, false); return new RecyclerViewHolders(itemView); } @Override public void onBindViewHolder(@NonNull TrailersAdapter.RecyclerViewHolders holder, int position) { final Trailer trailer = trailerList.get(position); Log.d("trailer","https://www.youtube.com/watch?v="+trailer.getKey()); holder.cueVideo(trailerList.get(position).getKey()); holder.trailerName.setText(trailer.getName()); } @Override public int getItemCount() { return trailerList.size(); } }
a6a83fb48f0e85649fb614a050aa69cf48a4da6d
81277d0bd4db9416feca7c9e2a4ea43bd3059111
/openCVVer410/src/main/java/org/opencv/ximgproc/DisparityWLSFilter.java
804f27d4ac19415074d754c348a1f4ddba9fdd70
[]
no_license
phucdeveloper/Project_Detect_Text
0c23f27cad4042dcded0b91281ce218b73d68ad5
2c25d9ec696785887b500fd00edb59929218887f
refs/heads/master
2022-12-02T22:57:45.026455
2020-08-26T10:46:52
2020-08-26T10:46:52
288,992,475
1
0
null
null
null
null
UTF-8
Java
false
false
5,098
java
// // This file is auto-generated. Please don't modify it! // package org.opencv.ximgproc; import org.opencv.core.Mat; import org.opencv.core.Rect; // C++: class DisparityWLSFilter //javadoc: DisparityWLSFilter public class DisparityWLSFilter extends DisparityFilter { protected DisparityWLSFilter(long addr) { super(addr); } // internal usage only public static DisparityWLSFilter __fromPtr__(long addr) { return new DisparityWLSFilter(addr); } // // C++: Mat cv::ximgproc::DisparityWLSFilter::getConfidenceMap() // //javadoc: DisparityWLSFilter::getConfidenceMap() public Mat getConfidenceMap() { Mat retVal = new Mat(getConfidenceMap_0(nativeObj)); return retVal; } // // C++: Rect cv::ximgproc::DisparityWLSFilter::getROI() // //javadoc: DisparityWLSFilter::getROI() public Rect getROI() { Rect retVal = new Rect(getROI_0(nativeObj)); return retVal; } // // C++: double cv::ximgproc::DisparityWLSFilter::getLambda() // //javadoc: DisparityWLSFilter::getLambda() public double getLambda() { double retVal = getLambda_0(nativeObj); return retVal; } // // C++: double cv::ximgproc::DisparityWLSFilter::getSigmaColor() // //javadoc: DisparityWLSFilter::getSigmaColor() public double getSigmaColor() { double retVal = getSigmaColor_0(nativeObj); return retVal; } // // C++: int cv::ximgproc::DisparityWLSFilter::getDepthDiscontinuityRadius() // //javadoc: DisparityWLSFilter::getDepthDiscontinuityRadius() public int getDepthDiscontinuityRadius() { int retVal = getDepthDiscontinuityRadius_0(nativeObj); return retVal; } // // C++: int cv::ximgproc::DisparityWLSFilter::getLRCthresh() // //javadoc: DisparityWLSFilter::getLRCthresh() public int getLRCthresh() { int retVal = getLRCthresh_0(nativeObj); return retVal; } // // C++: void cv::ximgproc::DisparityWLSFilter::setDepthDiscontinuityRadius(int _disc_radius) // //javadoc: DisparityWLSFilter::setDepthDiscontinuityRadius(_disc_radius) public void setDepthDiscontinuityRadius(int _disc_radius) { setDepthDiscontinuityRadius_0(nativeObj, _disc_radius); return; } // // C++: void cv::ximgproc::DisparityWLSFilter::setLRCthresh(int _LRC_thresh) // //javadoc: DisparityWLSFilter::setLRCthresh(_LRC_thresh) public void setLRCthresh(int _LRC_thresh) { setLRCthresh_0(nativeObj, _LRC_thresh); return; } // // C++: void cv::ximgproc::DisparityWLSFilter::setLambda(double _lambda) // //javadoc: DisparityWLSFilter::setLambda(_lambda) public void setLambda(double _lambda) { setLambda_0(nativeObj, _lambda); return; } // // C++: void cv::ximgproc::DisparityWLSFilter::setSigmaColor(double _sigma_color) // //javadoc: DisparityWLSFilter::setSigmaColor(_sigma_color) public void setSigmaColor(double _sigma_color) { setSigmaColor_0(nativeObj, _sigma_color); return; } @Override protected void finalize() throws Throwable { delete(nativeObj); } // C++: Mat cv::ximgproc::DisparityWLSFilter::getConfidenceMap() private static native long getConfidenceMap_0(long nativeObj); // C++: Rect cv::ximgproc::DisparityWLSFilter::getROI() private static native double[] getROI_0(long nativeObj); // C++: double cv::ximgproc::DisparityWLSFilter::getLambda() private static native double getLambda_0(long nativeObj); // C++: double cv::ximgproc::DisparityWLSFilter::getSigmaColor() private static native double getSigmaColor_0(long nativeObj); // C++: int cv::ximgproc::DisparityWLSFilter::getDepthDiscontinuityRadius() private static native int getDepthDiscontinuityRadius_0(long nativeObj); // C++: int cv::ximgproc::DisparityWLSFilter::getLRCthresh() private static native int getLRCthresh_0(long nativeObj); // C++: void cv::ximgproc::DisparityWLSFilter::setDepthDiscontinuityRadius(int _disc_radius) private static native void setDepthDiscontinuityRadius_0(long nativeObj, int _disc_radius); // C++: void cv::ximgproc::DisparityWLSFilter::setLRCthresh(int _LRC_thresh) private static native void setLRCthresh_0(long nativeObj, int _LRC_thresh); // C++: void cv::ximgproc::DisparityWLSFilter::setLambda(double _lambda) private static native void setLambda_0(long nativeObj, double _lambda); // C++: void cv::ximgproc::DisparityWLSFilter::setSigmaColor(double _sigma_color) private static native void setSigmaColor_0(long nativeObj, double _sigma_color); // native support for java finalize() private static native void delete(long nativeObj); }
9f9d768fec08ff8a1575bbec4b40b463ab9e388d
ed8d91dea9020f739d370dbccf7149e28cc0d5c3
/Part09/part09-Part09_02.PersonAndSubclasses/src/main/java/Teacher.java
31f6e1769554a7e2bd37a4a6080f264fbdd53ead
[]
no_license
jsmitthimedhin/mooc-java-programming-ii
aff8bd256b228fb567eb8bda5862b4dbf7ff3e30
50d0f33d761a096d1c01ca07b5ffd312a05da85d
refs/heads/main
2023-06-06T12:07:08.000536
2021-07-06T08:45:30
2021-07-06T08:45:30
370,261,149
0
0
null
null
null
null
UTF-8
Java
false
false
553
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. */ /** * * @author OS */ public class Teacher extends Person { private int salary; public Teacher(String name, String address, int salary) { super(name, address); this.salary = salary; } public String toString() { return super.toString() + "\n" + " salary " + salary + " euro/month"; } }
b36b39af4c959c5c09f00b0f540dd27eaa2288ea
02260ebd1b3834d778d759a7a4abb2bf59e7b064
/src/main/java/com/niit/ecommercemain/model/product.java
1829bde5032a8d1a88e47814a02c8aa3cb9f21f4
[]
no_license
ANJUPANIL/s171163400017_anju
7d887b72101bf2dbfe30434d7e19ed02782753e1
0d988daf03c39550db148a5d23c3a3874d815f2b
refs/heads/master
2020-04-15T12:42:01.793252
2016-09-28T17:40:30
2016-09-28T17:40:30
62,557,840
0
0
null
null
null
null
UTF-8
Java
false
false
4,159
java
package com.niit.ecommercemain.model; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.Serializable; import java.util.Set; import java.util.UUID; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.OneToMany; import javax.persistence.OneToOne; import javax.persistence.Table; import org.hibernate.validator.constraints.NotEmpty; import org.springframework.stereotype.Component; import org.springframework.web.multipart.MultipartFile; @Entity @Table(name="Product") @Component public class product implements Serializable { private static final long serialVersionUID = 1L; @Id @Column(name="product_id") private String id; @Column(name="product_name") @NotEmpty(message="Please enter product name") private String name; @Column(name="product_des") @NotEmpty(message="Please enter product description") private String des; @Column(name="product_type") @NotEmpty(message="Please select product type") private String product_type; @OneToOne @JoinColumn(name="category_id") private category categoryobj ; public category getCategoryobj() { return categoryobj; } public void setCategoryobj(category categoryobj) { this.categoryobj = categoryobj; } public brand getBrands() { return brands; } public void setBrands(brand brands) { this.brands = brands; } public supplier getSup() { return sup; } public void setSup(supplier sup) { this.sup = sup; } @OneToOne @JoinColumn(name="brand_id") private brand brands; @OneToOne @JoinColumn(name="sup_id") private supplier sup ; @Column(name="product_price") private int price; @Column(name="product_discount") private double discount; public boolean isStatus() { return status; } public void setStatus(boolean status) { this.status = status; } transient private MultipartFile prdfile; @Column(name="status") private boolean status; public MultipartFile getPrdfile() { return prdfile; } public void setPrdfile(MultipartFile prdfile) { this.prdfile = prdfile; } public double getDiscount() { return discount; } public void setDiscount(double discount) { this.discount = discount; } @Column(name="product_image") private String product_image; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getDes() { return des; } public void setDes(String des) { this.des = des; } public String getProduct_type() { return product_type; } public void setProduct_type(String product_type) { this.product_type = product_type; } public int getPrice() { return price; } public void setPrice(int price) { this.price = price; } public String getProduct_image() { return product_image; } public void setProduct_image(String product_image) { this.product_image = product_image; } public product() { this.id = "P" + UUID.randomUUID().toString().substring(30).toUpperCase(); } public String getFilePath(String path1,String contextPath) { String fileName=null; if(!prdfile.isEmpty()) { try { fileName=prdfile.getOriginalFilename(); byte[] bytes = prdfile.getBytes(); String npath=path1+"\\WEB-INF\\resources\\"+fileName; System.out.print("path :" + npath); BufferedOutputStream buffStream = new BufferedOutputStream(new FileOutputStream(new File(npath))); buffStream.write(bytes); buffStream.close(); String dbfilename=contextPath+"/resources/"+fileName; setProduct_image(dbfilename); return dbfilename; } catch(Exception e) { System.out.println(e.getMessage()); return "fail"; } } else { return "fail"; } } }
4f1dc9a88e45349fa5662215ce56eae92793385e
23d4b527a4468419725a5a28383dc4d35686f859
/app/src/main/java/com/wo1haitao/activities/VerifyActivity.java
2540cd49fb8124c65d0c72b952becf2f50cb79cd
[]
no_license
SunShine265/w1
4d2a5524135db04dd594d16b1b61d792e44a1c07
b717daf6a71cc414b4d585b7886b625ca90cde46
refs/heads/master
2020-03-22T11:10:15.524261
2018-07-06T08:06:01
2018-07-06T08:06:01
139,952,785
0
0
null
null
null
null
UTF-8
Java
false
false
13,352
java
package com.wo1haitao.activities; import android.Manifest; import android.app.ProgressDialog; import android.content.Intent; import android.content.pm.PackageManager; import android.os.Bundle; import android.os.Handler; import android.support.v4.app.ActivityCompat; import android.support.v4.content.ContextCompat; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.view.WindowManager; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import com.crashlytics.android.Crashlytics; import com.nostra13.universalimageloader.core.ImageLoader; import com.nostra13.universalimageloader.utils.DiskCacheUtils; import com.nostra13.universalimageloader.utils.MemoryCacheUtils; import com.wo1haitao.R; import com.wo1haitao.api.ApiServices; import com.wo1haitao.api.WebService; import com.wo1haitao.api.response.ErrorMessage; import com.wo1haitao.api.response.ResponseMessage; import com.wo1haitao.api.response.UserProfile; import com.wo1haitao.dialogs.DialogPermission; import com.wo1haitao.utils.Utils; import com.wo1haitao.views.ActionBarProject; import java.util.ArrayList; import java.util.List; import okhttp3.MultipartBody; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; public class VerifyActivity extends AppCompatActivity { ActionBarProject my_action_bar; ImageView iv_ID; TextView tv_top, tv_bottom; static String STATE_VERIFY_OPEN = "opened"; static String STATE_VERIFY_REJECT = "rejected"; static String STATE_VERIFY_CLOSE = "closed"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_verify); initControl(); } private void initControl() { my_action_bar = (ActionBarProject) findViewById(R.id.my_action_bar); // btn_to_main = (Button) findViewById(R.id.btn_to_main); my_action_bar.showTitle(R.string.title_verify); my_action_bar.showBack(new View.OnClickListener() { @Override public void onClick(View view) { //my_action_bar.changeButtonBack(); onBackPressed(); overridePendingTransition(R.anim.left_to_right, R.anim.right_to_left); } }); // ImageView verifies_user, id_verifies; // TextView tv_name_us; // RoundedImageView roundedImageUser; // // verifies_user = (ImageView) findViewById(R.id.verifies_user); // id_verifies = (ImageView) findViewById(R.id.id_verifies); // tv_name_us = (TextView) findViewById(R.id.tv_name_us); // roundedImageUser = (RoundedImageView) findViewById(R.id.roundedImageUser); // btn_to_main.setOnClickListener(new View.OnClickListener() { // @Override // public void onClick(View view) { // onBackPressed(); // // } // }); tv_top = (TextView) findViewById(R.id.tv_top); tv_bottom = (TextView) findViewById(R.id.tv_bottom); iv_ID = (ImageView) findViewById(R.id.iv_ID); GetUserApi(); iv_ID.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { int result; String mPermissions[] = {Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE}; List<String> listPermissionsNeeded = new ArrayList<>(); for (String p : mPermissions) { boolean showRationale = ActivityCompat.shouldShowRequestPermissionRationale(VerifyActivity.this, p); if(ContextCompat.checkSelfPermission(VerifyActivity.this, p) == PackageManager.PERMISSION_DENIED){ if (ContextCompat.checkSelfPermission(VerifyActivity.this, p) == PackageManager.PERMISSION_DENIED && !showRationale) { new Handler().post(new Runnable() { @Override public void run() { DialogPermission dialogPermission = new DialogPermission(VerifyActivity.this); WindowManager.LayoutParams lp = new WindowManager.LayoutParams(); lp.copyFrom(dialogPermission.getWindow().getAttributes()); lp.width = WindowManager.LayoutParams.MATCH_PARENT; lp.height = WindowManager.LayoutParams.MATCH_PARENT; dialogPermission.show(); } }); return; } else { result = ContextCompat.checkSelfPermission(VerifyActivity.this, p); if (result != PackageManager.PERMISSION_GRANTED) { listPermissionsNeeded.add(p); } } } } if (!listPermissionsNeeded.isEmpty()) { ActivityCompat.requestPermissions(VerifyActivity.this, listPermissionsNeeded.toArray(new String[listPermissionsNeeded.size()]), 1003); } else { Intent takePhotoIntent = Utils.getTakePictureIntent(VerifyActivity.this); startActivityForResult(takePhotoIntent, Utils.RQ_CODE_GET_IMAGE); } } }); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == Utils.RQ_CODE_GET_IMAGE) { if (resultCode == RESULT_OK) { Utils.getImageView(iv_ID, data, VerifyActivity.this); // btn_to_main.setEnabled(true); PostVerification(); } } } /** * Post verification * * @params: * @return: */ public void PostVerification() { final ProgressDialog progressDialog = Utils.createProgressDialog(VerifyActivity.this); ApiServices apiServices = ApiServices.getInstance(); WebService ws = apiServices.getRetrofit().create(WebService.class); if (iv_ID.getDrawable() != null) { MultipartBody.Part imageInvoice = Utils.createImagePart("identity_image", "identity_image" + ".png", iv_ID); Call<ResponseMessage> call = ws.actionPostVerification(imageInvoice); call.enqueue(new Callback<ResponseMessage>() { @Override public void onResponse(Call<ResponseMessage> call, Response<ResponseMessage> response) { try { progressDialog.dismiss(); // Toast.makeText(VerifyActivity.this, "恭喜您已成功上传您的身份证", Toast.LENGTH_SHORT).show(); onBackPressed(); } catch (Exception e) { Utils.crashLog(e); if (progressDialog != null) { progressDialog.dismiss(); } } } @Override public void onFailure(Call<ResponseMessage> call, Throwable t) { if (progressDialog != null) { progressDialog.dismiss(); } Utils.OnFailException(t); } }); } } /** * Get user me * * @params: * @return: */ public void GetUserApi() { final ProgressDialog progressDialogGetData = Utils.createProgressDialog(VerifyActivity.this); ApiServices api = ApiServices.getInstance(); WebService ws = api.getRetrofit().create(WebService.class); ws.actionGetUser().enqueue(new Callback<ResponseMessage<UserProfile>>() { @Override public void onResponse(Call<ResponseMessage<UserProfile>> call, Response<ResponseMessage<UserProfile>> response) { try { if (response.body() != null && response.isSuccessful()) { UserProfile userProfile = response.body().getData(); if (userProfile.getVerification_state().equals(STATE_VERIFY_OPEN)) { //iv_ID.setImageDrawable(null); if(userProfile.getIdentity_image().getUrl().isEmpty() == false) { tv_top.setText("申请已提交,正在等待我要海淘网的审核"); tv_bottom.setVisibility(View.VISIBLE); tv_bottom.setText("验证过程需要一到三日来完成。"); String urlVerify = ApiServices.BASE_URI + userProfile.getIdentity_image().getUrl(); DiskCacheUtils.removeFromCache(urlVerify, ImageLoader.getInstance().getDiskCache()); MemoryCacheUtils.removeFromCache(urlVerify, ImageLoader.getInstance().getMemoryCache()); ImageLoader il = ImageLoader.getInstance(); il.displayImage(urlVerify, iv_ID); iv_ID.setEnabled(false); // btn_to_main.setVisibility(View.VISIBLE); } else { tv_top.setText("请用户拍摄手持本人身份证身份证的照片"); // tv_bottom.setText("请参照示范"); iv_ID.setEnabled(true); // btn_to_main.setVisibility(View.GONE); } // btn_to_main.setEnabled(true); } else if(userProfile.getVerification_state().equals(STATE_VERIFY_REJECT)){ tv_top.setText("请用户拍摄手持本人身份证身份证的照片"); // tv_bottom.setText("请参照示范"); iv_ID.setEnabled(true); //iv_ID.setImageDrawable(null); //iv_ID.setBackgroundResource(R.drawable.upload_id_here); // btn_to_main.setEnabled(false); } else if(userProfile.getVerification_state().equals(STATE_VERIFY_CLOSE)){ iv_ID.setEnabled(false); iv_ID.setImageDrawable(null); // tv_bottom.setVisibility(View.INVISIBLE); tv_top.setText("恭喜您已通过实名认证"); String urlVerify = ApiServices.BASE_URI + userProfile.getIdentity_image().getUrl(); DiskCacheUtils.removeFromCache(urlVerify, ImageLoader.getInstance().getDiskCache()); MemoryCacheUtils.removeFromCache(urlVerify, ImageLoader.getInstance().getMemoryCache()); ImageLoader il = ImageLoader.getInstance(); il.displayImage(urlVerify, iv_ID); // btn_to_main.setEnabled(true); } progressDialogGetData.dismiss(); } else if (response.errorBody() != null) { try { ResponseMessage responseMessage = ApiServices.getGsonBuilder().create().fromJson(response.errorBody().string(), ResponseMessage.class); ErrorMessage error = responseMessage.getErrors(); Toast.makeText(VerifyActivity.this, "Can't get data... " + error.getStringErrFormList(), Toast.LENGTH_SHORT).show(); } catch (Exception e) { Crashlytics.logException(e); Toast.makeText(VerifyActivity.this, R.string.something_wrong, Toast.LENGTH_SHORT).show(); } if(progressDialogGetData != null){ progressDialogGetData.dismiss(); } } else { if(progressDialogGetData != null){ progressDialogGetData.dismiss(); } Toast.makeText(VerifyActivity.this, R.string.no_advesting, Toast.LENGTH_SHORT).show(); } } catch (Exception e) { if(progressDialogGetData != null){ progressDialogGetData.dismiss(); } Crashlytics.logException(e); } } @Override public void onFailure(Call<ResponseMessage<UserProfile>> call, Throwable t) { if(progressDialogGetData != null){ progressDialogGetData.dismiss(); } Utils.OnFailException(t); } }); } }
8c0484e176f8ab3527c599173d56ddd151acc979
1ce4065fe374c668d1410d9038927b8a6fc93746
/news-service/news-api/target/generated/cxf/com/vidur/news/model/SaveNews.java
56b2058aa0642a8b81081234fd742154a3088ded
[]
no_license
venkatesh4ever/JobPortal
26de42af5f30bb0eace1de365ab0f385ed01ac04
40064c2b2175c5a6b93ab3941689043003288e76
refs/heads/master
2020-06-08T08:19:14.304625
2014-12-25T16:05:54
2014-12-25T16:05:54
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,622
java
package com.vidur.news.model; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for anonymous complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="saveNewsRequestType" type="{http://www.w3.org/2001/XMLSchema}string"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "saveNewsRequestType" }) @XmlRootElement(name = "saveNews") public class SaveNews { @XmlElement(required = true) protected String saveNewsRequestType; /** * Gets the value of the saveNewsRequestType property. * * @return * possible object is * {@link String } * */ public String getSaveNewsRequestType() { return saveNewsRequestType; } /** * Sets the value of the saveNewsRequestType property. * * @param value * allowed object is * {@link String } * */ public void setSaveNewsRequestType(String value) { this.saveNewsRequestType = value; } }
2335d77bdb0a709f6d6215b1fc917921353ae9ae
f87b023f7437d65ed29eae1f2b1a00ddfd820177
/bitcamp-java-basic/src/step14_implements/ex2_Interface/Exam02.java
c8a1f3260415cce474a6ea861981a72e2745dabf
[]
no_license
GreedHJC/BitCamp
c0d01fc0713744e01832fabf06d2663577fde6e5
028894ab5171ef1fd89de73c3654e11cbc927a25
refs/heads/master
2021-01-24T10:28:07.820330
2018-06-04T07:51:58
2018-06-04T07:51:58
123,054,159
0
0
null
null
null
null
UTF-8
Java
false
false
558
java
// 인터페이스의 모든 메서드는 public이다. // 인터페이스를 구현하는 클래스는 // 메서드의 공개 범위를 public 보다 좁게할 순 없다. package step14_implements.ex2_Interface; public class Exam02 implements A3 { // public 보다 좁게 공개 범위를 줄일 수 없다. //private void m1() {} // 컴파일 오류! //protected void m1() {} // 컴파일 오류! //void m1() {} // 컴파일 오류! // 반드시 public 이어야 한다. public void m1() {} public void m2() {} }
caacb3eb53837bdc2886826760017ba51cc60f93
49dccd242965f93e5ae532e329ca6c2a21cf1bd3
/Knights Tour/src/main.java
fe9076649fbfadc4930dc0f8e2c6650619d1f7d3
[]
no_license
imyaamz/Knights-Tour
c90a50474bf07facc79b1146dd78bf8da022a924
1930ed4cc9058ea1e7a53e8f95b49aef204d7225
refs/heads/main
2023-01-01T15:15:54.394633
2020-10-26T03:53:21
2020-10-26T03:53:21
307,255,245
0
0
null
null
null
null
UTF-8
Java
false
false
153
java
public class main { public static void main(String[] args) { board board = new board(8); board.display(); board.knightsTour(); } }
9d1d874673ad405ed6ca16cc9f3f9bec67803e1f
39c927f540a29bc12b3bdcc6247a4b0e8d862f78
/src/main/java/server/frontend/commands/cars/Cars.java
99e1c14ed7e8aa8ab4fe939f2fb8413fb1dda85d
[]
no_license
marsofandrew/db_term_work_2019
7dd8fd308709e4cb212dc661910a79da3a25ff20
17ee4ef466d480de2bad5f90f778a8daa086cff3
refs/heads/master
2020-05-19T12:47:47.280321
2019-05-06T12:07:14
2019-05-06T12:07:14
185,023,853
0
0
null
null
null
null
UTF-8
Java
false
false
112
java
package server.frontend.commands.cars; public class Cars { public static final String TABLE_NAME = "CARS"; }
e79d2fc847550314372b068aa9910e17038d1e3b
a4f37fbb39aace9e20fb2bb66668d4cc35bb3021
/spring-in-action/src/main/java/ua/laposhko/part1/InjectableBean.java
9cb653e17dcb81b1afc573980192562522f565cd
[]
no_license
sergeylaposhko/spring-in-action
2f9f5a639983a8349d42ef4d6e20cda869167792
be3dc68e90bb8ebfb00edea6a0a2cf5ff55d195e
refs/heads/master
2020-12-24T10:14:39.606149
2016-11-12T08:49:01
2016-11-12T08:49:01
73,094,876
0
0
null
null
null
null
UTF-8
Java
false
false
121
java
package ua.laposhko.part1; import org.springframework.stereotype.Component; @Component public class InjectableBean { }
20a746d8fbb8a459a7138fb1b98cbca548f6fe45
8d7b7c075dd11fe4295e96c444138bef4c658de5
/src/main/java/demo/pattern/factory/method/HpMouseFactory.java
88e5c1af884b344fc03e87cdb17955ef50e7c319
[]
no_license
Alex-M-W-WU/simpleframework
7ba19e1119878ba0e940549a736fa9b8b1bbb5e3
e33e8754500404f037f0c2fa6dd661c2bc2a41ba
refs/heads/master
2023-02-05T11:10:16.531366
2020-12-31T16:40:03
2020-12-31T16:40:03
325,835,826
0
0
null
null
null
null
UTF-8
Java
false
false
264
java
package demo.pattern.factory.method; import demo.pattern.factory.entity.HpMouse; import demo.pattern.factory.entity.Mouse; public class HpMouseFactory implements MouseFactory{ @Override public Mouse createMouse() { return new HpMouse(); } }
f3e1745bac2058dd3699cd855748ee970fc5d4e3
4a3813c561e524ee3cb70087fa13497b15c3a051
/ImClient/src/main/java/com/lzr/client/clientBuilder/ExceptionHandler.java
cd0fa9c6e632a6369e518780f0e114e39799d6c8
[]
no_license
ziruiLiu-g/NettyIm
94ee79af33afa39914aba137db48ba160f04e1f5
b0ae64fb87380d61bf2c31243096a5fa782c08de
refs/heads/master
2023-06-25T04:52:40.403940
2021-07-21T14:26:24
2021-07-21T14:26:24
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,448
java
package com.lzr.client.clientBuilder; import com.lzr.client.client.CommandController; import com.lzr.im.common.exception.BusinessException; import com.lzr.im.common.exception.InvalidFrameException; import io.netty.channel.ChannelHandler; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelInboundHandlerAdapter; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; /** * ExceptionHandler * * Author: zirui liu * Date: 2021/7/21 */ @Slf4j @ChannelHandler.Sharable @Service("ExceptionHandler") public class ExceptionHandler extends ChannelInboundHandlerAdapter { @Autowired private CommandController commandController; @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { if (cause instanceof BusinessException) { // bussiness error, note client } else if (cause instanceof InvalidFrameException) { log.error(cause.getMessage()); // server handle the msg } else { log.error(cause.getMessage()); ctx.close(); commandController.setConnectFlag(false); commandController.startConnectServer(); } } @Override public void channelReadComplete(ChannelHandlerContext ctx) throws Exception { ctx.flush(); } }
555e2bdbc9da2ecc724206583a75591eb1344d4c
2fe88053b15afc58fac9473d8bb1a2b3364c1e74
/src/main/java/s/im/util/BeanConverterUtil.java
718f317b925b6a3ec1b2c1de14781222fe8cc670
[]
no_license
prize4u/nettyStarter
ffa729cdcb0f2f29a2052a35828d25df1b373053
bb4edf97d1978f643dcc52a347c0c388169b1c21
refs/heads/master
2021-01-20T00:03:23.818295
2017-06-12T09:31:55
2017-06-12T09:31:55
89,071,332
0
0
null
null
null
null
UTF-8
Java
false
false
102
java
package s.im.util; /** * Created by za-zhujun on 2017/5/27. */ public class BeanConverterUtil { }
b5e117f19657042c86609b9156ae32e6b9edbb53
43ca534032faa722e206f4585f3075e8dd43de6c
/src/com/instagram/android/fragment/ds.java
a1c2cf4f28a5522f465e82576d00a285de869a58
[]
no_license
dnoise/IG-6.9.1-decompiled
3e87ba382a60ba995e582fc50278a31505109684
316612d5e1bfd4a74cee47da9063a38e9d50af68
refs/heads/master
2021-01-15T12:42:37.833988
2014-10-29T13:17:01
2014-10-29T13:17:01
26,952,948
1
0
null
null
null
null
UTF-8
Java
false
false
663
java
// Decompiled by Jad v1.5.8e. Copyright 2001 Pavel Kouznetsov. // Jad home page: http://www.geocities.com/kpdus/jad.html // Decompiler options: braces fieldsfirst space lnc package com.instagram.android.fragment; import android.view.View; import com.instagram.android.nux.af; import com.instagram.b.c.a; // Referenced classes of package com.instagram.android.fragment: // dn final class ds implements android.view.View.OnClickListener { final dn a; ds(dn dn1) { a = dn1; super(); } public final void onClick(View view) { com.instagram.b.c.a.a().a(a.l(), "next"); af.a(a.l()); } }
8f5da0f9fd1d3c9d96f5d28906ef47135104d3c2
c21507ca2f940d23584c30f487620511dd529131
/app/src/main/java/example/ivanmagsino/remdy/ui/slideshow/SlideshowViewModel.java
e557a5fba54238083f7fc128d023cf9f7d37d753
[]
no_license
Okatsu99/GoldenchainMob
13637d6575d59fd3d5b7f9af4d95bc3d37c09f82
0e50f40fafe8e33ece6423764a3337a381aa42f9
refs/heads/master
2022-07-19T23:12:04.145912
2020-05-26T13:12:18
2020-05-26T13:12:18
262,274,679
0
0
null
null
null
null
UTF-8
Java
false
false
468
java
package example.ivanmagsino.remdy.ui.slideshow; import androidx.lifecycle.LiveData; import androidx.lifecycle.MutableLiveData; import androidx.lifecycle.ViewModel; public class SlideshowViewModel extends ViewModel { private MutableLiveData<String> mText; public SlideshowViewModel() { mText = new MutableLiveData<>(); mText.setValue("This is slideshow fragment"); } public LiveData<String> getText() { return mText; } }
1a06311de097852ec4daa4e1f679adde52bc6eb4
4024fddd49f7750997867f202c5e18e046459c25
/Workspace/Vectores/src/com/epn/AplicacionVector.java
696eedd3456d66aff507a5ebac048133dffc0997
[]
no_license
daven1995/PracticaCalidad
e649e2595f69e73b69ba002be3b98cc633a8a344
21c547babedf017862859c6badeda31b55542fb2
refs/heads/master
2021-01-11T17:54:31.228304
2017-01-24T02:39:25
2017-01-24T02:39:25
79,871,378
0
0
null
null
null
null
ISO-8859-1
Java
false
false
2,547
java
package com.epn; import javax.swing.JOptionPane; public class AplicacionVector { public static void main(String[] args) { String salida=""; Vector vector=new Vector(); vector.setVector(); salida+="El vector es : "+vector; salida+="\nLa suma de las entradas es = "+vector.sumatorio(); salida+="\nLa suma de los pares es = "+vector.sumapar(); salida+="\nLa suma de los numeros primos es = "+vector.sumaprimo(); JOptionPane.showMessageDialog(null, salida); vector.desorden(); int elemsec=Integer.parseInt(JOptionPane.showInputDialog("El vector original " + "es : "+vector.toString() + "\n * * BUSQUEDA SECUENCIAL * *\nEscriba un numero para buscar")); if((vector.busquedaSecuencial(elemsec))==-1)JOptionPane.showMessageDialog(null, "El vector es : "+vector + "\n * * BUSQUEDA SECUENCIAL * *\nEl numero ingresado no se encuentra\n"); else{JOptionPane.showMessageDialog(null, "El vector " + "es : "+vector.toString()+ "\n * * BUSQUEDA SECUENCIAL * *\n" + "El elemento existe en la posicion "+vector.busquedaSecuencial(elemsec)+" y es el" + " "+elemsec);} vector.sortBurbuja(); int elembin=Integer.parseInt(JOptionPane.showInputDialog( "El vector ordenado ascendentemente " + "es : \n "+vector.toString() + "\n * * BUSQUEDA BINARIA * *\nEscriba un numero para buscar")); if((vector.busquedaBinaria(elembin))==-1)JOptionPane.showMessageDialog(null, "El vector original " + "es : "+vector.toString() + "\n * * BUSQUEDA BINARIA * *\nEl numero ingresado no se encuentra\n"); else{JOptionPane.showMessageDialog(null, "El vector original " + "es : "+vector.toString() + "\n * * BUSQUEDA BINARIA * *\nEl elemento existe en la posicion "+vector.busquedaBinaria(elembin)+" y es el "+elembin);} vector.sortDes(); int elembindes=Integer.parseInt(JOptionPane.showInputDialog(" BUSQUEDA BINARIA DESCENDENTE \nDigite el número a buscar:")); if((vector.busquedaBinariades(elembindes))==-1)JOptionPane.showMessageDialog(null, " BUSQUEDA BINARIA \nNúmero digitado no encontrado\n"); else{JOptionPane.showMessageDialog(null, " BUSQUEDA BINARIA DESCENDENTE\nElemento encontrado en posición: "+vector.busquedaBinaria(elembindes)+" y es "+elembindes);} salida+="\nEl numero de elementos pares del vector es: "+vector.Pares(); salida+="\nEl numero de elementos primos del vector es: "+vector.Primos(); salida+="\nNúmero mayor es: "+vector.Mayor(); salida+="\nNúmero menor es: "+vector.Menor(); JOptionPane.showMessageDialog(null, salida); } }
429e66239f6f72c5f5733586d8b3ac3b828830b6
b029ed3f9b0c483af92b07997e8f7804c8660fd6
/src/LinkListPriorityQ.java
f1e4faf12edf0fcf6e8388b74530d4713e69389a
[]
no_license
husseinahmed-dev/JavaSE8
84c0df3587910f3d8b295a0ebdcb3c218c21abf2
ba10563c157d5a5d8bffe9b4d19f1f8fb98ad7a1
refs/heads/master
2020-12-25T15:17:38.157632
2017-05-02T22:44:05
2017-05-02T22:44:05
67,951,430
0
0
null
null
null
null
UTF-8
Java
false
false
2,163
java
/** * Created by Hussein */ class Link { public int iData; public Link next; public Link(int x) { iData = x; } public void displayLink() { System.out.print(iData + " "); } } class LinkList { private Link first; public LinkList() { first = null; } public boolean isEmpty() { return first == null; } public void insert(int x) { Link newLink = new Link(x); Link current = first; Link previous = null; while (current != null && x < current.iData) { previous = current; current = current.next; } if (previous == null) { newLink.next = first; first = newLink; } else { previous.next = newLink; newLink.next = current; } } public Link remove() { Link current = first; Link previous = null; Link temp = current; while (current.next != null) { previous = current; current = current.next; } previous.next = null; return temp; } public void display() { Link current = first; while (current != null) { current.displayLink(); current = current.next; } System.out.println(" "); } } class PriorityQ { private LinkList theList; public PriorityQ() { theList = new LinkList(); } public void insert(int x) { theList.insert(x); } public void remove() { theList.remove(); } public void displayList() { System.out.print("Priority Queue: "); theList.display(); } } public class LinkListPriorityQ { public static void main(String[] args) { PriorityQ queue1 = new PriorityQ(); queue1.insert(5); queue1.insert(3); queue1.insert(8); queue1.insert(2); queue1.displayList(); queue1.remove(); queue1.displayList(); queue1.remove(); queue1.displayList(); queue1.remove(); queue1.displayList(); } }
91930fdf19f88f72a939fdc80c17b0dd5e7db54a
8be567be86cd22af0b9d8a8d1b649cad7a0e2b97
/IdentityServer/src/service/UserGroupService.java
b06ae76c01e1f8a14e7d29211fb1dc38c49aa721
[ "MIT" ]
permissive
yalukezoudike/startpoint
b1a577bdc8115f4d8d5a1486ce50a2fddb111046
fe2402e7c262e06c4aee0f62b80015e11fcdfd80
refs/heads/master
2021-07-23T02:52:43.851763
2017-11-02T14:19:26
2017-11-02T14:19:26
null
0
0
null
null
null
null
UTF-8
Java
false
false
6,141
java
package service; import java.util.HashMap; import java.util.List; import java.util.Map; import org.grain.httpserver.HttpException; import org.grain.httpserver.HttpPacket; import org.grain.httpserver.IHttpListener; import action.UCErrorPack; import action.UserGroupAction; import dao.model.base.UserGroup; import http.HOpCodeUCenter; import protobuf.http.UCErrorProto.UCError; import protobuf.http.UCErrorProto.UCErrorCode; import protobuf.http.UserGroupProto.CreateUserGroupC; import protobuf.http.UserGroupProto.CreateUserGroupS; import protobuf.http.UserGroupProto.DeleteUserGroupC; import protobuf.http.UserGroupProto.DeleteUserGroupS; import protobuf.http.UserGroupProto.GetUserGroupC; import protobuf.http.UserGroupProto.GetUserGroupListC; import protobuf.http.UserGroupProto.GetUserGroupListS; import protobuf.http.UserGroupProto.GetUserGroupS; import protobuf.http.UserGroupProto.UpdateUserGroupC; import protobuf.http.UserGroupProto.UpdateUserGroupS; import tool.PageFormat; import tool.PageObj; public class UserGroupService implements IHttpListener { @Override public Map<String, String> getHttps() { HashMap<String, String> map = new HashMap<>(); map.put(HOpCodeUCenter.CREATE_USER_GROUP, "createUserGroupHandle"); map.put(HOpCodeUCenter.UPDATE_USER_GROUP, "updateUserGroupHandle"); map.put(HOpCodeUCenter.GET_USER_GROUP, "getUserGroupHandle"); map.put(HOpCodeUCenter.DELETE_USER_GROUP, "deleteUserGroupHandle"); map.put(HOpCodeUCenter.GET_USER_GROUP_LIST, "getUserGroupListHandle"); return map; } public HttpPacket createUserGroupHandle(HttpPacket httpPacket) throws HttpException { CreateUserGroupC message = (CreateUserGroupC) httpPacket.getData(); UserGroup userGroup = UserGroupAction.createUserGroup(message.getUserGroupName(), message.getUserGroupParentId()); if (userGroup == null) { UCError errorPack = UCErrorPack.create(UCErrorCode.ERROR_CODE_10, httpPacket.hSession.headParam.hOpCode); throw new HttpException(HOpCodeUCenter.UC_ERROR, errorPack); } CreateUserGroupS.Builder builder = CreateUserGroupS.newBuilder(); builder.setHOpCode(httpPacket.hSession.headParam.hOpCode); builder.setUserGroup(UserGroupAction.getUserGroupDataBuilder(userGroup)); HttpPacket packet = new HttpPacket(httpPacket.hSession.headParam.hOpCode, builder.build()); return packet; } public HttpPacket updateUserGroupHandle(HttpPacket httpPacket) throws HttpException { UpdateUserGroupC message = (UpdateUserGroupC) httpPacket.getData(); UserGroup userGroup = UserGroupAction.updateUserGroup(message.getUserGroupId(), message.getUserGroupName(), message.getIsUpdateUserGroupParent(), message.getUserGroupParentId(), message.getUserGroupState()); if (userGroup == null) { UCError errorPack = UCErrorPack.create(UCErrorCode.ERROR_CODE_11, httpPacket.hSession.headParam.hOpCode); throw new HttpException(HOpCodeUCenter.UC_ERROR, errorPack); } UpdateUserGroupS.Builder builder = UpdateUserGroupS.newBuilder(); builder.setHOpCode(httpPacket.hSession.headParam.hOpCode); builder.setUserGroup(UserGroupAction.getUserGroupDataBuilder(userGroup)); HttpPacket packet = new HttpPacket(httpPacket.hSession.headParam.hOpCode, builder.build()); return packet; } public HttpPacket getUserGroupHandle(HttpPacket httpPacket) throws HttpException { GetUserGroupC message = (GetUserGroupC) httpPacket.getData(); UserGroup userGroup = UserGroupAction.getUserGroupById(message.getUserGroupId()); if (userGroup == null) { UCError errorPack = UCErrorPack.create(UCErrorCode.ERROR_CODE_12, httpPacket.hSession.headParam.hOpCode); throw new HttpException(HOpCodeUCenter.UC_ERROR, errorPack); } GetUserGroupS.Builder builder = GetUserGroupS.newBuilder(); builder.setHOpCode(httpPacket.hSession.headParam.hOpCode); builder.setUserGroup(UserGroupAction.getUserGroupDataBuilder(userGroup)); HttpPacket packet = new HttpPacket(httpPacket.hSession.headParam.hOpCode, builder.build()); return packet; } public HttpPacket deleteUserGroupHandle(HttpPacket httpPacket) throws HttpException { DeleteUserGroupC message = (DeleteUserGroupC) httpPacket.getData(); boolean result = UserGroupAction.deleteUserGroup(message.getUserGroupId()); if (!result) { UCError errorPack = UCErrorPack.create(UCErrorCode.ERROR_CODE_15, httpPacket.hSession.headParam.hOpCode); throw new HttpException(HOpCodeUCenter.UC_ERROR, errorPack); } DeleteUserGroupS.Builder builder = DeleteUserGroupS.newBuilder(); builder.setHOpCode(httpPacket.hSession.headParam.hOpCode); HttpPacket packet = new HttpPacket(httpPacket.hSession.headParam.hOpCode, builder.build()); return packet; } public HttpPacket getUserGroupListHandle(HttpPacket httpPacket) throws HttpException { GetUserGroupListC message = (GetUserGroupListC) httpPacket.getData(); List<UserGroup> userGroupList = UserGroupAction.getUserGroupList(message.getUserGroupParentId(), message.getIsUserGroupParentIsNull(), message.getIsRecursion(), message.getUserGroupTopId(), message.getUserGroupState(), message.getUserGroupCreateTimeGreaterThan(), message.getUserGroupCreateTimeLessThan(), message.getUserGroupUpdateTimeGreaterThan(), message.getUserGroupUpdateTimeLessThan()); int currentPage = message.getCurrentPage(); int pageSize = message.getPageSize(); PageObj pageObj = PageFormat.getStartAndEnd(currentPage, pageSize, userGroupList.size()); GetUserGroupListS.Builder builder = GetUserGroupListS.newBuilder(); builder.setHOpCode(httpPacket.hSession.headParam.hOpCode); builder.setCurrentPage(pageObj.currentPage); builder.setPageSize(pageObj.pageSize); builder.setTotalPage(pageObj.totalPage); builder.setAllNum(pageObj.allNum); if (userGroupList != null) { for (int i = pageObj.start; i < pageObj.end; i++) { UserGroup userGroup = userGroupList.get(i); builder.addUserGroup(UserGroupAction.getUserGroupDataBuilder(userGroup)); } } HttpPacket packet = new HttpPacket(httpPacket.hSession.headParam.hOpCode, builder.build()); return packet; } }
dbde7ba4b8fefe8a128969afd64994e911a3faa5
dc4497107e1e5750b4f64380fbde4cb0df4b273d
/Workspace/src/workspace/service/debug/SrvDebugBreakpointVariable.java
61c29748ac8c7fa417e6a498b52f6af0488b9556
[]
no_license
M6C/workspace-neon
2c28ed019a8f9b3fbf1a30799ff2007dcf63ffef
23ea1b195dbd32eee715dac3ac07f6dada1b9e09
refs/heads/master
2022-10-24T16:23:40.743804
2022-10-18T14:37:26
2022-10-18T14:37:26
67,446,351
0
0
null
null
null
null
UTF-8
Java
false
false
3,878
java
package workspace.service.debug; import java.io.PrintWriter; import java.io.StringWriter; import java.util.Iterator; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import com.sun.jdi.LocalVariable; import com.sun.jdi.StackFrame; import com.sun.jdi.ThreadReference; import com.sun.jdi.Value; import com.sun.jdi.event.Event; import com.sun.jdi.event.LocatableEvent; import framework.beandata.BeanGenerique; import framework.service.SrvGenerique; import workspace.bean.debug.BeanDebug; /** * * a servlet handles upload request.<br> * refer to http://www.ietf.org/rfc/rfc1867.txt * */ public class SrvDebugBreakpointVariable extends SrvGenerique { public void init() { } public void execute(HttpServletRequest request, HttpServletResponse response, BeanGenerique bean) throws Exception { HttpSession session = request.getSession(); StringBuffer sb = new StringBuffer("<table border=1 cellspacing=0 cellpadding=0><tr><td>"); try { BeanDebug beanDebug = (BeanDebug)session.getAttribute("beanDebug"); if (beanDebug!=null) { // Event currentEvent = beanDebug.getCurrentEvent(); Event currentEvent = (beanDebug.getCurrentStepEvent() != null) ? beanDebug.getCurrentStepEvent() : beanDebug.getCurrentEvent(); if ((currentEvent!=null)&&(currentEvent instanceof LocatableEvent)) { LocatableEvent event = (LocatableEvent)currentEvent; ThreadReference thread = event.thread(); if (thread == null) { System.err.println("No Thread found for event"); return; } List frames = thread.frames(); if ((frames!=null)&&(!frames.isEmpty())) { StackFrame frame = null; Iterator it = frames.iterator(); while(it.hasNext()) { frame = (StackFrame)it.next(); try { sb.append("&nbsp;</td><td><table><tr><td colspan='3' nowrap>"); sb.append(frame.location().declaringType().name()); sb.append("<br><b>"); sb.append(frame.location().sourcePath()); sb.append("</b><br><u>"); sb.append(frame.location().method().name()); sb.append("</u>&nbsp;"); sb.append(frame.location().method().signature()); sb.append("</td></tr><tr><td>"); } catch(Exception ex) {} try { List visibleVariables = frame.visibleVariables(); if ((visibleVariables!=null)&&(!visibleVariables.isEmpty())) { LocalVariable variable = null; Value value = null; Iterator itV = visibleVariables.iterator(); while(itV.hasNext()) { variable = (LocalVariable)itV.next(); sb.append(variable.typeName()); sb.append("</td><td>"); sb.append(variable.name()); sb.append("</td><td>"); value = frame.getValue(variable); sb.append((value!=null) ? value.toString() : null); sb.append("</td></tr><tr><td>"); } } } catch(Exception ex) {} sb.append("</td></tr></table>"); sb.append("</td></tr><tr><td>"); } } } } sb.append("</td></tr></table>"); PrintWriter out = response.getWriter(); out.print(sb.toString()); } catch(Exception ex) { StringWriter sw = new StringWriter(); ex.printStackTrace(new PrintWriter(sw)); request.setAttribute("msgText", sw.toString()); throw ex; } } }
c986611ea6c5bc28832d4e0baa6d94e2b8c3916f
8750d5341c698002628cc2b6770e99e6e4875b6d
/app/src/main/java/com/example/bookpurchaseapp/adapters/MainAdapter.java
fbf4149ac4a72fb0759b99cc3b901a08953d297b
[]
no_license
Elif-Akkaya/E-Commerce-Android-Mobile-App
734c36a8b56e20dae9456677b277583e9d167da4
b89fdbf2dda9f2cdb7466ed987a1feada288f483
refs/heads/master
2023-03-20T00:42:53.106762
2021-03-09T20:21:38
2021-03-09T20:21:38
339,852,209
0
0
null
null
null
null
UTF-8
Java
false
false
2,905
java
package com.example.bookpurchaseapp.adapters; import android.content.Context; import android.content.Intent; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.recyclerview.widget.RecyclerView; import com.example.bookpurchaseapp.R; import com.example.bookpurchaseapp.ReceiveOrderActivity; import com.example.bookpurchaseapp.models.Main_Model; import java.util.ArrayList; public class MainAdapter extends RecyclerView.Adapter<MainAdapter.ViewHolder> { ArrayList<Main_Model> list; Context cont; public MainAdapter(ArrayList<Main_Model> list, Context cont) { this.list = list; this.cont = cont; } @NonNull @Override public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View view = LayoutInflater.from(cont).inflate(R.layout.example_book_main,parent,false); return new ViewHolder(view); } @Override public void onBindViewHolder(@NonNull ViewHolder holder, int position) { final Main_Model model = list.get (position); holder.image_book.setImageResource(model.getImage_book()); holder.book_name.setText(model.getBook_name()); holder.author_name.setText(model.getAuthor_name()); holder.price.setText(model.getPrice()); holder.category.setText(model.getCategory()); holder.itemView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(cont, ReceiveOrderActivity.class); intent.putExtra("image", model.getImage_book()); intent.putExtra("book_name", model.getBook_name()); intent.putExtra("author_name", model.getAuthor_name()); intent.putExtra("price", model.getPrice()); intent.putExtra("description", model.getDescription()); intent.putExtra("category", model.getCategory()); intent.putExtra("language", model.getLanguage()); cont.startActivity(intent); } }); } @Override public int getItemCount() { return list.size(); } public class ViewHolder extends RecyclerView.ViewHolder { ImageView image_book; TextView book_name,author_name, price, category; public ViewHolder(@NonNull View itemView) { super(itemView); image_book = itemView.findViewById(R.id.image_book); book_name = itemView.findViewById(R.id.text_book_name); author_name = itemView.findViewById(R.id.text_author_name); price = itemView.findViewById(R.id.text_price); category = itemView.findViewById(R.id.text_category); } } }
ca11a383bfba5fcaa1cd379c993e1129403641c9
e9faf07f168cfe7a5d7d02c303f74a876b6883fe
/src/main/java/net/abusingjava/sql/v1/impl/GenericActiveRecordFactory.java
d60b1a43b3204fb2969e24d9b6fb802aeb3339de
[ "BSD-2-Clause", "LicenseRef-scancode-warranty-disclaimer" ]
permissive
sarndt/AbusingSQL
5b591e03d2a76b93d3f5744955f29983d16b9498
3fe09ab7cb0655bd227cc6f1891d39c307d9d685
refs/heads/master
2016-09-05T18:40:44.802625
2012-03-20T10:47:11
2012-03-20T10:47:11
3,817,405
0
1
null
null
null
null
UTF-8
Java
false
false
535
java
package net.abusingjava.sql.v1.impl; import java.sql.ResultSet; import net.abusingjava.sql.v1.ActiveRecord; import net.abusingjava.sql.v1.ActiveRecordFactory; public class GenericActiveRecordFactory implements ActiveRecordFactory { @Override public <T extends ActiveRecord<T>> T create(Class<T> $class) { // TODO Auto-generated method stub return null; } @Override public <T extends ActiveRecord<T>> T createFromResultSet(Class<T> $class, ResultSet $resultSet) { // TODO Auto-generated method stub return null; } }
a341fb034ae0a2b6681bcae992cd4eb6480e4d2b
3170a2c7176d90b0e485514a1985343060731931
/evaluation/src/main/java/uk/ac/standrews/cs/trombone/evaluation/scenarios/Batch2EffectOfWorkload.java
bf85dbf4a840608ba1352f7fe67d23fc62a7c485
[]
no_license
stacs-srg/trombone
1bcff26f186eb02f1113d5e9ec7a053b5061a7d2
472196588ebf9fce6f26b425fad6101b3d4bd60f
refs/heads/master
2022-07-11T11:23:11.648112
2022-06-28T12:53:10
2022-06-28T12:53:10
87,552,967
2
1
null
2022-06-28T12:53:11
2017-04-07T14:07:50
Java
UTF-8
Java
false
false
1,135
java
package uk.ac.standrews.cs.trombone.evaluation.scenarios; import java.util.List; import uk.ac.standrews.cs.shabdiz.util.Duration; import uk.ac.standrews.cs.trombone.event.Scenario; import uk.ac.standrews.cs.trombone.event.environment.Churn; import static uk.ac.standrews.cs.trombone.evaluation.scenarios.Constants.EXPERIMENT_DURATION_4; import static uk.ac.standrews.cs.trombone.evaluation.scenarios.Constants.PEER_CONFIGURATIONS; /** * @author Masih Hajiarabderkani ([email protected]) */ public class Batch2EffectOfWorkload implements ScenarioBatch { private static final Batch2EffectOfWorkload BATCH_2_EFFECT_OF_WORKLOAD = new Batch2EffectOfWorkload(); public static Batch2EffectOfWorkload getInstance() { return BATCH_2_EFFECT_OF_WORKLOAD; } private Batch2EffectOfWorkload() { } @Override public List<Scenario> get() { return BaseScenario.generateAll(getName(), new Churn[] {Constants.CHURN_30_MIN}, Constants.WORKLOADS, PEER_CONFIGURATIONS, new Duration[] {EXPERIMENT_DURATION_4}); } @Override public String getName() { return "workload"; } }
ecc4f84e06d0650fd0f8a4ad8ec19d7c397bdf12
a300a276e5f93754bcc32fc06acdac3f9ec2a403
/jdbc/jdbc-demo/src/main/java/com/johnny/jdbc/jdbc2/Student.java
83f0e4cc7f16c1d1f8735e69892fb41d610d3535
[]
no_license
johnny8353/jproject
b7043678c41e5571159d5b6c4c312c158d16fe2f
fb48ab569056691eb5bfbbf4ac53a7e9bce65286
refs/heads/master
2021-01-11T00:52:49.167846
2017-02-18T11:01:42
2017-02-18T11:01:42
70,458,883
3
0
null
null
null
null
UTF-8
Java
false
false
1,918
java
package com.johnny.jdbc.jdbc2; public class Student { // 流水号 private int flowId; // 考试的类型 private int type; // 身份证号 private String idCard; // 准考证号 private String examCard; // 学生名 private String studentName; // 学生地址 private String location; // 考试分数. private int grade; public int getFlowId() { return flowId; } public void setFlowId(int flowId) { this.flowId = flowId; } public int getType() { return type; } public void setType(int type) { this.type = type; } public String getIdCard() { return idCard; } public void setIdCard(String idCard) { this.idCard = idCard; } public String getExamCard() { return examCard; } public void setExamCard(String examCard) { this.examCard = examCard; } public String getStudentName() { return studentName; } public void setStudentName(String studentName) { this.studentName = studentName; } public String getLocation() { return location; } public void setLocation(String location) { this.location = location; } public int getGrade() { return grade; } public void setGrade(int grade) { this.grade = grade; } public Student(int flowId, int type, String idCard, String examCard, String studentName, String location, int grade) { super(); this.flowId = flowId; this.type = type; this.idCard = idCard; this.examCard = examCard; this.studentName = studentName; this.location = location; this.grade = grade; } public Student() { // TODO Auto-generated constructor stub } @Override public String toString() { return "Student [flowId=" + flowId + ", type=" + type + ", idCard=" + idCard + ", examCard=" + examCard + ", studentName=" + studentName + ", location=" + location + ", grade=" + grade + "]"; } }
a8b24ac6e80fa3550eccb9badb8f17f84c3d4b89
7e4b2ee6ae29ef7ade1522e45dc8593b599382de
/org.eclipse.gmf.runtime/archive/org.eclipse.gmf.runtime/src/org/eclipse/gmf/diagramrt/util/DiagramRTSwitch.java
7f62a0ef0fb2fa8e05e1b78cc7641b18a2d20e4d
[]
no_license
schmeedy/gmf
ef8e2fb708c1a5c7b49d3cd9be48610ab9ee9620
78ec68d33e42788d89708af80f8e6bbe63c95566
refs/heads/master
2020-05-18T18:23:45.748774
2012-09-18T21:05:28
2012-09-18T21:05:28
5,876,834
0
2
null
null
null
null
UTF-8
Java
false
false
9,218
java
/** * <copyright> * </copyright> * * $Id$ */ package org.eclipse.gmf.diagramrt.util; import java.util.List; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.EObject; import org.eclipse.gmf.diagramrt.*; /** * <!-- begin-user-doc --> * The <b>Switch</b> for the model's inheritance hierarchy. * It supports the call {@link #doSwitch(EObject) doSwitch(object)} * to invoke the <code>caseXXX</code> method for each class of the model, * starting with the actual class of the object * and proceeding up the inheritance hierarchy * until a non-null result is returned, * which is the result of the switch. * <!-- end-user-doc --> * @see org.eclipse.gmf.diagramrt.DiagramRTPackage * @generated */ public class DiagramRTSwitch { /** * The cached model package * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected static DiagramRTPackage modelPackage; /** * Creates an instance of the switch. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public DiagramRTSwitch() { if (modelPackage == null) { modelPackage = DiagramRTPackage.eINSTANCE; } } /** * Calls <code>caseXXX</code> for each class of the model until one returns a non null result; it yields that result. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the first non-null result returned by a <code>caseXXX</code> call. * @generated */ public Object doSwitch(EObject theEObject) { return doSwitch(theEObject.eClass(), theEObject); } /** * Calls <code>caseXXX</code> for each class of the model until one returns a non null result; it yields that result. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the first non-null result returned by a <code>caseXXX</code> call. * @generated */ protected Object doSwitch(EClass theEClass, EObject theEObject) { if (theEClass.eContainer() == modelPackage) { return doSwitch(theEClass.getClassifierID(), theEObject); } else { List eSuperTypes = theEClass.getESuperTypes(); return eSuperTypes.isEmpty() ? defaultCase(theEObject) : doSwitch((EClass)eSuperTypes.get(0), theEObject); } } /** * Calls <code>caseXXX</code> for each class of the model until one returns a non null result; it yields that result. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the first non-null result returned by a <code>caseXXX</code> call. * @generated */ protected Object doSwitch(int classifierID, EObject theEObject) { switch (classifierID) { case DiagramRTPackage.DIAGRAM_NODE: { DiagramNode diagramNode = (DiagramNode)theEObject; Object result = caseDiagramNode(diagramNode); if (result == null) result = caseDiagramBaseNode(diagramNode); if (result == null) result = caseDiagramBaseElement(diagramNode); if (result == null) result = defaultCase(theEObject); return result; } case DiagramRTPackage.DIAGRAM_LINK: { DiagramLink diagramLink = (DiagramLink)theEObject; Object result = caseDiagramLink(diagramLink); if (result == null) result = caseDiagramBaseElement(diagramLink); if (result == null) result = defaultCase(theEObject); return result; } case DiagramRTPackage.DIAGRAM_CANVAS: { DiagramCanvas diagramCanvas = (DiagramCanvas)theEObject; Object result = caseDiagramCanvas(diagramCanvas); if (result == null) result = defaultCase(theEObject); return result; } case DiagramRTPackage.DIAGRAM_BASE_ELEMENT: { DiagramBaseElement diagramBaseElement = (DiagramBaseElement)theEObject; Object result = caseDiagramBaseElement(diagramBaseElement); if (result == null) result = defaultCase(theEObject); return result; } case DiagramRTPackage.DIAGRAM_BASE_NODE: { DiagramBaseNode diagramBaseNode = (DiagramBaseNode)theEObject; Object result = caseDiagramBaseNode(diagramBaseNode); if (result == null) result = caseDiagramBaseElement(diagramBaseNode); if (result == null) result = defaultCase(theEObject); return result; } case DiagramRTPackage.CHILD_NODE: { ChildNode childNode = (ChildNode)theEObject; Object result = caseChildNode(childNode); if (result == null) result = caseDiagramNode(childNode); if (result == null) result = caseDiagramBaseNode(childNode); if (result == null) result = caseDiagramBaseElement(childNode); if (result == null) result = defaultCase(theEObject); return result; } case DiagramRTPackage.RIGID_CHILD_NODE: { RigidChildNode rigidChildNode = (RigidChildNode)theEObject; Object result = caseRigidChildNode(rigidChildNode); if (result == null) result = defaultCase(theEObject); return result; } default: return defaultCase(theEObject); } } /** * Returns the result of interpretting the object as an instance of '<em>Diagram Node</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpretting the object as an instance of '<em>Diagram Node</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public Object caseDiagramNode(DiagramNode object) { return null; } /** * Returns the result of interpretting the object as an instance of '<em>Diagram Link</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpretting the object as an instance of '<em>Diagram Link</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public Object caseDiagramLink(DiagramLink object) { return null; } /** * Returns the result of interpretting the object as an instance of '<em>Diagram Canvas</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpretting the object as an instance of '<em>Diagram Canvas</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public Object caseDiagramCanvas(DiagramCanvas object) { return null; } /** * Returns the result of interpretting the object as an instance of '<em>Diagram Base Element</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpretting the object as an instance of '<em>Diagram Base Element</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public Object caseDiagramBaseElement(DiagramBaseElement object) { return null; } /** * Returns the result of interpretting the object as an instance of '<em>Diagram Base Node</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpretting the object as an instance of '<em>Diagram Base Node</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public Object caseDiagramBaseNode(DiagramBaseNode object) { return null; } /** * Returns the result of interpretting the object as an instance of '<em>Child Node</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpretting the object as an instance of '<em>Child Node</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public Object caseChildNode(ChildNode object) { return null; } /** * Returns the result of interpretting the object as an instance of '<em>Rigid Child Node</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpretting the object as an instance of '<em>Rigid Child Node</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public Object caseRigidChildNode(RigidChildNode object) { return null; } /** * Returns the result of interpretting the object as an instance of '<em>EObject</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch, but this is the last case anyway. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpretting the object as an instance of '<em>EObject</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) * @generated */ public Object defaultCase(EObject object) { return null; } } //DiagramRTSwitch
[ "atikhomirov" ]
atikhomirov
9cc4048f4195058ba1479e866f94043b174074b9
5cad59b093f6be43057e15754ad0edd101ed4f67
/src/Interview/Google/Array/ContainerwithMostWater.java
9e60cd30d5d437f7c2fb9c41cd62156abc15e181
[]
no_license
GeeKoders/Algorithm
fe7e58687bbbca307e027558f6a1b4907ee338db
fe5c2fca66017b0a278ee12eaf8107c79aef2a14
refs/heads/master
2023-04-01T16:31:50.820152
2021-04-21T23:55:31
2021-04-21T23:55:31
276,102,037
0
0
null
null
null
null
UTF-8
Java
false
false
1,650
java
package Interview.Google.Array; public class ContainerwithMostWater { /* * 11. Container With Most Water(Medium) * * https://leetcode.com/problems/container-with-most-water/ * * solution: https://leetcode.com/problems/container-with-most-water/solution/ * * Your runtime beats 14.96 % of java submissions. * Your memory usage beats 34.30 % of java submissions. * * Brute Force * * Time complexity: O(N^2) * Space complexity:O(1) * */ public int maxArea(int[] height) { int n = height.length ; int res = 0 ; for(int i = 0 ; i<n; i++){ for(int j=i+1; j<n; j++){ res = Math.max(res, Math.min(height[i], height[j]) * (j - i)) ; } } return res ; } /* * Your runtime beats 45.14 % of java submissions. * Your memory usage beats 8.72 % of java submissions. * * Two pointer * * Time complexity: O(N) * Space complexity: O(1) * */ public int maxArea2(int[] height) { int res = -1 ; if(height == null || height.length < 2) return res ; int n = height.length ; int left = 0 ; int right = n - 1 ; while(left < right){ res = Math.max(res, Math.min(height[left], height[right]) * (right - left)) ; if(height[left] < height[right]){ left ++ ; }else{ right -- ; } } return res ; } }
22035cb916b192ea32d33c4c4a4a27a07447fedf
71f2c58b0854cf4e32e6fc48f404d259b27e16b3
/src/chessGame/model/GenericChessPiece.java
da7d878e45e9ddf0a8a7da094e9b5391f95d38f4
[]
no_license
rub3z/GaemzMastah
fe2e4942a2bb4778ef7407a92aef77e5c3e2c09d
323cd91ac83ba3bb2396e9e230519538243e424a
refs/heads/master
2021-05-08T16:17:01.086753
2018-03-19T22:19:52
2018-03-19T22:19:52
120,151,636
1
0
null
null
null
null
UTF-8
Java
false
false
1,321
java
package chessGame.model; import javafx.geometry.Point2D; import java.util.List; public abstract class GenericChessPiece { private ChessPieceType type; private Point2D currentPosition; private int owner; private ChessManager manager; public GenericChessPiece() { type = ChessPieceType.PAWN; currentPosition = new Point2D(0, 0); owner = 0; } public GenericChessPiece(ChessPieceType type, int x, int y, int owner) { this.type = type; currentPosition = new Point2D(x, y); this.owner = owner; } public boolean move(Point2D nextPosition) { setCurrentPosition(nextPosition); return true; } public abstract void capture(); public abstract void captured(); public abstract List<Point2D> availableMove(int size); public abstract List<Point2D> availableCapture(int size); public Point2D getCurrentPosition() { return currentPosition; } public void setCurrentPosition(Point2D currentPosition) { this.currentPosition = currentPosition; } public int getOwner() { return owner; } public ChessManager getManager() { return manager; } public void setManager(ChessManager manager) { this.manager = manager; } public ChessPieceType getType() { return type; } }
2830fd667e06b0ac956fc6d7f9c00590631deab2
901d29d497f05f338d984a3bbd6fb0fc13137532
/MainLakshmi.java
c3a6529f725c394357139e7ef9d7335c4c4fc36c
[]
no_license
mahalakshmi586/Learning
fe5a67421d6182b30f81f9a174b0aaeef5a53139
957c51312852b0e965ecde382f42d60ef57c6d91
refs/heads/master
2020-12-14T16:04:15.542636
2020-02-01T05:54:30
2020-02-01T05:54:30
234,800,998
0
0
null
null
null
null
UTF-8
Java
false
false
1,423
java
public class MainLakshmi{ public static void main(String[] args){ Father father = new Father(" Krishna " , " Nitla "); Mother mother = new Mother(" Lakshmi " , " Nitla "); Husband husband = new Husband(" Narsimharao " , " kota "); Brother brother = new Brother(" Sudhakar " , " Nitla "); Lakshmi lakshmi = new Lakshmi(" maha "," vishnu ", father , mother , husband , brother); Father lakshmiFather = lakshmi.getFather(); Mother lakshmiMother = lakshmi.getMother(); Husband lakshmiHusband = lakshmi.getHusband(); Brother lakshmiBrother = lakshmi.getBrother(); System.out.println("FirstName" + lakshmi.getFirstName()); System.out.println("LastName" + lakshmi.getLastName()); // System.out.println("father" + lakshmi.getFather()); //System.out.println("mother" + lakshmi.getMother()); // System.out.println("husband" + lakshmi.getHusband()); //System.out.println("Brother" + lakshmi.getBrother()); System.out.println("Father" + lakshmiFather.getFirstName()); System.out.println("Father" + lakshmiFather.getLastName()); System.out.println("Mother" + lakshmiMother.getFirstName()); System.out.println("mother" + lakshmiMother.getLastName()); System.out.println("Husband" + lakshmiHusband.getFirstName()); System.out.println("Husband" + lakshmiHusband.getLastName()); System.out.println("Brother" + lakshmiBrother.getFirstName()); System.out.println("Brother" + lakshmiBrother.getLastName()); } }
e432c44ddf6682ed20bb08910a7b78b9f5d2eb32
2c37294849b9c578e95c027776d0f27f50e256c1
/VoronoiGenerator/src/fexla/vor/ui/item/TextFieldChecker.java
21d942195dc82177a3d4c8f4bf9f4ae3bbbd2119
[ "MIT" ]
permissive
fexla/VoronoiGenerator
11be4dd8d8bb624e08435aedeef3891106f6458a
16eedc286f8dacb5475766d26a033019d541b446
refs/heads/main
2023-03-22T19:49:15.219060
2021-03-21T05:28:05
2021-03-21T05:28:05
338,348,368
3
0
null
null
null
null
UTF-8
Java
false
false
100
java
package fexla.vor.ui.item; public interface TextFieldChecker { boolean check(String string); }
0078054e4f71fe529a41312e276bd1cddb82c769
474d42f14f588059ac1eab009615ed0b4c76f445
/xrpl4j-model/src/main/java/org/xrpl/xrpl4j/model/client/accounts/AccountTransactionsRequestParams.java
99b81ac361d1b2083c4f9cbbd37a60a70de72c07
[ "ISC" ]
permissive
kanumalivad/xrpl4j
0d0662d70b191bd9e5b2a4d5ead724e61e05d1dc
22324129281c1f1fb17ea4cada470c3e80a4d6f3
refs/heads/main
2023-08-16T04:32:24.043012
2021-10-01T16:21:40
2021-10-01T16:21:40
412,535,447
0
0
ISC
2021-10-01T16:12:21
2021-10-01T16:12:20
null
UTF-8
Java
false
false
8,520
java
package org.xrpl.xrpl4j.model.client.accounts; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonUnwrapped; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.fasterxml.jackson.databind.annotation.JsonSerialize; import com.google.common.base.Preconditions; import com.google.common.primitives.UnsignedInteger; import org.immutables.value.Value; import org.xrpl.xrpl4j.model.client.LegacyLedgerSpecifierUtils; import org.xrpl.xrpl4j.model.client.XrplRequestParams; import org.xrpl.xrpl4j.model.client.common.LedgerIndex; import org.xrpl.xrpl4j.model.client.common.LedgerIndexBound; import org.xrpl.xrpl4j.model.client.common.LedgerIndexShortcut; import org.xrpl.xrpl4j.model.client.common.LedgerSpecifier; import org.xrpl.xrpl4j.model.jackson.modules.AccountTransactionsRequestParamsDeserializer; import org.xrpl.xrpl4j.model.transactions.Address; import org.xrpl.xrpl4j.model.transactions.Hash256; import org.xrpl.xrpl4j.model.transactions.Marker; import java.util.Optional; import javax.annotation.Nullable; /** * Request parameters for the account_tx rippled method. */ @Value.Immutable @JsonSerialize(as = ImmutableAccountTransactionsRequestParams.class) @JsonDeserialize( as = ImmutableAccountTransactionsRequestParams.class, using = AccountTransactionsRequestParamsDeserializer.class ) public interface AccountTransactionsRequestParams extends XrplRequestParams { /** * Construct a builder for this class. * * @return An {@link ImmutableAccountTransactionsRequestParams.Builder}. */ static ImmutableAccountTransactionsRequestParams.Builder builder() { return ImmutableAccountTransactionsRequestParams.builder(); } /** * A unique {@link Address} for the account. * * @return The {@link Address} of the account. */ Address account(); /** * The earliest ledger to include transactions from. A value of {@code -1} instructs the server to use the * earliest validated ledger version available. * * @return A {@link LedgerIndex} with a default of empty. * @deprecated ledger_index_min field should be specified by {@link #ledgerIndexMinimum()} */ @JsonIgnore @Deprecated @Value.Auxiliary Optional<LedgerIndex> ledgerIndexMin(); /** * The most recent ledger to include transactions from. A value of {@code -1} instructs the server to use the most * recent validated ledger version available. * * @return A {@link LedgerIndex} with a default of empty. * @deprecated ledger_index_max field should be specified by {@link #ledgerIndexMaximum()}. */ @JsonIgnore @Deprecated @Value.Auxiliary Optional<LedgerIndex> ledgerIndexMax(); /** * The earliest ledger to include transactions from. A value of {@code -1} instructs the server to use the * earliest validated ledger version available. * * @return A {@link LedgerIndexBound} with a default of empty. */ @JsonProperty("ledger_index_min") @Value.Default @Nullable // Value.Default on Optional attributes takes away the non-optional builder method default LedgerIndexBound ledgerIndexMinimum() { // Gives deprecated field precedence return ledgerIndexMin() .map(LedgerIndex::unsignedIntegerValue) .map(UnsignedInteger::intValue) .map(LedgerIndexBound::of) .orElse(LedgerIndexBound.of(-1)); } /** * The most recent ledger to include transactions from. A value of {@code -1} instructs the server to use the most * recent validated ledger version available. * * @return A {@link LedgerIndexBound} with a default of empty. */ @JsonProperty("ledger_index_max") @Value.Default @Nullable // Value.Default on Optional attributes takes away the non-optional builder method default LedgerIndexBound ledgerIndexMaximum() { // Gives deprecated field precedence return ledgerIndexMax() .map(LedgerIndex::unsignedIntegerValue) .map(UnsignedInteger::intValue) .map(LedgerIndexBound::of) .orElse(LedgerIndexBound.of(-1)); } /** * Return transactions from the ledger with this hash only. * * @return An optionally-present {@link Hash256} containing the ledger hash. * @deprecated Ledger hash should be specified in {@link #ledgerSpecifier()}. */ @JsonIgnore @Deprecated @Value.Auxiliary Optional<Hash256> ledgerHash(); /** * Return transactions from the ledger with this index only. * * @return A {@link LedgerIndex} containing the ledger index, defaults to "current". * @deprecated Ledger index and any shortcut values should be specified in {@link #ledgerSpecifier()}. */ @JsonIgnore @Deprecated @Value.Auxiliary Optional<LedgerIndex> ledgerIndex(); /** * Specifies the ledger version to request. A ledger version can be specified by ledger hash, * numerical ledger index, or a shortcut value. * * <p>The only valid ledger index shortcut for this request object is * {@link org.xrpl.xrpl4j.model.client.common.LedgerIndexShortcut#VALIDATED}.</p> * * <p>Setting this value will nullify and take precedence over {@link #ledgerIndexMinimum()} * and {@link #ledgerIndexMaximum()}</p> * * @return A {@link LedgerSpecifier} specifying the ledger version to request. */ @JsonUnwrapped @Value.Default // TODO: Make non-default once ledgerIndex and ledgerHash are gone default Optional<LedgerSpecifier> ledgerSpecifier() { // If either ledgerHash or ledgerIndex are specified, return a LedgerSpecifier with the present field, // otherwise return empty return ledgerHash() .map(LedgerSpecifier::of) .map(Optional::of) .orElseGet(() -> ledgerIndex().map(LegacyLedgerSpecifierUtils::computeLedgerSpecifierFromLedgerIndex)); } /** * Whether or not to return transactions as JSON or binary-encoded hex strings. Always {@code false}. * * @return Always {@code false}. */ @Value.Derived default boolean binary() { return false; } /** * If set to {@code true}, returns values indexed with the oldest ledger first. Otherwise, the results are indexed * with the newest ledger first. (Each page of results may not be internally ordered, but the pages are overall * ordered.) * * @return {@code true} if values should be indexed with the oldest ledger first, otherwise {@code false}. Defaults * to {@code false}. */ @Value.Default default boolean forward() { return false; } /** * Limit the number of transactions to retrieve. The server is not required to honor this value. * * @return An optionally-present {@link UnsignedInteger} representing the number of transactions to return. */ Optional<UnsignedInteger> limit(); /** * Value from a previous paginated response. Resume retrieving data where that response left off. * This value is stable even if there is a change in the server's range of available ledgers. * * @return An optionally-present {@link String} containing the marker. */ Optional<Marker> marker(); /** * Validates that if {@link LedgerSpecifier#ledgerIndexShortcut()} is present, its value is * {@link LedgerIndexShortcut#VALIDATED}. */ @Value.Check default void validateSpecifierNotCurrentOrClosed() { ledgerSpecifier().ifPresent( ledgerSpecifier -> ledgerSpecifier.handle( ledgerHash -> { }, ledgerIndex -> { }, ledgerIndexShortcut -> Preconditions.checkArgument( ledgerIndexShortcut.equals(LedgerIndexShortcut.VALIDATED), "Invalid LedgerIndexShortcut. The account_tx API method only accepts 'validated' when specifying a shortcut." ) ) ); } /** * Nullifies {@link #ledgerIndexMinimum()} and {@link #ledgerIndexMaximum()} if {@link #ledgerSpecifier()} is present. * * @return An {@link AccountTransactionsRequestParams}. */ @Value.Check default AccountTransactionsRequestParams emptyBoundedParametersIfSpecifierPresent() { // If user included a ledgerSpecifier, this will blank out ledgerIndexMin and ledgerIndexMax // so that they do not override the ledgerSpecifier. if (ledgerSpecifier().isPresent() && (ledgerIndexMinimum() != null || ledgerIndexMaximum() != null)) { return AccountTransactionsRequestParams.builder() .from(this) .ledgerIndexMinimum(null) .ledgerIndexMaximum(null) .build(); } else { return this; } } }
a9927f7e016df72f19365cf36c1da0cbd1edc3a3
88ed30ae68858ad6365357d4b0a95ad07594c430
/agent/arcus-zw-controller/src/main/java/com/iris/agent/zw/ZWUtils.java
cc589b4f4aeb7b59d276bdb4847c4288f91ed8ff
[ "Apache-2.0" ]
permissive
Diffblue-benchmarks/arcusplatform
686f58654d2cdf3ca3c25bc475bf8f04db0c4eb3
b95cb4886b99548a6c67702e8ba770317df63fe2
refs/heads/master
2020-05-23T15:41:39.298441
2019-05-01T03:56:47
2019-05-01T03:56:47
186,830,996
0
0
Apache-2.0
2019-05-30T11:13:52
2019-05-15T13:22:26
Java
UTF-8
Java
false
false
1,765
java
/* * Copyright 2019 Arcus Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.iris.agent.zw; import java.nio.ByteOrder; import java.nio.charset.StandardCharsets; import com.iris.agent.hal.IrisHal; import com.iris.agent.util.ByteUtils; import com.iris.messages.address.ProtocolDeviceId; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; public class ZWUtils { public static boolean isValidNodeId(int nid) { return (nid > 0 && nid <= 232); } public static ProtocolDeviceId getDeviceId(long homeIdAsLong, int nodeIdAsInt) { int homeId = ByteUtils.from32BitToInt(ByteUtils.to32Bits(homeIdAsLong)); byte nodeId = (byte)nodeIdAsInt; byte[] hubId = ZWConfig.HAS_AGENT ? IrisHal.getHubId().getBytes(StandardCharsets.UTF_8) : "LWW-1202".getBytes(StandardCharsets.UTF_8); ByteBuf buffer = Unpooled.buffer(hubId.length + 6, hubId.length + 6).order(ByteOrder.BIG_ENDIAN); buffer.writeByte(nodeId); buffer.writeBytes(hubId); buffer.writeInt(homeId); buffer.writeByte(nodeId); return ProtocolDeviceId.fromBytes(buffer.array()); } public static int safeInt(Integer i, int def) { return i != null ? i : def; } }
c73563ba90e4eb8d4474d0da991a190f012ed975
5e08aa6ffb0be62990b28a64acc87edd45bb4f0a
/src/cn/foritou/model/FileImage.java
4f6a19abb6a5f3c5a187c2ba98edd61d28362a35
[]
no_license
Chenchicheng/foritou
1850c02b2938fb7320260dcc0bb5fd6f30da004c
1316c2e91b4df98fa9292fd8f83792ea55e0e8eb
refs/heads/master
2021-01-19T09:58:37.354301
2017-04-18T01:56:12
2017-04-18T01:56:12
87,801,635
0
0
null
null
null
null
UTF-8
Java
false
false
638
java
package cn.foritou.model; import java.io.File; public class FileImage { private File file; private String contentType; private String filename; public File getFile() { return file; } public String getContentType() { return contentType; } public String getFilename() { return filename; } public void setUpload(File file){ System.out.println("file:"+file); this.file=file; } public void setUploadContentType(String contentType){ System.out.println("contentType:"+contentType); this.contentType=contentType; } public void setUploadFileName(String filename){ System.out.println("filename:"+filename); this.filename=filename; } }
8e0aae36cd1cea0e6c8b0ceb9024018b40b93692
cd48013d7f890f0e6367a0149fe991c210ff2876
/C6 Solo Rush Source Code/Char_Dead_Piece.java
2a004ec10877d280dc69099492e0e75f5ace4c85
[]
no_license
WilliamJarboe/Personal-Projects
450d11084fed9df2e04fd05fb5b7c22464e7db18
35b8739478090a54762964cf34040a5cda25a121
refs/heads/main
2023-04-18T20:09:00.197238
2021-05-11T06:43:16
2021-05-11T06:43:16
324,918,995
0
0
null
null
null
null
UTF-8
Java
false
false
1,294
java
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo) /** * Write a description of class Char_Dead_Piece here. * * @author (your name) * @version (a version number or a date) */ public class Char_Dead_Piece extends Actor { boolean first = true; int speed; int fr = 0; public Char_Dead_Piece(int angle,int speed){ setRotation(angle); this.speed = speed; } /** * Act - do whatever the Char_Dead_Piece wants to do. This method is called whenever * the 'Act' or 'Run' button gets pressed in the environment. */ public void act() { if(first){ move(30); first = false; } if(fr<=100){ if(fr%10==0){ move(speed/2); } } else if(fr>100){ move(speed); } fr++; if(getX()<3){ setRotation(180-getRotation()); } if(getY()<3){ setRotation(180-getRotation()); } if(getX()>getWorld().getWidth()-3){ setRotation(180-getRotation()); } if(getY()>getWorld().getHeight()-3 || fr>140){ getWorld().removeObject(this); } } }
c0c647198b08a5db31eb643a20d5d06f77efca39
3060d15999d3c1d086b248fadd068b1d62d480e8
/src/test/java/com/techproed/tests/ExcelAutomation.java
0cb619d3631f538ebfa4d68becc8aa907cf97fd1
[]
no_license
YesimKaragulmez/mytestNgFramework
c0335abc75f22709a2a633d6c391837fd9b96e51
29689510121f117f8e858abd335336800e3bc765
refs/heads/master
2023-01-02T08:11:54.779664
2020-10-27T20:07:18
2020-10-27T20:07:18
286,987,624
0
0
null
null
null
null
UTF-8
Java
false
false
1,876
java
package com.techproed.tests; import com.techproed.pages.DataTablesExcel; import com.techproed.utilities.Driver; import com.techproed.utilities.ExcelUtil; import org.testng.Assert; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import java.util.List; import java.util.Map; public class ExcelAutomation { DataTablesExcel dtExcel = new DataTablesExcel(); ExcelUtil excelUtil; List<Map<String, String>> testData; int count = 0; @BeforeMethod public void getTestData() { //we are setting up the file path and sheet path using the Excel Util class excelUtil = new ExcelUtil("./src/test/resouces/exceldata.xlsx", "Sheet1"); //we are calling the getDataList method from teh ExelUtil class to get the data from the excel sheet testData = excelUtil.getDataList(); } @Test public void ExcelDataAutomation() throws InterruptedException { for (Map<String, String> appData : testData) { Driver.getDriver().get("https://editor.datatables.net/"); dtExcel.newButton.click(); dtExcel.firstName.sendKeys(appData.get("firstname")); dtExcel.lastName.sendKeys(appData.get("lastname")); dtExcel.position.sendKeys(appData.get("position")); dtExcel.office.sendKeys(appData.get("office")); dtExcel.extension.sendKeys(appData.get("extension")); //dtExcel.startDate.sendKeys(appData.get("startdate")); dtExcel.startDate.click(); dtExcel.day.click(); dtExcel.salary.sendKeys(appData.get("salary")); dtExcel.createButton.click(); dtExcel.searchBox.sendKeys(appData.get("firstname")); Thread.sleep(3000); Assert.assertTrue(dtExcel.nameField.getText().contains(appData.get("firstname"))); } } }
ee0c5d50397a4cc9e5d92095313a34cb3a0f0111
22bb64f4687acdc51890bc0f7096558406580760
/alipay-order-internal/src/main/java/com/shanyuan/alipayorderinternal/config/Swagger2Config.java
8da9e3a26cfc3dfffa03cab8a2016b25c41a4267
[]
no_license
shaoqiushen/order
52e27fc0c9bc5cae220e0b801a7d5e2ceaf0cc9e
45f050a1949595be2cf6cbd70f7d40cdc2b4cd23
refs/heads/master
2022-06-28T02:01:52.700013
2019-11-28T07:12:17
2019-11-28T07:12:23
219,706,417
0
0
null
2022-06-21T02:19:53
2019-11-05T09:28:26
Java
UTF-8
Java
false
false
1,301
java
package com.shanyuan.alipayorderinternal.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import springfox.documentation.builders.ApiInfoBuilder; import springfox.documentation.builders.PathSelectors; import springfox.documentation.builders.RequestHandlerSelectors; import springfox.documentation.service.ApiInfo; import springfox.documentation.spi.DocumentationType; import springfox.documentation.spring.web.plugins.Docket; import springfox.documentation.swagger2.annotations.EnableSwagger2; /** * Swagger2API文档的配置 * */ @Configuration @EnableSwagger2 public class Swagger2Config { @Bean public Docket createRestApi(){ return new Docket(DocumentationType.SWAGGER_2) .apiInfo(apiInfo()) .select() .apis(RequestHandlerSelectors.basePackage("com.shanyuan.alipayorderinternal.controller")) .paths(PathSelectors.any()) .build(); } private ApiInfo apiInfo() { return new ApiInfoBuilder() .title("点餐系统内部使用接口文档") .description("大帅比在此~") .contact("shenshaoqiu") .version("1.0") .build(); } }
02163c4679a7c839984fa41bd9d1d3860d7e215d
fae9e68c19ea08851b2f06e387b854eb6dff36e1
/Data Structures/src/com/tts/Node.java
dbf966ae5f5f2f3ab5c14fe3faeb40e63c75b205
[]
no_license
LLJ3288/DataStructuresOne
ace27e544506b230ae2406b73779eca1773d9727
532edfd4a22ee7a32e72bfeeb6c9f54c17163b2f
refs/heads/main
2023-02-20T04:56:43.770009
2021-01-13T04:13:16
2021-01-13T04:13:16
329,190,674
0
0
null
null
null
null
UTF-8
Java
false
false
154
java
package com.tts; public class Node { // this node needs the reference to the next node // this node needs the data its going to hold }
bd4effd198cc267db96031ba7410045d10b4773b
6cb60832969ec9232b359c2997e48e9f79fc6e52
/src/main/java/jp/co/stex/domain/mapper/typehandler/ComparisonTypeHandler.java
c8ffe00c721a5a3d5bae626f30138e8b72777900
[]
no_license
tnemotox/stex-next
de860d6b19e4dad6fc836423a25c233443201548
fab000f83d4caf47c40b9d078326b028402f61cd
refs/heads/master
2020-03-24T13:14:11.143933
2018-08-17T14:31:12
2018-08-17T14:31:12
142,737,723
0
0
null
null
null
null
UTF-8
Java
false
false
1,451
java
package jp.co.stex.domain.mapper.typehandler; import jp.co.stex.domain.model.strategy.code.ComparisonType; import org.apache.ibatis.type.BaseTypeHandler; import org.apache.ibatis.type.JdbcType; import java.sql.CallableStatement; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; /** * <p>比較種別をMyBatisでマッピングするハンドラです。</p> * * @author t.nemoto.x */ public class ComparisonTypeHandler extends BaseTypeHandler<ComparisonType> { /** * {@inheritDoc} */ @Override public void setNonNullParameter(PreparedStatement preparedStatement, int i, ComparisonType comparisonType, JdbcType jdbcType) throws SQLException { preparedStatement.setInt(i, comparisonType.getId()); } /** * {@inheritDoc} */ @Override public ComparisonType getNullableResult(ResultSet resultSet, String s) throws SQLException { return ComparisonType.findById(resultSet.getInt(s)); } /** * {@inheritDoc} */ @Override public ComparisonType getNullableResult(ResultSet resultSet, int i) throws SQLException { return ComparisonType.findById(resultSet.getInt(i)); } /** * {@inheritDoc} */ @Override public ComparisonType getNullableResult(CallableStatement callableStatement, int i) throws SQLException { return ComparisonType.findById(callableStatement.getInt(i)); } }
d011a2f398df1c254d1f010e7b38d9693720bf23
fe901a752b3eae6a7e83a21c120ecb00698a952b
/EurekaClient-Sentence/src/main/java/com/learn/spring/cloud/eureka/client/EurekaClientSentenceApplication.java
88f502d7ca71597c10c45feed18908fe132fe948
[]
no_license
arturbdr/SpringCloudEurekaRibbonFeignHystrix
f084fcf8c2abc0078c3ad58cbd075aa85ec7419c
6f90724e1eed532bb125259d4b458ee05ca881b8
refs/heads/master
2021-05-04T11:03:30.945077
2019-04-17T21:24:00
2019-04-17T21:24:00
54,495,030
1
0
null
null
null
null
UTF-8
Java
false
false
866
java
package com.learn.spring.cloud.eureka.client; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker; import org.springframework.cloud.client.discovery.EnableDiscoveryClient; import org.springframework.cloud.netflix.hystrix.dashboard.EnableHystrixDashboard; import org.springframework.cloud.openfeign.EnableFeignClients; @SpringBootApplication @EnableFeignClients @EnableDiscoveryClient @EnableHystrixDashboard @EnableCircuitBreaker @EnableConfigurationProperties public class EurekaClientSentenceApplication { public static void main(String[] args) { SpringApplication.run(EurekaClientSentenceApplication.class, args); } }
4f2ca7f297cc9ed2acf6633f2a6690fb533dfc29
8a75e1b5fa6b5f94997aacbde4e5a015119eb1c1
/cmsops/src/main/java/cabletie/cms/ops/operationDBModel/inventory/ItemLog.java
9fecf99fcddd9c3af2c91508ea5b4c4183bed412
[]
no_license
xyme/finalSR4main
33f0820aeccbb9ba169f41da2dfcd8c7364d867d
0744f8423585baf02a33e6f75d52bdf737e99f4b
refs/heads/master
2021-08-14T20:54:56.881059
2017-11-16T18:56:56
2017-11-16T18:56:56
110,790,736
0
0
null
null
null
null
UTF-8
Java
false
false
1,867
java
package cabletie.cms.ops.operationDBModel.inventory; import java.sql.Timestamp; import java.util.Date; import java.util.Random; import java.util.concurrent.ThreadLocalRandom; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; @Entity public class ItemLog { @Id private int logID; private int itemID; private String infraID; private Timestamp modDate; private String modBy; private int befQuantity; private int aftQuantity; public ItemLog() { } public ItemLog(int itemID, String infraID, String modBy, int befQuantity, int aftQuantity) { super(); int randomNum = ThreadLocalRandom.current().nextInt(1, 999999999+1); this.logID = randomNum; this.itemID = itemID; this.infraID = infraID; //Set current time Date date = new Date(); long time = date.getTime(); this.modDate = new Timestamp(time); this.modBy = modBy; this.befQuantity = befQuantity; this.aftQuantity = aftQuantity; } public String getInfraID() { return infraID; } public void setInfraID(String infraID) { this.infraID = infraID; } public long getLogID() { return logID; } public void setLogID(int logID) { this.logID = logID; } public int getItemID() { return itemID; } public void setItemID(int itemID) { this.itemID = itemID; } public Timestamp getModDate() { return modDate; } public void setModDate(Timestamp modDate) { this.modDate = modDate; } public String getModBy() { return modBy; } public void setModBy(String modBy) { this.modBy = modBy; } public int getBefQuantity() { return befQuantity; } public void setBefQuantity(int befQuantity) { this.befQuantity = befQuantity; } public int getAftQuantity() { return aftQuantity; } public void setAftQuantity(int aftQuantity) { this.aftQuantity = aftQuantity; } }
9a8dbb6278f2b8869bab9a953a8abd5af9d7afaf
d3081853363c4755af14357a216d0092def3c6ff
/src/main/java/proyectofinal/CallBack.java
6107ecf380f40eead25cc1940ca0c2064ccd76a4
[]
no_license
MiguelZapata11/Maven_Basic
866695dbe15d749b8b8b5f1aea5d674fc6544996
d33e4174521ca64a7964c7104a5661605631a952
refs/heads/master
2020-05-16T17:10:56.555961
2019-05-21T08:40:32
2019-05-21T08:40:32
183,187,187
0
1
null
2019-04-24T08:44:04
2019-04-24T08:44:04
null
UTF-8
Java
false
false
116
java
package proyectofinal; public interface CallBack { public void doWork(boolean llevagafas, String... strings); }
05bccae4168f76b8e7285f107a4550f7fd089216
5cc7d36e996060c7290d0403a303449e2e88dc0e
/app/src/main/java/com/health/myapplication/SymptomService.java
cc757fef31f2c58cea4bd0bf1a7d4e18c4e7cc05
[]
no_license
rahimo01uni/MyApplication
b6dab73e6decda0e568b8e3fb177648e612e098f
324002cb05195e95a14d66c6c2d238a242505e3f
refs/heads/master
2022-11-13T20:40:52.533054
2020-07-08T15:59:22
2020-07-08T15:59:22
272,500,017
0
0
null
2020-06-27T09:54:45
2020-06-15T17:17:21
Java
UTF-8
Java
false
false
1,258
java
package com.health.myapplication; import android.app.Service; import android.content.Intent; import android.os.IBinder; import android.util.Log; import android.view.GestureDetector; import android.view.MotionEvent; import com.health.myapplication.bubles.sleep_buble; import com.health.myapplication.bubles.symptom_buble; /** * Created by graphics on 9/22/2016. */ public class SymptomService extends Service { @Override public IBinder onBind(Intent intent) { // Not used Log.d("what",intent.getStringExtra("wake_up")); return null; } @Override public void onCreate() { super.onCreate(); Log.v("Service Created","Service Created"); } @Override public void onDestroy() { super.onDestroy(); } @Override public int onStartCommand(Intent intent, int flags, int startId) { new symptom_buble(getApplicationContext(),""); return super.onStartCommand(intent, flags, startId); } private class SingleTapConfirm extends GestureDetector.SimpleOnGestureListener { @Override public boolean onSingleTapUp(MotionEvent event) { return true; } } }
f07a3d490aa1d6e8eac1216a6ce67345b535e5a2
0cfd46a0748c22ee4fd886237ea683cd79b8bf9b
/youke-common-dao/src/main/java/youke/common/dao/IMobcodePackageDao.java
6d55e9c2a9de1f17562c78a8259000fe9e116e4d
[]
no_license
liumingaccp/youke
c1c78a99ad358f50ea0319cb585426aafd1129d1
3a9cfbf31c50b2a84def79b3979ede63f8d65c32
refs/heads/master
2022-12-24T20:09:03.510822
2019-06-29T10:51:49
2019-06-29T10:51:49
194,226,669
0
4
null
2022-12-10T00:16:58
2019-06-28T07:17:01
Java
UTF-8
Java
false
false
446
java
package youke.common.dao; import youke.common.model.TMobcodePackage; import java.util.List; public interface IMobcodePackageDao { int deleteByPrimaryKey(Integer id); int insertSelective(TMobcodePackage record); TMobcodePackage selectByPrimaryKey(Integer id); int updateByPrimaryKeySelective(TMobcodePackage record); /** * 获取短信套餐 * * @return */ List<TMobcodePackage> getPackages(); }
5d7ba81856407898554674327ae63d5f391f0037
294d9d5df0275d404389b96e6beabb35b355f7d3
/src/main/java/dosn/utility/json/RRequestJSON.java
939d7711b3a257aefa9c89cfba5be11cf26c16ee
[]
no_license
fsalem/DOSN.database.module
3145cb75f7ffaaab3bcc54d15e15b431dfdfd5d1
dbbd5d35a57232921b5c3ea1a7fbc6179435879d
refs/heads/master
2021-01-17T18:50:36.122099
2016-05-28T17:21:41
2016-05-28T17:21:41
59,906,321
0
0
null
null
null
null
UTF-8
Java
false
false
3,024
java
package dosn.utility.json; import java.util.List; import java.util.UUID; public class RRequestJSON { private String responseURI; private List<String> interests; private String msgID; private String userID; private Integer friendLevel; private Integer maxFriendLevel; private Integer maxResults; private Double minSimilarityScore; private Boolean includeFriends; public RRequestJSON(String responseURI, List<String> interests, String msgID, String userID, Integer friendLevel, Integer maxFriendLevel) { super(); this.responseURI = responseURI; this.interests = interests; this.msgID = msgID; this.userID = userID; this.friendLevel = friendLevel; this.maxFriendLevel = maxFriendLevel; } public RRequestJSON(String responseURI, List<String> interests, String msgID, String userID, Integer friendLevel, Integer maxFriendLevel, Integer maxResults, Double minSimilarityScore, Boolean includeFriends) { super(); this.responseURI = responseURI; this.interests = interests; this.msgID = msgID; this.userID = userID; this.friendLevel = friendLevel; this.maxFriendLevel = maxFriendLevel; this.maxResults = maxResults; this.minSimilarityScore = minSimilarityScore; this.includeFriends = includeFriends; } public String getResponseURI() { return responseURI; } public void setResponseURI(String responseURI) { this.responseURI = responseURI; } public List<String> getInterests() { return interests; } public void setInterests(List<String> interests) { this.interests = interests; } public String getMsgID() { return msgID; } public void setMsgID(String msgID) { this.msgID = msgID; } public String getUserID() { return userID; } public void setUserID(String userID) { this.userID = userID; } public Integer getFriendLevel() { return friendLevel; } public void setFriendLevel(Integer friendLevel) { this.friendLevel = friendLevel; } public Integer getMaxFriendLevel() { return maxFriendLevel; } public void setMaxFriendLevel(Integer maxFriendLevel) { this.maxFriendLevel = maxFriendLevel; } @Override public String toString() { return "RRequestJSON [responseURI=" + responseURI + ", interests=" + interests + ", msgID=" + msgID + ", userID=" + userID + ", friendLevel=" + friendLevel + ", maxFriendLevel=" + maxFriendLevel + "]"; } public Integer getMaxResults() { return maxResults; } public void setMaxResults(Integer maxResults) { this.maxResults = maxResults; } public Double getMinSimilarityScore() { return minSimilarityScore; } public void setMinSimilarityScore(Double minSimilarityScore) { this.minSimilarityScore = minSimilarityScore; } public Boolean getIncludeFriends() { return includeFriends; } public void setIncludeFriends(Boolean includeFriends) { this.includeFriends = includeFriends; } }
fb5ec2e240fba1f745b1206431c1bd1c3aad26f7
cda03b10ea30656a03b3be86ef754adcd900a15d
/avoider/AvoiderGameOverWorld.java
73f8a4a600206281ef1d92582b3a3c32833e75c0
[]
no_license
JimenaAlvarado/avoider-game
c78d69b7f0c5d4e0b18298d44b520ccc1fb5983c
f5cc7d0ad13a66c4c9fb7119062325deadd8329e
refs/heads/master
2020-08-24T14:37:09.657996
2019-10-25T06:04:39
2019-10-25T06:04:39
216,845,978
0
0
null
null
null
null
UTF-8
Java
false
false
749
java
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo) /** * Write a description of class AvoiderGameOverWorld here. * * @author (your name) * @version (a version number or a date) */ public class AvoiderGameOverWorld extends World { /** * Constructor for objects of class AvoiderGameOverWorld. * */ public AvoiderGameOverWorld() { // Create a new world with 600x400 cells with a cell size of 1x1 pixels. super(600, 400, 1); } public void act() { //Restart the game if the user clicks the mouse anywhere if(Greenfoot.mouseClicked(this)){ AvoiderWorld world = new AvoiderWorld(); Greenfoot.setWorld(world); } } }
6b7de471c7f0deb81a364a6868f451950dd4be55
9aeb14b18e15fca937245064fea9dcb505707bc9
/src/main/java/com/api/cdms/command/infrastructure/error/ErrorHandler.java
5ec28934440b7725babc709100a116534bb50d34
[]
no_license
moralescristian1001/mutant-api
fbd7f5d649de2da46e45f90819b134452a098196
c011d921a0b51ad4d5568292ecfaae670617d88d
refs/heads/master
2023-04-22T05:01:17.840830
2021-05-17T04:44:03
2021-05-17T04:44:03
368,046,313
0
0
null
null
null
null
UTF-8
Java
false
false
2,023
java
package com.api.cdms.command.infrastructure.error; import com.api.cdms.command.domain.exception.HumanException; import com.api.cdms.command.domain.exception.MutantException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import java.util.concurrent.ConcurrentHashMap; /** * Clase que maneja todos los errores a nivel global de la aplicación (dependiendo su tipo de excepción). */ @ControllerAdvice public class ErrorHandler { private static final Logger LOGGER_ERROR = LoggerFactory.getLogger(ErrorHandler.class); private static final String AN_ERROR_OCCURRED_PLEASE_CONTACT_THE_ADMINISTRATOR = "An error occurred please contact the administrator"; private static final ConcurrentHashMap<String, Integer> STATUS_CODE = new ConcurrentHashMap<>(); public ErrorHandler() { STATUS_CODE.put(MutantException.class.getSimpleName(), HttpStatus.BAD_REQUEST.value()); STATUS_CODE.put(HumanException.class.getSimpleName(), HttpStatus.FORBIDDEN.value()); } @ExceptionHandler(Exception.class) public final ResponseEntity<Error> handleAllExceptions(Exception exception) { ResponseEntity<Error> result; String exceptionName = exception.getClass().getSimpleName(); String message = exception.getMessage(); Integer code = STATUS_CODE.get(exceptionName); LOGGER_ERROR.error(exceptionName, exception); if (code != null) { Error error = new Error(exceptionName, message); result = new ResponseEntity<>(error, HttpStatus.valueOf(code)); } else { Error error = new Error(exceptionName, AN_ERROR_OCCURRED_PLEASE_CONTACT_THE_ADMINISTRATOR); result = new ResponseEntity<>(error, HttpStatus.INTERNAL_SERVER_ERROR); } return result; } }
c023638db515382a50452e4a15feb06c2ea81fb0
d52e273247d23de9c5f6db80b4dda3a360d2e482
/01_java_basic/src/step1_03/operator/OpEx05.java
77882a97dbc700eb6e672235dd712f0695f63f38
[]
no_license
calvinpark1110/01_java_basic
d146880af53aad7e66e0281d0eef1e7670fa8e00
cb2411fef8394331dcdf5916d4fe6153754b8782
refs/heads/master
2023-05-07T20:05:41.444031
2021-06-01T07:35:07
2021-06-01T07:35:07
372,741,513
0
0
null
null
null
null
UTF-8
Java
false
false
1,108
java
package step1_03.operator; /* * * # 논리 연산자 * * && (and) : 양쪽 모두다 참이어야 최종적으로 참(true) * Ex) 무주택 세대주이어야 '하고' 연봉이 3400 미만이어야 한다. * * || (or) : 어느 한쪽이라도 참이면 최종적으로 참(true) * Ex) 무주택 세대주 '이거나' 연봉이 3400 미만이어야 한다. * * ! (not) : 부정 (true > false , false > true) * * * [ 중요 ] * * - 논리 연산자의 결과도 참(true) 또는 거짓(false)이다. * * */ public class OpEx05 { public static void main(String[] args) { System.out.println(10 == 10 && 3 == 3); System.out.println(10 != 10 && 3 == 3); System.out.println(10 == 10 && 3 != 3); System.out.println(10 != 10 && 3 != 3); System.out.println(); System.out.println(10 == 10 || 3 == 3); System.out.println(10 != 10 || 3 == 3); System.out.println(10 == 10 || 3 != 3); System.out.println(10 != 10 || 3 != 3); System.out.println(); System.out.println(!(10 == 10)); System.out.println(!(10 != 10)); } }
7b3002fddd380ce5314119f48a8c8c07a8d18fb4
58cb3452c36e40ece74850497ec05819330f31c1
/src/main/java/com/notsay/myspring/helper/ControllerHelper.java
5400da9af942595ad0270575a740e1817cce190d
[]
no_license
notsayyu/myspring
a4f37dbc5b37071e8a21f26c947d2cd7129168f0
a1a97326cc2e4be835643d29c11f504c0b6fb1fb
refs/heads/master
2022-12-03T05:36:06.327684
2020-08-24T11:39:28
2020-08-24T11:39:28
288,882,268
0
0
null
null
null
null
UTF-8
Java
false
false
2,272
java
package com.notsay.myspring.helper; import com.notsay.myspring.annotation.RequestMapping; import com.notsay.myspring.bean.Handler; import com.notsay.myspring.bean.Request; import org.apache.commons.collections4.CollectionUtils; import org.apache.commons.lang3.ArrayUtils; import java.lang.reflect.Method; import java.util.HashMap; import java.util.Map; import java.util.Set; /** * @description: * @author: dsy * @date: 2020/8/21 14:48 */ public final class ControllerHelper { /** * REQUEST_MAP为 "请求-处理器" 的映射 */ private static final Map<Request, Handler> REQUEST_MAP = new HashMap<Request, Handler>(); static { //遍历所有Controller类 Set<Class<?>> controllerClassSet = ClassHelper.getControllerClassSet(); if (CollectionUtils.isNotEmpty(controllerClassSet)) { for (Class<?> controllerClass : controllerClassSet) { //暴力反射获取所有方法 Method[] methods = controllerClass.getDeclaredMethods(); //遍历方法 if (ArrayUtils.isNotEmpty(methods)) { for (Method method : methods) { //判断是否带RequestMapping注解 if (method.isAnnotationPresent(RequestMapping.class)) { RequestMapping requestMapping = method.getAnnotation(RequestMapping.class); //请求路径 String requestPath = requestMapping.value(); //请求方法 String requestMethod = requestMapping.method().name(); //封装请求和处理器 Request request = new Request(requestMethod, requestPath); Handler handler = new Handler(controllerClass, method); REQUEST_MAP.put(request, handler); } } } } } } /** * 获取 Handler */ public static Handler getHandler(String requestMethod, String requestPath) { Request request = new Request(requestMethod, requestPath); return REQUEST_MAP.get(request); } }
473df747c7b037a429dd6319e36429faeb29584e
55a7ba1af91070f55a2e3eb4c0eafdbbcb5a94db
/2.JavaCore/src/com/javarush/task/task16/task1613/Solution.java
0f9c237559e97899bae80f6436a27ebde640a534
[]
no_license
chas7610/JavaRushTasks
41d05f777f6b3027a50603daba92fff23099dab5
c99ed35404c78f00dceec9597bc7a66bb73f903a
refs/heads/master
2020-04-05T13:32:03.322618
2017-06-29T13:37:59
2017-06-29T13:37:59
94,867,170
0
0
null
null
null
null
UTF-8
Java
false
false
1,826
java
package com.javarush.task.task16.task1613; /* Big Ben clock */ import javax.xml.crypto.Data; import java.util.Date; public class Solution { public static volatile boolean isStopped = false; public static void main(String[] args) throws InterruptedException { Clock clock = new Clock("Лондон", 23, 59, 57); Thread.sleep(4000); isStopped = true; Thread.sleep(1000); } public static class Clock extends Thread { private String cityName; private int hours; private int minutes; private int seconds; public Clock(String cityName, int hours, int minutes, int seconds) { this.cityName = cityName; this.hours = hours; this.minutes = minutes; this.seconds = seconds; start(); } public void run() { try { while (!isStopped) { printTime(); } } catch (InterruptedException e) { } } private void printTime() throws InterruptedException { //add your code here - добавь код тут Thread.sleep(1000); seconds++; if (seconds>59){ seconds=0; minutes++; } if (minutes>59){ minutes=0; hours++; } if (hours>23){ hours=00; } if (hours == 0 && minutes == 0 && seconds == 0) { System.out.println(String.format("В г. %s сейчас полночь!", cityName)); } else { System.out.println(String.format("В г. %s сейчас %d:%d:%d!", cityName, hours, minutes, seconds)); } } } }
0c215820153a01fac7854f435356bdbb9ce1cdbf
09533de5b0dcf7b89873e63321b516e9a5fb71ca
/LinkedHashMap.java
fa6895478bfdc10a14bceadb3b86a725aacde0a9
[]
no_license
angelhigueros/AlgoritmosEj6
116f23df42e51193a0a01cd522f7bed02ffb9f05
08b29ec8ba600abdd8ed8c36eb5fe2f1841a6a69
refs/heads/main
2023-04-07T04:30:25.441630
2021-04-09T04:27:41
2021-04-09T04:27:41
null
0
0
null
null
null
null
UTF-8
Java
false
false
2,773
java
import java.util.LinkedList; import java.util.List; import java.util.Objects; class MyKeyValueEntry1<K, V> { private K key; private V value; public MyKeyValueEntry1(K key, V value) { this.key = key; this.value = value; } // getters & setters public K getKey() { return this.key; } public void setKey(K key) { this.key = key; } public V getValue() { return this.value; } public void setValue(V value) { this.value = value; } // hashCode & equals } class MyMapBucket1 { private List<MyKeyValueEntry1> entries; public MyMapBucket1() { if (entries == null) { entries = new LinkedList<>(); } } public List<MyKeyValueEntry1> getEntries() { return entries; } public void addEntry(MyKeyValueEntry1 entry) { this.entries.add(entry); } public void removeEntry(MyKeyValueEntry1 entry) { this.entries.remove(entry); } } public class LinkedHashMap<K, V> implements IMap<K, V> { private int CAPACITY = 10; private MyMapBucket1[] bucket; private int size = 0; public LinkedHashMap() { this.bucket = new MyMapBucket1[CAPACITY]; } private int getHash(K key) { return (key.hashCode() & 0xfffffff) % CAPACITY; } private MyKeyValueEntry1 getEntry(K key) { int hash = getHash(key); for (int i = 0; i < bucket[hash].getEntries().size(); i++) { MyKeyValueEntry1 myKeyValueEntry1 = bucket[hash].getEntries().get(i); if (myKeyValueEntry1.getKey().equals(key)) { return myKeyValueEntry1; } } return null; } public void put(K key, V value) { if (containsKey(key)) { MyKeyValueEntry1 entry = getEntry(key); entry.setValue(value); } else { int hash = getHash(key); if (bucket[hash] == null) { bucket[hash] = new MyMapBucket1(); } bucket[hash].addEntry(new MyKeyValueEntry1<>(key, value)); size++; } } public V get(K key) { return containsKey(key) ? (V) getEntry(key).getValue() : null; } public boolean containsKey(K key) { int hash = getHash(key); return !(Objects.isNull(bucket[hash]) || Objects.isNull(getEntry(key))); } public void delete(K key) { if (containsKey(key)) { int hash = getHash(key); bucket[hash].removeEntry(getEntry(key)); size--; } } public int size() { return size; } }
563ee459b1b9b9466bd4bb5adc8cbeefc09bb9b9
9777b5e5c6653fd97232b2cd5a60f32cac8d181c
/src/main/java/de/fnortheim/didemo/config/PropertyConfig.java
a8f44850c9cb81d9aa499d772fc8e5874b22360c
[]
no_license
areyouready/spring5-di-demo
47b79bb948bcd120eef6c8622804e7fd4740719b
0e7101f4e170287867640138f3457a5915609631
refs/heads/master
2020-04-29T13:01:16.794402
2019-04-22T20:42:00
2019-04-22T20:42:00
176,157,590
0
0
null
null
null
null
UTF-8
Java
false
false
1,308
java
package de.fnortheim.didemo.config; import de.fnortheim.didemo.examplebeans.FakeDataSource; import de.fnortheim.didemo.examplebeans.FakeJmsBroker; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.stereotype.Controller; /** * created by sebastian on Apr, 2019 */ @Controller public class PropertyConfig { @Value("${fnortheim.username}") String user; @Value("${fnortheim.password}") String password; @Value("${fnortheim.dburl}") String url; @Value("${fnortheim.jms.username}") String jmsUsername; @Value("${fnortheim.jms.password}") String jmsPassword; @Value("${fnortheim.jms.url}") String jmsUrl; @Bean public FakeDataSource fakeDataSource() { FakeDataSource fakeDataSource = new FakeDataSource(); fakeDataSource.setUser(user); fakeDataSource.setPassword(password); fakeDataSource.setUrl(url); return fakeDataSource; } @Bean public FakeJmsBroker fakeJmsBroker() { FakeJmsBroker fakeJmsBroker = new FakeJmsBroker(); fakeJmsBroker.setUsername(jmsUsername); fakeJmsBroker.setPassword(jmsPassword); fakeJmsBroker.setUrl(jmsUrl); return fakeJmsBroker; } }
b085212ce74bb20152204fc1fd950c058ba3a91e
8a54e99a07e2c77e7da264b3ef96448f0ab627f1
/src/main/java/io/cesarcneto/moneytransfer/transfer/service/TransferService.java
8e9db6573f65906d066eea6039bbfc3f7f57039a
[]
no_license
cesarcneto/money-transfer-api
159d6154f5efd47032e912203b544f4eeda6b29d
f58ac3314de62d18c404af7416c7ae3577e837c6
refs/heads/master
2021-01-16T10:39:24.274070
2020-03-01T14:08:48
2020-03-01T14:08:48
243,086,490
1
0
null
null
null
null
UTF-8
Java
false
false
3,017
java
package io.cesarcneto.moneytransfer.transfer.service; import io.cesarcneto.moneytransfer.account.model.Account; import io.cesarcneto.moneytransfer.account.service.AccountService; import io.cesarcneto.moneytransfer.transfer.exception.InsufficientBalanceInAccountException; import io.cesarcneto.moneytransfer.transfer.exception.UpdateBalanceException; import io.cesarcneto.moneytransfer.transfer.model.TransferRequest; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.jdbi.v3.core.Jdbi; import org.jdbi.v3.core.transaction.TransactionIsolationLevel; import java.math.BigDecimal; import java.util.List; import java.util.Map; import java.util.UUID; import static java.lang.String.format; @Slf4j @RequiredArgsConstructor public class TransferService { private final Jdbi jdbi; private final AccountService accountService; public void performTransferRequest(TransferRequest transferRequest) { jdbi.inTransaction(TransactionIsolationLevel.READ_COMMITTED, handle -> executeTransferRequest(transferRequest)); } // Visible for unit testing int executeTransferRequest(TransferRequest transferRequest) { Map<UUID, Account> accountsById = accountService.getAccountsById( List.of(transferRequest.getFrom(), transferRequest.getTo()) ); Account fromAccount = accountsById.get(transferRequest.getFrom()); Account toAccount = accountsById.get(transferRequest.getTo()); BigDecimal transferAmount = transferRequest.getAmount(); assertAccountHasBalance(fromAccount, transferAmount); Account newFromAccount = performDebit(fromAccount, transferAmount); Account newToAccount = performCredit(toAccount, transferAmount); // We could store such operations in a transfer facts table here int numberOfUpdates = accountService.updateAccountsBalances(List.of(newFromAccount, newToAccount)); if(numberOfUpdates != 2) { throw new UpdateBalanceException(format( "The transfer occurredAt %s with purpose '%s' from %s to %s in the amount of %s failed", transferRequest.getOccurredAt(), transferRequest.getPurpose(), transferRequest.getFrom(), transferRequest.getTo(), transferRequest.getAmount() )); } return numberOfUpdates; } private Account performCredit(Account account, BigDecimal amount) { return account.toBuilder().balance(account.getBalance().add(amount)).build(); } private Account performDebit(Account account, BigDecimal amount) { return account.toBuilder().balance(account.getBalance().subtract(amount)).build(); } private void assertAccountHasBalance(Account account, BigDecimal amount) { if(account.getBalance().compareTo(amount) < 0) { throw new InsufficientBalanceInAccountException(account.getId().toString()); } } }
6cf719db30b1f0979d039756a3bff2ea640567a2
cf7aa09f5ed1d2543280159f5dfd80853007fdc3
/src/dao/BaseDao.java
b2828d87c7e1917e5628419a0a98da01081cca32
[]
no_license
helicopter0v0/book
35e95447223ad5d53bc1ddd5d7537f3f42c7c5e9
23db61cf0ea8f7fbce71aec7915489ef5727cce2
refs/heads/master
2023-08-24T00:32:54.050721
2021-10-14T04:50:19
2021-10-14T04:50:19
416,252,521
0
0
null
null
null
null
UTF-8
Java
false
false
1,991
java
package dao; import org.apache.commons.dbutils.QueryRunner; import org.apache.commons.dbutils.handlers.BeanHandler; import org.apache.commons.dbutils.handlers.BeanListHandler; import org.apache.commons.dbutils.handlers.ScalarHandler; import utils.JdbcUtils; import java.sql.Connection; import java.sql.SQLException; import java.util.List; import java.util.Objects; public abstract class BaseDao { private QueryRunner queryRunner = new QueryRunner(); public int update(String sql, Object...args){ Connection connection = JdbcUtils.getConnection(); try { return queryRunner.update(connection,sql,args); } catch (SQLException e) { e.printStackTrace(); }finally { JdbcUtils.close(connection); } return -1; } public <T> T queryForOne(Class<T> type,String sql,Object ... args){ Connection connection = JdbcUtils.getConnection(); try { return queryRunner.query(connection,sql,new BeanHandler<T>(type),args); } catch (SQLException e) { e.printStackTrace(); }finally { JdbcUtils.close(connection); } return null; } public <T>List<T> queryForList(Class<T> type,String sql,Object ... args){ Connection connection = JdbcUtils.getConnection(); try { return queryRunner.query(connection,sql,new BeanListHandler<T>(type),args); } catch (SQLException e) { e.printStackTrace(); }finally { JdbcUtils.close(connection); } return null; } public Object queryForSingleValue(String sql,Object ... args){ Connection connection = JdbcUtils.getConnection(); try { return queryRunner.query(connection,sql,new ScalarHandler(),args); } catch (SQLException e) { e.printStackTrace(); }finally { JdbcUtils.close(connection); } return null; } }
79d0181a007f5c5dc7bd80be4e84a608478685f8
98da111ae8b9c901f0450138c59f22d21429300c
/src/main/java/com/tsq/security/Letters.java
74f8bc94e520b1754e56b5036d5bc96e4b92bc05
[]
no_license
shemTian/testBaseCode
01d5e816766b9ab1ad42eef8dd99346e608ab968
2bfb82bc413f01a6fd3af0818f735163d5bf1215
refs/heads/master
2021-01-18T13:48:52.063763
2017-03-08T06:19:43
2017-03-08T06:19:43
42,638,522
0
0
null
null
null
null
UTF-8
Java
false
false
2,149
java
package com.tsq.security; /** * 字母 * @author tsq * */ public enum Letters { uppercase_a(65,'A'), uppercase_b(66,'B'), uppercase_c(67,'C'), uppercase_d(68,'D'), uppercase_e(69,'E'), uppercase_f(70,'F'), uppercase_g(71,'G'), uppercase_h(72,'H'), uppercase_i(73,'I'), uppercase_j(74,'J'), uppercase_k(75,'K'), uppercase_l(76,'L'), uppercase_m(77,'M'), uppercase_n(78,'N'), uppercase_o(79,'O'), uppercase_p(80,'P'), uppercase_q(81,'Q'), uppercase_r(82,'R'), uppercase_s(83,'S'), uppercase_t(84,'T'), uppercase_u(85,'U'), uppercase_v(86,'V'), uppercase_w(87,'W'), uppercase_x(88,'X'), uppercase_y(89,'Y'), uppercase_z(90,'Z'), lowercase_a(97,'a'), lowercase_b(98,'b'), lowercase_c(99,'c'), lowercase_d(100,'d'), lowercase_e(101,'e'), lowercase_f(102,'f'), lowercase_g(103,'g'), lowercase_h(104,'h'), lowercase_i(105,'i'), lowercase_j(106,'j'), lowercase_k(107,'k'), lowercase_l(108,'l'), lowercase_m(109,'m'), lowercase_n(110,'n'), lowercase_o(111,'o'), lowercase_p(112,'p'), lowercase_q(113,'q'), lowercase_r(114,'r'), lowercase_s(115,'s'), lowercase_t(116,'t'), lowercase_u(117,'u'), lowercase_v(118,'v'), lowercase_w(119,'w'), lowercase_x(120,'x'), lowercase_y(121,'y'), lowercase_z(122,'z'); private int asciiCode; private char charStr; Letters(int asciiCode,char charStr){ this.asciiCode = asciiCode; this.charStr = charStr; } public int getAsciiCode() { return asciiCode; } /** * 根据ascii码值返回字符 * @param index * @return ascii值在此枚举中,返回对应值;否则返回 0 * @author tsq */ public static char getCharStr(int index) { for(Letters letter : Letters.values()){ if(index==letter.asciiCode){ return letter.charStr; } } return 0; } /** * 判断传入的值 是否在此枚举中 * @param equalIndex * @return 存在返回true,不存在返回false * @author tsq */ public static boolean checkIn(int equalIndex){ for(Letters letter : Letters.values()){ if(equalIndex==letter.asciiCode){ return true; } } return false; } }
65589cb09b87410a1ada61c6a4ba13b11ae56160
93c7e807608aed6f90b17799550698ba4b4f2284
/src/com/kerhomjarnoin/pokemon/harmony/view/HarmonyFragment.java
2162c1c489d703e07070c97d2ed8c64c1d5c1cdf
[]
no_license
Ptipoi-jf/harmoyPokemonAndroid
6c25734550d7a80b75688febdc2c7c644b10e920
852b7199a5120e57bf8699218315c49757311a6f
refs/heads/master
2021-05-31T12:13:41.355431
2016-05-27T19:47:26
2016-05-27T19:47:26
null
0
0
null
null
null
null
UTF-8
Java
false
false
2,239
java
/************************************************************************** * HarmonyFragment.java, pokemon Android * * Copyright 2016 * Description : * Author(s) : Harmony * Licence : * Last update : May 27, 2016 * **************************************************************************/ package com.kerhomjarnoin.pokemon.harmony.view; import android.content.Intent; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import com.kerhomjarnoin.pokemon.menu.PokemonMenu; /** * Harmony custom Fragment. * This fragment will help you use a lot of harmony's functionnality * (menu wrappers, etc.) */ public abstract class HarmonyFragment extends Fragment { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); this.setHasOptionsMenu(true); } @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { super.onCreateOptionsMenu(menu, inflater); try { PokemonMenu.getInstance(this.getActivity(), this) .clear(menu); PokemonMenu.getInstance(this.getActivity(), this) .updateMenu(menu, this.getActivity()); } catch (Exception e) { e.printStackTrace(); } } @Override public boolean onOptionsItemSelected(MenuItem item) { boolean result; try { result = PokemonMenu.getInstance( this.getActivity(), this).dispatch(item, this.getActivity()); } catch (Exception e) { e.printStackTrace(); result = false; } return result; } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { try { PokemonMenu.getInstance(this.getActivity(), this) .onActivityResult(requestCode, resultCode, data, this.getActivity(), this); } catch (Exception e) { e.printStackTrace(); } super.onActivityResult(requestCode, resultCode, data); } }
5931d191c1b3069f7f484ebf39892f3b1d127fc1
71e5073b971499839434b9d582e051abd01c3795
/src/main/java/com/metasoft/ibilling/controller/ajax/InvoiceAjaxController.java
6ac92258eb58c8508ca6d67aac29fb33c4c9fbbf
[]
no_license
tongjongjaroenGmail/iBilling
4669fd39cabc80bffce91bc6aa23fdbf97be41d8
20e49674014d6b38cdc67f750b65f6d481009f4d
refs/heads/master
2021-01-21T05:00:04.206553
2016-06-14T16:16:36
2016-06-14T16:16:36
45,057,782
0
0
null
null
null
null
UTF-8
Java
false
false
9,767
java
/** * */ package com.metasoft.ibilling.controller.ajax; import java.io.IOException; import java.text.ParseException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import javax.servlet.ServletException; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import net.sf.jasperreports.engine.JRException; import org.apache.commons.lang.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; 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 com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.metasoft.ibilling.bean.SaveResult; import com.metasoft.ibilling.bean.paging.ClaimSearchResultVoPaging; import com.metasoft.ibilling.bean.paging.InvoiceReportVoPaging; import com.metasoft.ibilling.bean.paging.InvoiceSearchResultVoPaging; import com.metasoft.ibilling.bean.paging.ReportStatisticsSurveyVoPaging; import com.metasoft.ibilling.bean.vo.ClaimSearchResultVo; import com.metasoft.ibilling.bean.vo.InvoiceDetailVo; import com.metasoft.ibilling.bean.vo.InvoiceReportVo; import com.metasoft.ibilling.bean.vo.InvoiceSearchResultVo; import com.metasoft.ibilling.bean.vo.ResultVo; import com.metasoft.ibilling.controller.vo.ReportStatisticsSurveyVo; import com.metasoft.ibilling.dao.InvoiceDao; import com.metasoft.ibilling.dao.UserDao; import com.metasoft.ibilling.model.Claim; import com.metasoft.ibilling.model.Invoice; import com.metasoft.ibilling.model.User; import com.metasoft.ibilling.service.ClaimService; import com.metasoft.ibilling.service.InvoiceService; import com.metasoft.ibilling.service.impl.ClaimServiceImpl; import com.metasoft.ibilling.service.impl.report.DownloadService; import com.metasoft.ibilling.service.impl.report.ExporterService; import com.metasoft.ibilling.service.impl.report.TokenService; import com.metasoft.ibilling.util.DateToolsUtil; import com.metasoft.ibilling.util.NumberToolsUtil; @Controller public class InvoiceAjaxController extends BaseAjaxController { @Autowired private ClaimService claimService; @Autowired private InvoiceService invoiceService; @Autowired private InvoiceDao invoiceDao; @Autowired private UserDao userDao; @Autowired private DownloadService downloadService; @Autowired private TokenService tokenService; @RequestMapping(value = "/invoiceGroup/search", method = RequestMethod.POST) public @ResponseBody String searchClaim(Model model, @RequestParam(required = false) String txtDispatchDateStart, @RequestParam(required = false) String txtDispatchDateEnd, @RequestParam(required = false) Integer selBranch, @RequestParam(required = true) String selClaimStatus, @RequestParam(required = false) String firstTime, @RequestParam(required = true) Integer draw, @RequestParam(required = true) Integer start, @RequestParam(required = true) Integer length) throws ParseException { ClaimSearchResultVoPaging resultPaging = new ClaimSearchResultVoPaging(); resultPaging.setDraw(++draw); if(new Boolean(firstTime)){ resultPaging.setRecordsFiltered(0L); resultPaging.setRecordsTotal(0L); resultPaging.setData(new ArrayList<ClaimSearchResultVo>()); }else{ resultPaging = claimService.searchGroupClaimPaging(txtDispatchDateStart, txtDispatchDateEnd, selBranch,selClaimStatus, start, length); } Gson gson = new GsonBuilder().setPrettyPrinting().create(); String json = gson.toJson(resultPaging); return json; } @RequestMapping(value = "/invoice/save", method = RequestMethod.GET,headers = { "Content-type=application/json;charset=UTF-8" }, produces = { "application/json;charset=UTF-8" }) public @ResponseBody String save(Model model, @RequestParam(required = true) String claimIds, @RequestParam(required = true) String invoiceNo, HttpSession session) throws ParseException { Gson gson = new GsonBuilder().setPrettyPrinting().create(); ResultVo resultVo = new ResultVo(); User loginUser = (User) session.getAttribute("loginUser"); SaveResult saveResult = invoiceService.save(claimIds, invoiceNo, loginUser.getId()); if(saveResult.isSeccess()){ resultVo.setMessage("บันทึกข้อมูลเรียบร้อย"); resultVo.setData(saveResult.getId()); }else{ resultVo.setMessage(saveResult.getErrorDesc()); resultVo.setError(true); } String json2 = gson.toJson(resultVo); return json2; } @RequestMapping(value = "/invoice/search", method = RequestMethod.POST) public @ResponseBody String searchInvoice(Model model, @RequestParam(required = false) String txtCreateDateStart, @RequestParam(required = false) String txtCreateDateEnd, @RequestParam(required = false) String txtInvoiceCode, @RequestParam(required = false) String firstTime, @RequestParam(required = true) Integer draw, @RequestParam(required = true) Integer start, @RequestParam(required = true) Integer length) throws ParseException { InvoiceSearchResultVoPaging resultPaging = new InvoiceSearchResultVoPaging(); resultPaging.setDraw(++draw); if(new Boolean(firstTime)){ resultPaging.setRecordsFiltered(0L); resultPaging.setRecordsTotal(0L); resultPaging.setData(new ArrayList<InvoiceSearchResultVo>()); }else{ resultPaging = invoiceService.searchPaging(txtCreateDateStart, txtCreateDateEnd, txtInvoiceCode, start, length); } Gson gson = new GsonBuilder().setPrettyPrinting().create(); String json = gson.toJson(resultPaging); return json; } @RequestMapping(value = "/invoice/find", method = RequestMethod.GET) public @ResponseBody String find(Model model,@RequestParam(required = false) int id) throws ParseException { Invoice invoice = invoiceDao.findById(id); InvoiceDetailVo invoiceDetailVo = new InvoiceDetailVo(); invoiceDetailVo.setInvoiceId(invoice.getId()); invoiceDetailVo.setInvoiceCode(invoice.getCode()); invoiceDetailVo.setInvoiceCreateDate(DateToolsUtil.convertToString(invoice.getCreateDate(), DateToolsUtil.LOCALE_TH)); for (Claim claim : invoice.getClaims()) { ClaimSearchResultVo vo = new ClaimSearchResultVo(); vo.setClaimNo(StringUtils.trimToEmpty(claim.getClaimNo())); vo.setClaimId(claim.getId().intValue()); vo.setSurInvest(NumberToolsUtil.nullToFloat(claim.getSurInvest())); vo.setSurTrans(NumberToolsUtil.nullToFloat(claim.getSurTrans())); vo.setSurDaily(NumberToolsUtil.nullToFloat(claim.getSurDaily())); vo.setSurPhoto(NumberToolsUtil.nullToFloat(claim.getSurPhoto())); vo.setSurClaim(NumberToolsUtil.nullToFloat(claim.getSurClaim())); vo.setSurTel(NumberToolsUtil.nullToFloat(claim.getSurTel())); vo.setSurInsure(NumberToolsUtil.nullToFloat(claim.getSurInsure())); vo.setSurTowcar(NumberToolsUtil.nullToFloat(claim.getSurTowcar())); vo.setSurOther(NumberToolsUtil.nullToFloat(claim.getSurOther())); vo.setSurTotal(ClaimServiceImpl.calcTotalSur(claim)); vo.setSurTax(ClaimServiceImpl.calcVat(vo.getSurTotal())); vo.setSurTotal(vo.getSurTotal() + vo.getSurTax()); invoiceDetailVo.getClaims().add(vo); } Gson gson = new GsonBuilder().setPrettyPrinting().create(); String json = gson.toJson(invoiceDetailVo); return json; } @RequestMapping(value = "/invoice/report/search", method = RequestMethod.POST) public @ResponseBody String searchInvoiceReport(Model model, @RequestParam(required = false) String paramDispatchDateStart, @RequestParam(required = false) String paramDispatchDateEnd, @RequestParam(required = false) Integer paramBranchDhip, @RequestParam(required = false) Integer paramType, @RequestParam(required = true) String paramFirstTime, @RequestParam(required = true) Integer draw, @RequestParam(required = true) Integer start, @RequestParam(required = true) Integer length) throws ParseException { InvoiceReportVoPaging resultPaging = new InvoiceReportVoPaging(); resultPaging.setDraw(++draw); if (new Boolean(paramFirstTime)) { resultPaging.setRecordsFiltered(0L); resultPaging.setRecordsTotal(0L); resultPaging.setData(new ArrayList<InvoiceReportVo>()); } else { resultPaging = claimService.searchInvoiceReportPaging(paramDispatchDateStart, paramDispatchDateEnd, paramBranchDhip, paramType, start, length); } Gson gson = new GsonBuilder().setPrettyPrinting().create(); String json = gson.toJson(resultPaging); return json; } @RequestMapping(value = "/invoice/report/export", method = RequestMethod.POST) public void export(@RequestParam(required = false) String txtDispatchDateStart, @RequestParam(required = false) String txtDispatchDateEnd, @RequestParam(required = false) Integer selBranchDhip, @RequestParam(required = false) Integer selType, @RequestParam(required = false) String token, HttpSession session, HttpServletResponse response) throws ServletException, IOException, JRException, Exception { InvoiceReportVoPaging results = claimService.searchInvoiceReportPaging(txtDispatchDateStart, txtDispatchDateEnd, selBranchDhip, selType,0,0); HashMap param =new HashMap(); downloadService.download(ExporterService.EXTENSION_TYPE_EXCEL, "invoiceReport", session.getServletContext().getRealPath("/report/invoiceReport"), param, results.getData(), token, response); } }
95e294de11f8876ca503e7535040e1030e8baf83
34fc9efed6168b7261bdc5866305f7346f2ad56d
/easeui/src/com/hyphenate/easeui/utils/EaseUserUtils.java
9740e980030876fb42dd97072c8e8856b22151a0
[ "Apache-2.0" ]
permissive
HXACA/IM
703eee03daa40c4a9ba1307ef4702ba29f0f4648
50812fe5079bd8bb81a53915ec7c2d7bb803139d
refs/heads/master
2020-12-02T21:23:35.492893
2017-07-07T03:21:16
2017-07-07T03:21:16
96,306,714
2
0
null
null
null
null
UTF-8
Java
false
false
4,356
java
package com.hyphenate.easeui.utils; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.util.Log; import android.widget.ImageView; import android.widget.TextView; import com.bumptech.glide.Glide; import com.hyphenate.easeui.R; import com.hyphenate.easeui.adapter.User; import com.hyphenate.easeui.controller.EaseUI; import com.hyphenate.easeui.controller.EaseUI.EaseUserProfileProvider; import com.hyphenate.easeui.domain.EaseUser; import java.util.List; import cn.bmob.v3.BmobQuery; import cn.bmob.v3.datatype.BmobFile; import cn.bmob.v3.exception.BmobException; import cn.bmob.v3.listener.DownloadFileListener; import cn.bmob.v3.listener.FindListener; public class EaseUserUtils { static EaseUserProfileProvider userProvider; static { userProvider = EaseUI.getInstance().getUserProfileProvider(); } /** * get EaseUser according username * * @param username * @return */ public static EaseUser getUserInfo(String username) { if (userProvider != null) return userProvider.getUser(username); return null; } /** * set user avatar * * @param username */ public static void setUserAvatar(final Context context, String username, final ImageView imageView) { BmobQuery<User> query = new BmobQuery<>(); query.addWhereEqualTo("telephone", username); query.findObjects(new FindListener<User>() { @Override public void done(List<User> list, BmobException e) { if (e == null) { User user = list.get(0); final BmobFile bmobFile = user.getAvatar(); if (bmobFile != null) { bmobFile.download(new DownloadFileListener() { @Override public void done(String s, BmobException e) { Log.d("MainActivity", "图片路径:" + s); Bitmap bm = BitmapFactory.decodeFile(s); imageView.setImageBitmap(bm); } @Override public void onProgress(Integer integer, long l) { } }); } else { Glide.with(context).load(R.drawable.ease_default_avatar).into(imageView); } } } }); /* EaseUser user = getUserInfo(username); if (user != null && user.getAvatar() != null) { try { int avatarResId = Integer.parseInt(user.getAvatar()); Glide.with(context).load(avatarResId).into(imageView); } catch (Exception e) { //use default avatar Glide.with(context).load(user.getAvatar()).diskCacheStrategy(DiskCacheStrategy.ALL).placeholder(R.drawable.ease_default_avatar).into(imageView); } } else { Glide.with(context).load(R.drawable.ease_default_avatar).into(imageView); }*/ } /** * set user's nickname */ public static void setUserNick(String username, final TextView textView) { BmobQuery<User> query = new BmobQuery<>(); query.addWhereEqualTo("telephone", username); query.findObjects(new FindListener<User>() { @Override public void done(List<User> list, BmobException e) { if (e == null && list.size()>0) { User user = list.get(0); String nickName = user.getNickName(); int state = user.getState(); String string; if(state==1) string="在线"; else string="离线"; textView.setText(nickName + "("+string+")"); } } }); if (textView.getText()== null) { EaseUser user = getUserInfo(username); if (user != null && user.getNick() != null) { textView.setText(user.getNick()); } else { textView.setText(username); } } } }
4b42a3a98386e2d31e2779430d8c84ba49fa8896
3a77e7ffa78b51e1be18576f0c3e99048be8734f
/fe/fe-core/src/main/java/org/apache/doris/nereids/glue/translator/PhysicalPlanTranslator.java
41be06be44da4ebff6ba0ec75971896794082f5a
[ "Apache-2.0", "OpenSSL", "BSD-3-Clause", "LicenseRef-scancode-facebook-patent-rights-2", "PSF-2.0", "dtoa", "MIT", "GPL-2.0-only", "LicenseRef-scancode-public-domain" ]
permissive
yiguolei/incubator-doris
e73e2c44c7e3a3869d379555a29abfe48f97de6c
ada01b7ba6eac5d442b7701b78cea44235ed5017
refs/heads/master
2023-08-18T23:28:09.915740
2023-08-05T05:18:18
2023-08-05T05:18:44
160,305,067
1
1
Apache-2.0
2023-07-07T08:05:16
2018-12-04T05:43:20
Java
UTF-8
Java
false
false
119,897
java
// Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. package org.apache.doris.nereids.glue.translator; import org.apache.doris.analysis.AggregateInfo; import org.apache.doris.analysis.AnalyticWindow; import org.apache.doris.analysis.BaseTableRef; import org.apache.doris.analysis.BinaryPredicate; import org.apache.doris.analysis.BoolLiteral; import org.apache.doris.analysis.CompoundPredicate; import org.apache.doris.analysis.Expr; import org.apache.doris.analysis.FunctionCallExpr; import org.apache.doris.analysis.GroupByClause.GroupingType; import org.apache.doris.analysis.GroupingInfo; import org.apache.doris.analysis.IsNullPredicate; import org.apache.doris.analysis.OrderByElement; import org.apache.doris.analysis.OutFileClause; import org.apache.doris.analysis.SlotDescriptor; import org.apache.doris.analysis.SlotId; import org.apache.doris.analysis.SlotRef; import org.apache.doris.analysis.SortInfo; import org.apache.doris.analysis.TableName; import org.apache.doris.analysis.TableRef; import org.apache.doris.analysis.TupleDescriptor; import org.apache.doris.analysis.TupleId; import org.apache.doris.catalog.Column; import org.apache.doris.catalog.Function.NullableMode; import org.apache.doris.catalog.OlapTable; import org.apache.doris.catalog.Table; import org.apache.doris.catalog.TableIf; import org.apache.doris.catalog.Type; import org.apache.doris.catalog.external.ExternalTable; import org.apache.doris.catalog.external.HMSExternalTable; import org.apache.doris.catalog.external.IcebergExternalTable; import org.apache.doris.catalog.external.JdbcExternalTable; import org.apache.doris.catalog.external.MaxComputeExternalTable; import org.apache.doris.catalog.external.PaimonExternalTable; import org.apache.doris.common.UserException; import org.apache.doris.common.util.Util; import org.apache.doris.nereids.exceptions.AnalysisException; import org.apache.doris.nereids.properties.DistributionSpec; import org.apache.doris.nereids.properties.DistributionSpecAny; import org.apache.doris.nereids.properties.DistributionSpecExecutionAny; import org.apache.doris.nereids.properties.DistributionSpecGather; import org.apache.doris.nereids.properties.DistributionSpecHash; import org.apache.doris.nereids.properties.DistributionSpecReplicated; import org.apache.doris.nereids.properties.DistributionSpecStorageAny; import org.apache.doris.nereids.properties.DistributionSpecStorageGather; import org.apache.doris.nereids.properties.OrderKey; import org.apache.doris.nereids.rules.implementation.LogicalWindowToPhysicalWindow.WindowFrameGroup; import org.apache.doris.nereids.stats.StatsErrorEstimator; import org.apache.doris.nereids.trees.UnaryNode; import org.apache.doris.nereids.trees.expressions.AggregateExpression; import org.apache.doris.nereids.trees.expressions.CTEId; import org.apache.doris.nereids.trees.expressions.EqualTo; import org.apache.doris.nereids.trees.expressions.ExprId; import org.apache.doris.nereids.trees.expressions.Expression; import org.apache.doris.nereids.trees.expressions.NamedExpression; import org.apache.doris.nereids.trees.expressions.OrderExpression; import org.apache.doris.nereids.trees.expressions.Slot; import org.apache.doris.nereids.trees.expressions.SlotReference; import org.apache.doris.nereids.trees.expressions.VirtualSlotReference; import org.apache.doris.nereids.trees.expressions.WindowFrame; import org.apache.doris.nereids.trees.expressions.functions.agg.AggregateFunction; import org.apache.doris.nereids.trees.expressions.functions.agg.AggregateParam; import org.apache.doris.nereids.trees.expressions.literal.BooleanLiteral; import org.apache.doris.nereids.trees.plans.AbstractPlan; import org.apache.doris.nereids.trees.plans.AggMode; import org.apache.doris.nereids.trees.plans.AggPhase; import org.apache.doris.nereids.trees.plans.JoinType; import org.apache.doris.nereids.trees.plans.Plan; import org.apache.doris.nereids.trees.plans.PreAggStatus; import org.apache.doris.nereids.trees.plans.physical.AbstractPhysicalJoin; import org.apache.doris.nereids.trees.plans.physical.AbstractPhysicalSort; import org.apache.doris.nereids.trees.plans.physical.PhysicalAssertNumRows; import org.apache.doris.nereids.trees.plans.physical.PhysicalCTEAnchor; import org.apache.doris.nereids.trees.plans.physical.PhysicalCTEConsumer; import org.apache.doris.nereids.trees.plans.physical.PhysicalCTEProducer; import org.apache.doris.nereids.trees.plans.physical.PhysicalDeferMaterializeOlapScan; import org.apache.doris.nereids.trees.plans.physical.PhysicalDeferMaterializeResultSink; import org.apache.doris.nereids.trees.plans.physical.PhysicalDeferMaterializeTopN; import org.apache.doris.nereids.trees.plans.physical.PhysicalDistribute; import org.apache.doris.nereids.trees.plans.physical.PhysicalEmptyRelation; import org.apache.doris.nereids.trees.plans.physical.PhysicalEsScan; import org.apache.doris.nereids.trees.plans.physical.PhysicalExcept; import org.apache.doris.nereids.trees.plans.physical.PhysicalFileScan; import org.apache.doris.nereids.trees.plans.physical.PhysicalFileSink; import org.apache.doris.nereids.trees.plans.physical.PhysicalFilter; import org.apache.doris.nereids.trees.plans.physical.PhysicalGenerate; import org.apache.doris.nereids.trees.plans.physical.PhysicalHashAggregate; import org.apache.doris.nereids.trees.plans.physical.PhysicalHashJoin; import org.apache.doris.nereids.trees.plans.physical.PhysicalIntersect; import org.apache.doris.nereids.trees.plans.physical.PhysicalJdbcScan; import org.apache.doris.nereids.trees.plans.physical.PhysicalLimit; import org.apache.doris.nereids.trees.plans.physical.PhysicalNestedLoopJoin; import org.apache.doris.nereids.trees.plans.physical.PhysicalOlapScan; import org.apache.doris.nereids.trees.plans.physical.PhysicalOlapTableSink; import org.apache.doris.nereids.trees.plans.physical.PhysicalOneRowRelation; import org.apache.doris.nereids.trees.plans.physical.PhysicalPartitionTopN; import org.apache.doris.nereids.trees.plans.physical.PhysicalPlan; import org.apache.doris.nereids.trees.plans.physical.PhysicalProject; import org.apache.doris.nereids.trees.plans.physical.PhysicalQuickSort; import org.apache.doris.nereids.trees.plans.physical.PhysicalRepeat; import org.apache.doris.nereids.trees.plans.physical.PhysicalResultSink; import org.apache.doris.nereids.trees.plans.physical.PhysicalSchemaScan; import org.apache.doris.nereids.trees.plans.physical.PhysicalSetOperation; import org.apache.doris.nereids.trees.plans.physical.PhysicalStorageLayerAggregate; import org.apache.doris.nereids.trees.plans.physical.PhysicalTVFRelation; import org.apache.doris.nereids.trees.plans.physical.PhysicalTopN; import org.apache.doris.nereids.trees.plans.physical.PhysicalUnion; import org.apache.doris.nereids.trees.plans.physical.PhysicalWindow; import org.apache.doris.nereids.trees.plans.physical.RuntimeFilter; import org.apache.doris.nereids.trees.plans.visitor.DefaultPlanVisitor; import org.apache.doris.nereids.util.ExpressionUtils; import org.apache.doris.nereids.util.JoinUtils; import org.apache.doris.nereids.util.Utils; import org.apache.doris.planner.AggregationNode; import org.apache.doris.planner.AnalyticEvalNode; import org.apache.doris.planner.AssertNumRowsNode; import org.apache.doris.planner.CTEScanNode; import org.apache.doris.planner.DataPartition; import org.apache.doris.planner.DataStreamSink; import org.apache.doris.planner.EmptySetNode; import org.apache.doris.planner.EsScanNode; import org.apache.doris.planner.ExceptNode; import org.apache.doris.planner.ExchangeNode; import org.apache.doris.planner.HashJoinNode; import org.apache.doris.planner.HashJoinNode.DistributionMode; import org.apache.doris.planner.IntersectNode; import org.apache.doris.planner.JoinNodeBase; import org.apache.doris.planner.MultiCastDataSink; import org.apache.doris.planner.MultiCastPlanFragment; import org.apache.doris.planner.NestedLoopJoinNode; import org.apache.doris.planner.OlapScanNode; import org.apache.doris.planner.OlapTableSink; import org.apache.doris.planner.PartitionSortNode; import org.apache.doris.planner.PlanFragment; import org.apache.doris.planner.PlanNode; import org.apache.doris.planner.RepeatNode; import org.apache.doris.planner.ResultFileSink; import org.apache.doris.planner.ResultSink; import org.apache.doris.planner.ScanNode; import org.apache.doris.planner.SchemaScanNode; import org.apache.doris.planner.SelectNode; import org.apache.doris.planner.SetOperationNode; import org.apache.doris.planner.SortNode; import org.apache.doris.planner.TableFunctionNode; import org.apache.doris.planner.UnionNode; import org.apache.doris.planner.external.HiveScanNode; import org.apache.doris.planner.external.MaxComputeScanNode; import org.apache.doris.planner.external.hudi.HudiScanNode; import org.apache.doris.planner.external.iceberg.IcebergScanNode; import org.apache.doris.planner.external.jdbc.JdbcScanNode; import org.apache.doris.planner.external.paimon.PaimonScanNode; import org.apache.doris.qe.ConnectContext; import org.apache.doris.tablefunction.TableValuedFunctionIf; import org.apache.doris.thrift.TFetchOption; import org.apache.doris.thrift.TPartitionType; import org.apache.doris.thrift.TPushAggOp; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.collect.Sets; import org.apache.commons.collections.CollectionUtils; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Set; import java.util.stream.Collectors; import java.util.stream.Stream; /** * Used to translate to physical plan generated by new optimizer to the plan fragments. * <STRONG> * ATTENTION: * Must always visit plan's children first when you implement a method to translate from PhysicalPlan to PlanNode. * </STRONG> */ public class PhysicalPlanTranslator extends DefaultPlanVisitor<PlanFragment, PlanTranslatorContext> { private static final Logger LOG = LogManager.getLogger(PhysicalPlanTranslator.class); private final StatsErrorEstimator statsErrorEstimator; private final PlanTranslatorContext context; public PhysicalPlanTranslator() { this(null, null); } public PhysicalPlanTranslator(PlanTranslatorContext context) { this(context, null); } public PhysicalPlanTranslator(PlanTranslatorContext context, StatsErrorEstimator statsErrorEstimator) { this.context = context; this.statsErrorEstimator = statsErrorEstimator; } /** * Translate Nereids Physical Plan tree to Stale Planner PlanFragment tree. * * @param physicalPlan Nereids Physical Plan tree * @return Stale Planner PlanFragment tree */ public PlanFragment translatePlan(PhysicalPlan physicalPlan) { PlanFragment rootFragment = physicalPlan.accept(this, context); List<Expr> outputExprs = Lists.newArrayList(); physicalPlan.getOutput().stream().map(Slot::getExprId) .forEach(exprId -> outputExprs.add(context.findSlotRef(exprId))); rootFragment.setOutputExprs(outputExprs); Collections.reverse(context.getPlanFragments()); // TODO: maybe we need to trans nullable directly? and then we could remove call computeMemLayout context.getDescTable().computeMemLayout(); return rootFragment; } /* ******************************************************************************************** * distribute node * ******************************************************************************************** */ @Override public PlanFragment visitPhysicalDistribute(PhysicalDistribute<? extends Plan> distribute, PlanTranslatorContext context) { PlanFragment inputFragment = distribute.child().accept(this, context); // TODO: why need set streaming here? should remove this. if (inputFragment.getPlanRoot() instanceof AggregationNode && distribute.child() instanceof PhysicalHashAggregate && context.getFirstAggregateInFragment(inputFragment) == distribute.child()) { PhysicalHashAggregate<?> hashAggregate = (PhysicalHashAggregate<?>) distribute.child(); if (hashAggregate.getAggPhase() == AggPhase.LOCAL && hashAggregate.getAggMode() == AggMode.INPUT_TO_BUFFER) { AggregationNode aggregationNode = (AggregationNode) inputFragment.getPlanRoot(); aggregationNode.setUseStreamingPreagg(hashAggregate.isMaybeUsingStream()); } } ExchangeNode exchangeNode = new ExchangeNode(context.nextPlanNodeId(), inputFragment.getPlanRoot()); updateLegacyPlanIdToPhysicalPlan(exchangeNode, distribute); List<ExprId> validOutputIds = distribute.getOutputExprIds(); if (distribute.child() instanceof PhysicalHashAggregate) { // we must add group by keys to output list, // otherwise we could not process aggregate's output without group by keys List<ExprId> keys = ((PhysicalHashAggregate<?>) distribute.child()).getGroupByExpressions().stream() .filter(SlotReference.class::isInstance) .map(SlotReference.class::cast) .map(SlotReference::getExprId) .collect(Collectors.toList()); keys.addAll(validOutputIds); validOutputIds = keys; } DataPartition dataPartition = toDataPartition(distribute.getDistributionSpec(), validOutputIds, context); PlanFragment parentFragment = new PlanFragment(context.nextFragmentId(), exchangeNode, dataPartition); exchangeNode.setNumInstances(inputFragment.getPlanRoot().getNumInstances()); if (distribute.getDistributionSpec() instanceof DistributionSpecGather) { // gather to one instance exchangeNode.setNumInstances(1); } // process multicast sink if (inputFragment instanceof MultiCastPlanFragment) { MultiCastDataSink multiCastDataSink = (MultiCastDataSink) inputFragment.getSink(); DataStreamSink dataStreamSink = multiCastDataSink.getDataStreamSinks().get( multiCastDataSink.getDataStreamSinks().size() - 1); TupleDescriptor tupleDescriptor = generateTupleDesc(distribute.getOutput(), null, context); exchangeNode.updateTupleIds(tupleDescriptor); dataStreamSink.setExchNodeId(exchangeNode.getId()); dataStreamSink.setOutputPartition(dataPartition); parentFragment.addChild(inputFragment); ((MultiCastPlanFragment) inputFragment).addToDest(exchangeNode); CTEScanNode cteScanNode = context.getCteScanNodeMap().get(inputFragment.getFragmentId()); Preconditions.checkState(cteScanNode != null, "cte scan node is null"); cteScanNode.setFragment(inputFragment); cteScanNode.setPlanNodeId(exchangeNode.getId()); context.getRuntimeTranslator().ifPresent(runtimeFilterTranslator -> runtimeFilterTranslator.getContext().getPlanNodeIdToCTEDataSinkMap() .put(cteScanNode.getId(), dataStreamSink)); } else { inputFragment.setDestination(exchangeNode); inputFragment.setOutputPartition(dataPartition); DataStreamSink streamSink = new DataStreamSink(exchangeNode.getId()); streamSink.setOutputPartition(dataPartition); inputFragment.setSink(streamSink); } context.addPlanFragment(parentFragment); return parentFragment; } /* ******************************************************************************************** * sink Node, in lexicographical order * ******************************************************************************************** */ @Override public PlanFragment visitPhysicalResultSink(PhysicalResultSink<? extends Plan> physicalResultSink, PlanTranslatorContext context) { PlanFragment planFragment = physicalResultSink.child().accept(this, context); planFragment.setSink(new ResultSink(planFragment.getPlanRoot().getId())); return planFragment; } @Override public PlanFragment visitPhysicalDeferMaterializeResultSink( PhysicalDeferMaterializeResultSink<? extends Plan> sink, PlanTranslatorContext context) { PlanFragment planFragment = visitPhysicalResultSink(sink.getPhysicalResultSink(), context); TFetchOption fetchOption = sink.getOlapTable().generateTwoPhaseReadOption(sink.getSelectedIndexId()); ((ResultSink) planFragment.getSink()).setFetchOption(fetchOption); return planFragment; } @Override public PlanFragment visitPhysicalOlapTableSink(PhysicalOlapTableSink<? extends Plan> olapTableSink, PlanTranslatorContext context) { PlanFragment rootFragment = olapTableSink.child().accept(this, context); rootFragment.setOutputPartition(DataPartition.UNPARTITIONED); TupleDescriptor olapTuple = context.generateTupleDesc(); List<Column> targetTableColumns = olapTableSink.getTargetTable().getFullSchema(); for (Column column : targetTableColumns) { SlotDescriptor slotDesc = context.addSlotDesc(olapTuple); slotDesc.setIsMaterialized(true); slotDesc.setType(column.getType()); slotDesc.setColumn(column); slotDesc.setIsNullable(column.isAllowNull()); } OlapTableSink sink = new OlapTableSink( olapTableSink.getTargetTable(), olapTuple, olapTableSink.getPartitionIds().isEmpty() ? null : olapTableSink.getPartitionIds(), olapTableSink.isSingleReplicaLoad() ); if (olapTableSink.isPartialUpdate()) { HashSet<String> partialUpdateCols = new HashSet<>(); for (Column col : olapTableSink.getCols()) { partialUpdateCols.add(col.getName()); } sink.setPartialUpdateInputColumns(true, partialUpdateCols); } rootFragment.setSink(sink); return rootFragment; } @Override public PlanFragment visitPhysicalFileSink(PhysicalFileSink<? extends Plan> fileSink, PlanTranslatorContext context) { PlanFragment rootFragment = fileSink.child().accept(this, context); OutFileClause outFile = new OutFileClause( fileSink.getFilePath(), fileSink.getFormat(), fileSink.getProperties() ); List<Expr> outputExprs = Lists.newArrayList(); fileSink.getOutput().stream().map(Slot::getExprId) .forEach(exprId -> outputExprs.add(context.findSlotRef(exprId))); rootFragment.setOutputExprs(outputExprs); // TODO: should not call legacy planner analyze in Nereids try { outFile.analyze(null, outputExprs, fileSink.getOutput().stream().map(NamedExpression::getName).collect(Collectors.toList())); } catch (Exception e) { throw new AnalysisException(e.getMessage(), e.getCause()); } ResultFileSink sink = new ResultFileSink(rootFragment.getPlanRoot().getId(), outFile); rootFragment.setSink(sink); return rootFragment; } /* ******************************************************************************************** * scan Node, in lexicographical order * ******************************************************************************************** */ @Override public PlanFragment visitPhysicalFileScan(PhysicalFileScan fileScan, PlanTranslatorContext context) { List<Slot> slots = fileScan.getOutput(); ExternalTable table = fileScan.getTable(); TupleDescriptor tupleDescriptor = generateTupleDesc(slots, table, context); // TODO(cmy): determine the needCheckColumnPriv param ScanNode scanNode; if (table instanceof HMSExternalTable) { switch (((HMSExternalTable) table).getDlaType()) { case HUDI: scanNode = new HudiScanNode(context.nextPlanNodeId(), tupleDescriptor, false); break; case ICEBERG: scanNode = new IcebergScanNode(context.nextPlanNodeId(), tupleDescriptor, false); break; case HIVE: scanNode = new HiveScanNode(context.nextPlanNodeId(), tupleDescriptor, false); break; default: throw new RuntimeException("do not support DLA type " + ((HMSExternalTable) table).getDlaType()); } } else if (table instanceof IcebergExternalTable) { scanNode = new IcebergScanNode(context.nextPlanNodeId(), tupleDescriptor, false); } else if (table instanceof PaimonExternalTable) { scanNode = new PaimonScanNode(context.nextPlanNodeId(), tupleDescriptor, false); } else if (table instanceof MaxComputeExternalTable) { scanNode = new MaxComputeScanNode(context.nextPlanNodeId(), tupleDescriptor, false); } else { throw new RuntimeException("do not support table type " + table.getType()); } scanNode.addConjuncts(translateToLegacyConjuncts(fileScan.getConjuncts())); TableName tableName = new TableName(null, "", ""); TableRef ref = new TableRef(tableName, null, null); BaseTableRef tableRef = new BaseTableRef(ref, table, tableName); tupleDescriptor.setRef(tableRef); Utils.execWithUncheckedException(scanNode::init); context.addScanNode(scanNode); ScanNode finalScanNode = scanNode; context.getRuntimeTranslator().ifPresent( runtimeFilterGenerator -> runtimeFilterGenerator.getTargetOnScanNode(fileScan.getRelationId()).forEach( expr -> runtimeFilterGenerator.translateRuntimeFilterTarget(expr, finalScanNode, context) ) ); Utils.execWithUncheckedException(scanNode::finalizeForNereids); // Create PlanFragment DataPartition dataPartition = DataPartition.RANDOM; PlanFragment planFragment = createPlanFragment(scanNode, dataPartition, fileScan); context.addPlanFragment(planFragment); updateLegacyPlanIdToPhysicalPlan(planFragment.getPlanRoot(), fileScan); return planFragment; } @Override public PlanFragment visitPhysicalEmptyRelation(PhysicalEmptyRelation emptyRelation, PlanTranslatorContext context) { List<Slot> output = emptyRelation.getOutput(); TupleDescriptor tupleDescriptor = generateTupleDesc(output, null, context); for (Slot slot : output) { SlotRef slotRef = context.findSlotRef(slot.getExprId()); slotRef.setLabel(slot.getName()); } ArrayList<TupleId> tupleIds = new ArrayList<>(); tupleIds.add(tupleDescriptor.getId()); EmptySetNode emptySetNode = new EmptySetNode(context.nextPlanNodeId(), tupleIds); PlanFragment planFragment = createPlanFragment(emptySetNode, DataPartition.UNPARTITIONED, emptyRelation); context.addPlanFragment(planFragment); updateLegacyPlanIdToPhysicalPlan(planFragment.getPlanRoot(), emptyRelation); return planFragment; } @Override public PlanFragment visitPhysicalEsScan(PhysicalEsScan esScan, PlanTranslatorContext context) { List<Slot> slots = esScan.getOutput(); ExternalTable table = esScan.getTable(); TupleDescriptor tupleDescriptor = generateTupleDesc(slots, table, context); EsScanNode esScanNode = new EsScanNode(context.nextPlanNodeId(), tupleDescriptor, true); Utils.execWithUncheckedException(esScanNode::init); context.addScanNode(esScanNode); context.getRuntimeTranslator().ifPresent( runtimeFilterGenerator -> runtimeFilterGenerator.getTargetOnScanNode(esScan.getRelationId()).forEach( expr -> runtimeFilterGenerator.translateRuntimeFilterTarget(expr, esScanNode, context) ) ); Utils.execWithUncheckedException(esScanNode::finalizeForNereids); DataPartition dataPartition = DataPartition.RANDOM; PlanFragment planFragment = new PlanFragment(context.nextFragmentId(), esScanNode, dataPartition); context.addPlanFragment(planFragment); updateLegacyPlanIdToPhysicalPlan(planFragment.getPlanRoot(), esScan); return planFragment; } @Override public PlanFragment visitPhysicalJdbcScan(PhysicalJdbcScan jdbcScan, PlanTranslatorContext context) { List<Slot> slots = jdbcScan.getOutput(); TableIf table = jdbcScan.getTable(); TupleDescriptor tupleDescriptor = generateTupleDesc(slots, table, context); JdbcScanNode jdbcScanNode = new JdbcScanNode(context.nextPlanNodeId(), tupleDescriptor, table instanceof JdbcExternalTable); jdbcScanNode.addConjuncts(translateToLegacyConjuncts(jdbcScan.getConjuncts())); Utils.execWithUncheckedException(jdbcScanNode::init); context.addScanNode(jdbcScanNode); context.getRuntimeTranslator().ifPresent( runtimeFilterGenerator -> runtimeFilterGenerator.getTargetOnScanNode(jdbcScan.getRelationId()).forEach( expr -> runtimeFilterGenerator.translateRuntimeFilterTarget(expr, jdbcScanNode, context) ) ); Utils.execWithUncheckedException(jdbcScanNode::finalizeForNereids); DataPartition dataPartition = DataPartition.RANDOM; PlanFragment planFragment = new PlanFragment(context.nextFragmentId(), jdbcScanNode, dataPartition); context.addPlanFragment(planFragment); updateLegacyPlanIdToPhysicalPlan(planFragment.getPlanRoot(), jdbcScan); return planFragment; } @Override public PlanFragment visitPhysicalOlapScan(PhysicalOlapScan olapScan, PlanTranslatorContext context) { List<Slot> slots = olapScan.getOutput(); OlapTable olapTable = olapScan.getTable(); // generate real output tuple TupleDescriptor tupleDescriptor = generateTupleDesc(slots, olapTable, context); // generate base index tuple because this fragment partitioned expr relay on slots of based index if (olapScan.getSelectedIndexId() != olapScan.getTable().getBaseIndexId()) { generateTupleDesc(olapScan.getBaseOutputs(), olapTable, context); } OlapScanNode olapScanNode = new OlapScanNode(context.nextPlanNodeId(), tupleDescriptor, "OlapScanNode"); // TODO: move all node set cardinality into one place if (olapScan.getStats() != null) { olapScanNode.setCardinality((long) olapScan.getStats().getRowCount()); } // TODO: Do we really need tableName here? TableName tableName = new TableName(null, "", ""); TableRef ref = new TableRef(tableName, null, null); BaseTableRef tableRef = new BaseTableRef(ref, olapTable, tableName); tupleDescriptor.setRef(tableRef); olapScanNode.setSelectedPartitionIds(olapScan.getSelectedPartitionIds()); olapScanNode.setSampleTabletIds(olapScan.getSelectedTabletIds()); // TODO: remove this switch? switch (olapScan.getTable().getKeysType()) { case AGG_KEYS: case UNIQUE_KEYS: case DUP_KEYS: PreAggStatus preAgg = olapScan.getPreAggStatus(); olapScanNode.setSelectedIndexInfo(olapScan.getSelectedIndexId(), preAgg.isOn(), preAgg.getOffReason()); break; default: throw new RuntimeException("Not supported key type: " + olapScan.getTable().getKeysType()); } // create scan range Utils.execWithUncheckedException(olapScanNode::init); // TODO: process collect scan node in one place context.addScanNode(olapScanNode); // TODO: process translate runtime filter in one place // use real plan node to present rf apply and rf generator context.getRuntimeTranslator().ifPresent( runtimeFilterTranslator -> runtimeFilterTranslator.getTargetOnScanNode(olapScan.getRelationId()) .forEach(expr -> runtimeFilterTranslator.translateRuntimeFilterTarget( expr, olapScanNode, context) ) ); // TODO: we need to remove all finalizeForNereids olapScanNode.finalizeForNereids(); // Create PlanFragment // TODO: use a util function to convert distribution to DataPartition DataPartition dataPartition = DataPartition.RANDOM; if (olapScan.getDistributionSpec() instanceof DistributionSpecHash) { DistributionSpecHash distributionSpecHash = (DistributionSpecHash) olapScan.getDistributionSpec(); List<Expr> partitionExprs = distributionSpecHash.getOrderedShuffledColumns().stream() .map(context::findSlotRef).collect(Collectors.toList()); dataPartition = new DataPartition(TPartitionType.HASH_PARTITIONED, partitionExprs); } // TODO: maybe we could have a better way to create fragment PlanFragment planFragment = createPlanFragment(olapScanNode, dataPartition, olapScan); context.addPlanFragment(planFragment); updateLegacyPlanIdToPhysicalPlan(planFragment.getPlanRoot(), olapScan); return planFragment; } @Override public PlanFragment visitPhysicalDeferMaterializeOlapScan( PhysicalDeferMaterializeOlapScan deferMaterializeOlapScan, PlanTranslatorContext context) { PlanFragment planFragment = visitPhysicalOlapScan(deferMaterializeOlapScan.getPhysicalOlapScan(), context); OlapScanNode olapScanNode = (OlapScanNode) planFragment.getPlanRoot(); TupleDescriptor tupleDescriptor = context.getTupleDesc(olapScanNode.getTupleId()); for (SlotDescriptor slotDescriptor : tupleDescriptor.getSlots()) { if (deferMaterializeOlapScan.getDeferMaterializeSlotIds() .contains(context.findExprId(slotDescriptor.getId()))) { slotDescriptor.setNeedMaterialize(false); } } context.createSlotDesc(tupleDescriptor, deferMaterializeOlapScan.getColumnIdSlot()); return planFragment; } @Override public PlanFragment visitPhysicalOneRowRelation(PhysicalOneRowRelation oneRowRelation, PlanTranslatorContext context) { List<Slot> slots = oneRowRelation.getLogicalProperties().getOutput(); TupleDescriptor oneRowTuple = generateTupleDesc(slots, null, context); List<Expr> legacyExprs = oneRowRelation.getProjects() .stream() .map(expr -> ExpressionTranslator.translate(expr, context)) .collect(Collectors.toList()); for (int i = 0; i < legacyExprs.size(); i++) { SlotDescriptor slotDescriptor = oneRowTuple.getSlots().get(i); Expr expr = legacyExprs.get(i); slotDescriptor.setSourceExpr(expr); slotDescriptor.setIsNullable(slots.get(i).nullable()); } UnionNode unionNode = new UnionNode(context.nextPlanNodeId(), oneRowTuple.getId()); unionNode.setCardinality(1L); unionNode.addConstExprList(legacyExprs); unionNode.finalizeForNereids(oneRowTuple.getSlots(), new ArrayList<>()); PlanFragment planFragment = createPlanFragment(unionNode, DataPartition.UNPARTITIONED, oneRowRelation); context.addPlanFragment(planFragment); updateLegacyPlanIdToPhysicalPlan(planFragment.getPlanRoot(), oneRowRelation); return planFragment; } @Override public PlanFragment visitPhysicalSchemaScan(PhysicalSchemaScan schemaScan, PlanTranslatorContext context) { Table table = schemaScan.getTable(); List<Slot> slots = ImmutableList.copyOf(schemaScan.getOutput()); TupleDescriptor tupleDescriptor = generateTupleDesc(slots, table, context); SchemaScanNode scanNode = new SchemaScanNode(context.nextPlanNodeId(), tupleDescriptor); context.getRuntimeTranslator().ifPresent( runtimeFilterGenerator -> runtimeFilterGenerator.getTargetOnScanNode(schemaScan.getRelationId()) .forEach(expr -> runtimeFilterGenerator.translateRuntimeFilterTarget(expr, scanNode, context) ) ); scanNode.finalizeForNereids(); context.addScanNode(scanNode); PlanFragment planFragment = createPlanFragment(scanNode, DataPartition.RANDOM, schemaScan); context.addPlanFragment(planFragment); updateLegacyPlanIdToPhysicalPlan(planFragment.getPlanRoot(), schemaScan); return planFragment; } @Override public PlanFragment visitPhysicalTVFRelation(PhysicalTVFRelation tvfRelation, PlanTranslatorContext context) { List<Slot> slots = tvfRelation.getLogicalProperties().getOutput(); TupleDescriptor tupleDescriptor = generateTupleDesc(slots, tvfRelation.getFunction().getTable(), context); TableValuedFunctionIf catalogFunction = tvfRelation.getFunction().getCatalogFunction(); ScanNode scanNode = catalogFunction.getScanNode(context.nextPlanNodeId(), tupleDescriptor); Utils.execWithUncheckedException(scanNode::init); context.getRuntimeTranslator().ifPresent( runtimeFilterGenerator -> runtimeFilterGenerator.getTargetOnScanNode(tvfRelation.getRelationId()) .forEach(expr -> runtimeFilterGenerator.translateRuntimeFilterTarget(expr, scanNode, context) ) ); Utils.execWithUncheckedException(scanNode::finalizeForNereids); context.addScanNode(scanNode); // TODO: it is weird update label in this way // set label for explain for (Slot slot : slots) { String tableColumnName = "_table_valued_function_" + tvfRelation.getFunction().getName() + "." + slots.get(0).getName(); context.findSlotRef(slot.getExprId()).setLabel(tableColumnName); } PlanFragment planFragment = createPlanFragment(scanNode, DataPartition.RANDOM, tvfRelation); context.addPlanFragment(planFragment); updateLegacyPlanIdToPhysicalPlan(planFragment.getPlanRoot(), tvfRelation); return planFragment; } /* ******************************************************************************************** * other Node, in lexicographical order, ignore algorithm name. for example, HashAggregate -> Aggregate * ******************************************************************************************** */ /** * Translate Agg. */ @Override public PlanFragment visitPhysicalHashAggregate( PhysicalHashAggregate<? extends Plan> aggregate, PlanTranslatorContext context) { PlanFragment inputPlanFragment = aggregate.child(0).accept(this, context); List<Expression> groupByExpressions = aggregate.getGroupByExpressions(); List<NamedExpression> outputExpressions = aggregate.getOutputExpressions(); // 1. generate slot reference for each group expression List<SlotReference> groupSlots = collectGroupBySlots(groupByExpressions, outputExpressions); ArrayList<Expr> execGroupingExpressions = groupByExpressions.stream() .map(e -> ExpressionTranslator.translate(e, context)) .collect(Collectors.toCollection(ArrayList::new)); // 2. collect agg expressions and generate agg function to slot reference map List<Slot> aggFunctionOutput = Lists.newArrayList(); List<AggregateExpression> aggregateExpressionList = outputExpressions.stream() .filter(o -> o.anyMatch(AggregateExpression.class::isInstance)) .peek(o -> aggFunctionOutput.add(o.toSlot())) .map(o -> o.<Set<AggregateExpression>>collect(AggregateExpression.class::isInstance)) .flatMap(Set::stream) .collect(Collectors.toList()); ArrayList<FunctionCallExpr> execAggregateFunctions = aggregateExpressionList.stream() .map(aggregateFunction -> (FunctionCallExpr) ExpressionTranslator.translate(aggregateFunction, context)) .collect(Collectors.toCollection(ArrayList::new)); // 3. generate output tuple List<Slot> slotList = Lists.newArrayList(); TupleDescriptor outputTupleDesc; slotList.addAll(groupSlots); slotList.addAll(aggFunctionOutput); outputTupleDesc = generateTupleDesc(slotList, null, context); List<Integer> aggFunOutputIds = ImmutableList.of(); if (!aggFunctionOutput.isEmpty()) { aggFunOutputIds = outputTupleDesc .getSlots() .subList(groupSlots.size(), outputTupleDesc.getSlots().size()) .stream() .map(slot -> slot.getId().asInt()) .collect(ImmutableList.toImmutableList()); } boolean isPartial = aggregate.getAggregateParam().aggMode.productAggregateBuffer; AggregateInfo aggInfo = AggregateInfo.create(execGroupingExpressions, execAggregateFunctions, aggFunOutputIds, isPartial, outputTupleDesc, outputTupleDesc, aggregate.getAggPhase().toExec()); AggregationNode aggregationNode = new AggregationNode(context.nextPlanNodeId(), inputPlanFragment.getPlanRoot(), aggInfo); if (!aggregate.getAggMode().isFinalPhase) { aggregationNode.unsetNeedsFinalize(); } switch (aggregate.getAggPhase()) { case LOCAL: // we should set is useStreamingAgg when has exchange, // so the `aggregationNode.setUseStreamingPreagg()` in the visitPhysicalDistribute break; case DISTINCT_LOCAL: aggregationNode.setIntermediateTuple(); break; case GLOBAL: case DISTINCT_GLOBAL: break; default: throw new RuntimeException("Unsupported agg phase: " + aggregate.getAggPhase()); } // TODO: use to set useStreamingAgg, we should remove it by set it in Nereids PhysicalHashAggregate firstAggregateInFragment = context.getFirstAggregateInFragment(inputPlanFragment); if (firstAggregateInFragment == null) { context.setFirstAggregateInFragment(inputPlanFragment, aggregate); } // in pipeline engine, we use parallel scan by default, but it broke the rule of data distribution // so, if we do final phase or merge without exchange. // we need turn of parallel scan to ensure to get correct result. PlanNode leftMostNode = inputPlanFragment.getPlanRoot(); while (leftMostNode.getChildren().size() != 0 && !(leftMostNode instanceof ExchangeNode)) { leftMostNode = leftMostNode.getChild(0); } // TODO: nereids forbid all parallel scan under aggregate temporary, because nereids could generate // so complex aggregate plan than legacy planner, and should add forbid parallel scan hint when // generate physical aggregate plan. // There is one exception, we use some precondition in optimizer, input to buffer always require any for input, // so when agg mode is INPUT_TO_BUFFER, we do not forbid parallel scan if (leftMostNode instanceof OlapScanNode && inputPlanFragment.getDataPartition().getType() != TPartitionType.RANDOM && aggregate.getAggregateParam().aggMode != AggMode.INPUT_TO_BUFFER) { inputPlanFragment.setHasColocatePlanNode(true); } setPlanRoot(inputPlanFragment, aggregationNode, aggregate); if (aggregate.getStats() != null) { aggregationNode.setCardinality((long) aggregate.getStats().getRowCount()); } updateLegacyPlanIdToPhysicalPlan(inputPlanFragment.getPlanRoot(), aggregate); return inputPlanFragment; } @Override public PlanFragment visitPhysicalStorageLayerAggregate( PhysicalStorageLayerAggregate storageLayerAggregate, PlanTranslatorContext context) { Preconditions.checkState(storageLayerAggregate.getRelation() instanceof PhysicalOlapScan, "PhysicalStorageLayerAggregate only support PhysicalOlapScan: " + storageLayerAggregate.getRelation().getClass().getName()); PlanFragment planFragment = storageLayerAggregate.getRelation().accept(this, context); OlapScanNode olapScanNode = (OlapScanNode) planFragment.getPlanRoot(); TPushAggOp pushAggOp; switch (storageLayerAggregate.getAggOp()) { case COUNT: pushAggOp = TPushAggOp.COUNT; break; case MIN_MAX: pushAggOp = TPushAggOp.MINMAX; break; case MIX: pushAggOp = TPushAggOp.MIX; break; default: throw new AnalysisException("Unsupported storage layer aggregate: " + storageLayerAggregate.getAggOp()); } olapScanNode.setPushDownAggNoGrouping(pushAggOp); updateLegacyPlanIdToPhysicalPlan(planFragment.getPlanRoot(), storageLayerAggregate); return planFragment; } @Override public PlanFragment visitPhysicalAssertNumRows(PhysicalAssertNumRows<? extends Plan> assertNumRows, PlanTranslatorContext context) { PlanFragment currentFragment = assertNumRows.child().accept(this, context); // create assertNode AssertNumRowsNode assertNumRowsNode = new AssertNumRowsNode(context.nextPlanNodeId(), currentFragment.getPlanRoot(), ExpressionTranslator.translateAssert(assertNumRows.getAssertNumRowsElement())); addPlanRoot(currentFragment, assertNumRowsNode, assertNumRows); return currentFragment; } /** * NOTICE: Must translate left, which it's the producer of consumer. */ @Override public PlanFragment visitPhysicalCTEAnchor(PhysicalCTEAnchor<? extends Plan, ? extends Plan> cteAnchor, PlanTranslatorContext context) { cteAnchor.child(0).accept(this, context); return cteAnchor.child(1).accept(this, context); } @Override public PlanFragment visitPhysicalCTEConsumer(PhysicalCTEConsumer cteConsumer, PlanTranslatorContext context) { CTEId cteId = cteConsumer.getCteId(); MultiCastPlanFragment multiCastFragment = (MultiCastPlanFragment) context.getCteProduceFragments().get(cteId); Preconditions.checkState(multiCastFragment.getSink() instanceof MultiCastDataSink, "invalid multiCastFragment"); MultiCastDataSink multiCastDataSink = (MultiCastDataSink) multiCastFragment.getSink(); Preconditions.checkState(multiCastDataSink != null, "invalid multiCastDataSink"); PhysicalCTEProducer<?> cteProducer = context.getCteProduceMap().get(cteId); Preconditions.checkState(cteProducer != null, "invalid cteProducer"); context.getCteConsumerMap().put(cteId, cteConsumer); // set datasink to multicast data sink but do not set target now // target will be set when translate distribute DataStreamSink streamSink = new DataStreamSink(); streamSink.setFragment(multiCastFragment); multiCastDataSink.getDataStreamSinks().add(streamSink); multiCastDataSink.getDestinations().add(Lists.newArrayList()); // update expr to slot mapping TupleDescriptor tupleDescriptor = null; for (Slot producerSlot : cteProducer.getOutput()) { Slot consumerSlot = cteConsumer.getProducerToConsumerSlotMap().get(producerSlot); SlotRef slotRef = context.findSlotRef(producerSlot.getExprId()); tupleDescriptor = slotRef.getDesc().getParent(); context.addExprIdSlotRefPair(consumerSlot.getExprId(), slotRef); } CTEScanNode cteScanNode = new CTEScanNode(tupleDescriptor); context.getRuntimeTranslator().ifPresent(runtimeFilterTranslator -> runtimeFilterTranslator.getTargetOnScanNode(cteConsumer.getRelationId()).forEach( expr -> runtimeFilterTranslator.translateRuntimeFilterTarget(expr, cteScanNode, context))); context.getCteScanNodeMap().put(multiCastFragment.getFragmentId(), cteScanNode); return multiCastFragment; } @Override public PlanFragment visitPhysicalCTEProducer(PhysicalCTEProducer<? extends Plan> cteProducer, PlanTranslatorContext context) { PlanFragment child = cteProducer.child().accept(this, context); CTEId cteId = cteProducer.getCteId(); context.getPlanFragments().remove(child); MultiCastPlanFragment multiCastPlanFragment = new MultiCastPlanFragment(child); MultiCastDataSink multiCastDataSink = new MultiCastDataSink(); multiCastPlanFragment.setSink(multiCastDataSink); List<Expr> outputs = cteProducer.getOutput().stream() .map(e -> ExpressionTranslator.translate(e, context)) .collect(Collectors.toList()); multiCastPlanFragment.setOutputExprs(outputs); context.getCteProduceFragments().put(cteId, multiCastPlanFragment); context.getCteProduceMap().put(cteId, cteProducer); if (context.getRuntimeTranslator().isPresent()) { context.getRuntimeTranslator().get().getContext().getCteProduceMap().put(cteId, cteProducer); } context.getPlanFragments().add(multiCastPlanFragment); return child; } @Override public PlanFragment visitPhysicalFilter(PhysicalFilter<? extends Plan> filter, PlanTranslatorContext context) { if (filter.child(0) instanceof AbstractPhysicalJoin) { AbstractPhysicalJoin<?, ?> join = (AbstractPhysicalJoin<?, ?>) filter.child(); join.addFilterConjuncts(filter.getConjuncts()); } PlanFragment inputFragment = filter.child(0).accept(this, context); // process multicast sink if (inputFragment instanceof MultiCastPlanFragment) { MultiCastDataSink multiCastDataSink = (MultiCastDataSink) inputFragment.getSink(); DataStreamSink dataStreamSink = multiCastDataSink.getDataStreamSinks().get( multiCastDataSink.getDataStreamSinks().size() - 1); filter.getConjuncts().stream() .map(e -> ExpressionTranslator.translate(e, context)) .forEach(dataStreamSink::addConjunct); return inputFragment; } PlanNode planNode = inputFragment.getPlanRoot(); if (planNode instanceof ExchangeNode || planNode instanceof SortNode || planNode instanceof UnionNode) { // the three nodes don't support conjuncts, need create a SelectNode to filter data SelectNode selectNode = new SelectNode(context.nextPlanNodeId(), planNode); addConjunctsToPlanNode(filter, selectNode, context); addPlanRoot(inputFragment, selectNode, filter); } else { if (!(filter.child(0) instanceof AbstractPhysicalJoin)) { addConjunctsToPlanNode(filter, planNode, context); updateLegacyPlanIdToPhysicalPlan(inputFragment.getPlanRoot(), filter); } } //in ut, filter.stats may be null if (filter.getStats() != null) { inputFragment.getPlanRoot().setCardinalityAfterFilter((long) filter.getStats().getRowCount()); } return inputFragment; } @Override public PlanFragment visitPhysicalGenerate(PhysicalGenerate<? extends Plan> generate, PlanTranslatorContext context) { PlanFragment currentFragment = generate.child().accept(this, context); ArrayList<Expr> functionCalls = generate.getGenerators().stream() .map(e -> ExpressionTranslator.translate(e, context)) .collect(Collectors.toCollection(ArrayList::new)); TupleDescriptor tupleDescriptor = generateTupleDesc(generate.getGeneratorOutput(), null, context); List<TupleId> childOutputTupleIds = currentFragment.getPlanRoot().getOutputTupleIds(); if (childOutputTupleIds == null || childOutputTupleIds.isEmpty()) { childOutputTupleIds = currentFragment.getPlanRoot().getTupleIds(); } List<SlotId> outputSlotIds = Stream.concat(childOutputTupleIds.stream(), Stream.of(tupleDescriptor.getId())) .map(id -> context.getTupleDesc(id).getSlots()) .flatMap(List::stream) .map(SlotDescriptor::getId) .collect(Collectors.toList()); TableFunctionNode tableFunctionNode = new TableFunctionNode(context.nextPlanNodeId(), currentFragment.getPlanRoot(), tupleDescriptor.getId(), functionCalls, outputSlotIds); addPlanRoot(currentFragment, tableFunctionNode, generate); return currentFragment; } /** * the contract of hash join node with BE * 1. hash join contains 3 types of predicates: * a. equal join conjuncts * b. other join conjuncts * c. other predicates (denoted by filter conjuncts in the rest of comments) * <p> * 2. hash join contains 3 tuple descriptors * a. input tuple descriptors, corresponding to the left child output and right child output. * If its column is selected, it will be displayed in explain by `tuple ids`. * for example, select L.* from L join R on ..., because no column from R are selected, tuple ids only * contains output tuple of L. * equal join conjuncts is bound on input tuple descriptors. * <p> * b.intermediate tuple. * This tuple describes schema of the output block after evaluating equal join conjuncts * and other join conjuncts. * <p> * Other join conjuncts currently is bound on intermediate tuple. There are some historical reason, and it * should be bound on input tuple in the future. * <p> * filter conjuncts will be evaluated on the intermediate tuple. That means the input block of filter is * described by intermediate tuple, and hence filter conjuncts should be bound on intermediate tuple. * <p> * In order to be compatible with old version, intermediate tuple is not pruned. For example, intermediate * tuple contains all slots from both sides of children. After probing hash-table, BE does not need to * materialize all slots in intermediate tuple. The slots in HashJoinNode.hashOutputSlotIds will be * materialized by BE. If `hashOutputSlotIds` is empty, all slots will be materialized. * <p> * In case of outer join, the slots in intermediate should be set nullable. * For example, * select L.*, R.* from L left outer join R on ... * All slots from R in intermediate tuple should be nullable. * <p> * c. output tuple * This describes the schema of hash join output block. * 3. Intermediate tuple * for BE performance reason, the slots in intermediate tuple * depends on the join type and other join conjuncts. * In general, intermediate tuple contains all slots of both children, except one case. * For left-semi/left-ant (right-semi/right-semi) join without other join conjuncts, intermediate tuple * only contains left (right) children output slots. * */ @Override public PlanFragment visitPhysicalHashJoin( PhysicalHashJoin<? extends Plan, ? extends Plan> hashJoin, PlanTranslatorContext context) { Preconditions.checkArgument(hashJoin.left() instanceof PhysicalPlan, "HashJoin's left child should be PhysicalPlan"); Preconditions.checkArgument(hashJoin.right() instanceof PhysicalPlan, "HashJoin's left child should be PhysicalPlan"); PhysicalHashJoin<PhysicalPlan, PhysicalPlan> physicalHashJoin = (PhysicalHashJoin<PhysicalPlan, PhysicalPlan>) hashJoin; // NOTICE: We must visit from right to left, to ensure the last fragment is root fragment PlanFragment rightFragment = hashJoin.child(1).accept(this, context); PlanFragment leftFragment = hashJoin.child(0).accept(this, context); if (JoinUtils.shouldNestedLoopJoin(hashJoin)) { throw new RuntimeException("Physical hash join could not execute without equal join condition."); } PlanNode leftPlanRoot = leftFragment.getPlanRoot(); PlanNode rightPlanRoot = rightFragment.getPlanRoot(); JoinType joinType = hashJoin.getJoinType(); List<Expr> execEqConjuncts = hashJoin.getHashJoinConjuncts().stream() .map(EqualTo.class::cast) .map(e -> JoinUtils.swapEqualToForChildrenOrder(e, hashJoin.left().getOutputSet())) .map(e -> ExpressionTranslator.translate(e, context)) .collect(Collectors.toList()); HashJoinNode hashJoinNode = new HashJoinNode(context.nextPlanNodeId(), leftPlanRoot, rightPlanRoot, JoinType.toJoinOperator(joinType), execEqConjuncts, Lists.newArrayList(), null, null, null, hashJoin.isMarkJoin()); PlanFragment currentFragment = connectJoinNode(hashJoinNode, leftFragment, rightFragment, context, hashJoin); if (JoinUtils.shouldColocateJoin(physicalHashJoin)) { // TODO: add reason hashJoinNode.setColocate(true, ""); leftFragment.setHasColocatePlanNode(true); } else if (JoinUtils.shouldBroadcastJoin(physicalHashJoin)) { Preconditions.checkState(rightPlanRoot instanceof ExchangeNode, "right child of broadcast join must be ExchangeNode but it is " + rightFragment.getPlanRoot()); Preconditions.checkState(rightFragment.getChildren().size() == 1, "right child of broadcast join must have 1 child, but meet " + rightFragment.getChildren().size()); ((ExchangeNode) rightPlanRoot).setRightChildOfBroadcastHashJoin(true); hashJoinNode.setDistributionMode(DistributionMode.BROADCAST); } else if (JoinUtils.shouldBucketShuffleJoin(physicalHashJoin)) { hashJoinNode.setDistributionMode(DistributionMode.BUCKET_SHUFFLE); } else { hashJoinNode.setDistributionMode(DistributionMode.PARTITIONED); } // Nereids does not care about output order of join, // but BE need left child's output must be before right child's output. // So we need to swap the output order of left and right child if necessary. // TODO: revert this after Nereids could ensure the output order is correct. List<TupleDescriptor> leftTuples = context.getTupleDesc(leftPlanRoot); List<SlotDescriptor> leftSlotDescriptors = leftTuples.stream() .map(TupleDescriptor::getSlots) .flatMap(Collection::stream) .collect(Collectors.toList()); List<TupleDescriptor> rightTuples = context.getTupleDesc(rightPlanRoot); List<SlotDescriptor> rightSlotDescriptors = rightTuples.stream() .map(TupleDescriptor::getSlots) .flatMap(Collection::stream) .collect(Collectors.toList()); Map<ExprId, SlotReference> outputSlotReferenceMap = Maps.newHashMap(); hashJoin.getOutput().stream() .map(SlotReference.class::cast) .forEach(s -> outputSlotReferenceMap.put(s.getExprId(), s)); List<SlotReference> outputSlotReferences = Stream.concat(leftTuples.stream(), rightTuples.stream()) .map(TupleDescriptor::getSlots) .flatMap(Collection::stream) .map(sd -> context.findExprId(sd.getId())) .map(outputSlotReferenceMap::get) .filter(Objects::nonNull) .collect(Collectors.toList()); Map<ExprId, SlotReference> hashOutputSlotReferenceMap = Maps.newHashMap(outputSlotReferenceMap); hashJoin.getOtherJoinConjuncts() .stream() .filter(e -> !(e.equals(BooleanLiteral.TRUE))) .flatMap(e -> e.getInputSlots().stream()) .map(SlotReference.class::cast) .forEach(s -> hashOutputSlotReferenceMap.put(s.getExprId(), s)); hashJoin.getFilterConjuncts().stream() .filter(e -> !(e.equals(BooleanLiteral.TRUE))) .flatMap(e -> e.getInputSlots().stream()) .map(SlotReference.class::cast) .forEach(s -> hashOutputSlotReferenceMap.put(s.getExprId(), s)); Map<ExprId, SlotReference> leftChildOutputMap = Maps.newHashMap(); hashJoin.child(0).getOutput().stream() .map(SlotReference.class::cast) .forEach(s -> leftChildOutputMap.put(s.getExprId(), s)); Map<ExprId, SlotReference> rightChildOutputMap = Maps.newHashMap(); hashJoin.child(1).getOutput().stream() .map(SlotReference.class::cast) .forEach(s -> rightChildOutputMap.put(s.getExprId(), s)); // translate runtime filter context.getRuntimeTranslator().ifPresent(runtimeFilterTranslator -> runtimeFilterTranslator .getRuntimeFilterOfHashJoinNode(physicalHashJoin) .forEach(filter -> runtimeFilterTranslator.createLegacyRuntimeFilter(filter, hashJoinNode, context))); // make intermediate tuple List<SlotDescriptor> leftIntermediateSlotDescriptor = Lists.newArrayList(); List<SlotDescriptor> rightIntermediateSlotDescriptor = Lists.newArrayList(); TupleDescriptor intermediateDescriptor = context.generateTupleDesc(); if (hashJoin.getOtherJoinConjuncts().isEmpty() && (joinType == JoinType.LEFT_ANTI_JOIN || joinType == JoinType.LEFT_SEMI_JOIN || joinType == JoinType.NULL_AWARE_LEFT_ANTI_JOIN)) { for (SlotDescriptor leftSlotDescriptor : leftSlotDescriptors) { if (!leftSlotDescriptor.isMaterialized()) { continue; } SlotReference sf = leftChildOutputMap.get(context.findExprId(leftSlotDescriptor.getId())); SlotDescriptor sd; if (sf == null && leftSlotDescriptor.getColumn().getName().equals(Column.ROWID_COL)) { // TODO: temporary code for two phase read, should remove it after refactor sd = context.getDescTable().copySlotDescriptor(intermediateDescriptor, leftSlotDescriptor); } else { sd = context.createSlotDesc(intermediateDescriptor, sf); if (hashOutputSlotReferenceMap.get(sf.getExprId()) != null) { hashJoinNode.addSlotIdToHashOutputSlotIds(leftSlotDescriptor.getId()); hashJoinNode.getHashOutputExprSlotIdMap().put(sf.getExprId(), leftSlotDescriptor.getId()); } } leftIntermediateSlotDescriptor.add(sd); } } else if (hashJoin.getOtherJoinConjuncts().isEmpty() && (joinType == JoinType.RIGHT_ANTI_JOIN || joinType == JoinType.RIGHT_SEMI_JOIN)) { for (SlotDescriptor rightSlotDescriptor : rightSlotDescriptors) { if (!rightSlotDescriptor.isMaterialized()) { continue; } SlotReference sf = rightChildOutputMap.get(context.findExprId(rightSlotDescriptor.getId())); SlotDescriptor sd; if (sf == null && rightSlotDescriptor.getColumn().getName().equals(Column.ROWID_COL)) { // TODO: temporary code for two phase read, should remove it after refactor sd = context.getDescTable().copySlotDescriptor(intermediateDescriptor, rightSlotDescriptor); } else { sd = context.createSlotDesc(intermediateDescriptor, sf); if (hashOutputSlotReferenceMap.get(sf.getExprId()) != null) { hashJoinNode.addSlotIdToHashOutputSlotIds(rightSlotDescriptor.getId()); hashJoinNode.getHashOutputExprSlotIdMap().put(sf.getExprId(), rightSlotDescriptor.getId()); } } rightIntermediateSlotDescriptor.add(sd); } } else { for (SlotDescriptor leftSlotDescriptor : leftSlotDescriptors) { if (!leftSlotDescriptor.isMaterialized()) { continue; } SlotReference sf = leftChildOutputMap.get(context.findExprId(leftSlotDescriptor.getId())); SlotDescriptor sd; if (sf == null && leftSlotDescriptor.getColumn().getName().equals(Column.ROWID_COL)) { // TODO: temporary code for two phase read, should remove it after refactor sd = context.getDescTable().copySlotDescriptor(intermediateDescriptor, leftSlotDescriptor); } else { sd = context.createSlotDesc(intermediateDescriptor, sf); if (hashOutputSlotReferenceMap.get(sf.getExprId()) != null) { hashJoinNode.addSlotIdToHashOutputSlotIds(leftSlotDescriptor.getId()); hashJoinNode.getHashOutputExprSlotIdMap().put(sf.getExprId(), leftSlotDescriptor.getId()); } } leftIntermediateSlotDescriptor.add(sd); } for (SlotDescriptor rightSlotDescriptor : rightSlotDescriptors) { if (!rightSlotDescriptor.isMaterialized()) { continue; } SlotReference sf = rightChildOutputMap.get(context.findExprId(rightSlotDescriptor.getId())); SlotDescriptor sd; if (sf == null && rightSlotDescriptor.getColumn().getName().equals(Column.ROWID_COL)) { // TODO: temporary code for two phase read, should remove it after refactor sd = context.getDescTable().copySlotDescriptor(intermediateDescriptor, rightSlotDescriptor); } else { sd = context.createSlotDesc(intermediateDescriptor, sf); if (hashOutputSlotReferenceMap.get(sf.getExprId()) != null) { hashJoinNode.addSlotIdToHashOutputSlotIds(rightSlotDescriptor.getId()); hashJoinNode.getHashOutputExprSlotIdMap().put(sf.getExprId(), rightSlotDescriptor.getId()); } } rightIntermediateSlotDescriptor.add(sd); } } if (hashJoin.getMarkJoinSlotReference().isPresent()) { SlotReference sf = hashJoin.getMarkJoinSlotReference().get(); outputSlotReferences.add(sf); context.createSlotDesc(intermediateDescriptor, sf); if (hashOutputSlotReferenceMap.get(sf.getExprId()) != null) { SlotRef markJoinSlotId = context.findSlotRef(sf.getExprId()); Preconditions.checkState(markJoinSlotId != null); hashJoinNode.addSlotIdToHashOutputSlotIds(markJoinSlotId.getSlotId()); hashJoinNode.getHashOutputExprSlotIdMap().put(sf.getExprId(), markJoinSlotId.getSlotId()); } } // set slots as nullable for outer join if (joinType == JoinType.LEFT_OUTER_JOIN || joinType == JoinType.FULL_OUTER_JOIN) { rightIntermediateSlotDescriptor.forEach(sd -> sd.setIsNullable(true)); } if (joinType == JoinType.RIGHT_OUTER_JOIN || joinType == JoinType.FULL_OUTER_JOIN) { leftIntermediateSlotDescriptor.forEach(sd -> sd.setIsNullable(true)); } List<Expr> otherJoinConjuncts = hashJoin.getOtherJoinConjuncts() .stream() // TODO add constant expr will cause be crash, currently we only handle true literal. // remove it after Nereids could ensure no constant expr in other join condition .filter(e -> !(e.equals(BooleanLiteral.TRUE))) .map(e -> ExpressionTranslator.translate(e, context)) .collect(Collectors.toList()); hashJoin.getFilterConjuncts().stream() .filter(e -> !(e.equals(BooleanLiteral.TRUE))) .map(e -> ExpressionTranslator.translate(e, context)) .forEach(hashJoinNode::addConjunct); hashJoinNode.setOtherJoinConjuncts(otherJoinConjuncts); hashJoinNode.setvIntermediateTupleDescList(Lists.newArrayList(intermediateDescriptor)); if (hashJoin.isShouldTranslateOutput()) { // translate output expr on intermediate tuple List<Expr> srcToOutput = outputSlotReferences.stream() .map(e -> ExpressionTranslator.translate(e, context)) .collect(Collectors.toList()); TupleDescriptor outputDescriptor = context.generateTupleDesc(); outputSlotReferences.forEach(s -> context.createSlotDesc(outputDescriptor, s)); hashJoinNode.setvOutputTupleDesc(outputDescriptor); hashJoinNode.setvSrcToOutputSMap(srcToOutput); } if (hashJoin.getStats() != null) { hashJoinNode.setCardinality((long) hashJoin.getStats().getRowCount()); } updateLegacyPlanIdToPhysicalPlan(currentFragment.getPlanRoot(), hashJoin); return currentFragment; } @Override public PlanFragment visitPhysicalNestedLoopJoin( PhysicalNestedLoopJoin<? extends Plan, ? extends Plan> nestedLoopJoin, PlanTranslatorContext context) { // NOTICE: We must visit from right to left, to ensure the last fragment is root fragment // TODO: we should add a helper method to wrap this logic. // Maybe something like private List<PlanFragment> postOrderVisitChildren( // PhysicalPlan plan, PlanVisitor visitor, Context context). PlanFragment rightFragment = nestedLoopJoin.child(1).accept(this, context); PlanFragment leftFragment = nestedLoopJoin.child(0).accept(this, context); PlanNode leftFragmentPlanRoot = leftFragment.getPlanRoot(); PlanNode rightFragmentPlanRoot = rightFragment.getPlanRoot(); if (JoinUtils.shouldNestedLoopJoin(nestedLoopJoin)) { List<TupleDescriptor> leftTuples = context.getTupleDesc(leftFragmentPlanRoot); List<TupleDescriptor> rightTuples = context.getTupleDesc(rightFragmentPlanRoot); List<TupleId> tupleIds = Stream.concat(leftTuples.stream(), rightTuples.stream()) .map(TupleDescriptor::getId) .collect(Collectors.toList()); JoinType joinType = nestedLoopJoin.getJoinType(); NestedLoopJoinNode nestedLoopJoinNode = new NestedLoopJoinNode(context.nextPlanNodeId(), leftFragmentPlanRoot, rightFragmentPlanRoot, tupleIds, JoinType.toJoinOperator(joinType), null, null, null, nestedLoopJoin.isMarkJoin()); if (nestedLoopJoin.getStats() != null) { nestedLoopJoinNode.setCardinality((long) nestedLoopJoin.getStats().getRowCount()); } nestedLoopJoinNode.setChild(0, leftFragment.getPlanRoot()); nestedLoopJoinNode.setChild(1, rightFragment.getPlanRoot()); setPlanRoot(leftFragment, nestedLoopJoinNode, nestedLoopJoin); // TODO: what's this? do we really need to set this? rightFragment.getPlanRoot().setCompactData(false); context.mergePlanFragment(rightFragment, leftFragment); for (PlanFragment rightChild : rightFragment.getChildren()) { leftFragment.addChild(rightChild); } // translate runtime filter context.getRuntimeTranslator().ifPresent(runtimeFilterTranslator -> { Set<RuntimeFilter> filters = runtimeFilterTranslator .getRuntimeFilterOfHashJoinNode(nestedLoopJoin); filters.forEach(filter -> runtimeFilterTranslator .createLegacyRuntimeFilter(filter, nestedLoopJoinNode, context)); if (!filters.isEmpty()) { nestedLoopJoinNode.setOutputLeftSideOnly(true); } }); Map<ExprId, SlotReference> leftChildOutputMap = Maps.newHashMap(); nestedLoopJoin.child(0).getOutput().stream() .map(SlotReference.class::cast) .forEach(s -> leftChildOutputMap.put(s.getExprId(), s)); Map<ExprId, SlotReference> rightChildOutputMap = Maps.newHashMap(); nestedLoopJoin.child(1).getOutput().stream() .map(SlotReference.class::cast) .forEach(s -> rightChildOutputMap.put(s.getExprId(), s)); // make intermediate tuple List<SlotDescriptor> leftIntermediateSlotDescriptor = Lists.newArrayList(); List<SlotDescriptor> rightIntermediateSlotDescriptor = Lists.newArrayList(); TupleDescriptor intermediateDescriptor = context.generateTupleDesc(); // Nereids does not care about output order of join, // but BE need left child's output must be before right child's output. // So we need to swap the output order of left and right child if necessary. // TODO: revert this after Nereids could ensure the output order is correct. List<SlotDescriptor> leftSlotDescriptors = leftTuples.stream() .map(TupleDescriptor::getSlots) .flatMap(Collection::stream) .collect(Collectors.toList()); List<SlotDescriptor> rightSlotDescriptors = rightTuples.stream() .map(TupleDescriptor::getSlots) .flatMap(Collection::stream) .collect(Collectors.toList()); Map<ExprId, SlotReference> outputSlotReferenceMap = Maps.newHashMap(); nestedLoopJoin.getOutput().stream() .map(SlotReference.class::cast) .forEach(s -> outputSlotReferenceMap.put(s.getExprId(), s)); nestedLoopJoin.getFilterConjuncts().stream() .filter(e -> !(e.equals(BooleanLiteral.TRUE))) .flatMap(e -> e.getInputSlots().stream()) .map(SlotReference.class::cast) .forEach(s -> outputSlotReferenceMap.put(s.getExprId(), s)); List<SlotReference> outputSlotReferences = Stream.concat(leftTuples.stream(), rightTuples.stream()) .map(TupleDescriptor::getSlots) .flatMap(Collection::stream) .map(sd -> context.findExprId(sd.getId())) .map(outputSlotReferenceMap::get) .filter(Objects::nonNull) .collect(Collectors.toList()); // TODO: because of the limitation of be, the VNestedLoopJoinNode will output column from both children // in the intermediate tuple, so fe have to do the same, if be fix the problem, we can change it back. for (SlotDescriptor leftSlotDescriptor : leftSlotDescriptors) { if (!leftSlotDescriptor.isMaterialized()) { continue; } SlotReference sf = leftChildOutputMap.get(context.findExprId(leftSlotDescriptor.getId())); SlotDescriptor sd; if (sf == null && leftSlotDescriptor.getColumn().getName().equals(Column.ROWID_COL)) { // TODO: temporary code for two phase read, should remove it after refactor sd = context.getDescTable().copySlotDescriptor(intermediateDescriptor, leftSlotDescriptor); } else { sd = context.createSlotDesc(intermediateDescriptor, sf); } leftIntermediateSlotDescriptor.add(sd); } for (SlotDescriptor rightSlotDescriptor : rightSlotDescriptors) { if (!rightSlotDescriptor.isMaterialized()) { continue; } SlotReference sf = rightChildOutputMap.get(context.findExprId(rightSlotDescriptor.getId())); SlotDescriptor sd; if (sf == null && rightSlotDescriptor.getColumn().getName().equals(Column.ROWID_COL)) { // TODO: temporary code for two phase read, should remove it after refactor sd = context.getDescTable().copySlotDescriptor(intermediateDescriptor, rightSlotDescriptor); } else { sd = context.createSlotDesc(intermediateDescriptor, sf); } rightIntermediateSlotDescriptor.add(sd); } if (nestedLoopJoin.getMarkJoinSlotReference().isPresent()) { outputSlotReferences.add(nestedLoopJoin.getMarkJoinSlotReference().get()); context.createSlotDesc(intermediateDescriptor, nestedLoopJoin.getMarkJoinSlotReference().get()); } // set slots as nullable for outer join if (joinType == JoinType.LEFT_OUTER_JOIN || joinType == JoinType.FULL_OUTER_JOIN) { rightIntermediateSlotDescriptor.forEach(sd -> sd.setIsNullable(true)); } if (joinType == JoinType.RIGHT_OUTER_JOIN || joinType == JoinType.FULL_OUTER_JOIN) { leftIntermediateSlotDescriptor.forEach(sd -> sd.setIsNullable(true)); } nestedLoopJoinNode.setvIntermediateTupleDescList(Lists.newArrayList(intermediateDescriptor)); List<Expr> joinConjuncts = nestedLoopJoin.getOtherJoinConjuncts().stream() .filter(e -> !nestedLoopJoin.isBitmapRuntimeFilterCondition(e)) .map(e -> ExpressionTranslator.translate(e, context)).collect(Collectors.toList()); if (!nestedLoopJoin.isBitMapRuntimeFilterConditionsEmpty() && joinConjuncts.isEmpty()) { //left semi join need at least one conjunct. otherwise left-semi-join fallback to cross-join joinConjuncts.add(new BoolLiteral(true)); } nestedLoopJoinNode.setJoinConjuncts(joinConjuncts); nestedLoopJoin.getFilterConjuncts().stream() .filter(e -> !(e.equals(BooleanLiteral.TRUE))) .map(e -> ExpressionTranslator.translate(e, context)) .forEach(nestedLoopJoinNode::addConjunct); if (nestedLoopJoin.isShouldTranslateOutput()) { // translate output expr on intermediate tuple List<Expr> srcToOutput = outputSlotReferences.stream() .map(e -> ExpressionTranslator.translate(e, context)) .collect(Collectors.toList()); TupleDescriptor outputDescriptor = context.generateTupleDesc(); outputSlotReferences.forEach(s -> context.createSlotDesc(outputDescriptor, s)); nestedLoopJoinNode.setvOutputTupleDesc(outputDescriptor); nestedLoopJoinNode.setvSrcToOutputSMap(srcToOutput); } if (nestedLoopJoin.getStats() != null) { nestedLoopJoinNode.setCardinality((long) nestedLoopJoin.getStats().getRowCount()); } updateLegacyPlanIdToPhysicalPlan(leftFragment.getPlanRoot(), nestedLoopJoin); return leftFragment; } else { throw new RuntimeException("Physical nested loop join could not execute with equal join condition."); } } @Override public PlanFragment visitPhysicalLimit(PhysicalLimit<? extends Plan> physicalLimit, PlanTranslatorContext context) { PlanFragment inputFragment = physicalLimit.child(0).accept(this, context); PlanNode child = inputFragment.getPlanRoot(); child.setOffset(physicalLimit.getOffset()); child.setLimit(physicalLimit.getLimit()); updateLegacyPlanIdToPhysicalPlan(child, physicalLimit); return inputFragment; } @Override public PlanFragment visitPhysicalPartitionTopN(PhysicalPartitionTopN<? extends Plan> partitionTopN, PlanTranslatorContext context) { PlanFragment inputFragment = partitionTopN.child(0).accept(this, context); PartitionSortNode partitionSortNode = translatePartitionSortNode( partitionTopN, inputFragment.getPlanRoot(), context); addPlanRoot(inputFragment, partitionSortNode, partitionTopN); return inputFragment; } // TODO: generate expression mapping when be project could do in ExecNode. @Override public PlanFragment visitPhysicalProject(PhysicalProject<? extends Plan> project, PlanTranslatorContext context) { if (project.child(0) instanceof AbstractPhysicalJoin) { ((AbstractPhysicalJoin<?, ?>) project.child(0)).setShouldTranslateOutput(false); } if (project.child(0) instanceof PhysicalFilter) { if (project.child(0).child(0) instanceof AbstractPhysicalJoin) { ((AbstractPhysicalJoin<?, ?>) project.child(0).child(0)).setShouldTranslateOutput(false); } } PlanFragment inputFragment = project.child(0).accept(this, context); List<Expr> projectionExprs = project.getProjects() .stream() .map(e -> ExpressionTranslator.translate(e, context)) .collect(Collectors.toList()); List<Slot> slots = project.getProjects() .stream() .map(NamedExpression::toSlot) .collect(Collectors.toList()); // process multicast sink if (inputFragment instanceof MultiCastPlanFragment) { MultiCastDataSink multiCastDataSink = (MultiCastDataSink) inputFragment.getSink(); DataStreamSink dataStreamSink = multiCastDataSink.getDataStreamSinks().get( multiCastDataSink.getDataStreamSinks().size() - 1); TupleDescriptor projectionTuple = generateTupleDesc(slots, null, context); dataStreamSink.setProjections(projectionExprs); dataStreamSink.setOutputTupleDesc(projectionTuple); return inputFragment; } PlanNode inputPlanNode = inputFragment.getPlanRoot(); List<Expr> conjuncts = inputPlanNode.getConjuncts(); Set<SlotId> requiredSlotIdSet = Sets.newHashSet(); for (Expr expr : projectionExprs) { Expr.extractSlots(expr, requiredSlotIdSet); } Set<SlotId> requiredByProjectSlotIdSet = Sets.newHashSet(requiredSlotIdSet); for (Expr expr : conjuncts) { Expr.extractSlots(expr, requiredSlotIdSet); } // For hash join node, use vSrcToOutputSMap to describe the expression calculation, use // vIntermediateTupleDescList as input, and set vOutputTupleDesc as the final output. // TODO: HashJoinNode's be implementation is not support projection yet, remove this after when supported. if (inputPlanNode instanceof JoinNodeBase) { TupleDescriptor tupleDescriptor = generateTupleDesc(slots, null, context); JoinNodeBase joinNode = (JoinNodeBase) inputPlanNode; joinNode.setvOutputTupleDesc(tupleDescriptor); joinNode.setvSrcToOutputSMap(projectionExprs); // prune the hashOutputSlotIds if (joinNode instanceof HashJoinNode) { ((HashJoinNode) joinNode).getHashOutputSlotIds().clear(); Set<ExprId> requiredExprIds = Sets.newHashSet(); Set<SlotId> requiredOtherConjunctsSlotIdSet = Sets.newHashSet(); List<Expr> otherConjuncts = ((HashJoinNode) joinNode).getOtherJoinConjuncts(); for (Expr expr : otherConjuncts) { Expr.extractSlots(expr, requiredOtherConjunctsSlotIdSet); } requiredOtherConjunctsSlotIdSet.forEach(e -> requiredExprIds.add(context.findExprId(e))); requiredSlotIdSet.forEach(e -> requiredExprIds.add(context.findExprId(e))); for (ExprId exprId : requiredExprIds) { SlotId slotId = ((HashJoinNode) joinNode).getHashOutputExprSlotIdMap().get(exprId); Preconditions.checkState(slotId != null); ((HashJoinNode) joinNode).addSlotIdToHashOutputSlotIds(slotId); } } return inputFragment; } if (inputPlanNode instanceof TableFunctionNode) { TableFunctionNode tableFunctionNode = (TableFunctionNode) inputPlanNode; tableFunctionNode.setOutputSlotIds(Lists.newArrayList(requiredSlotIdSet)); } if (inputPlanNode instanceof ScanNode) { TupleDescriptor projectionTuple = null; // slotIdsByOrder is used to ensure the ScanNode's output order is same with current Project // if we change the output order in translate project, the upper node will receive wrong order // tuple, since they get the order from project.getOutput() not scan.getOutput()./ List<SlotId> slotIdsByOrder = Lists.newArrayList(); if (requiredByProjectSlotIdSet.size() != requiredSlotIdSet.size() || new HashSet<>(projectionExprs).size() != projectionExprs.size() || projectionExprs.stream().anyMatch(expr -> !(expr instanceof SlotRef))) { projectionTuple = generateTupleDesc(slots, null, context); inputPlanNode.setProjectList(projectionExprs); inputPlanNode.setOutputTupleDesc(projectionTuple); } else { for (int i = 0; i < slots.size(); ++i) { context.addExprIdSlotRefPair(slots.get(i).getExprId(), (SlotRef) projectionExprs.get(i)); slotIdsByOrder.add(((SlotRef) projectionExprs.get(i)).getSlotId()); } } // TODO: this is a temporary scheme to support two phase read when has project. // we need to refactor all topn opt into rbo stage. if (inputPlanNode instanceof OlapScanNode) { ArrayList<SlotDescriptor> olapScanSlots = context.getTupleDesc(inputPlanNode.getTupleIds().get(0)).getSlots(); SlotDescriptor lastSlot = olapScanSlots.get(olapScanSlots.size() - 1); if (lastSlot.getColumn() != null && lastSlot.getColumn().getName().equals(Column.ROWID_COL)) { if (projectionTuple != null) { injectRowIdColumnSlot(projectionTuple); SlotRef slotRef = new SlotRef(lastSlot); inputPlanNode.getProjectList().add(slotRef); requiredByProjectSlotIdSet.add(lastSlot.getId()); } else { slotIdsByOrder.add(lastSlot.getId()); } requiredSlotIdSet.add(lastSlot.getId()); } } updateScanSlotsMaterialization((ScanNode) inputPlanNode, requiredSlotIdSet, requiredByProjectSlotIdSet, slotIdsByOrder, context); } else { TupleDescriptor tupleDescriptor = generateTupleDesc(slots, null, context); inputPlanNode.setProjectList(projectionExprs); inputPlanNode.setOutputTupleDesc(tupleDescriptor); } return inputFragment; } /** * Returns a new fragment with a UnionNode as its root. The data partition of the * returned fragment and how the data of the child fragments is consumed depends on the * data partitions of the child fragments: * - All child fragments are unpartitioned or partitioned: The returned fragment has an * UNPARTITIONED or RANDOM data partition, respectively. The UnionNode absorbs the * plan trees of all child fragments. * - Mixed partitioned/unpartitioned child fragments: The returned fragment is * RANDOM partitioned. The plan trees of all partitioned child fragments are absorbed * into the UnionNode. All unpartitioned child fragments are connected to the * UnionNode via a RANDOM exchange, and remain unchanged otherwise. */ @Override public PlanFragment visitPhysicalSetOperation( PhysicalSetOperation setOperation, PlanTranslatorContext context) { List<PlanFragment> childrenFragments = new ArrayList<>(); for (Plan plan : setOperation.children()) { childrenFragments.add(plan.accept(this, context)); } TupleDescriptor setTuple = generateTupleDesc(setOperation.getOutput(), null, context); List<SlotDescriptor> outputSlotDescs = new ArrayList<>(setTuple.getSlots()); SetOperationNode setOperationNode; // create setOperationNode if (setOperation instanceof PhysicalUnion) { setOperationNode = new UnionNode(context.nextPlanNodeId(), setTuple.getId()); } else if (setOperation instanceof PhysicalExcept) { setOperationNode = new ExceptNode(context.nextPlanNodeId(), setTuple.getId()); } else if (setOperation instanceof PhysicalIntersect) { setOperationNode = new IntersectNode(context.nextPlanNodeId(), setTuple.getId()); } else { throw new RuntimeException("not support set operation type " + setOperation); } setOperation.children().stream() .map(Plan::getOutput) .map(l -> l.stream() .map(e -> ExpressionTranslator.translate(e, context)) .collect(ImmutableList.toImmutableList())) .forEach(setOperationNode::addResultExprLists); if (setOperation instanceof PhysicalUnion) { ((PhysicalUnion) setOperation).getConstantExprsList().stream() .map(l -> l.stream() .map(e -> ExpressionTranslator.translate(e, context)) .collect(ImmutableList.toImmutableList())) .forEach(setOperationNode::addConstExprList); } for (PlanFragment childFragment : childrenFragments) { setOperationNode.addChild(childFragment.getPlanRoot()); } setOperationNode.finalizeForNereids(outputSlotDescs, outputSlotDescs); PlanFragment setOperationFragment; if (childrenFragments.isEmpty()) { setOperationFragment = createPlanFragment(setOperationNode, DataPartition.UNPARTITIONED, setOperation); context.addPlanFragment(setOperationFragment); } else { int childrenSize = childrenFragments.size(); setOperationFragment = childrenFragments.get(childrenSize - 1); for (int i = childrenSize - 2; i >= 0; i--) { context.mergePlanFragment(childrenFragments.get(i), setOperationFragment); for (PlanFragment child : childrenFragments.get(i).getChildren()) { setOperationFragment.addChild(child); } } setPlanRoot(setOperationFragment, setOperationNode, setOperation); } return setOperationFragment; } /*- * Physical sort: * 1. Build sortInfo * There are two types of slotRef: * one is generated by the previous node, collectively called old. * the other is newly generated by the sort node, collectively called new. * Filling of sortInfo related data structures, * a. ordering use newSlotRef. * b. sortTupleSlotExprs use oldSlotRef. * 2. Create sortNode * 3. Create mergeFragment * TODO: When the slotRef of sort is currently generated, * it will be based on the expression in select and orderBy expression in to ensure the uniqueness of slotRef. * But eg: * select a+1 from table order by a+1; * the expressions of the two are inconsistent. * The former will perform an additional Alias. * Currently we cannot test whether this will have any effect. * After a+1 can be parsed , reprocessing. */ @Override public PlanFragment visitPhysicalQuickSort(PhysicalQuickSort<? extends Plan> sort, PlanTranslatorContext context) { PlanFragment inputFragment = sort.child(0).accept(this, context); // 2. According to the type of sort, generate physical plan if (!sort.getSortPhase().isMerge()) { // For localSort or Gather->Sort, we just need to add sortNode SortNode sortNode = translateSortNode(sort, inputFragment.getPlanRoot(), context); addPlanRoot(inputFragment, sortNode, sort); } else { // For mergeSort, we need to push sortInfo to exchangeNode if (!(inputFragment.getPlanRoot() instanceof ExchangeNode)) { // if there is no exchange node for mergeSort // e.g., localSort -> mergeSort // It means the local has satisfied the Gather property. We can just ignore mergeSort return inputFragment; } SortNode sortNode = (SortNode) inputFragment.getPlanRoot().getChild(0); ((ExchangeNode) inputFragment.getPlanRoot()).setMergeInfo(sortNode.getSortInfo()); } return inputFragment; } @Override public PlanFragment visitPhysicalTopN(PhysicalTopN<? extends Plan> topN, PlanTranslatorContext context) { PlanFragment inputFragment = topN.child(0).accept(this, context); // 2. According to the type of sort, generate physical plan if (!topN.getSortPhase().isMerge()) { // For localSort or Gather->Sort, we just need to add TopNNode SortNode sortNode = translateSortNode(topN, inputFragment.getPlanRoot(), context); sortNode.setOffset(topN.getOffset()); sortNode.setLimit(topN.getLimit()); if (topN.getMutableState(PhysicalTopN.TOPN_RUNTIME_FILTER).isPresent()) { sortNode.setUseTopnOpt(true); PlanNode child = sortNode.getChild(0); Preconditions.checkArgument(child instanceof OlapScanNode, "topN opt expect OlapScanNode, but we get " + child); OlapScanNode scanNode = ((OlapScanNode) child); scanNode.setUseTopnOpt(true); } // push sort to scan opt if (sortNode.getChild(0) instanceof OlapScanNode) { OlapScanNode scanNode = ((OlapScanNode) sortNode.getChild(0)); if (checkPushSort(sortNode, scanNode.getOlapTable())) { SortInfo sortInfo = sortNode.getSortInfo(); scanNode.setSortInfo(sortInfo); scanNode.getSortInfo().setSortTupleSlotExprs(sortNode.getResolvedTupleExprs()); for (Expr expr : sortInfo.getOrderingExprs()) { scanNode.getSortInfo().addMaterializedOrderingExpr(expr); } if (sortNode.getOffset() > 0) { scanNode.setSortLimit(sortNode.getLimit() + sortNode.getOffset()); } else { scanNode.setSortLimit(sortNode.getLimit()); } } } addPlanRoot(inputFragment, sortNode, topN); } else { // For mergeSort, we need to push sortInfo to exchangeNode if (!(inputFragment.getPlanRoot() instanceof ExchangeNode)) { // if there is no exchange node for mergeSort // e.g., mergeTopN -> localTopN // It means the local has satisfied the Gather property. We can just ignore mergeSort inputFragment.getPlanRoot().setOffset(topN.getOffset()); inputFragment.getPlanRoot().setLimit(topN.getLimit()); return inputFragment; } ExchangeNode exchangeNode = (ExchangeNode) inputFragment.getPlanRoot(); exchangeNode.setMergeInfo(((SortNode) exchangeNode.getChild(0)).getSortInfo()); exchangeNode.setLimit(topN.getLimit()); exchangeNode.setOffset(topN.getOffset()); } updateLegacyPlanIdToPhysicalPlan(inputFragment.getPlanRoot(), topN); return inputFragment; } @Override public PlanFragment visitPhysicalDeferMaterializeTopN(PhysicalDeferMaterializeTopN<? extends Plan> topN, PlanTranslatorContext context) { PlanFragment planFragment = visitPhysicalTopN(topN.getPhysicalTopN(), context); if (planFragment.getPlanRoot() instanceof SortNode) { SortNode sortNode = (SortNode) planFragment.getPlanRoot(); sortNode.setUseTwoPhaseReadOpt(true); sortNode.getSortInfo().setUseTwoPhaseRead(); TupleDescriptor tupleDescriptor = sortNode.getSortInfo().getSortTupleDescriptor(); for (SlotDescriptor slotDescriptor : tupleDescriptor.getSlots()) { if (topN.getDeferMaterializeSlotIds() .contains(context.findExprId(slotDescriptor.getId()))) { slotDescriptor.setNeedMaterialize(false); } } } return planFragment; } @Override public PlanFragment visitPhysicalRepeat(PhysicalRepeat<? extends Plan> repeat, PlanTranslatorContext context) { PlanFragment inputPlanFragment = repeat.child(0).accept(this, context); Set<VirtualSlotReference> sortedVirtualSlots = repeat.getSortedVirtualSlots(); TupleDescriptor virtualSlotsTuple = generateTupleDesc(ImmutableList.copyOf(sortedVirtualSlots), null, context); ImmutableSet<Expression> flattenGroupingSetExprs = ImmutableSet.copyOf( ExpressionUtils.flatExpressions(repeat.getGroupingSets())); List<Slot> aggregateFunctionUsedSlots = repeat.getOutputExpressions() .stream() .filter(output -> !(output instanceof VirtualSlotReference)) .filter(output -> !flattenGroupingSetExprs.contains(output)) .distinct() .map(NamedExpression::toSlot) .collect(ImmutableList.toImmutableList()); Set<Expression> usedSlotInRepeat = ImmutableSet.<Expression>builder() .addAll(flattenGroupingSetExprs) .addAll(aggregateFunctionUsedSlots) .build(); List<Expr> preRepeatExprs = usedSlotInRepeat.stream() .map(expr -> ExpressionTranslator.translate(expr, context)) .collect(ImmutableList.toImmutableList()); List<Slot> outputSlots = repeat.getOutputExpressions() .stream() .map(NamedExpression::toSlot) .collect(ImmutableList.toImmutableList()); // NOTE: we should first translate preRepeatExprs, then generate output tuple, // or else the preRepeatExprs can not find the bottom slotRef and throw // exception: invalid slot id TupleDescriptor outputTuple = generateTupleDesc(outputSlots, null, context); // cube and rollup already convert to grouping sets in LogicalPlanBuilder.withAggregate() GroupingInfo groupingInfo = new GroupingInfo( GroupingType.GROUPING_SETS, virtualSlotsTuple, outputTuple, preRepeatExprs); List<Set<Integer>> repeatSlotIdList = repeat.computeRepeatSlotIdList(getSlotIds(outputTuple)); Set<Integer> allSlotId = repeatSlotIdList.stream() .flatMap(Set::stream) .collect(ImmutableSet.toImmutableSet()); RepeatNode repeatNode = new RepeatNode(context.nextPlanNodeId(), inputPlanFragment.getPlanRoot(), groupingInfo, repeatSlotIdList, allSlotId, repeat.computeVirtualSlotValues(sortedVirtualSlots)); repeatNode.setNumInstances(inputPlanFragment.getPlanRoot().getNumInstances()); addPlanRoot(inputPlanFragment, repeatNode, repeat); updateLegacyPlanIdToPhysicalPlan(inputPlanFragment.getPlanRoot(), repeat); return inputPlanFragment; } @Override public PlanFragment visitPhysicalWindow(PhysicalWindow<? extends Plan> physicalWindow, PlanTranslatorContext context) { PlanFragment inputPlanFragment = physicalWindow.child(0).accept(this, context); // 1. translate to old optimizer variable // variable in Nereids WindowFrameGroup windowFrameGroup = physicalWindow.getWindowFrameGroup(); List<Expression> partitionKeyList = Lists.newArrayList(windowFrameGroup.getPartitionKeys()); List<OrderExpression> orderKeyList = windowFrameGroup.getOrderKeys(); List<NamedExpression> windowFunctionList = windowFrameGroup.getGroups(); WindowFrame windowFrame = windowFrameGroup.getWindowFrame(); // partition by clause List<Expr> partitionExprs = partitionKeyList.stream() .map(e -> ExpressionTranslator.translate(e, context)) .collect(Collectors.toList()); // order by clause List<OrderByElement> orderByElements = orderKeyList.stream() .map(orderKey -> new OrderByElement( ExpressionTranslator.translate(orderKey.child(), context), orderKey.isAsc(), orderKey.isNullFirst())) .collect(Collectors.toList()); // function calls List<Expr> analyticFnCalls = windowFunctionList.stream() .map(e -> { Expression function = e.child(0).child(0); if (function instanceof AggregateFunction) { AggregateParam param = AggregateParam.LOCAL_RESULT; function = new AggregateExpression((AggregateFunction) function, param); } return ExpressionTranslator.translate(function, context); }) .map(FunctionCallExpr.class::cast) .peek(fnCall -> { fnCall.setIsAnalyticFnCall(true); ((org.apache.doris.catalog.AggregateFunction) fnCall.getFn()).setIsAnalyticFn(true); }) .collect(Collectors.toList()); // analytic window AnalyticWindow analyticWindow = physicalWindow.translateWindowFrame(windowFrame, context); // 2. get bufferedTupleDesc from SortNode and compute isNullableMatched Map<ExprId, SlotRef> bufferedSlotRefForWindow = getBufferedSlotRefForWindow(windowFrameGroup, context); TupleDescriptor bufferedTupleDesc = context.getBufferedTupleForWindow(); // generate predicates to check if the exprs of partitionKeys and orderKeys have matched isNullable between // sortNode and analyticNode Expr partitionExprsIsNullableMatched = partitionExprs.isEmpty() ? null : windowExprsHaveMatchedNullable( partitionKeyList, partitionExprs, bufferedSlotRefForWindow); Expr orderElementsIsNullableMatched = orderByElements.isEmpty() ? null : windowExprsHaveMatchedNullable( orderKeyList.stream().map(UnaryNode::child).collect(Collectors.toList()), orderByElements.stream().map(OrderByElement::getExpr).collect(Collectors.toList()), bufferedSlotRefForWindow); // 3. generate tupleDesc List<Slot> windowSlotList = windowFunctionList.stream() .map(NamedExpression::toSlot) .collect(Collectors.toList()); TupleDescriptor outputTupleDesc = generateTupleDesc(windowSlotList, null, context); // 4. generate AnalyticEvalNode AnalyticEvalNode analyticEvalNode = new AnalyticEvalNode( context.nextPlanNodeId(), inputPlanFragment.getPlanRoot(), analyticFnCalls, partitionExprs, orderByElements, analyticWindow, outputTupleDesc, outputTupleDesc, partitionExprsIsNullableMatched, orderElementsIsNullableMatched, bufferedTupleDesc ); analyticEvalNode.setNumInstances(inputPlanFragment.getPlanRoot().getNumInstances()); inputPlanFragment.addPlanRoot(analyticEvalNode); return inputPlanFragment; } /* ******************************************************************************************** * private functions * ******************************************************************************************** */ private PartitionSortNode translatePartitionSortNode(PhysicalPartitionTopN<? extends Plan> partitionTopN, PlanNode childNode, PlanTranslatorContext context) { List<Expr> partitionExprs = partitionTopN.getPartitionKeys().stream() .map(e -> ExpressionTranslator.translate(e, context)) .collect(Collectors.toList()); // partition key should on child tuple, sort key should on partition top's tuple TupleDescriptor sortTuple = generateTupleDesc(partitionTopN.child().getOutput(), null, context); List<Expr> orderingExprs = Lists.newArrayList(); List<Boolean> ascOrders = Lists.newArrayList(); List<Boolean> nullsFirstParams = Lists.newArrayList(); List<OrderKey> orderKeys = partitionTopN.getOrderKeys(); orderKeys.forEach(k -> { orderingExprs.add(ExpressionTranslator.translate(k.getExpr(), context)); ascOrders.add(k.isAsc()); nullsFirstParams.add(k.isNullFirst()); }); SortInfo sortInfo = new SortInfo(orderingExprs, ascOrders, nullsFirstParams, sortTuple); PartitionSortNode partitionSortNode = new PartitionSortNode(context.nextPlanNodeId(), childNode, partitionTopN.getFunction(), partitionExprs, sortInfo, partitionTopN.hasGlobalLimit(), partitionTopN.getPartitionLimit()); if (partitionTopN.getStats() != null) { partitionSortNode.setCardinality((long) partitionTopN.getStats().getRowCount()); } updateLegacyPlanIdToPhysicalPlan(partitionSortNode, partitionTopN); return partitionSortNode; } private SortNode translateSortNode(AbstractPhysicalSort<? extends Plan> sort, PlanNode childNode, PlanTranslatorContext context) { TupleDescriptor sortTuple = generateTupleDesc(sort.child().getOutput(), null, context); List<Expr> orderingExprs = Lists.newArrayList(); List<Boolean> ascOrders = Lists.newArrayList(); List<Boolean> nullsFirstParams = Lists.newArrayList(); List<OrderKey> orderKeys = sort.getOrderKeys(); orderKeys.forEach(k -> { orderingExprs.add(ExpressionTranslator.translate(k.getExpr(), context)); ascOrders.add(k.isAsc()); nullsFirstParams.add(k.isNullFirst()); }); SortInfo sortInfo = new SortInfo(orderingExprs, ascOrders, nullsFirstParams, sortTuple); SortNode sortNode = new SortNode(context.nextPlanNodeId(), childNode, sortInfo, sort instanceof PhysicalTopN); if (sort.getStats() != null) { sortNode.setCardinality((long) sort.getStats().getRowCount()); } updateLegacyPlanIdToPhysicalPlan(sortNode, sort); return sortNode; } private void updateScanSlotsMaterialization(ScanNode scanNode, Set<SlotId> requiredSlotIdSet, Set<SlotId> requiredByProjectSlotIdSet, List<SlotId> slotIdsByOrder, PlanTranslatorContext context) { // TODO: use smallest slot if do not need any slot in upper node SlotDescriptor smallest = scanNode.getTupleDesc().getSlots().get(0); if (CollectionUtils.isNotEmpty(slotIdsByOrder)) { // if we eliminate project above scan, we should ensure the slot order of scan's output is same with // the projection's output. So, we need to reorder the output slot in scan's tuple. Map<SlotId, SlotDescriptor> idToSlotDescMap = scanNode.getTupleDesc().getSlots().stream() .filter(s -> requiredSlotIdSet.contains(s.getId())) .collect(Collectors.toMap(SlotDescriptor::getId, s -> s)); scanNode.getTupleDesc().getSlots().clear(); for (SlotId slotId : slotIdsByOrder) { scanNode.getTupleDesc().getSlots().add(idToSlotDescMap.get(slotId)); } } else { scanNode.getTupleDesc().getSlots().removeIf(s -> !requiredSlotIdSet.contains(s.getId())); } if (scanNode.getTupleDesc().getSlots().isEmpty()) { scanNode.getTupleDesc().getSlots().add(smallest); } try { scanNode.updateRequiredSlots(context, requiredByProjectSlotIdSet); } catch (UserException e) { Util.logAndThrowRuntimeException(LOG, "User Exception while reset external file scan node contexts.", e); } } private void addConjunctsToPlanNode(PhysicalFilter<? extends Plan> filter, PlanNode planNode, PlanTranslatorContext context) { filter.getConjuncts().stream() .map(e -> ExpressionTranslator.translate(e, context)) .forEach(planNode::addConjunct); updateLegacyPlanIdToPhysicalPlan(planNode, filter); } private TupleDescriptor generateTupleDesc(List<Slot> slotList, TableIf table, PlanTranslatorContext context) { TupleDescriptor tupleDescriptor = context.generateTupleDesc(); tupleDescriptor.setTable(table); for (Slot slot : slotList) { context.createSlotDesc(tupleDescriptor, (SlotReference) slot, table); } return tupleDescriptor; } private PlanFragment connectJoinNode(HashJoinNode hashJoinNode, PlanFragment leftFragment, PlanFragment rightFragment, PlanTranslatorContext context, AbstractPlan join) { hashJoinNode.setChild(0, leftFragment.getPlanRoot()); hashJoinNode.setChild(1, rightFragment.getPlanRoot()); setPlanRoot(leftFragment, hashJoinNode, join); context.mergePlanFragment(rightFragment, leftFragment); for (PlanFragment rightChild : rightFragment.getChildren()) { leftFragment.addChild(rightChild); } return leftFragment; } private List<SlotReference> collectGroupBySlots(List<Expression> groupByExpressions, List<NamedExpression> outputExpressions) { List<SlotReference> groupSlots = Lists.newArrayList(); Set<VirtualSlotReference> virtualSlotReferences = groupByExpressions.stream() .filter(VirtualSlotReference.class::isInstance) .map(VirtualSlotReference.class::cast) .collect(Collectors.toSet()); for (Expression e : groupByExpressions) { if (e instanceof SlotReference && outputExpressions.stream().anyMatch(o -> o.anyMatch(e::equals))) { groupSlots.add((SlotReference) e); } else if (e instanceof SlotReference && !virtualSlotReferences.isEmpty()) { // When there is a virtualSlot, it is a groupingSets scenario, // and the original exprId should be retained at this time. groupSlots.add((SlotReference) e); } else { groupSlots.add(new SlotReference(e.toSql(), e.getDataType(), e.nullable(), ImmutableList.of())); } } return groupSlots; } private List<Integer> getSlotIds(TupleDescriptor tupleDescriptor) { return tupleDescriptor.getSlots() .stream() .map(slot -> slot.getId().asInt()) .collect(ImmutableList.toImmutableList()); } private Map<ExprId, SlotRef> getBufferedSlotRefForWindow(WindowFrameGroup windowFrameGroup, PlanTranslatorContext context) { Map<ExprId, SlotRef> bufferedSlotRefForWindow = context.getBufferedSlotRefForWindow(); // set if absent windowFrameGroup.getPartitionKeys().stream() .map(NamedExpression.class::cast) .forEach(expression -> { ExprId exprId = expression.getExprId(); bufferedSlotRefForWindow.putIfAbsent(exprId, context.findSlotRef(exprId)); }); windowFrameGroup.getOrderKeys().stream() .map(UnaryNode::child) .map(NamedExpression.class::cast) .forEach(expression -> { ExprId exprId = expression.getExprId(); bufferedSlotRefForWindow.putIfAbsent(exprId, context.findSlotRef(exprId)); }); return bufferedSlotRefForWindow; } private Expr windowExprsHaveMatchedNullable(List<Expression> expressions, List<Expr> exprs, Map<ExprId, SlotRef> bufferedSlotRef) { Map<ExprId, Expr> exprIdToExpr = Maps.newHashMap(); for (int i = 0; i < expressions.size(); i++) { NamedExpression expression = (NamedExpression) expressions.get(i); exprIdToExpr.put(expression.getExprId(), exprs.get(i)); } return windowExprsHaveMatchedNullable(exprIdToExpr, bufferedSlotRef, expressions, 0, expressions.size()); } private Expr windowExprsHaveMatchedNullable(Map<ExprId, Expr> exprIdToExpr, Map<ExprId, SlotRef> exprIdToSlotRef, List<Expression> expressions, int i, int size) { if (i > size - 1) { return new BoolLiteral(true); } ExprId exprId = ((NamedExpression) expressions.get(i)).getExprId(); Expr lhs = exprIdToExpr.get(exprId); Expr rhs = exprIdToSlotRef.get(exprId); Expr bothNull = new CompoundPredicate(CompoundPredicate.Operator.AND, new IsNullPredicate(lhs, false, true), new IsNullPredicate(rhs, false, true)); Expr lhsEqRhsNotNull = new CompoundPredicate(CompoundPredicate.Operator.AND, new CompoundPredicate(CompoundPredicate.Operator.AND, new IsNullPredicate(lhs, true, true), new IsNullPredicate(rhs, true, true)), new BinaryPredicate(BinaryPredicate.Operator.EQ, lhs, rhs, Type.BOOLEAN, NullableMode.DEPEND_ON_ARGUMENT)); Expr remainder = windowExprsHaveMatchedNullable(exprIdToExpr, exprIdToSlotRef, expressions, i + 1, size); return new CompoundPredicate(CompoundPredicate.Operator.AND, new CompoundPredicate(CompoundPredicate.Operator.OR, bothNull, lhsEqRhsNotNull), remainder); } private PlanFragment createPlanFragment(PlanNode planNode, DataPartition dataPartition, AbstractPlan physicalPlan) { PlanFragment planFragment = new PlanFragment(context.nextFragmentId(), planNode, dataPartition); updateLegacyPlanIdToPhysicalPlan(planNode, physicalPlan); return planFragment; } // TODO: refactor this, call it every where is not a good way private void setPlanRoot(PlanFragment fragment, PlanNode planNode, AbstractPlan physicalPlan) { fragment.setPlanRoot(planNode); updateLegacyPlanIdToPhysicalPlan(planNode, physicalPlan); } // TODO: refactor this, call it every where is not a good way private void addPlanRoot(PlanFragment fragment, PlanNode planNode, AbstractPlan physicalPlan) { fragment.addPlanRoot(planNode); updateLegacyPlanIdToPhysicalPlan(planNode, physicalPlan); } private DataPartition toDataPartition(DistributionSpec distributionSpec, List<ExprId> childOutputIds, PlanTranslatorContext context) { if (distributionSpec instanceof DistributionSpecAny || distributionSpec instanceof DistributionSpecStorageAny || distributionSpec instanceof DistributionSpecExecutionAny) { return DataPartition.RANDOM; } else if (distributionSpec instanceof DistributionSpecGather || distributionSpec instanceof DistributionSpecStorageGather || distributionSpec instanceof DistributionSpecReplicated) { return DataPartition.UNPARTITIONED; } else if (distributionSpec instanceof DistributionSpecHash) { DistributionSpecHash distributionSpecHash = (DistributionSpecHash) distributionSpec; List<Expr> partitionExprs = Lists.newArrayList(); for (int i = 0; i < distributionSpecHash.getEquivalenceExprIds().size(); i++) { Set<ExprId> equivalenceExprId = distributionSpecHash.getEquivalenceExprIds().get(i); for (ExprId exprId : equivalenceExprId) { if (childOutputIds.contains(exprId)) { partitionExprs.add(context.findSlotRef(exprId)); break; } } if (partitionExprs.size() != i + 1) { throw new RuntimeException("Cannot translate DistributionSpec to DataPartition," + " DistributionSpec: " + distributionSpec + ", child output: " + childOutputIds); } } TPartitionType partitionType; switch (distributionSpecHash.getShuffleType()) { case STORAGE_BUCKETED: partitionType = TPartitionType.BUCKET_SHFFULE_HASH_PARTITIONED; break; case EXECUTION_BUCKETED: partitionType = TPartitionType.HASH_PARTITIONED; break; case NATURAL: default: throw new RuntimeException("Do not support shuffle type: " + distributionSpecHash.getShuffleType()); } return new DataPartition(partitionType, partitionExprs); } else { throw new RuntimeException("Unknown DistributionSpec: " + distributionSpec); } } // TODO: refactor this, call it every where is not a good way private void updateLegacyPlanIdToPhysicalPlan(PlanNode planNode, AbstractPlan physicalPlan) { if (statsErrorEstimator != null) { statsErrorEstimator.updateLegacyPlanIdToPhysicalPlan(planNode, physicalPlan); } } private void injectRowIdColumnSlot(TupleDescriptor tupleDesc) { SlotDescriptor slotDesc = context.addSlotDesc(tupleDesc); LOG.debug("inject slot {}", slotDesc); String name = Column.ROWID_COL; Column col = new Column(name, Type.STRING, false, null, false, "", "rowid column"); slotDesc.setType(Type.STRING); slotDesc.setColumn(col); slotDesc.setIsNullable(false); slotDesc.setIsMaterialized(true); } /** * topN opt: using storage data ordering to accelerate topn operation. * refer pr: optimize topn query if order by columns is prefix of sort keys of table (#10694) */ private boolean checkPushSort(SortNode sortNode, OlapTable olapTable) { // Ensure limit is less than threshold if (sortNode.getLimit() <= 0 || sortNode.getLimit() > ConnectContext.get().getSessionVariable().topnOptLimitThreshold) { return false; } // Ensure all isAscOrder is same, ande length != 0. Can't be z-order. if (sortNode.getSortInfo().getIsAscOrder().stream().distinct().count() != 1 || olapTable.isZOrderSort()) { return false; } // Tablet's order by key only can be the front part of schema. // Like: schema: a.b.c.d.e.f.g order by key: a.b.c (no a,b,d) // Do **prefix match** to check if order by key can be pushed down. // olap order by key: a.b.c.d // sort key: (a) (a,b) (a,b,c) (a,b,c,d) is ok // (a,c) (a,c,d), (a,c,b) (a,c,f) (a,b,c,d,e)is NOT ok List<Expr> sortExprs = sortNode.getSortInfo().getOrderingExprs(); List<Boolean> nullsFirsts = sortNode.getSortInfo().getNullsFirst(); List<Boolean> isAscOrders = sortNode.getSortInfo().getIsAscOrder(); if (sortExprs.size() > olapTable.getDataSortInfo().getColNum()) { return false; } for (int i = 0; i < sortExprs.size(); i++) { // table key. Column tableKey = olapTable.getFullSchema().get(i); // sort slot. Expr sortExpr = sortExprs.get(i); if (sortExpr instanceof SlotRef) { SlotRef slotRef = (SlotRef) sortExpr; if (tableKey.equals(slotRef.getColumn())) { // ORDER BY DESC NULLS FIRST can not be optimized to only read file tail, // since NULLS is at file head but data is at tail if (tableKey.isAllowNull() && nullsFirsts.get(i) && !isAscOrders.get(i)) { return false; } } else { return false; } } else { return false; } } return true; } private List<Expr> translateToLegacyConjuncts(Set<Expression> conjuncts) { List<Expr> outputExprs = Lists.newArrayList(); if (conjuncts != null) { conjuncts.stream() .map(e -> ExpressionTranslator.translate(e, context)) .forEach(outputExprs::add); } return outputExprs; } }
141aaf4bcc3abc3077b71f58dd6220e9810605db
a5dfb6f0a0152d6142e6ddd0bc7c842fdea3daf9
/second_semester/second_semester_sdj/ClientServer/src/chat/domain/view/ClientView.java
a0f679e64c269e9001cb5fd2948e9b0cf82af6fe
[]
no_license
jimmi280586/Java_school_projects
e7c97dfe380cd3f872487232f1cc060e1fabdc1c
86b0cb5d38c65e4f7696bc841e3c5eed74e4d552
refs/heads/master
2021-01-11T11:58:06.578737
2016-12-16T20:55:48
2016-12-16T20:55:48
76,685,030
2
0
null
null
null
null
UTF-8
Java
false
false
3,593
java
package chat.domain.view; import java.awt.BorderLayout; import java.awt.Color; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.Observable; import java.util.Observer; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTextArea; import javax.swing.JTextField; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.TransformerException; import chat.domain.mediator.ClientController; import chat.domain.model.AbstractMessage; public class ClientView extends JFrame implements ActionListener, Observer { private JTextField textFieldInput; private JTextArea textAreaOutput; private JButton buttonSend; private JButton buttonQuit; private ClientController controller; public ClientView() { super("Client View"); initialize(); addComponentsToFrame(); } public void start(ClientController controller) { this.controller = controller; buttonSend.addActionListener(this); buttonQuit.addActionListener(this); textFieldInput.addActionListener(this); setVisible(true); } public String getAndRemoveInput() { String txt = textFieldInput.getText(); textFieldInput.setText(""); return txt; } public String getNickName() { return JOptionPane.showInputDialog("Nickname?"); } private void initialize() { textFieldInput = new JTextField(); textAreaOutput = new JTextArea(); textAreaOutput.setEditable(false); textAreaOutput.setBackground(Color.LIGHT_GRAY); buttonSend = new JButton("Send"); buttonQuit = new JButton("Quit"); setSize(400, 500); // set frame size setLocationRelativeTo(null); // center of the screen setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } private void addComponentsToFrame() { JPanel panelButtons = new JPanel(); panelButtons.add(buttonSend); panelButtons.add(buttonQuit); JPanel panel1 = new JPanel(new BorderLayout()); panel1.add(textFieldInput, BorderLayout.CENTER); panel1.add(panelButtons, BorderLayout.EAST); JScrollPane scrollPane = new JScrollPane(textAreaOutput); JPanel contentPane = new JPanel(new BorderLayout()); contentPane.add(panel1, BorderLayout.NORTH); contentPane.add(scrollPane, BorderLayout.CENTER); setContentPane(contentPane); } @Override public void actionPerformed(ActionEvent e) { if ((e.getSource() instanceof JTextField)) { try { controller.execute("Send"); } catch (TransformerException | ParserConfigurationException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } else { try { controller.execute(((JButton) (e.getSource())).getText()); } catch (TransformerException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } catch (ParserConfigurationException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } } @Override public void update(Observable o, Object arg) { String old = textAreaOutput.getText(); if (old.length() > 1) old = "\n" + old; AbstractMessage msg = (AbstractMessage) arg; textAreaOutput.setText(msg.getFrom() + " >" + msg.getBody() + old); textAreaOutput.setCaretPosition(0); } }
f19cb50ee3fcebb4fa0ca5f64273575e205f7186
cb23f67ab2a8b659e095e6b34e49c3e091cfb449
/src/test/java/com/keeggo/clientsjavaapi/test/controller/client/ClientControllerTest.java
58763aa405a746aea22123047cbe7b962a870a3e
[ "MIT" ]
permissive
kecolima/client-java-api
eacfe1e8ceb3c8a85866215374a7fcc854f56a83
1f21693a1d1b14e114bd3e063d03e08ecfd3b3a1
refs/heads/master
2023-03-24T15:28:15.664822
2021-03-25T03:20:45
2021-03-25T03:20:45
350,197,250
0
0
null
null
null
null
UTF-8
Java
false
false
5,060
java
package com.keeggo.clientsjavaapi.test.controller.client; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import java.text.ParseException; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.MethodOrderer.OrderAnnotation; import org.junit.jupiter.api.Order; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.TestInstance; import org.junit.jupiter.api.TestInstance.Lifecycle; import org.junit.jupiter.api.TestMethodOrder; import org.mockito.BDDMockito; import org.mockito.Mockito; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.boot.test.mock.mockito.MockitoTestExecutionListener; import org.springframework.http.HttpHeaders; import org.springframework.http.MediaType; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.TestExecutionListeners; import org.springframework.test.context.support.DependencyInjectionTestExecutionListener; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import org.springframework.test.web.servlet.result.MockMvcResultHandlers; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.keeggo.clientsjavaapi.dto.model.client.ClientDTO; import com.keeggo.clientsjavaapi.model.client.Client; import com.keeggo.clientsjavaapi.service.client.ClientService; /** * Class that implements tests of the TransactionController features * * @author Mariana Azevedo * @since 05/04/2020 */ @SpringBootTest @AutoConfigureMockMvc @ActiveProfiles("test") @TestInstance(Lifecycle.PER_CLASS) @TestMethodOrder(OrderAnnotation.class) @TestExecutionListeners({ DependencyInjectionTestExecutionListener.class, MockitoTestExecutionListener.class }) public class ClientControllerTest { static final Long ID = 1L; static final String NAME = "Client"; static final String CPF = "123456789"; static final String ADDRESS = "Rua"; static final String NUMBER = "34"; static final String ZIP_CODE = "19901230"; static final String DISTRICT = "Jardim"; static final String STATE = "São Paulo"; static final String CITY = "Ourinhos"; static final String URL = "/api-clients/v1/clients"; HttpHeaders headers; @Autowired MockMvc mockMvc; @MockBean ClientService clientService; @BeforeAll private void setUp() { headers = new HttpHeaders(); headers.set("X-api-key", "FX001-ZBSY6YSLP"); } /** * Method that tests to save an object Client in the API * * @author Mariana Azevedo * @since 05/04/2020 * * @throws Exception */ @Test @Order(1) public void testSave() throws Exception { BDDMockito.given(clientService.save(Mockito.any(Client.class))).willReturn(getMockClient()); mockMvc.perform(MockMvcRequestBuilders .post(URL) .content(getJsonPayload(ID, NAME, CPF, ADDRESS, NUMBER, ZIP_CODE, DISTRICT, STATE, CITY)) .contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON) .headers(headers)) .andDo(MockMvcResultHandlers.print()) .andExpect(status().isCreated()) .andExpect(jsonPath("$.data.id").value(ID)) .andExpect(jsonPath("$.data.name").value(NAME)) .andExpect(jsonPath("$.data.cpf").value(CPF)) .andExpect(jsonPath("$.data.address").value(ADDRESS)) .andExpect(jsonPath("$.data.numberHouse").value(NUMBER)) .andExpect(jsonPath("$.data.zipCode").value(ZIP_CODE)) .andExpect(jsonPath("$.data.district").value(DISTRICT)) .andExpect(jsonPath("$.data.state").value(STATE)) .andExpect(jsonPath("$.data.city").value(CITY)); } /** * Method that fill a mock User object to use as return in the tests. * * @author Mariana Azevedo * @since 13/12/2020 * * @return <code>User</code> object * @throws ParseException */ private Client getMockClient() throws ParseException { return new Client(1L, "Client", "123456789", "Rua", "34", "19901230", "Jardim", "São Paulo", "Ourinhos"); } /** * Method that fill a mock UserDTO object to use as return in the tests. * * @author Mariana Azevedo * @since 13/12/2020 * * @param id * @param accountNumber * @param accountType * @return <code>String</code> with the UserDTO payload * * @throws JsonProcessingException */ private String getJsonPayload(Long id, String name, String cpf, String address, String number, String zipCode, String district, String state, String city) throws JsonProcessingException { ClientDTO dto = new ClientDTO(id, name, cpf, address, number, zipCode, district, state, city); return new ObjectMapper().writeValueAsString(dto); } /* @AfterAll private void tearDown() { clientService.deleteById(1L); } */ }
75a705a7c83037762fce5041e5a93ec850c27e04
8148514af5e5584a93d9bbfda23d894bf15bd910
/app/src/main/java/com/fabloplatforms/business/onboard/model/KycResponse.java
3999073226675c24738c9ddb08e9a33bc629c18b
[]
no_license
Shakti1410/Fablo
4d729d3752f39ca1a19ad67507f3b8dc7324523a
bf6232555c26edc796d5283bc560c48ef05783a5
refs/heads/master
2023-08-22T09:54:24.015584
2021-10-01T05:29:58
2021-10-01T05:29:58
412,336,945
0
0
null
null
null
null
UTF-8
Java
false
false
14,106
java
package com.fabloplatforms.business.onboard.model; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; public class KycResponse { @SerializedName("status") @Expose private Boolean status; @SerializedName("message") @Expose private String message; @SerializedName("error") @Expose private String error; @SerializedName("items") @Expose private Items items; public Boolean getStatus() { return status; } public void setStatus(Boolean status) { this.status = status; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } public String getError() { return error; } public void setError(String error) { this.error = error; } public Items getItems() { return items; } public void setItems(Items items) { this.items = items; } public class Items { @SerializedName("business_name") @Expose private String businessName; @SerializedName("business_logo") @Expose private String businessLogo; @SerializedName("country_id") @Expose private String countryId; @SerializedName("country_name") @Expose private String countryName; @SerializedName("state_id") @Expose private String stateId; @SerializedName("state_name") @Expose private String stateName; @SerializedName("city_id") @Expose private String cityId; @SerializedName("city_name") @Expose private String cityName; @SerializedName("area_id") @Expose private String areaId; @SerializedName("area_name") @Expose private String areaName; @SerializedName("pincode") @Expose private String pincode; @SerializedName("address") @Expose private Address address; @SerializedName("phone") @Expose private String phone; @SerializedName("token") @Expose private String token; @SerializedName("business_type") @Expose private Integer businessType; @SerializedName("business_type_name") @Expose private String businessTypeName; @SerializedName("category_id") @Expose private String categoryId; @SerializedName("category_english") @Expose private String categoryEnglish; @SerializedName("category_hindi") @Expose private String categoryHindi; @SerializedName("settlement_rate") @Expose private Integer settlementRate; @SerializedName("settlement_type") @Expose private Integer settlementType; @SerializedName("wallet") @Expose private Integer wallet; @SerializedName("credit") @Expose private Integer credit; @SerializedName("paylater_payment_limit") @Expose private Integer paylaterPaymentLimit; @SerializedName("other_payment_limit") @Expose private Integer otherPaymentLimit; @SerializedName("qr") @Expose private String qr; @SerializedName("listed") @Expose private Boolean listed; @SerializedName("agent_code") @Expose private String agentCode; @SerializedName("blocked") @Expose private Boolean blocked; @SerializedName("overall_verified") @Expose private Boolean overallVerified; @SerializedName("verification") @Expose private Integer verification; @SerializedName("stages_verification") @Expose private StagesVerification stagesVerification; @SerializedName("app_version") @Expose private String appVersion; @SerializedName("schema_version") @Expose private String schemaVersion; @SerializedName("_id") @Expose private String id; @SerializedName("createdAt") @Expose private String createdAt; @SerializedName("updatedAt") @Expose private String updatedAt; @SerializedName("__v") @Expose private Integer v; public String getBusinessName() { return businessName; } public void setBusinessName(String businessName) { this.businessName = businessName; } public String getBusinessLogo() { return businessLogo; } public void setBusinessLogo(String businessLogo) { this.businessLogo = businessLogo; } public String getCountryId() { return countryId; } public void setCountryId(String countryId) { this.countryId = countryId; } public String getCountryName() { return countryName; } public void setCountryName(String countryName) { this.countryName = countryName; } public String getStateId() { return stateId; } public void setStateId(String stateId) { this.stateId = stateId; } public String getStateName() { return stateName; } public void setStateName(String stateName) { this.stateName = stateName; } public String getCityId() { return cityId; } public void setCityId(String cityId) { this.cityId = cityId; } public String getCityName() { return cityName; } public void setCityName(String cityName) { this.cityName = cityName; } public String getAreaId() { return areaId; } public void setAreaId(String areaId) { this.areaId = areaId; } public String getAreaName() { return areaName; } public void setAreaName(String areaName) { this.areaName = areaName; } public String getPincode() { return pincode; } public void setPincode(String pincode) { this.pincode = pincode; } public Address getAddress() { return address; } public void setAddress(Address address) { this.address = address; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } public String getToken() { return token; } public void setToken(String token) { this.token = token; } public Integer getBusinessType() { return businessType; } public void setBusinessType(Integer businessType) { this.businessType = businessType; } public String getBusinessTypeName() { return businessTypeName; } public void setBusinessTypeName(String businessTypeName) { this.businessTypeName = businessTypeName; } public String getCategoryId() { return categoryId; } public void setCategoryId(String categoryId) { this.categoryId = categoryId; } public String getCategoryEnglish() { return categoryEnglish; } public void setCategoryEnglish(String categoryEnglish) { this.categoryEnglish = categoryEnglish; } public String getCategoryHindi() { return categoryHindi; } public void setCategoryHindi(String categoryHindi) { this.categoryHindi = categoryHindi; } public Integer getSettlementRate() { return settlementRate; } public void setSettlementRate(Integer settlementRate) { this.settlementRate = settlementRate; } public Integer getSettlementType() { return settlementType; } public void setSettlementType(Integer settlementType) { this.settlementType = settlementType; } public Integer getWallet() { return wallet; } public void setWallet(Integer wallet) { this.wallet = wallet; } public Integer getCredit() { return credit; } public void setCredit(Integer credit) { this.credit = credit; } public Integer getPaylaterPaymentLimit() { return paylaterPaymentLimit; } public void setPaylaterPaymentLimit(Integer paylaterPaymentLimit) { this.paylaterPaymentLimit = paylaterPaymentLimit; } public Integer getOtherPaymentLimit() { return otherPaymentLimit; } public void setOtherPaymentLimit(Integer otherPaymentLimit) { this.otherPaymentLimit = otherPaymentLimit; } public String getQr() { return qr; } public void setQr(String qr) { this.qr = qr; } public Boolean getListed() { return listed; } public void setListed(Boolean listed) { this.listed = listed; } public String getAgentCode() { return agentCode; } public void setAgentCode(String agentCode) { this.agentCode = agentCode; } public Boolean getBlocked() { return blocked; } public void setBlocked(Boolean blocked) { this.blocked = blocked; } public Boolean getOverallVerified() { return overallVerified; } public void setOverallVerified(Boolean overallVerified) { this.overallVerified = overallVerified; } public Integer getVerification() { return verification; } public void setVerification(Integer verification) { this.verification = verification; } public StagesVerification getStagesVerification() { return stagesVerification; } public void setStagesVerification(StagesVerification stagesVerification) { this.stagesVerification = stagesVerification; } public String getAppVersion() { return appVersion; } public void setAppVersion(String appVersion) { this.appVersion = appVersion; } public String getSchemaVersion() { return schemaVersion; } public void setSchemaVersion(String schemaVersion) { this.schemaVersion = schemaVersion; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getCreatedAt() { return createdAt; } public void setCreatedAt(String createdAt) { this.createdAt = createdAt; } public String getUpdatedAt() { return updatedAt; } public void setUpdatedAt(String updatedAt) { this.updatedAt = updatedAt; } public Integer getV() { return v; } public void setV(Integer v) { this.v = v; } public class StagesVerification { @SerializedName("contactDetails") @Expose private Integer contactDetails; @SerializedName("bankDetails") @Expose private Integer bankDetails; @SerializedName("taxDetails") @Expose private Integer taxDetails; @SerializedName("fssaiDetails") @Expose private Integer fssaiDetails; @SerializedName("kycDetails") @Expose private Integer kycDetails; @SerializedName("commissionDetails") @Expose private Integer commissionDetails; @SerializedName("eSignatureDetails") @Expose private Integer eSignatureDetails; public Integer getContactDetails() { return contactDetails; } public void setContactDetails(Integer contactDetails) { this.contactDetails = contactDetails; } public Integer getBankDetails() { return bankDetails; } public void setBankDetails(Integer bankDetails) { this.bankDetails = bankDetails; } public Integer getTaxDetails() { return taxDetails; } public void setTaxDetails(Integer taxDetails) { this.taxDetails = taxDetails; } public Integer getFssaiDetails() { return fssaiDetails; } public void setFssaiDetails(Integer fssaiDetails) { this.fssaiDetails = fssaiDetails; } public Integer getKycDetails() { return kycDetails; } public void setKycDetails(Integer kycDetails) { this.kycDetails = kycDetails; } public Integer getCommissionDetails() { return commissionDetails; } public void setCommissionDetails(Integer commissionDetails) { this.commissionDetails = commissionDetails; } public Integer geteSignatureDetails() { return eSignatureDetails; } public void seteSignatureDetails(Integer eSignatureDetails) { this.eSignatureDetails = eSignatureDetails; } } } }
709d71e4cb00149570dc6a6de86c3b2f4a6ce124
74f8a323550628ac25966043c4c3c7d5598e38f3
/src/test/java/org/online/editor/JavaRunnerMainTest.java
1961242e0b358156c82e6c028df028d8c1a4559c
[]
no_license
iordancatalin/run-java-dynamic
63cf6381ce3e8714d6633d030d592a04f65952b0
29eddb339dfb179a3d888af6a0ef3f83b55bff83
refs/heads/master
2022-12-04T07:54:09.029406
2020-08-11T14:55:03
2020-08-11T14:55:03
285,619,946
0
0
null
null
null
null
UTF-8
Java
false
false
65
java
package org.online.editor; public class JavaRunnerMainTest { }
2eeb662090d94edf54846dd9e85fe1c84c757711
02ca8c10ae97d6e1cf3046408a288de125b89186
/SampleEnterpriseAppEJB/src/main/java/com/ibm/jp/blmx/sample/ejb/bean/ObjectStrageCredentials.java
31b1ec2fb55128a5b05ef296da4081b0b7bec76f
[]
no_license
prismboy/SampleEnterpriseApp
5f49ba09f7115f85f02675d9a4f34f46122e14e6
6dbe3194cf220452d10e5cef65f2c5f2baed424b
refs/heads/master
2020-01-23T22:00:10.077594
2017-01-27T04:39:45
2017-01-27T04:39:45
74,716,954
0
0
null
null
null
null
UTF-8
Java
false
false
3,024
java
package com.ibm.jp.blmx.sample.ejb.bean; import java.io.Serializable; import java.io.StringReader; import javax.json.Json; import javax.json.JsonObject; import javax.json.JsonReader; import org.openstack4j.model.common.Identifier; public class ObjectStrageCredentials implements Serializable { /** * */ private static final long serialVersionUID = 2404373647731748591L; private static final String _VCAP_SERVICES = "VCAP_SERVICES"; private static final String _OBJECT_STRAGE = "Object-Storage"; private static final String _CREDENTIALS = "credentials"; private static final String _USER_NAME = "username"; private static final String _PASSWORD = "password"; private static final String _AUTH_URL = "auth_url"; private static final String _DOMAIN_ID = "domainId"; private static final String _PROJECT_ID = "projectId"; private static final String _REGION = "region"; private String userName; private String password; private String auth_url; private String domainId; private String projectId; private Identifier domainIdent; private Identifier projectIdent; private String region; public ObjectStrageCredentials() { StringReader sr = new StringReader(System.getenv(_VCAP_SERVICES)); JsonReader reader = Json.createReader(sr); JsonObject vcapServices = reader.readObject(); JsonObject vcap = vcapServices.getJsonArray(_OBJECT_STRAGE).getJsonObject(0); JsonObject credentials = vcap.getJsonObject(_CREDENTIALS); setUserName(credentials.getString(_USER_NAME)); setPassword(credentials.getString(_PASSWORD)); setAuth_url(credentials.getString(_AUTH_URL)+"/v3"); setDomainId(credentials.getString(_DOMAIN_ID)); setProjectId(credentials.getString(_PROJECT_ID)); setDomainIdent(Identifier.byId(getDomainId())); setProjectIdent(Identifier.byId(getProjectId())); setRegion(credentials.getString(_REGION)); } public final String getPassword() { return password; } public final void setPassword(String password) { this.password = password; } public final String getAuth_url() { return auth_url; } public final void setAuth_url(String auth_url) { this.auth_url = auth_url; } public final Identifier getDomainIdent() { return domainIdent; } public final void setDomainIdent(Identifier domainIdent) { this.domainIdent = domainIdent; } public final Identifier getProjectIdent() { return projectIdent; } public final void setProjectIdent(Identifier projectIdent) { this.projectIdent = projectIdent; } public String getDomainId() { return domainId; } public void setDomainId(String domainId) { this.domainId = domainId; } public String getProjectId() { return projectId; } public void setProjectId(String projectId) { this.projectId = projectId; } public final String getUserName() { return userName; } public final void setUserName(String userName) { this.userName = userName; } public final String getRegion() { return region; } public final void setRegion(String region) { this.region = region; } }
c01aa56eb3b660b868d2866449ea0cbac9f39bbf
ebddf75fc76666d644cf1a3536649ec943247085
/src/main/java/com.saienko/service/userService/UserService.java
59b105f1bda8cff3886e22f15a596d1078bb5c91
[]
no_license
Glebachka/App
eafa5095370238956d9ea0afcf3e5ac4bb79d8ac
f2d7ccf04bc7a74843364180050b6460c604c53e
refs/heads/master
2021-01-10T17:43:11.132046
2015-12-14T15:37:05
2015-12-14T15:37:05
45,279,034
0
0
null
null
null
null
UTF-8
Java
false
false
451
java
package com.saienko.service.userService; import com.saienko.model.User; import java.util.List; /** * Created by gleb on 30.10.2015. */ public interface UserService { User findByUserId(int userId); void saveUser(User user); void updateUser(User user); void deleteUserByUserLogin(String login); List<User> findAllUsers(); User findUserByLogin(String login); boolean isUserLoginUnique(Integer id, String login); }
081509b1dd7ab4bdaf346befbe1ae1f84d191874
0ff078e4db3c0c9b60cf1bd24200fcb7c38662e9
/src/main/java/top/zbeboy/isy/web/bean/error/ErrorBean.java
89fdf00af9fd1528b150863fadc05f0238915904
[ "MIT" ]
permissive
pin062788/ISY
aabada9feca8210793b60d9309bfa5e7befd3777
df1e916dd5b14366f2d7dced9dd0b9848c74fcbe
refs/heads/master
2021-08-06T23:36:31.134588
2017-10-23T14:51:23
2017-10-23T14:51:23
null
0
0
null
null
null
null
UTF-8
Java
false
false
363
java
package top.zbeboy.isy.web.bean.error; import lombok.Data; import java.util.List; import java.util.Map; /** * Created by zbeboy on 2016/11/24. */ @Data(staticConstructor = "of") public class ErrorBean<T> { private boolean hasError; private String errorMsg; private T data; private Map<String, Object> mapData; private List<T> listData; }
030ebb0c6f8cb4ce7a02f807ff7e0432792e2ad6
47a0f826caf858d7e58901059624b09e314c1308
/my_weibo/gen/com/coderdream/weibo/BuildConfig.java
d284c08f62d933ad6b1897465f379e52dc765433
[]
no_license
CoderDream/my_weibo
77a1a93b925453dd97c3c46e346ea4c9331e6873
652536cfaf3b2632efe0ae6ee1685f1460bc0a2b
refs/heads/master
2016-09-05T14:31:42.249093
2014-12-29T13:44:19
2014-12-29T13:44:19
null
0
0
null
null
null
null
UTF-8
Java
false
false
162
java
/** Automatically generated file. DO NOT MODIFY */ package com.coderdream.weibo; public final class BuildConfig { public final static boolean DEBUG = true; }
919136255ea8ecfe695b4e7d4281be26b8223bdd
9073dddd9e90f6f46ffbf4b32db8bab4072fdfe2
/src/custom/Tool.java
94cac684c94f1a1d5f44e0d92b5d34198fa2ca74
[]
no_license
rickbert/QCraft
5d9de05d2770360f1a50cccb775b31857902d13f
e4f2cd3144416a9002341a6b063e3541d0cfcb29
refs/heads/master
2021-01-22T16:17:53.243520
2013-08-04T01:10:14
2013-08-04T01:10:14
null
0
0
null
null
null
null
UTF-8
Java
false
false
671
java
package custom; import org.bukkit.inventory.ItemStack; public enum Tool { AXE, HOE, NONE, PICKAXE, SPADE, SWORD, FISHING_ROD, OTHER; public static Tool getTool(ItemStack item) { String tool = item.getType().name(); if (tool.contains("_AXE")) { return AXE; } else if (tool.contains("_HOE")) { return HOE; } else if (tool.contains("AIR")) { return NONE; } else if (tool.contains("_PICKAXE")) { return PICKAXE; } else if (tool.contains("_SPADE")) { return SPADE; } else if (tool.contains("_SWORD")) { return SWORD; } else if (tool.contains("FISHING_ROD")) { return FISHING_ROD; } else { return OTHER; } } }
203ba885ccb4379f94cfe4bb7f6260d8ec7ee406
9b2669499c3d5fe13eea0f0772f0c4243b35395e
/part02-Part02_08.NumberOfNumbers/src/main/java/NumberOfNumbers.java
d8364c8d08d94ff5c52484b552fd9156b2b3065a
[]
no_license
lenconstan/MOOC
7cc36bc7afe47c5b706c94a252e391c75684ab17
4d4f36c0dde8d8fedcffb11b6da11922980b17bf
refs/heads/master
2023-03-21T22:18:04.215857
2021-03-02T18:46:52
2021-03-02T18:46:52
343,878,110
0
0
null
null
null
null
UTF-8
Java
false
false
522
java
import java.util.Scanner; public class NumberOfNumbers { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int nums = 0; while (true) { System.out.println("Give a number:"); int num = Integer.valueOf(scanner.nextLine()); if (num == 0) { break; } if (num != 0){ nums += 1; } } System.out.println("Number of numbers: " + nums); } }
5d929ff9b68825989404baf8a1216d4d65023afe
2d965bbdf3c2047e65adb570b1880f448ecd2013
/unit-test-one/src/main/java/com/ismail/unittestone/service/ProduceService.java
dfb48c90d8f8a9b878fce1c53c4a74f02a74d9bf
[]
no_license
ismailraju/SpringBootTest
4ec8f0b7a93e73b8426482c9574c7828394fdeec
3f2471e0e9043b4ef5dc06dc5b6bf041582126b2
refs/heads/main
2023-07-03T20:48:12.504325
2021-08-11T07:58:08
2021-08-11T07:58:08
394,909,694
0
0
null
null
null
null
UTF-8
Java
false
false
807
java
package com.ismail.unittestone.service; import com.ismail.unittestone.model.Produce; import com.ismail.unittestone.repository.ProduceRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; @Service public class ProduceService { @Autowired private ProduceRepository productRepository; public ProduceService(ProduceRepository productRepository) { this.productRepository = productRepository; } public Produce add(Produce produce) { return productRepository.save(produce); } public Produce get(Produce produce) { return productRepository.getById(produce.getId()); } public List<Produce> getAll() { return productRepository.findAll(); } }
48ae893e0ad646ddb9b4008e3bf120a3d2621493
60d596e322fe434f39709d7fa79a5ba69055b6b2
/Example_25.java
a4aed742a927c4742bf19265a67267f44bf4fe0c
[ "BSD-2-Clause" ]
permissive
ThePowerOfSwift/PDFjet-Open-Source
d6d885fd1f133df3ee4ae2d4d63c1700c4940adb
61545e0badeefd23683e185b10dbf3401cc7b5f9
refs/heads/master
2022-06-14T06:39:46.063295
2020-05-05T19:58:55
2020-05-05T19:58:55
null
0
0
null
null
null
null
UTF-8
Java
false
false
2,841
java
import java.io.*; import com.pdfjet.*; /** * Example_25.java * */ public class Example_25 { public Example_25() throws Exception { PDF pdf = new PDF( new BufferedOutputStream( new FileOutputStream("Example_25.pdf"))); Font f1 = new Font(pdf, CoreFont.HELVETICA); Font f2 = new Font(pdf, CoreFont.HELVETICA_BOLD); Font f3 = new Font(pdf, CoreFont.HELVETICA); Font f4 = new Font(pdf, CoreFont.HELVETICA_BOLD); Font f5 = new Font(pdf, CoreFont.HELVETICA); Font f6 = new Font(pdf, CoreFont.HELVETICA_BOLD); Page page = new Page(pdf, Letter.PORTRAIT); CompositeTextLine composite = new CompositeTextLine(50f, 50f); composite.setFontSize(14f); TextLine text1 = new TextLine(f1, "C"); TextLine text2 = new TextLine(f2, "6"); TextLine text3 = new TextLine(f3, "H"); TextLine text4 = new TextLine(f4, "12"); TextLine text5 = new TextLine(f5, "O"); TextLine text6 = new TextLine(f6, "6"); text1.setColor(Color.dodgerblue); text3.setColor(Color.dodgerblue); text5.setColor(Color.dodgerblue); text2.setTextEffect(Effect.SUBSCRIPT); text4.setTextEffect(Effect.SUBSCRIPT); text6.setTextEffect(Effect.SUBSCRIPT); composite.addComponent(text1); composite.addComponent(text2); composite.addComponent(text3); composite.addComponent(text4); composite.addComponent(text5); composite.addComponent(text6); float[] xy = composite.drawOn(page); Box box = new Box(); box.setLocation(xy[0], xy[1]); box.setSize(20f, 20f); box.drawOn(page); CompositeTextLine composite2 = new CompositeTextLine(50f, 100f); composite2.setFontSize(14f); text1 = new TextLine(f1, "SO"); text2 = new TextLine(f2, "4"); text3 = new TextLine(f4, "2-"); // Use bold font here text2.setTextEffect(Effect.SUBSCRIPT); text3.setTextEffect(Effect.SUPERSCRIPT); composite2.addComponent(text1); composite2.addComponent(text2); composite2.addComponent(text3); composite2.drawOn(page); composite2.setLocation(100f, 150f); composite2.drawOn(page); float[] yy = composite2.getMinMax(); Line line1 = new Line(50f, yy[0], 200f, yy[0]); Line line2 = new Line(50f, yy[1], 200f, yy[1]); line1.drawOn(page); line2.drawOn(page); pdf.close(); } public static void main(String[] args) throws Exception { long t0 = System.currentTimeMillis(); new Example_25(); long t1 = System.currentTimeMillis(); System.out.println("Example_25 => " + (t1 - t0)); } } // End of Example_25.java
9eea321d712729b8901c443502656630d1c42d98
70e7dc3b897a07ddfddff7d7d5b5b41ff53b0c6b
/shared/src/main/java/org/consumersunion/stories/server/index/profile/UpdatePersonAddressIndexer.java
fb43419d843edc890e0f652bfc0711803a2e44f1
[ "Apache-2.0" ]
permissive
stori-es/stori_es
e8c61dd8d9048a645b4ff9c63f013bb08e2e2e79
12b22e7f203964979dd873b96c122ffd955596bf
refs/heads/master
2023-01-14T11:03:34.553622
2022-12-31T01:16:36
2022-12-31T01:16:36
47,994,289
3
0
Apache-2.0
2022-12-31T01:16:37
2015-12-14T18:45:43
Java
UTF-8
Java
false
false
2,318
java
package org.consumersunion.stories.server.index.profile; import javax.inject.Inject; import org.consumersunion.stories.common.shared.model.Address; import org.consumersunion.stories.server.index.Indexer; import org.consumersunion.stories.server.index.Script; import org.consumersunion.stories.server.index.ScriptFactory; import org.consumersunion.stories.server.index.elasticsearch.UpdateByQuery; import org.consumersunion.stories.server.index.elasticsearch.query.Query; import org.consumersunion.stories.server.index.elasticsearch.query.QueryBuilder; import org.consumersunion.stories.server.index.story.StoryDocument; import org.springframework.stereotype.Component; @Component public class UpdatePersonAddressIndexer { private final ScriptFactory scriptFactory; private final Indexer<ProfileDocument> profileIndexer; private final Indexer<StoryDocument> storyIndexer; @Inject public UpdatePersonAddressIndexer( ScriptFactory scriptFactory, Indexer<ProfileDocument> profileIndexer, Indexer<StoryDocument> storyIndexer) { this.scriptFactory = scriptFactory; this.profileIndexer = profileIndexer; this.storyIndexer = storyIndexer; } public void index(Address address) { this.index(0, address); } public void index(int idx, Address address) { if (idx == 0) { // then it's the primary address // First update the Person ProfileDocument profileDocument = profileIndexer.get(address.getEntity()); if (profileDocument != null) { profileDocument.setPrimaryCity(address.getCity()); profileDocument.setPrimaryState(address.getState()); profileDocument.setPrimaryPostalCode(address.getPostalCode()); profileDocument.setPrimaryAddress1(address.getAddress1()); profileIndexer.index(profileDocument); } // Update the Stories Query query = QueryBuilder.newBuilder() .withTerm("authorId", address.getEntity()) .build(); Script updateAddressScript = scriptFactory.createUpdateAddressScript(address); storyIndexer.updateFromQuery(new UpdateByQuery(query, updateAddressScript)); } } }
a4b743173e193a2a37197f59e0b53d04abe5ccfb
d60e56292f717b90367fb95563af7691999ce92a
/DataStructures/src/Array/Employee.java
5da9b54487140b7dc519ee29dc532e11b923af87
[]
no_license
derekjgrove/DataStructures
6d00746a479815f8e67c6fbd32f4e658449d1743
c1a65520f914f853d172fe7e3ffee9fccbc9fa6b
refs/heads/master
2021-01-22T03:49:38.188385
2017-05-25T17:03:18
2017-05-25T17:03:18
92,408,379
0
0
null
null
null
null
UTF-8
Java
false
false
2,827
java
package Array; /** * Employee gets the employees associated with each department. * There is a many to one relationship regarding a department. * * @author Derek J. Grove * */ public class Employee { private String employeeId; private String empConIndicator; private String deptCode; private String fName; private String lName; private float salary; private String hireDate; private int vacDays; private int training; /** * Constructor for Employee * @param employeeId - Unique String of characters that identify an employee * @param empConIndicator - A single character to identify the person as a * employee('E') or a contractor('C') * @param deptCode - Unique string of characters that identify the employee * to their department * @param fName - String of characters to identify the employee's first name * @param lName - String of characters to identify the employee's last name * @param salary - Floating point to express the salary of the employee * @param hireDate - Formatted string to express the hire date of the employee * @param vacDays - An integer to express the amount of vacation days * @param training - An integer to express the amount of training days */ public Employee(String employeeId, String empConIndicator, String deptCode, String fName, String lName, float salary, String hireDate, int vacDays, int training) { super(); this.employeeId = employeeId; this.empConIndicator = empConIndicator; this.deptCode = deptCode; this.fName = fName; this.lName = lName; this.salary = salary; this.hireDate = hireDate; this.vacDays = vacDays; this.training = training; } /** * Get the employee ID * @return employeeId */ public String getEmployeeId() { return employeeId; } /** * Get the employee/contractor indicator * @return empConIndicator */ public String getEmpConIndicator() { return empConIndicator; } /** * Get the department code * @return deptCode */ public String getDeptCode() { return deptCode; } /** * Get the first name * @return fName */ public String getfName() { return fName; } /** * Get the last name * @return lName */ public String getlName() { return lName; } /** * Get the salary of the employee * @return salary */ public float getSalary() { return salary; } /** * Get the date of hire * @return hireDate */ public String getHireDate() { return hireDate; } /** * Get the amount of vacation days * @return vacDays */ public int getVacDays() { return vacDays; } /** * Get the amount of training days * @return training */ public int getTraining() { return training; } }
625a53f8e552db7efda01a18f8f0d35da9b666b7
08b8d598fbae8332c1766ab021020928aeb08872
/src/gcom/financeiro/ControladorFinanceiroCAERNSEJB.java
d38891a4a260d1ba96c96e5dcac3fb2df1172c01
[]
no_license
Procenge/GSAN-CAGEPA
53bf9bab01ae8116d08cfee7f0044d3be6f2de07
dfe64f3088a1357d2381e9f4280011d1da299433
refs/heads/master
2020-05-18T17:24:51.407985
2015-05-18T23:08:21
2015-05-18T23:08:21
25,368,185
3
1
null
null
null
null
WINDOWS-1252
Java
false
false
2,994
java
/* * Copyright (C) 2007-2007 the GSAN – Sistema Integrado de Gestão de Serviços de Saneamento * * This file is part of GSAN, an integrated service management system for Sanitation * * GSAN 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 2 of the License. * * GSAN 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, write to the Free Software * Foundation, Inc., 59 Temple Place – Suite 330, Boston, MA 02111-1307, USA */ /* * GSAN – Sistema Integrado de Gestão de Serviços de Saneamento * Copyright (C) <2007> * Adriano Britto Siqueira * Alexandre Santos Cabral * Ana Carolina Alves Breda * Ana Maria Andrade Cavalcante * Aryed Lins de Araújo * Bruno Leonardo Rodrigues Barros * Carlos Elmano Rodrigues Ferreira * Cláudio de Andrade Lira * Denys Guimarães Guenes Tavares * Eduardo Breckenfeld da Rosa Borges * Fabíola Gomes de Araújo * Flávio Leonardo Cavalcanti Cordeiro * Francisco do Nascimento Júnior * Homero Sampaio Cavalcanti * Ivan Sérgio da Silva Júnior * José Edmar de Siqueira * José Thiago Tenório Lopes * Kássia Regina Silvestre de Albuquerque * Leonardo Luiz Vieira da Silva * Márcio Roberto Batista da Silva * Maria de Fátima Sampaio Leite * Micaela Maria Coelho de Araújo * Nelson Mendonça de Carvalho * Newton Morais e Silva * Pedro Alexandre Santos da Silva Filho * Rafael Corrêa Lima e Silva * Rafael Francisco Pinto * Rafael Koury Monteiro * Rafael Palermo de Araújo * Raphael Veras Rossiter * Roberto Sobreira Barbalho * Rodrigo Avellar Silveira * Rosana Carvalho Barbosa * Sávio Luiz de Andrade Cavalcante * Tai Mu Shih * Thiago Augusto Souza do Nascimento * Tiago Moreno Rodrigues * Vivianne Barbosa Sousa * * Este programa é software livre; você pode redistribuí-lo e/ou * modificá-lo sob os termos de Licença Pública Geral GNU, conforme * publicada pela Free Software Foundation; versão 2 da * Licença. * Este programa é distribuído na expectativa de ser útil, mas SEM * QUALQUER GARANTIA; sem mesmo a garantia implícita de * COMERCIALIZAÇÃO ou de ADEQUAÇÃO A QUALQUER PROPÓSITO EM * PARTICULAR. Consulte a Licença Pública Geral GNU para obter mais * detalhes. * Você deve ter recebido uma cópia da Licença Pública Geral GNU * junto com este programa; se não, escreva para Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA * 02111-1307, USA. */ package gcom.financeiro; import javax.ejb.SessionBean; public class ControladorFinanceiroCAERNSEJB extends ControladorFinanceiro implements SessionBean { }
060f2c1df5848ef25b1532e84d626fd3d5c34b58
74560c4da133b811b14273757124750ae07767d1
/src/main/java/StreamAPI.java
e7ec689526c0fad40396deaa1cc8a804b2794d34
[]
no_license
swatr-1234/StreamApi
571edf26adb2cbac53a2338b3474a910d9d9be7f
e8ffd8349bf29cb24640cdeedaceac011043f0c3
refs/heads/main
2023-03-25T07:39:52.255713
2021-03-16T11:16:40
2021-03-16T11:16:40
348,316,396
0
0
null
null
null
null
UTF-8
Java
false
false
8,247
java
import java.util.*; import java.util.function.Function; import java.util.stream.Collectors; import java.util.stream.IntStream; import java.util.stream.Stream; import static java.util.stream.Collectors.reducing; public class StreamAPI { public static void main(String[] args) { Employee e1 = new Employee("tom", 10, 1000.1); Employee e2 = new Employee("dick", 30, 2000.1); Employee e3 = new Employee("tommy", 20, 2000.1); Employee e4 = new Employee("harry", 20, 1000.1); Employee e5 = new Employee("mina", 10, 5000.3); List.of(e1, e2, e3) .stream() .map(Employee::getAge) .collect(Collectors.toList()) .forEach(System.out::println); Set<Integer> i1 = List.of(e1, e2, e3) .stream() .map(Employee::getAge) .collect(Collectors.toCollection(TreeSet::new)); System.out.println(i1); String s = List.of(e1, e2, e3) .stream() .map(Employee::getName) .collect(Collectors.joining(",")); String s1 = List.of(e1, e2, e3) .stream() .map(Employee::getName) .collect(Collectors.joining(",", "Employees are ", " .")); System.out.println(s1); int sum = List.of(e1, e2, e3) .stream() .collect(Collectors.summingInt(Employee::getAge)); /*int sum=List.of(e1,e2,e3) .stream() .mapToInt(Employee::getAge).sum();*/ System.out.println(sum); Map<Integer, List<Employee>> groupByAge = List.of(e1, e2, e3, e4) .stream() .collect(Collectors.groupingBy(Employee::getAge)); System.out.println(groupByAge); Map<String, Integer> groupByNameAndSummingAge = List.of(e1, e2, e3, e4, e5) .stream() .collect(Collectors.groupingBy(Employee::getName, Collectors.summingInt(Employee::getAge))); System.out.println(groupByNameAndSummingAge); Map<Boolean, List<Employee>> partitionByAge = List.of(e1, e2, e3, e4, e5) .stream() .collect(Collectors.partitioningBy(e -> e.getAge() >= 20)); System.out.println(partitionByAge); Map<Integer, Set<String>> nameByAge = List.of(e1, e2, e3, e4, e5) .stream() .collect(Collectors.groupingBy(Employee::getAge, Collectors.mapping(Employee::getName, Collectors.toSet()))); System.out.println(nameByAge); List<Employee> empList = List.of(e1, e2, e3, e4, e5) .stream() .collect(Collectors.collectingAndThen(Collectors.toList(), Collections::unmodifiableList)); System.out.println(empList); Map<Integer, Long> countingByAge = List.of(e1, e2, e3, e4, e5) .stream() .collect(Collectors.groupingBy(Employee::getAge, Collectors.counting())); System.out.println(countingByAge); /*Optional<Employee> minByAge=List.of(e1,e2,e3,e4,e5) .stream() .collect(Collectors.minBy((emp1,emp2)-> emp1.getAge()-emp2.getAge()));*/ Optional<Employee> minByAge = List.of(e1, e2, e3, e4, e5) .stream() .min((emp1, emp2) -> emp1.getAge() - emp2.getAge()); System.out.println(minByAge); /*Optional<Employee> maxByAge=List.of(e1,e2,e3,e4,e5) .stream() .collect(Collectors.maxBy((emp1,emp2)-> emp1.getAge()-emp2.getAge()));*/ Optional<Employee> maxByAge = List.of(e1, e2, e3, e4, e5) .stream() .max((emp1, emp2) -> emp1.getAge() - emp2.getAge()); System.out.println(maxByAge); Double averageSalary = List.of(e1, e2, e3, e4, e5) .stream() .collect(Collectors.averagingDouble(Employee::getSalary)); System.out.println(averageSalary); Double sumSalaryByAgeTwenty = List.of(e1, e2, e3, e4, e5) .parallelStream() .filter(e -> e.getAge() == 20) .peek(System.out::println) .mapToDouble(e -> e.getSalary()) .peek(System.out::println) .sum(); System.out.println(sumSalaryByAgeTwenty); int[] intArray={1,2,3,4,5,6,7,8,9,10}; IntStream.of(intArray) .filter(i->i%2==0) .skip(2) .forEach(System.out::println); IntStream.of(intArray) .filter(i->i%2==0) .limit(2) .forEach(System.out::println); List.of(e1, e2, e3, e4, e5) .stream() .collect(Collectors.toMap(Employee::getName,Employee::getSalary)) .forEach((k,v)->System.out.println("Key:"+k+"--"+"value:"+v)); List.of(e1, e2, e3, e4, e5) .stream() .collect(Collectors.toMap(Employee::getSalary, Function.identity(),(exist,replace)->exist)) .forEach((k,v)->System.out.println("Key:"+k+"--"+"value:"+v)); List.of(e1, e2, e3, e4, e5) .stream() .collect(Collectors.toMap(Employee::getName, Function.identity(),(p1,p2)->p1,TreeMap::new)) .forEach((k,v)->System.out.println("Key:"+k+"--"+"value:"+v)); int[] a1=IntStream.rangeClosed(0,10).boxed().mapToInt(i->i).toArray(); Map<Employee,Integer> mapEmp=new HashMap<>(); mapEmp.put(e1,1); mapEmp.put(e2,2); mapEmp.put(e3,3); mapEmp.put(e4,4); mapEmp.put(e5,5); mapEmp.entrySet().stream().map(e->e.getKey()).forEachOrdered(System.out::println); long count = List.of(e1, e2, e3, e4, e5) .stream() .filter(c -> c.getName().startsWith("t")) .count(); System.out.println(count); int max = IntStream.of(2000, 980, 112, 711, 35) .max() .getAsInt(); System.out.println(max); int sumOfData = IntStream.of(2000, 980, 112, 711, 35) .sum(); System.out.println(sumOfData); Stream<Integer> stream1 = Stream.of(1, 30, 15); Stream<Integer> stream2 = Stream.of(9, 4, 6); Stream<Integer> finalStream=Stream.concat(stream1,stream2); finalStream.collect(Collectors.toList()).forEach(System.out::println); Stream<Integer> integers = Stream.iterate(0, i -> i + 1).limit(10); integers.forEach(System.out::println); List<String> list = Arrays.asList("Apple", "Bat", "Cat", "Dog"); Optional<String> result = list.stream().findFirst(); result.stream().forEach(System.out::println); } }
fb0838acef684907616f934a4dc81ddf3bc75006
8b2c9d9914939cadc99c6190706521be0cd577b9
/src/main/java/cc/mrbird/common/service/impl/BaseService.java
907081ab56cc4e86727675e6c9cc5c419b51fa2d
[ "Apache-2.0" ]
permissive
iclockwork/febs
a1c66f3aef265a5d5a3c940298052b2295c367bb
cc55cd2b034ba36c7b2e1dd75d4bf3042428d79a
refs/heads/master
2022-09-13T02:25:11.255843
2019-07-15T09:34:15
2019-07-15T09:34:15
170,794,507
1
0
null
2022-09-01T23:02:50
2019-02-15T03:11:55
Java
UTF-8
Java
false
false
1,845
java
package cc.mrbird.common.service.impl; import java.util.List; import org.apache.ibatis.annotations.Param; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; import cc.mrbird.common.dao.SeqenceMapper; import cc.mrbird.common.service.IService; import tk.mybatis.mapper.common.Mapper; import tk.mybatis.mapper.entity.Example; @Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class) public abstract class BaseService<T> implements IService<T> { @Autowired protected Mapper<T> mapper; @Autowired protected SeqenceMapper seqenceMapper; public Mapper<T> getMapper() { return mapper; } @Override public Long getSequence(@Param("seqName") String seqName) { return seqenceMapper.getSequence(seqName); } @Override public List<T> selectAll() { return mapper.selectAll(); } @Override public T selectByKey(Object key) { return mapper.selectByPrimaryKey(key); } @Override @Transactional public int save(T entity) { return mapper.insert(entity); } @Override @Transactional public int delete(Object key) { return mapper.deleteByPrimaryKey(key); } @Override @Transactional public int batchDelete(List<String> list, String property, Class<T> clazz) { Example example = new Example(clazz); example.createCriteria().andIn(property, list); return this.mapper.deleteByExample(example); } @Override @Transactional public int updateAll(T entity) { return mapper.updateByPrimaryKey(entity); } @Override @Transactional public int updateNotNull(T entity) { return mapper.updateByPrimaryKeySelective(entity); } @Override public List<T> selectByExample(Object example) { return mapper.selectByExample(example); } }
11d1a97da46ef4ad5d48e0e05f5a408180373bd3
2bf30c31677494a379831352befde4a5e3d8ed19
/vipr-portal/com.iwave.ext.linux/src/java/com/iwave/ext/linux/command/MultipathException.java
399a1acba7496b631a960a9491a41c5d27cac9d3
[]
no_license
dennywangdengyu/coprhd-controller
fed783054a4970c5f891e83d696a4e1e8364c424
116c905ae2728131e19631844eecf49566e46db9
refs/heads/master
2020-12-30T22:43:41.462865
2015-07-23T18:09:30
2015-07-23T18:09:30
null
0
0
null
null
null
null
UTF-8
Java
false
false
443
java
/* * Copyright 2012-2015 iWave Software LLC * All Rights Reserved */ package com.iwave.ext.linux.command; import com.iwave.ext.command.CommandException; import com.iwave.ext.command.CommandOutput; public class MultipathException extends CommandException { private static final long serialVersionUID = 1470336800328054076L; public MultipathException(String message, CommandOutput output) { super(message, output); } }
8d924a3dbd7b054abbc271878839c9e16c0c5204
25ffcb590cfd0f8be26ae8704b34d6ff132e0516
/jOOQ/src/main/java/org/jooq/util/xml/jaxb/InformationSchema.java
45aa28f2a483e5a54130bfa889e8f88e5c7fa06d
[ "Apache-2.0" ]
permissive
togaurav/jOOQ
66030b04cd9f642fc83381211de380294f0a2391
5b32938b6116361acb5f143aefe085b7f87a2ac5
refs/heads/master
2021-07-17T01:06:34.359931
2017-10-05T16:12:30
2017-10-05T16:12:30
null
0
0
null
null
null
null
UTF-8
Java
false
false
13,533
java
package org.jooq.util.xml.jaxb; import java.io.Serializable; import java.util.ArrayList; import java.util.Collection; import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlElementWrapper; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for anonymous complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType&gt; * &lt;complexContent&gt; * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"&gt; * &lt;all&gt; * &lt;element name="schemata" type="{http://www.jooq.org/xsd/jooq-meta-3.10.0.xsd}Schemata" minOccurs="0"/&gt; * &lt;element name="sequences" type="{http://www.jooq.org/xsd/jooq-meta-3.10.0.xsd}Sequences" minOccurs="0"/&gt; * &lt;element name="tables" type="{http://www.jooq.org/xsd/jooq-meta-3.10.0.xsd}Tables" minOccurs="0"/&gt; * &lt;element name="columns" type="{http://www.jooq.org/xsd/jooq-meta-3.10.0.xsd}Columns" minOccurs="0"/&gt; * &lt;element name="table_constraints" type="{http://www.jooq.org/xsd/jooq-meta-3.10.0.xsd}TableConstraints" minOccurs="0"/&gt; * &lt;element name="key_column_usages" type="{http://www.jooq.org/xsd/jooq-meta-3.10.0.xsd}KeyColumnUsages" minOccurs="0"/&gt; * &lt;element name="referential_constraints" type="{http://www.jooq.org/xsd/jooq-meta-3.10.0.xsd}ReferentialConstraints" minOccurs="0"/&gt; * &lt;element name="indexes" type="{http://www.jooq.org/xsd/jooq-meta-3.10.0.xsd}Indexes" minOccurs="0"/&gt; * &lt;element name="index_column_usages" type="{http://www.jooq.org/xsd/jooq-meta-3.10.0.xsd}IndexColumnUsages" minOccurs="0"/&gt; * &lt;element name="routines" type="{http://www.jooq.org/xsd/jooq-meta-3.10.0.xsd}Routines" minOccurs="0"/&gt; * &lt;element name="parameters" type="{http://www.jooq.org/xsd/jooq-meta-3.10.0.xsd}Parameters" minOccurs="0"/&gt; * &lt;/all&gt; * &lt;/restriction&gt; * &lt;/complexContent&gt; * &lt;/complexType&gt; * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { }) @XmlRootElement(name = "information_schema") @SuppressWarnings({ "all" }) public class InformationSchema implements Serializable { private final static long serialVersionUID = 31000L; @XmlElementWrapper(name = "schemata") @XmlElement(name = "schema") protected List<Schema> schemata; @XmlElementWrapper(name = "sequences") @XmlElement(name = "sequence") protected List<Sequence> sequences; @XmlElementWrapper(name = "tables") @XmlElement(name = "table") protected List<Table> tables; @XmlElementWrapper(name = "columns") @XmlElement(name = "column") protected List<Column> columns; @XmlElementWrapper(name = "table_constraints") @XmlElement(name = "table_constraint") protected List<TableConstraint> tableConstraints; @XmlElementWrapper(name = "key_column_usages") @XmlElement(name = "key_column_usage") protected List<KeyColumnUsage> keyColumnUsages; @XmlElementWrapper(name = "referential_constraints") @XmlElement(name = "referential_constraint") protected List<ReferentialConstraint> referentialConstraints; @XmlElementWrapper(name = "indexes") @XmlElement(name = "index") protected List<Index> indexes; @XmlElementWrapper(name = "index_column_usages") @XmlElement(name = "index_column_usage") protected List<IndexColumnUsage> indexColumnUsages; @XmlElementWrapper(name = "routines") @XmlElement(name = "routine") protected List<Routine> routines; @XmlElementWrapper(name = "parameters") @XmlElement(name = "parameter") protected List<Parameter> parameters; public List<Schema> getSchemata() { if (schemata == null) { schemata = new ArrayList<Schema>(); } return schemata; } public void setSchemata(List<Schema> schemata) { this.schemata = schemata; } public List<Sequence> getSequences() { if (sequences == null) { sequences = new ArrayList<Sequence>(); } return sequences; } public void setSequences(List<Sequence> sequences) { this.sequences = sequences; } public List<Table> getTables() { if (tables == null) { tables = new ArrayList<Table>(); } return tables; } public void setTables(List<Table> tables) { this.tables = tables; } public List<Column> getColumns() { if (columns == null) { columns = new ArrayList<Column>(); } return columns; } public void setColumns(List<Column> columns) { this.columns = columns; } public List<TableConstraint> getTableConstraints() { if (tableConstraints == null) { tableConstraints = new ArrayList<TableConstraint>(); } return tableConstraints; } public void setTableConstraints(List<TableConstraint> tableConstraints) { this.tableConstraints = tableConstraints; } public List<KeyColumnUsage> getKeyColumnUsages() { if (keyColumnUsages == null) { keyColumnUsages = new ArrayList<KeyColumnUsage>(); } return keyColumnUsages; } public void setKeyColumnUsages(List<KeyColumnUsage> keyColumnUsages) { this.keyColumnUsages = keyColumnUsages; } public List<ReferentialConstraint> getReferentialConstraints() { if (referentialConstraints == null) { referentialConstraints = new ArrayList<ReferentialConstraint>(); } return referentialConstraints; } public void setReferentialConstraints(List<ReferentialConstraint> referentialConstraints) { this.referentialConstraints = referentialConstraints; } public List<Index> getIndexes() { if (indexes == null) { indexes = new ArrayList<Index>(); } return indexes; } public void setIndexes(List<Index> indexes) { this.indexes = indexes; } public List<IndexColumnUsage> getIndexColumnUsages() { if (indexColumnUsages == null) { indexColumnUsages = new ArrayList<IndexColumnUsage>(); } return indexColumnUsages; } public void setIndexColumnUsages(List<IndexColumnUsage> indexColumnUsages) { this.indexColumnUsages = indexColumnUsages; } public List<Routine> getRoutines() { if (routines == null) { routines = new ArrayList<Routine>(); } return routines; } public void setRoutines(List<Routine> routines) { this.routines = routines; } public List<Parameter> getParameters() { if (parameters == null) { parameters = new ArrayList<Parameter>(); } return parameters; } public void setParameters(List<Parameter> parameters) { this.parameters = parameters; } public InformationSchema withSchemata(Schema... values) { if (values!= null) { for (Schema value: values) { getSchemata().add(value); } } return this; } public InformationSchema withSchemata(Collection<Schema> values) { if (values!= null) { getSchemata().addAll(values); } return this; } public InformationSchema withSchemata(List<Schema> schemata) { setSchemata(schemata); return this; } public InformationSchema withSequences(Sequence... values) { if (values!= null) { for (Sequence value: values) { getSequences().add(value); } } return this; } public InformationSchema withSequences(Collection<Sequence> values) { if (values!= null) { getSequences().addAll(values); } return this; } public InformationSchema withSequences(List<Sequence> sequences) { setSequences(sequences); return this; } public InformationSchema withTables(Table... values) { if (values!= null) { for (Table value: values) { getTables().add(value); } } return this; } public InformationSchema withTables(Collection<Table> values) { if (values!= null) { getTables().addAll(values); } return this; } public InformationSchema withTables(List<Table> tables) { setTables(tables); return this; } public InformationSchema withColumns(Column... values) { if (values!= null) { for (Column value: values) { getColumns().add(value); } } return this; } public InformationSchema withColumns(Collection<Column> values) { if (values!= null) { getColumns().addAll(values); } return this; } public InformationSchema withColumns(List<Column> columns) { setColumns(columns); return this; } public InformationSchema withTableConstraints(TableConstraint... values) { if (values!= null) { for (TableConstraint value: values) { getTableConstraints().add(value); } } return this; } public InformationSchema withTableConstraints(Collection<TableConstraint> values) { if (values!= null) { getTableConstraints().addAll(values); } return this; } public InformationSchema withTableConstraints(List<TableConstraint> tableConstraints) { setTableConstraints(tableConstraints); return this; } public InformationSchema withKeyColumnUsages(KeyColumnUsage... values) { if (values!= null) { for (KeyColumnUsage value: values) { getKeyColumnUsages().add(value); } } return this; } public InformationSchema withKeyColumnUsages(Collection<KeyColumnUsage> values) { if (values!= null) { getKeyColumnUsages().addAll(values); } return this; } public InformationSchema withKeyColumnUsages(List<KeyColumnUsage> keyColumnUsages) { setKeyColumnUsages(keyColumnUsages); return this; } public InformationSchema withReferentialConstraints(ReferentialConstraint... values) { if (values!= null) { for (ReferentialConstraint value: values) { getReferentialConstraints().add(value); } } return this; } public InformationSchema withReferentialConstraints(Collection<ReferentialConstraint> values) { if (values!= null) { getReferentialConstraints().addAll(values); } return this; } public InformationSchema withReferentialConstraints(List<ReferentialConstraint> referentialConstraints) { setReferentialConstraints(referentialConstraints); return this; } public InformationSchema withIndexes(Index... values) { if (values!= null) { for (Index value: values) { getIndexes().add(value); } } return this; } public InformationSchema withIndexes(Collection<Index> values) { if (values!= null) { getIndexes().addAll(values); } return this; } public InformationSchema withIndexes(List<Index> indexes) { setIndexes(indexes); return this; } public InformationSchema withIndexColumnUsages(IndexColumnUsage... values) { if (values!= null) { for (IndexColumnUsage value: values) { getIndexColumnUsages().add(value); } } return this; } public InformationSchema withIndexColumnUsages(Collection<IndexColumnUsage> values) { if (values!= null) { getIndexColumnUsages().addAll(values); } return this; } public InformationSchema withIndexColumnUsages(List<IndexColumnUsage> indexColumnUsages) { setIndexColumnUsages(indexColumnUsages); return this; } public InformationSchema withRoutines(Routine... values) { if (values!= null) { for (Routine value: values) { getRoutines().add(value); } } return this; } public InformationSchema withRoutines(Collection<Routine> values) { if (values!= null) { getRoutines().addAll(values); } return this; } public InformationSchema withRoutines(List<Routine> routines) { setRoutines(routines); return this; } public InformationSchema withParameters(Parameter... values) { if (values!= null) { for (Parameter value: values) { getParameters().add(value); } } return this; } public InformationSchema withParameters(Collection<Parameter> values) { if (values!= null) { getParameters().addAll(values); } return this; } public InformationSchema withParameters(List<Parameter> parameters) { setParameters(parameters); return this; } }
0d1d6b89b29915a8902eb799285979268cc3df2a
d9f4fd57f7836b0d7a292264dca22b9b97eba174
/Alkitab/src/main/java/yuku/alkitab/reminder/widget/HackedTimePickerDialog.java
c562e295ee5b84a57675052ff27dbcf6d25cc887
[ "Apache-2.0", "LicenseRef-scancode-free-unknown" ]
permissive
BitJetKit/androidbible
cf5e9faa54204ee553b20992252e64374a3079e1
fb1d6c209f95b11f8c45f7cfd3da1f553703b3ac
refs/heads/develop
2020-08-08T07:23:16.169654
2019-05-28T05:57:53
2019-05-28T05:57:53
213,776,850
0
0
Apache-2.0
2020-05-13T01:01:06
2019-10-08T23:35:19
null
UTF-8
Java
false
false
5,289
java
/* * Copyright (C) 2007 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package yuku.alkitab.reminder.widget; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.widget.TimePicker; import yuku.alkitab.debug.R; /** * A dialog that prompts the user for the time of day using a {@link android.widget.TimePicker}. * * <p>See the <a href="{@docRoot}guide/topics/ui/controls/pickers.html">Pickers</a> * guide.</p> */ public class HackedTimePickerDialog extends AlertDialog implements DialogInterface.OnClickListener, TimePicker.OnTimeChangedListener { /** * The callback interface used to indicate the user is done filling in * the time (they clicked on the 'Set' button). */ public interface HackedTimePickerListener { /** * @param view The view associated with this listener. * @param hourOfDay The hour that was set. * @param minute The minute that was set. */ void onTimeSet(TimePicker view, int hourOfDay, int minute); /** * @param view The view associated with this listener. */ void onTimeOff(TimePicker view); } private static final String HOUR = "hour"; private static final String MINUTE = "minute"; private static final String IS_24_HOUR = "is24hour"; private final TimePicker mTimePicker; private final HackedTimePickerListener mCallback; int mInitialHourOfDay; int mInitialMinute; boolean mIs24HourView; /** * @param context Parent. * @param callBack How parent is notified. * @param hourOfDay The initial hour. * @param minute The initial minute. * @param is24HourView Whether this is a 24 hour view, or AM/PM. */ public HackedTimePickerDialog(Context context, CharSequence dialogTitle, CharSequence setButtonTitle, CharSequence offButtonTitle, HackedTimePickerListener callBack, int hourOfDay, int minute, boolean is24HourView) { super(context, 0); mCallback = callBack; mInitialHourOfDay = hourOfDay; mInitialMinute = minute; mIs24HourView = is24HourView; setIcon(0); setTitle(dialogTitle); Context themeContext = getContext(); setButton(BUTTON_POSITIVE, setButtonTitle, this); setButton(BUTTON_NEGATIVE, offButtonTitle, this); LayoutInflater inflater = (LayoutInflater) themeContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE); View view = inflater.inflate(R.layout.dialog_hacked_time_picker, null); setView(view); mTimePicker = view.findViewById(R.id.timePicker); // initialize state mTimePicker.setIs24HourView(mIs24HourView); mTimePicker.setCurrentHour(mInitialHourOfDay); mTimePicker.setCurrentMinute(mInitialMinute); mTimePicker.setOnTimeChangedListener(this); } @Override public void onClick(DialogInterface dialog, int which) { if (mCallback != null) { mTimePicker.clearFocus(); if (which == AlertDialog.BUTTON_POSITIVE) { mCallback.onTimeSet(mTimePicker, mTimePicker.getCurrentHour(), mTimePicker.getCurrentMinute()); } else if (which == AlertDialog.BUTTON_NEGATIVE) { mCallback.onTimeOff(mTimePicker); } } } public void updateTime(int hourOfDay, int minutOfHour) { mTimePicker.setCurrentHour(hourOfDay); mTimePicker.setCurrentMinute(minutOfHour); } @Override public void onTimeChanged(TimePicker view, int hourOfDay, int minute) { /* do nothing */ } /* Removed on this hacked version protected void onStop() { tryNotifyTimeSet(); super.onStop(); } */ @Override public Bundle onSaveInstanceState() { Bundle state = super.onSaveInstanceState(); state.putInt(HOUR, mTimePicker.getCurrentHour()); state.putInt(MINUTE, mTimePicker.getCurrentMinute()); state.putBoolean(IS_24_HOUR, mTimePicker.is24HourView()); return state; } @Override public void onRestoreInstanceState(Bundle savedInstanceState) { super.onRestoreInstanceState(savedInstanceState); int hour = savedInstanceState.getInt(HOUR); int minute = savedInstanceState.getInt(MINUTE); mTimePicker.setIs24HourView(savedInstanceState.getBoolean(IS_24_HOUR)); mTimePicker.setCurrentHour(hour); mTimePicker.setCurrentMinute(minute); } }
32dd5a56b1b1d7e6aef06fc0165502e90a877ee6
d2e96926c0da460d07622aab9d9e26c10286c048
/src/main/java/com/exames/crud/repository/UpdateRepository.java
4a431287f98c9d1a3f0f18737837a63ee7db96f2
[]
no_license
ItalloMartins/AvaliacaoSoc
9334e823750d2e504969bb888861555eb0aa4c5a
a75d649f2ecb673c2301a4e627f6ed14db2ab170
refs/heads/main
2022-12-24T03:39:05.015428
2020-10-06T13:43:06
2020-10-06T13:43:06
301,730,469
0
0
null
null
null
null
UTF-8
Java
false
false
277
java
package com.exames.crud.repository; import org.springframework.data.repository.CrudRepository; import org.springframework.stereotype.Repository; import com.exames.crud.model.UserModel; @Repository public interface UpdateRepository extends CrudRepository<UserModel, Long>{ }