text
stringlengths
10
2.72M
/* Copyright 2015 Alfio Zappala 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 co.runrightfast.component.events.impl; import co.runrightfast.app.ComponentId; import co.runrightfast.component.events.ComponentEvent; import co.runrightfast.component.events.ComponentEventFactory; import co.runrightfast.component.events.Event; import com.google.common.collect.ImmutableSet; import java.util.Optional; import lombok.Getter; import lombok.NonNull; import lombok.RequiredArgsConstructor; import org.apache.commons.lang3.ArrayUtils; /** * * @author alfio */ @RequiredArgsConstructor public class ComponentEventFactoryImpl implements ComponentEventFactory { @NonNull @Getter private final ComponentId componentId; @Override public ComponentEvent componentEvent(@NonNull final Event event, final String... tags) { final ComponentEventImpl.ComponentEventImplBuilder builder = ComponentEventImpl.builder() .componentId(componentId) .event(event); if (ArrayUtils.isNotEmpty(tags)) { return builder.tags(Optional.of(ImmutableSet.copyOf(tags))).build(); } return builder.build(); } @Override public ComponentEvent componentEvent(@NonNull final Event event, @NonNull final Throwable exception, final String... tags) { final ComponentEventImpl.ComponentEventImplBuilder builder = ComponentEventImpl.builder() .componentId(componentId) .event(event) .exception(Optional.of(exception)); if (ArrayUtils.isNotEmpty(tags)) { return builder.tags(Optional.of(ImmutableSet.copyOf(tags))).build(); } return builder.build(); } @Override public <DATA> ComponentEvent<DATA> componentEvent(@NonNull final Event<DATA> event, @NonNull final Class<DATA> eventDataType, @NonNull final DATA data, @NonNull final String... tags) { final ComponentEventImpl.ComponentEventImplBuilder<DATA> builder = ComponentEventImpl.<DATA>builder() .componentId(componentId) .event(event) .data(Optional.of(data)); if (ArrayUtils.isNotEmpty(tags)) { return builder.tags(Optional.of(ImmutableSet.copyOf(tags))).build(); } return builder.build(); } @Override public <DATA> ComponentEvent<DATA> componentEvent(@NonNull final Event<DATA> event, @NonNull final Class<DATA> eventDataType, @NonNull final DATA data, @NonNull final Throwable exception, String... tags) { final ComponentEventImpl.ComponentEventImplBuilder<DATA> builder = ComponentEventImpl.<DATA>builder() .componentId(componentId) .event(event) .data(Optional.of(data)) .exception(Optional.of(exception)); if (ArrayUtils.isNotEmpty(tags)) { return builder.tags(Optional.of(ImmutableSet.copyOf(tags))).build(); } return builder.build(); } }
package com.gaurav.main; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; import com.gaurav.entity.Address; /*import com.gaurav.entity.EmployeeDetails;*/ import com.gaurav.entity.EmployeeDetails; import com.gaurav.entity.Vehicle; public class Test { public static void main(String args[]) { System.out.println("exception occured"); EmployeeDetails ed=new EmployeeDetails(); ed.setUserName("gauravAwasthi"); Vehicle vc=new Vehicle(); vc.setVehicleName("maruti"); Vehicle vc1=new Vehicle(); vc1.setVehicleName("Jeep"); ed.getSvc().add(vc); ed.getSvc().add(vc1); SessionFactory sf=new Configuration().configure().buildSessionFactory(); Session session=sf.openSession(); session.beginTransaction(); session.save(ed); session.save(vc); session.save(vc1); session.getTransaction().commit(); session.close(); } }
package com.mavenmokito.test.appmokito; import static org.hamcrest.Matchers.empty; import static org.hamcrest.Matchers.hasItems; import static org.hamcrest.Matchers.haaSize; import static org.junit.Assert.assertThat; import static org.mockito.Mockito.atLeast; import static org.mockito.Mockito.never; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; import java.util.stream.IntStreams; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; import com.mavenmokito.test.appmokito.service.TaskService; import com.mavenmokito.test.appmokito.serviceimpl.AppServiceFindTask; /* * Service verification counter to stub * Creating mock objects with Mokito * - Class as well as interface Mocks * - Mocks are both * (your object gives indirect input to your test through Stubbing * and gathers indirect output through spying) * - Using Annotations instead of methods * @Mock * @RunWith(MockitoJUnitRunner.class) - The runner injects mocked beans */ @RunWith(MockitoJUnitRunner.class) public class AppServiceFindTaskMockWithHamcrest { // We can use @Mock to create and inject mocked instances without having to call Mockito.mock manually. @Mock TaskService service; // to inject mock fields into the tested object automatically. @InjectMocks AppServiceFindTask findTask; /* * Utilize already mocked object using @Mock and @InjectMock * Call function filterOverPreicate of AppServiceFindTask - passing Predicate * assertThat - returned List hasSize = 0 (hamcrest) */ @Test public void testServiceWithEmptyMock() { List<Integer> resultList = findTask.filterOverPreicate(x -> x < 3); assertThat(resultList, hasSize(0)); } /* * when findAllTask is called for TaskService - return List range 1..9 [excluding 10] * Call function filterOverPreicate of AppServiceFindTask - passing Predicate [x<3] * assertThat - expected List hasSize = 2 (i.e. hasItems 1 and 2) */ @Test public void testServiceWithWhenThenMock() { List<Integer> mokedList = IntStream.range(1, 10) .boxed() .collect(Collectors.toList()); when(service.findAllTask()).thenReturn(mokedList); List<Integer> resultList = findTask.filterOverPreicate(x -> x < 3); assertThat(resultList, hasItems(1, 2)); assertThat(resultList, hasSize(2)); } /* * when findAllTask is called for TaskService - return List range 1..9 [excluding 10] * Call function filterOverPreicate of AppServiceFindTask - passing Predicate [x%2 == 0] even numbers * assertTrue - expected List jasSize = 4 (i.e. 2, 4 , 6 and 8) */ @Test public void testServiceWithEvenNumberPredicateMock() { // @formatter: off List<Integer> list = IntStream.range(1, 10) .boxed() .collect(Collectors.toList()); // @formatter: on when(service.findAllTask()).thenReturn(list); List<Integer> resultList = findTask.filterOverPreicate(x -> x % 2 == 0); assertThat(resultList, hasItems(2, 4, 6, 8)); } /* * when findAllTask is called for TaskService - * return List range 1..9 [excluding 10] * return emptyList - passing null argument * Call function filterOverPreicate of AppServiceFindTask - passing Predicate [x%2 == 0] even numbers * assertThat - expected List hasSize = 4 (i.e. 2, 4 , 6 and 8) * * assertThat - expectedList is empty [hamcrest] */ @Test public void testServiceWithDataFollowedByNullListMock() { // @formatter:off List<Integer> list = IntStream.range(1, 10) .boxed() .collect(Collectors.toList()); // @formatter:on when(service.findAllTask()).thenReturn(list).thenReturn(null); List<Integer> resultList = findTask.filterOverPreicate(x -> x % 2 == 0); assertThat(resultList, hasItems(2, 4, 6, 8)); List<Integer> nullList = findTask.filterOverPreicate(x -> x % 2 == 0); assertThat(nullList, empty()); } }
/** * <copyright> * </copyright> * * $Id$ */ package simulator.srl.impl; import java.util.Collection; import org.eclipse.emf.common.notify.Notification; import org.eclipse.emf.common.util.EList; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.impl.ENotificationImpl; import org.eclipse.emf.ecore.impl.EObjectImpl; import org.eclipse.emf.ecore.util.EDataTypeUniqueEList; import simulator.srl.ResultsPackage; import simulator.srl.SimulationElement; /** * <!-- begin-user-doc --> * An implementation of the model object '<em><b>Simulation Element</b></em>'. * <!-- end-user-doc --> * <p> * The following features are implemented: * <ul> * <li>{@link simulator.srl.impl.SimulationElementImpl#getType <em>Type</em>}</li> * <li>{@link simulator.srl.impl.SimulationElementImpl#getParams <em>Params</em>}</li> * </ul> * </p> * * @generated */ public abstract class SimulationElementImpl extends EObjectImpl implements SimulationElement { /** * The default value of the '{@link #getType() <em>Type</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getType() * @generated * @ordered */ protected static final String TYPE_EDEFAULT = null; /** * The cached value of the '{@link #getType() <em>Type</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getType() * @generated * @ordered */ protected String type = TYPE_EDEFAULT; /** * The cached value of the '{@link #getParams() <em>Params</em>}' attribute list. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getParams() * @generated * @ordered */ protected EList<String> params; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected SimulationElementImpl() { super(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override protected EClass eStaticClass() { return ResultsPackage.Literals.SIMULATION_ELEMENT; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public String getType() { return type; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setType(String newType) { String oldType = type; type = newType; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, ResultsPackage.SIMULATION_ELEMENT__TYPE, oldType, type)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EList<String> getParams() { if (params == null) { params = new EDataTypeUniqueEList<String>(String.class, this, ResultsPackage.SIMULATION_ELEMENT__PARAMS); } return params; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public Object eGet(int featureID, boolean resolve, boolean coreType) { switch (featureID) { case ResultsPackage.SIMULATION_ELEMENT__TYPE: return getType(); case ResultsPackage.SIMULATION_ELEMENT__PARAMS: return getParams(); } return super.eGet(featureID, resolve, coreType); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @SuppressWarnings("unchecked") @Override public void eSet(int featureID, Object newValue) { switch (featureID) { case ResultsPackage.SIMULATION_ELEMENT__TYPE: setType((String)newValue); return; case ResultsPackage.SIMULATION_ELEMENT__PARAMS: getParams().clear(); getParams().addAll((Collection<? extends String>)newValue); return; } super.eSet(featureID, newValue); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void eUnset(int featureID) { switch (featureID) { case ResultsPackage.SIMULATION_ELEMENT__TYPE: setType(TYPE_EDEFAULT); return; case ResultsPackage.SIMULATION_ELEMENT__PARAMS: getParams().clear(); return; } super.eUnset(featureID); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public boolean eIsSet(int featureID) { switch (featureID) { case ResultsPackage.SIMULATION_ELEMENT__TYPE: return TYPE_EDEFAULT == null ? type != null : !TYPE_EDEFAULT.equals(type); case ResultsPackage.SIMULATION_ELEMENT__PARAMS: return params != null && !params.isEmpty(); } return super.eIsSet(featureID); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public String toString() { if (eIsProxy()) return super.toString(); StringBuffer result = new StringBuffer(super.toString()); result.append(" (type: "); result.append(type); result.append(", params: "); result.append(params); result.append(')'); return result.toString(); } } //SimulationElementImpl
package Customer; import java.awt.CardLayout; import java.awt.Color; import java.awt.Dimension; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Insets; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.sql.ResultSet; import javax.swing.JButton; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JTextField; import oracleDBA.CustomerOra; import Templates.JPanelTemplate; public class CheckReservationPanel extends JPanelTemplate { /** * */ private static final long serialVersionUID = 1L; private JTextField resCodeBox; private JLabel statusLabel; private GridBagConstraints gbc; public CheckReservationPanel(JPanel mainPanel) { super(mainPanel); this.setLayout(new GridBagLayout()); this.setBackground(Color.white); gbc = new GridBagConstraints(); setUpScreen(); } private void setUpScreen() { JLabel enterLabel = new JLabel("Enter your Reservation ID: "); JButton cancelButton = new JButton("Cancel"); JButton okButton = new JButton("OK"); resCodeBox = new JTextField(10); statusLabel = new JLabel(" "); gbc.insets = new Insets(3, 3, 3, 3); gbc.gridx = 1; gbc.gridy = 1; this.add(enterLabel, gbc); gbc.gridx = 2; gbc.gridy = 1; this.add(resCodeBox, gbc); gbc.gridx = 1; gbc.gridy = 2; gbc.anchor = GridBagConstraints.CENTER; statusLabel.setForeground(Color.red); this.add(statusLabel, gbc); gbc.gridx = 1; gbc.gridy = 3; this.add(cancelButton, gbc); cancelButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { statusLabel.setText(" "); CardLayout cardLayout = (CardLayout) parentCardPanel.getLayout(); cardLayout.show(parentCardPanel, "START"); } } ); gbc.gridx = 2; gbc.gridy = 3; this.add(okButton, gbc); okButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { changeToModify(); } } ); } private void changeToModify() { CustomerOra ora = new CustomerOra(); Reservation res = ora.getReservation(resCodeBox.getText()); if (res != null) { ModifyPanel modify = new ModifyPanel(parentCardPanel); modify.setOriginalData(res); parentCardPanel.add(modify, "MODIFYRES"); CardLayout cardLayout = (CardLayout) parentCardPanel.getLayout(); cardLayout.show(parentCardPanel, "MODIFYRES"); statusLabel.setText(" "); } else { statusLabel.setText("Invalid Reservation ID, try again!"); } } public ResultSet getReservation() { ResultSet resData = null; return resData; } }
package com.cinema.biz.model; import com.cinema.biz.model.base.TSimType; public class SimType extends TSimType { }
package beakjoon11; import java.util.Arrays; import java.util.Scanner; public class Hw_2447 { static char[][] board; public static void main(String[] args) { Scanner sc = new Scanner(System.in); int N=sc.nextInt(); board = new char[N][N]; for(int i=0; i<N; i++) { Arrays.fill(board[i], ' '); } makeStar( 0, 0,N); for(int i=0; i<N; i++) { System.out.println(board[i]); } } public static void makeStar(int x, int y, int n) { if(n==1) { board[x][y]='*'; return; } int k=n/3; for(int i=0; i<3; i++) { for(int j=0; j<3; j++) { //i=0 j=1 k=3 //i=0 j=2 k=3 //i=1 j=0 k=3 if(i==1&&j==1) { continue; } makeStar(x+k*i, y+k*j, k); //0 3 3 -> 0 3 1 //0 6 3 -> 0 6 1 //3 0 3 -> 3 0 1 } } } } /*************************** makeStar(0,0,1) 의 결과 -> N이 3일때 *** * * *** makeStar(0,0,3) 의 결과 -> N이 9일때 ********* * ** ** * ********* *** *** * * * * *** *** ********* * ** ** * ********* **************************/
package de.wiltherr.ws2812fx.ui.views.live; import com.vaadin.data.Binder; import com.vaadin.data.StatusChangeListener; import com.vaadin.data.provider.ListDataProvider; import com.vaadin.event.selection.MultiSelectionListener; import com.vaadin.shared.ui.slider.SliderOrientation; import com.vaadin.ui.CheckBoxGroup; import com.vaadin.ui.ComboBox; import com.vaadin.ui.Slider; import com.vaadin.ui.VerticalLayout; import de.wiltherr.ws2812fx.Mode; import de.wiltherr.ws2812fx.Segment; import de.wiltherr.ws2812fx.SegmentConfig; import de.wiltherr.ws2812fx.WS2812FX; import de.wiltherr.ws2812fx.ui.WS2812FXStripModel; import de.wiltherr.ws2812fx.ui.components.WS2812ColorPicker; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Arrays; import java.util.concurrent.atomic.AtomicBoolean; import java.util.stream.Collectors; import java.util.stream.IntStream; public class LiveModeViewImpl extends VerticalLayout implements LiveModeView { private static final Logger log = LoggerFactory.getLogger(LiveModeViewImpl.class); private final Binder<SegmentConfig> liveSegmentConfigBinder = new Binder<>(); private final CheckBoxGroup<SegmentSelectItem> segmentSelectCheckBoxGroup; private final Binder<AtomicBoolean> segmentationModeBinder = new Binder<>(); Binder<WS2812FXStripModel> ws2812FXStripBinder = new Binder<>(); public LiveModeViewImpl() { segmentationModeBinder.setBean(new AtomicBoolean(false)); segmentSelectCheckBoxGroup = new CheckBoxGroup<>("Segment Auswahl"); /********* *************************/ ComboBox<Mode> modeComboBox = new ComboBox<>(); modeComboBox.setCaption("Mode"); modeComboBox.setItemCaptionGenerator(Mode::getModeName); modeComboBox.setTextInputAllowed(false); modeComboBox.setDataProvider(new ListDataProvider<>(Arrays.asList(Mode.values()))); liveSegmentConfigBinder.bind(modeComboBox, SegmentConfig::getMode, SegmentConfig::setMode); Slider speedValueSlider = new Slider(0, 100, 1); speedValueSlider.setCaption("Speed"); speedValueSlider.setOrientation(SliderOrientation.HORIZONTAL); speedValueSlider.setWidth(600, Unit.PIXELS); liveSegmentConfigBinder.forField(speedValueSlider).withConverter(sliderValue -> { int absolut_speed = (int) ((WS2812FX.SPEED_MAX / speedValueSlider.getMax()) * sliderValue); int speed = (int) (WS2812FX.SPEED_MAX - absolut_speed); if (speed < WS2812FX.SPEED_MIN) speed = WS2812FX.SPEED_MIN; return speed; }, ws2812fxValue -> { double sliderValue = ((WS2812FX.SPEED_MAX - ws2812fxValue) * speedValueSlider.getMax()) / WS2812FX.SPEED_MAX; return sliderValue; }).bind(SegmentConfig::getSpeed, SegmentConfig::setSpeed); VerticalLayout colorPickersLayout = new VerticalLayout(); colorPickersLayout.setMargin(false); IntStream.range(0, 3).forEach(i -> { //TODO replace range end (3) with static config variable WS2812ColorPicker ws2812ColorPicker = new WS2812ColorPicker(); liveSegmentConfigBinder.forField(ws2812ColorPicker).bind(segmentConfig -> segmentConfig.getColors().get(i), (segmentConfig, color) -> segmentConfig.getColors().set(i, color)); colorPickersLayout.addComponent(ws2812ColorPicker); }); /************ *********************/ this.addComponents(segmentSelectCheckBoxGroup, modeComboBox, speedValueSlider, colorPickersLayout); this.setSizeFull(); this.setMargin(false); } @Override public void setListener(LiveModeView.Listener listener) { liveSegmentConfigBinder.addStatusChangeListener((StatusChangeListener) event -> { listener.onLiveSegmentConfigChange(); }); segmentSelectCheckBoxGroup.addSelectionListener((MultiSelectionListener<SegmentSelectItem>) event -> { listener.onSegmentSelect(event.getAddedSelection().stream().map(segmentSelectItem -> (Segment) segmentSelectItem).collect(Collectors.toSet())); listener.onSegmentUnselect(event.getRemovedSelection().stream().map(segmentSelectItem -> (Segment) segmentSelectItem).collect(Collectors.toSet())); }); ws2812FXStripBinder.addStatusChangeListener(event -> log.error("ws2812fxbinder status changed " + ws2812FXStripBinder.getBean().getSegments().stream().map(Segment::toString).collect(Collectors.joining("\n", "[\n", "}"))) ); } @Override public void setWS2812FXModel(WS2812FXStripModel ws2812FXStripModel) { ws2812FXStripBinder.setBean(ws2812FXStripModel); if (liveSegmentConfigBinder.getBean() == null && ws2812FXStripModel.getSegments().size() > 0) { //init work configuration setLiveSegmentConfigModel(ws2812FXStripModel.getSegment(0).getConfig().copy()); } segmentSelectCheckBoxGroup.setItems(ws2812FXStripBinder.getBean().getSegments().stream().map(SegmentSelectItem::new).collect(Collectors.toList())); } @Override public void setLiveSegmentConfigModel(SegmentConfig segmentConfig) { liveSegmentConfigBinder.setBean(segmentConfig); } public class SegmentSelectItem extends Segment { public SegmentSelectItem(Segment segment) { super(segment.getIndex(), segment.getStart(), segment.getStop(), segment.getConfig()); } @Override public String toString() { return "Segment " + this.getIndex() + " (" + this.getStart() + " - " + this.getStop() + ")"; } @Override public boolean equals(Object o) { return super.equals(o); } @Override public int hashCode() { return super.hashCode(); } @Override public int compareTo(Segment o) { return super.compareTo(o); } } }
package com.openclassrooms.apisafetynet; import static org.hamcrest.CoreMatchers.containsString; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import java.nio.charset.Charset; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.header; import org.json.JSONObject; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import org.mockito.Mockito; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.test.web.servlet.MockMvc; import org.springframework.util.LinkedMultiValueMap; import org.springframework.util.MultiValueMap; import org.springframework.http.MediaType; import com.openclassrooms.apisafetynet.controller.FireStationController; import com.openclassrooms.apisafetynet.controller.MedicalRecordController; import com.openclassrooms.apisafetynet.service.FireStationService; import com.openclassrooms.apisafetynet.service.MedicalRecordService; @WebMvcTest(controllers = MedicalRecordController.class) public class MedicalRecordControllerTest { @Autowired private MockMvc mockMvc; @MockBean private MedicalRecordService mS; static int x; String random = "random"; //JSONObject json = Mockito.mock(JSONObject.class); //public static final MediaType APPLICATION_JSON_UTF8 = new MediaType(MediaType.JSON_UTF_8.type(), MediaType.JSON_UTF_8.subtype(), MediaType.JSON_UTF_8.parameters()); // //public static final MediaType APPLICATION_JSON_UTF82 = new MediaType(null, null, null); @BeforeAll static public void setup() { x = (int) (Math.random()*((10-1)+1))+1; // nombre entier au hasard - double x = (int)(Math.random()*((max-min)+1))+min; } //---------- Méthodes de base -------- @Test public void testDeleteMedicalRecord() throws Exception { mockMvc.perform( delete("/medicalrecord/"+ random)).andExpect(status().isOk()); } @Test public void testGetMedicalRecords() throws Exception{ mockMvc.perform(get("/medicalrecord")).andExpect(status().isOk()); } // Problème avec ce test, retourne un code 204 pcq il considère que p (de la méthode original est null)... // Mais je me demande pourquoi pour le test d'une personne il fait ça mais pas quand il y a plusieurs personnnes... @Test public void testPostMedicalRecord() throws Exception{ mockMvc.perform( post("/medicalrecord") .contentType(MediaType.APPLICATION_JSON) .content("{\"adress\":\"sqqsdf\"}")) //.content("{\""+Mockito.anyString()+"\"}")) .andExpect(status(). isCreated()); // perform(post("/myapi").contentType(MediaType.APPLICATION_JSON).content("{\"mykey\":\"myvalue\"}")) } @Test public void testPostMedicalRecords() throws Exception{ mockMvc.perform( post("/medicalrecords") .contentType(MediaType.APPLICATION_JSON) .content("[{\"address\":\"sqqsdf\", \"station\":"+5+"},\n" + "{\"address\":\"rqzed\", \"station\":"+5+" }]")) //.content("{\""+Mockito.anyString()+"\":\""+Mockito.anyString()+"\"}]")) .andExpect(status(). isCreated()); // perform(post("/myapi").contentType(MediaType.APPLICATION_JSON).content("{\"mykey\":\"myvalue\"}")) } @Test public void testPutMedicalRecord() throws Exception{ mockMvc.perform( put("/medicalrecord/"+x) .contentType(MediaType.APPLICATION_JSON) .content("{\""+random+"\":\""+random+"\"}")) .andExpect(status().isOk()); //put("/person/"+x).contentType(MediaType.JSON_UTF_8.subtype()).content(("{\"mykey\":\"myvalue\"}"))).andExpect(status().isOk()); // perform(post("/myapi").contentType(MediaType.APPLICATION_JSON).content("{\"mykey\":\"myvalue\"}")) } }
package com.javabeans.home; import javax.faces.bean.ManagedBean; @ManagedBean public class HomeProducts { private int product_id; private String product_name; private float price; private String product_image; private String product_category; private String description; public String getProduct_category() { return product_category; } public void setProduct_category(String product_category) { this.product_category = product_category; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public HomeProducts() { } public HomeProducts(int product_id, String product_name, float price, String product_image) { this.product_id = product_id; this.product_name = product_name; this.price = price; this.product_image = product_image; } public int getProduct_id() { return product_id; } public void setProduct_id(int product_id) { this.product_id = product_id; } public String getProduct_name() { return product_name; } public void setProduct_name(String product_name) { this.product_name = product_name; } public float getPrice() { return price; } public void setPrice(float price) { this.price = price; } public String getProduct_image() { return product_image; } public void setProduct_image(String product_image) { this.product_image = product_image; } }
/* * Copyright 2002-2022 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 * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.web.reactive.result.view; import java.beans.PropertyEditor; import java.util.Arrays; import java.util.List; import org.springframework.beans.BeanWrapper; import org.springframework.beans.PropertyAccessorFactory; import org.springframework.context.NoSuchMessageException; import org.springframework.lang.Nullable; import org.springframework.util.ObjectUtils; import org.springframework.util.StringUtils; import org.springframework.validation.BindingResult; import org.springframework.validation.Errors; import org.springframework.validation.ObjectError; import org.springframework.web.util.HtmlUtils; /** * Simple adapter to expose the bind status of a field or object. * Set as a variable by FreeMarker macros and other tag libraries. * * <p>Obviously, object status representations (i.e. errors at the object level * rather than the field level) do not have an expression and a value but only * error codes and messages. For simplicity's sake and to be able to use the same * tags and macros, the same status class is used for both scenarios. * * @author Rossen Stoyanchev * @author Juergen Hoeller * @since 5.0 * @see RequestContext#getBindStatus */ public class BindStatus { private final RequestContext requestContext; private final String path; private final boolean htmlEscape; @Nullable private final String expression; @Nullable private final Errors errors; private final String[] errorCodes; @Nullable private String[] errorMessages; @Nullable private List<? extends ObjectError> objectErrors; @Nullable private Object value; @Nullable private Class<?> valueType; @Nullable private Object actualValue; @Nullable private PropertyEditor editor; @Nullable private BindingResult bindingResult; /** * Create a new BindStatus instance, representing a field or object status. * @param requestContext the current RequestContext * @param path the bean and property path for which values and errors * will be resolved (e.g. "customer.address.street") * @param htmlEscape whether to HTML-escape error messages and string values * @throws IllegalStateException if no corresponding Errors object found */ public BindStatus(RequestContext requestContext, String path, boolean htmlEscape) throws IllegalStateException { this.requestContext = requestContext; this.path = path; this.htmlEscape = htmlEscape; // determine name of the object and property String beanName; int dotPos = path.indexOf('.'); if (dotPos == -1) { // property not set, only the object itself beanName = path; this.expression = null; } else { beanName = path.substring(0, dotPos); this.expression = path.substring(dotPos + 1); } this.errors = requestContext.getErrors(beanName, false); if (this.errors != null) { // Usual case: A BindingResult is available as request attribute. // Can determine error codes and messages for the given expression. // Can use a custom PropertyEditor, as registered by a form controller. if (this.expression != null) { if ("*".equals(this.expression)) { this.objectErrors = this.errors.getAllErrors(); } else if (this.expression.endsWith("*")) { this.objectErrors = this.errors.getFieldErrors(this.expression); } else { this.objectErrors = this.errors.getFieldErrors(this.expression); this.value = this.errors.getFieldValue(this.expression); this.valueType = this.errors.getFieldType(this.expression); if (this.errors instanceof BindingResult br) { this.bindingResult = br; this.actualValue = this.bindingResult.getRawFieldValue(this.expression); this.editor = this.bindingResult.findEditor(this.expression, null); } else { this.actualValue = this.value; } } } else { this.objectErrors = this.errors.getGlobalErrors(); } this.errorCodes = initErrorCodes(this.objectErrors); } else { // No BindingResult available as request attribute: // Probably forwarded directly to a form view. // Let's do the best we can: extract a plain target if appropriate. Object target = requestContext.getModelObject(beanName); if (target == null) { throw new IllegalStateException( "Neither BindingResult nor plain target object for bean name '" + beanName + "' available as request attribute"); } if (this.expression != null && !"*".equals(this.expression) && !this.expression.endsWith("*")) { BeanWrapper bw = PropertyAccessorFactory.forBeanPropertyAccess(target); this.value = bw.getPropertyValue(this.expression); this.valueType = bw.getPropertyType(this.expression); this.actualValue = this.value; } this.errorCodes = new String[0]; this.errorMessages = new String[0]; } if (htmlEscape && this.value instanceof String text) { this.value = HtmlUtils.htmlEscape(text); } } /** * Extract the error codes from the ObjectError list. */ private static String[] initErrorCodes(List<? extends ObjectError> objectErrors) { String[] errorCodes = new String[objectErrors.size()]; for (int i = 0; i < objectErrors.size(); i++) { ObjectError error = objectErrors.get(i); errorCodes[i] = error.getCode(); } return errorCodes; } /** * Return the bean and property path for which values and errors * will be resolved (e.g. "customer.address.street"). */ public String getPath() { return this.path; } /** * Return a bind expression that can be used in HTML forms as input name * for the respective field, or {@code null} if not field-specific. * <p>Returns a bind path appropriate for resubmission, e.g. "address.street". * Note that the complete bind path as required by the bind tag is * "customer.address.street", if bound to a "customer" bean. */ @Nullable public String getExpression() { return this.expression; } /** * Return the current value of the field, i.e. either the property value * or a rejected update, or {@code null} if not field-specific. * <p>This value will be an HTML-escaped String if the original value * already was a String. */ @Nullable public Object getValue() { return this.value; } /** * Get the '{@code Class}' type of the field. Favor this instead of * '{@code getValue().getClass()}' since '{@code getValue()}' may * return '{@code null}'. */ @Nullable public Class<?> getValueType() { return this.valueType; } /** * Return the actual value of the field, i.e. the raw property value, * or {@code null} if not available. */ @Nullable public Object getActualValue() { return this.actualValue; } /** * Return a suitable display value for the field, i.e. the stringified * value if not null, and an empty string in case of a null value. * <p>This value will be an HTML-escaped String if the original value * was non-null: the {@code toString} result of the original value * will get HTML-escaped. */ public String getDisplayValue() { if (this.value instanceof String displayValue) { return displayValue; } if (this.value != null) { return (this.htmlEscape ? HtmlUtils.htmlEscape(this.value.toString()) : this.value.toString()); } return ""; } /** * Return if this status represents a field or object error. */ public boolean isError() { return (this.errorCodes.length > 0); } /** * Return the error codes for the field or object, if any. * Returns an empty array instead of null if none. */ public String[] getErrorCodes() { return this.errorCodes; } /** * Return the first error codes for the field or object, if any. */ public String getErrorCode() { return (!ObjectUtils.isEmpty(this.errorCodes) ? this.errorCodes[0] : ""); } /** * Return the resolved error messages for the field or object, * if any. Returns an empty array instead of null if none. */ public String[] getErrorMessages() { return initErrorMessages(); } /** * Return the first error message for the field or object, if any. */ public String getErrorMessage() { String[] errorMessages = initErrorMessages(); return (errorMessages.length > 0 ? errorMessages[0] : ""); } /** * Return an error message string, concatenating all messages * separated by the given delimiter. * @param delimiter separator string, e.g. ", " or "<br>" * @return the error message string */ public String getErrorMessagesAsString(String delimiter) { return StringUtils.arrayToDelimitedString(initErrorMessages(), delimiter); } /** * Extract the error messages from the ObjectError list. */ private String[] initErrorMessages() throws NoSuchMessageException { if (this.errorMessages == null) { if (this.objectErrors != null) { this.errorMessages = new String[this.objectErrors.size()]; for (int i = 0; i < this.objectErrors.size(); i++) { ObjectError error = this.objectErrors.get(i); this.errorMessages[i] = this.requestContext.getMessage(error, this.htmlEscape); } } else { this.errorMessages = new String[0]; } } return this.errorMessages; } /** * Return the Errors instance (typically a BindingResult) that this * bind status is currently associated with. * @return the current Errors instance, or {@code null} if none * @see org.springframework.validation.BindingResult */ @Nullable public Errors getErrors() { return this.errors; } /** * Return the PropertyEditor for the property that this bind status * is currently bound to. * @return the current PropertyEditor, or {@code null} if none */ @Nullable public PropertyEditor getEditor() { return this.editor; } /** * Find a PropertyEditor for the given value class, associated with * the property that this bound status is currently bound to. * @param valueClass the value class that an editor is needed for * @return the associated PropertyEditor, or {@code null} if none */ @Nullable public PropertyEditor findEditor(Class<?> valueClass) { return (this.bindingResult != null ? this.bindingResult.findEditor(this.expression, valueClass) : null); } @Override public String toString() { StringBuilder sb = new StringBuilder("BindStatus: "); sb.append("expression=[").append(this.expression).append("]; "); sb.append("value=[").append(this.value).append(']'); if (!ObjectUtils.isEmpty(this.errorCodes)) { sb.append("; errorCodes=").append(Arrays.asList(this.errorCodes)); } return sb.toString(); } }
/* ------------------------------------------------------------------------------ * 软件名称:BB语音 * 公司名称:乐多科技 * 开发作者:Yongchao.Yang * 开发时间:2016年3月4日/2016 * All Rights Reserved 2012-2015 * ------------------------------------------------------------------------------ * 注意:本内容均来自乐多科技,仅限内部交流使用,未经过公司许可 禁止转发 * ------------------------------------------------------------------------------ * prj-name:com.ace.database * fileName:Gift.java * ------------------------------------------------------------------------------- */ package com.rednovo.ace.entity; import java.math.BigDecimal; /** * @author yongchao.Yang/2016年3月4日 */ public class Gift implements Comparable<Gift> { private String id; private String name; private String pic; private BigDecimal sendPrice; private BigDecimal transformPrice; private String isCombined; private int sortId; private String status; private String createTime; private String schemaId; private String type; 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 getPic() { return pic; } public void setPic(String pic) { this.pic = pic; } public BigDecimal getSendPrice() { return sendPrice; } public void setSendPrice(BigDecimal sendPrice) { this.sendPrice = sendPrice; } public BigDecimal getTransformPrice() { return transformPrice; } public void setTransformPrice(BigDecimal transformPrice) { this.transformPrice = transformPrice; } public String getIsCombined() { return isCombined; } public void setIsCombined(String isCombined) { this.isCombined = isCombined; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public String getCreateTime() { return createTime; } public void setCreateTime(String createTime) { this.createTime = createTime; } public String getSchemaId() { return schemaId; } public void setSchemaId(String schemaId) { this.schemaId = schemaId; } public int getSortId() { return sortId; } public void setSortId(int sortId) { this.sortId = sortId; } @Override public int compareTo(Gift o) { return Integer.valueOf(sortId).compareTo(Integer.valueOf(o.sortId)); } /** * */ public Gift() { } public String getType() { return type; } public void setType(String type) { this.type = type; } }
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.bk.rs.dao; import com.bk.rs.entity.Person; import com.bk.rs.entity.Student; import java.util.ArrayList; /** * * @author bkawan * @date Feb 27, 2016 * @time 5:34:21 PM */ // interface to acess person object public interface RegistrationDAO { void register(Person person); boolean delete(int id); Person findByID(int id); ArrayList<Person> findAll(); ArrayList<Person> findByString(String param); void deleteAll(); ArrayList<Person> findAllTeachers(); ArrayList<Person> findAllStudents(); }
package com.example.ezyfood3.views; import android.os.Bundle; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.fragment.app.Fragment; import androidx.lifecycle.ViewModelProvider; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.example.ezyfood3.R; import com.example.ezyfood3.databinding.FragmentDetailBinding; import com.example.ezyfood3.viewmodels.DrinkViewModel; public class DetailFragment extends Fragment { FragmentDetailBinding fragmentDetailBinding; DrinkViewModel drinkViewModel; public DetailFragment() { // Required empty public constructor } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment fragmentDetailBinding = FragmentDetailBinding.inflate(inflater,container,false); return fragmentDetailBinding.getRoot(); } @Override public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); drinkViewModel = new ViewModelProvider(requireActivity()).get(DrinkViewModel.class); fragmentDetailBinding.setDrinkViewModel(drinkViewModel); } }
package com.sha.springbootmongo.projection; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import org.springframework.data.annotation.Id; /** * @author sa * @date 1/10/21 * @time 12:04 PM */ @Data @NoArgsConstructor @AllArgsConstructor public class CountryAggregation { private @Id String country; private Long total; }
package com.miyatu.tianshixiaobai.activities.search; import android.app.Activity; import android.content.Intent; import android.view.View; import android.widget.Button; import com.miyatu.tianshixiaobai.R; import com.miyatu.tianshixiaobai.activities.BaseActivity; import com.miyatu.tianshixiaobai.activities.homepage.ViewOrderDetailsActivity; public class PayResultActivity extends BaseActivity { private Button backToHomePage; private Button viewOrder; public static void startActivity(Activity activity){ Intent intent = new Intent(activity, PayResultActivity.class); activity.startActivity(intent); } @Override protected int getLayoutId() { return R.layout.activity_pay_result; } @Override protected void initView() { initTitle(); backToHomePage = findViewById(R.id.backToHomePage); viewOrder = findViewById(R.id.viewOrder); } @Override protected void initData() { } @Override protected void initEvent() { backToHomePage.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { // Intent intent = new Intent(PayResultActivity.this, HotProjectActivity.class); // intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP|Intent.FLAG_ACTIVITY_NEW_TASK); // startActivity(intent); // PayResultActivity.this.finish(); } }); viewOrder.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { ViewOrderDetailsActivity.startActivity(PayResultActivity.this); } }); } @Override protected void updateView() { } @Override public void initTitle() { super.initTitle(); setTitleCenter("支付结果"); setImageRight(R.mipmap.icon_share1); } }
package com.netcracker.app.domain.shop.controllers; import com.netcracker.app.domain.shop.services.TechService; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; @Controller @RequestMapping("/techs") public class TechsController { private final TechService service; public TechsController(TechService service) { this.service = service; } @GetMapping public String techs(@RequestParam(required = false) String filter, Model model) { if (filter != null && !filter.isEmpty()) { model.addAttribute("techs", service.getAllByName(filter)); } else { model.addAttribute("techs", service.getAll()); } model.addAttribute("filter", filter); return "techs"; } @GetMapping("/{id}") public String tech(@PathVariable("id") int id, Model model) { model.addAttribute("tech", service.getById(id)); return "tech"; } }
package com.honor.mybatis.entity; public class Order { private Integer id; private String orderName; private User user; private Student student; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getOrderName() { return orderName; } public void setOrderName(String orderName) { this.orderName = orderName; } public User getUser() { return user; } public void setUser(User user) { this.user = user; } public Student getStudent() { return student; } public void setStudent(Student student) { this.student = student; } @Override public String toString() { return "Order{" + "id=" + id + ", orderName='" + orderName + '\'' + ", user=" + user + ", student=" + student + '}'; } }
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package stockhelper; import org.jsoup.Jsoup; import org.jsoup.nodes.*; import java.net.URL; import java.net.MalformedURLException; import java.io.*; import org.jsoup.select.*; import structure.Stock; /** * This class test the parser of jsoup. The parser is resposible to extract stock information from http://www.finanzen.net/bilanz_guv/Wirecard * @author GGTTF */ public class testParser { public void testParser(){ String wirecardURLString = "http://www.finanzen.net/bilanz_guv/Wirecard"; //String wirecardURLString = "http://www.google.com"; /* URL wirecardURL = null; try{ wirecardURL = new URL(wirecardURLString); }catch(MalformedURLException e){ e.printStackTrace(); } */ Document doc = null; try{ doc = Jsoup.connect(wirecardURLString).get(); }catch(IOException e){ e.printStackTrace();; } Element bguvFormElement = doc.getElementById("bguvform"); Elements mainElementList = bguvFormElement.getElementsByClass("main"); if(mainElementList.isEmpty()) throw new IllegalArgumentException("No main class found"); // Get the list of "content tableQuote" elements. Elements contentBoxTableQuoteElementList = mainElementList.get(0).getElementsByClass("contentBox tableQuotes"); // Check the number of elements in contentTableQuoteElementList if(contentBoxTableQuoteElementList.isEmpty()) throw new IllegalArgumentException("No content tableQuote class element found."); // The first "content tableQuote" element contains "Ergebnis je Aktie (unverwaessert, nach Steurn)", // "Ergebnis je Aktie (verwaessert, nach Steurn)", "Dividende je Aktie". Element firstContentTableQuote = contentBoxTableQuoteElementList.get(0); //Get the class content elements. Elements contentElementList = firstContentTableQuote.getElementsByClass("content"); if(contentElementList.isEmpty()) throw new IllegalArgumentException("No content class element found."); // Get the table elements. Elements tableElementList = contentElementList.get(0).getElementsByTag("table"); if(tableElementList.isEmpty()) throw new IllegalArgumentException ("No table tag element found."); // Get the tbody elements. Elements tbodyElementList = tableElementList.get(0).getElementsByTag("tbody"); if(tbodyElementList.isEmpty()) throw new IllegalArgumentException("No tbody tag element found."); // Get the tr elements. Elements trElementList = tbodyElementList.get(0).getElementsByTag("tr"); if(trElementList.isEmpty()) throw new IllegalArgumentException("No tr tag element found."); //The first row contains the years Elements yearList = trElementList.get(0).getElementsByTag("th"); if(yearList.isEmpty()) throw new IllegalArgumentException("No th tag element found."); // Output the years. for(int i=0;i<yearList.size();i++) System.out.println("Year: "+yearList.get(i).text()); //The second row contains the "Ergebnis je Aktie (unverwässert, nach Steurn)" Elements eps1ElementList = trElementList.get(1).getElementsByTag("td"); //Output the "Ergebnis je Aktie (unverwässert, nach Steurn)" for(int i=0;i<eps1ElementList.size();i++) System.out.println("Ergebnis je Aktie (unverwaessert, nach Steurn): "+eps1ElementList.get(i).text()); //The third row contains the "Ergebnis je Aktie (verwässert, nach Steurn)" Elements eps2ElementList = trElementList.get(2).getElementsByTag("td"); //Output the "Ergebnis je Aktie (verwässert, nach Steurn)" for(int i=0;i<eps2ElementList.size();i++) System.out.println("Ergebnis je Aktie (verwaessert, nach Steurn): "+eps2ElementList.get(i).text()); } public void testExtractRevenue(){ Stock s = new Stock(); String url = "http://www.finanzen.net/bilanz_guv/Wirecard"; //url = "http://www.google.com"; s.parseWebpage(url); float[] revenue = s.getRevenue(); for(int i=0;i<revenue.length;i++) System.out.println(revenue[i]); } public static void main(String args[]){ new testParser().testExtractRevenue(); } }
package codewars; import java.util.LinkedList; import java.util.List; public class UpsideDown { public UpsideDown() { // TODO Auto-generated constructor stub } public static int solve(int x, int y) { int countUpdown = 0; for (int i=x; i < y; i++) { String currNum = String.valueOf(i); String currNumUp = currNum.replaceAll("[23457]", ""); if (!currNum.equals(currNumUp)) {continue;} String reverse = new StringBuilder().append(currNum).reverse().toString(); reverse = reverse.replaceAll("9", "d"); reverse = reverse.replaceAll("6", "9"); reverse = reverse.replaceAll("d", "6"); if (currNum.equals(reverse)) { System.out.println(currNum); countUpdown++;} } return countUpdown; } public static List<Integer> primeNumbersBruteForce(int n) { List<Integer> primeNumbers = new LinkedList<>(); if (n >= 2) { primeNumbers.add(2); } for (int i = 3; i <= n; i += 2) { if (isPrimeBruteForce(i)) { primeNumbers.add(i); } } return primeNumbers; } private static boolean isPrimeBruteForce(int number) { for (int i = 2; i*i < number; i++) { if (number % i == 0) { return false; } } return true; } public withoutPrime public static void main(String[] args) { // TODO Auto-generated method stub System.out.println(solve(100,1000)); } }
/* * 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 listya */ public class Literacy implements Comparable<Literacy> { private String country; private String year; private String gender; private double number; public Literacy(String country, String year, String gender, double number) { this.country = country; this.year = year; this.gender = gender; this.number = number; } public String getCountry() { return country; } public String getYear() { return year; } public String getGender() { return gender; } public double getNumber() { return number; } @Override public int compareTo(Literacy o) { if (this.getNumber() > o.getNumber()) { return 1; } else if (this.getNumber() == o.getNumber()) { return 0; } return -1; } public String toString() { return this.country + " (" + this.year +"), " + this.gender + ", " + this.number; } }
import java.awt.Graphics; import java.lang.Math; public class EntityEnemy4 extends Enemy { private static int numberOfInstances = 0; private static String[] paths; private static int[] indexs; private int sprite = 0; public EntityEnemy4(GameSprites s, int w, int h, Sounds sounds) { super((int)((w - 32) * Math.random()), h + 40, -6, 'y', 40, 30, 2, 28, 1, 40, s, sounds); if(numberOfInstances == 0) { paths = new String[3]; paths[0] = "sprites\\enemy4_1.gif"; paths[1] = "sprites\\enemy4_2.gif"; paths[2] = "sprites\\enemy4_3.gif"; indexs = new int[paths.length]; for(int i = 0; i < paths.length; i++) { indexs[i] = s.loadImage(paths[i]); } } numberOfInstances++; } public void draw(Graphics g, GameSprites s, int h, int w) { if(exploding) { drawExplosion(g, s); } calculateLocation(); s.draw(g, xLocation, yLocation, indexs[sprite]); sprite++; if(sprite == 3) { sprite = 0; } } public void offScreen(int h, int w) { if(yLocation < -40) { yLocation = h + 40; xLocation = (int)((w - 32) * Math.random()); } } }
package com.defalt.lelangonline.ui.items.add; import android.Manifest; import android.app.Activity; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.pm.PackageManager; import android.graphics.Rect; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.view.MotionEvent; import android.view.View; import android.view.inputmethod.InputMethodManager; import android.widget.EditText; import android.widget.ImageView; import android.widget.Toast; import androidx.annotation.NonNull; import androidx.appcompat.app.AlertDialog; import androidx.appcompat.app.AppCompatActivity; import androidx.appcompat.widget.Toolbar; import androidx.cardview.widget.CardView; import com.basgeekball.awesomevalidation.AwesomeValidation; import com.basgeekball.awesomevalidation.ValidationStyle; import com.basgeekball.awesomevalidation.utility.custom.SimpleCustomValidation; import com.bumptech.glide.Glide; import com.defalt.lelangonline.R; import com.defalt.lelangonline.data.RestApi; import com.defalt.lelangonline.data.login.LoginRepository; import com.defalt.lelangonline.ui.SharedFunctions; import com.theartofdev.edmodo.cropper.CropImage; import com.theartofdev.edmodo.cropper.CropImageView; import org.json.JSONException; import org.json.JSONObject; import java.io.File; import java.io.IOException; import java.util.Objects; import me.abhinay.input.CurrencyEditText; import okhttp3.MediaType; import okhttp3.MultipartBody; import okhttp3.RequestBody; import okhttp3.ResponseBody; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; public class ItemsAddActivity extends AppCompatActivity { private boolean isImageEmpty = true; private Uri mCropImageUri; private Activity mActivity; private Context mContext; private EditText nameEditText; private EditText descEditText; private EditText categoryEditText; private CurrencyEditText valueEditText; private ImageView thumbImageView; private CardView progressBarCard; private AwesomeValidation mAwesomeValidation; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_add_item); Toolbar toolbar = findViewById(R.id.toolbar); setSupportActionBar(toolbar); mActivity = ItemsAddActivity.this; mContext = getApplicationContext(); nameEditText = findViewById(R.id.name); categoryEditText = findViewById(R.id.category); valueEditText = SharedFunctions.setEditTextCurrency((CurrencyEditText) findViewById(R.id.value)); descEditText = findViewById(R.id.description); thumbImageView = findViewById(R.id.thumbnail); progressBarCard = findViewById(R.id.progressCard); SimpleCustomValidation validationEmpty = new SimpleCustomValidation() { @Override public boolean compare(String input) { return input.length() > 0; } }; mAwesomeValidation = new AwesomeValidation(ValidationStyle.BASIC); mAwesomeValidation.addValidation(mActivity, R.id.name, validationEmpty, R.string.form_invalid_item_name); mAwesomeValidation.addValidation(mActivity, R.id.category, validationEmpty, R.string.form_invalid_item_cat); mAwesomeValidation.addValidation(mActivity, R.id.value, validationEmpty, R.string.form_invalid_item_val); mAwesomeValidation.addValidation(mActivity, R.id.description, validationEmpty, R.string.form_invalid_item_desc); enableImageAdd(); } private void enableImageAdd() { thumbImageView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (CropImage.isExplicitCameraPermissionRequired(mContext)) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { requestPermissions(new String[]{Manifest.permission.CAMERA}, CropImage.CAMERA_CAPTURE_PERMISSIONS_REQUEST_CODE); } } else { CropImage.startPickImageActivity(mActivity); } } }); } private void enableImageRemove() { thumbImageView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { final CharSequence[] options = {"Hapus"}; final AlertDialog.Builder imgDialog = new AlertDialog.Builder(mActivity); imgDialog.setTitle(R.string.item_post_img_hint); imgDialog.setItems(options, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int item) { if (options[item].equals("Hapus")) { thumbImageView.setImageResource(R.drawable.placeholder_image); isImageEmpty = true; mCropImageUri = null; enableImageAdd(); } } }); imgDialog.show(); } }); } private void disableImage() { thumbImageView.setOnClickListener(null); } private void startCropImageActivity(Uri imageUri) { CropImage.activity(imageUri) .setFixAspectRatio(true) .setAspectRatio(16,9) .setRequestedSize(800, 450, CropImageView.RequestSizeOptions.RESIZE_INSIDE) .start(this); } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { switch (requestCode) { case (CropImage.CAMERA_CAPTURE_PERMISSIONS_REQUEST_CODE): { if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { CropImage.startPickImageActivity(this); } else { Toast.makeText(this, "Batal, izin kamera tidak diberikan", Toast.LENGTH_LONG).show(); } break; } case (CropImage.PICK_IMAGE_PERMISSIONS_REQUEST_CODE): { if (mCropImageUri != null && grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { startCropImageActivity(mCropImageUri); } else { Toast.makeText(this, "Batal, izin penyimpanan tidak diberikan", Toast.LENGTH_LONG).show(); } break; } } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (resultCode == Activity.RESULT_OK) { switch (requestCode) { case (CropImage.PICK_IMAGE_CHOOSER_REQUEST_CODE): { Uri imageUri = CropImage.getPickImageResultUri(this, data); if (CropImage.isReadExternalStoragePermissionsRequired(this, imageUri)) { mCropImageUri = imageUri; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, CropImage.PICK_IMAGE_PERMISSIONS_REQUEST_CODE); } } else { startCropImageActivity(imageUri); } break; } case (CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE): { CropImage.ActivityResult result = CropImage.getActivityResult(data); mCropImageUri = result.getUri(); Glide.with(mActivity).load(mCropImageUri).into(thumbImageView); enableImageRemove(); isImageEmpty = false; break; } } } } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_add_item, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { if (item.getItemId() == R.id.action_save) { if (mAwesomeValidation.validate()) { uploadToServer(); } return true; } return super.onOptionsItemSelected(item); } private void uploadToServer() { progressBarCard.setVisibility(View.VISIBLE); SharedFunctions.disableEditText(nameEditText); SharedFunctions.disableEditText(descEditText); SharedFunctions.disableEditText(categoryEditText); SharedFunctions.disableEditText(valueEditText); disableImage(); RestApi server = SharedFunctions.getRetrofit().create(RestApi.class); RequestBody itemName = RequestBody.create(MediaType.parse("text/plain"), nameEditText.getText().toString()); RequestBody itemDesc = RequestBody.create(MediaType.parse("text/plain"), descEditText.getText().toString()); RequestBody itemCat = RequestBody.create(MediaType.parse("text/plain"), categoryEditText.getText().toString()); RequestBody itemVal = RequestBody.create(MediaType.parse("text/plain"), String.valueOf(valueEditText.getCleanIntValue())); RequestBody isImageEmptyBody = RequestBody.create(MediaType.parse("text/plain"), String.valueOf(this.isImageEmpty)); RequestBody userToken = RequestBody.create(MediaType.parse("text/plain"), LoginRepository.getLoggedInUser().getToken()); Call<ResponseBody> req; if (!this.isImageEmpty) { File file = new File(Objects.requireNonNull(mCropImageUri.getPath())); RequestBody reqFile = RequestBody.create(MediaType.parse("image/*"), file); MultipartBody.Part itemImage = MultipartBody.Part.createFormData("upload", file.getName(), reqFile); req = server.postItemWithImage(itemName, itemDesc, itemCat, itemVal, isImageEmptyBody, userToken, itemImage); } else { req = server.postItemNoImage(itemName, itemDesc, itemCat, itemVal, isImageEmptyBody, userToken); } req.enqueue(new Callback<ResponseBody>() { @Override public void onResponse(@NonNull Call<ResponseBody> call, @NonNull Response<ResponseBody> response) { try { JSONObject json = new JSONObject(Objects.requireNonNull(response.body()).string()); int success = json.getInt("success"); int imgSuccess = json.getInt("imgSuccess"); AlertDialog.Builder alertDialog = new AlertDialog.Builder(mActivity); if (success == 0) { showConnError(); } else { alertDialog.setPositiveButton(mContext.getString(R.string.alert_agree), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { finish(); } }); if (success == 1 && imgSuccess == 0) { alertDialog.setTitle(R.string.alert_post_success_title) .setMessage(R.string.alert_post_success_item_0_desc) .setIcon(R.drawable.ic_check_circle_black_24dp); } else if (success == 1 && (imgSuccess == 1 || imgSuccess == -1)) { alertDialog.setTitle(R.string.alert_post_success_title) .setMessage(R.string.alert_post_success_item_1_desc) .setIcon(R.drawable.ic_check_circle_black_24dp); } } progressBarCard.setVisibility(View.GONE); alertDialog.setCancelable(false) .show(); } catch (IOException | JSONException e) { e.printStackTrace(); } } @Override public void onFailure(@NonNull Call<ResponseBody> call, @NonNull Throwable t) { t.printStackTrace(); showConnError(); } }); } private void showConnError() { progressBarCard.setVisibility(View.GONE); SharedFunctions.enableEditText(nameEditText); SharedFunctions.enableEditText(descEditText); SharedFunctions.enableEditText(categoryEditText); SharedFunctions.enableEditText(valueEditText); if (isImageEmpty) { enableImageAdd(); } else { enableImageRemove(); } AlertDialog.Builder alertDialog = new AlertDialog.Builder(mActivity); alertDialog.setTitle(R.string.alert_conn_title) .setMessage(R.string.alert_conn_desc) .setIcon(R.drawable.ic_error_black_24dp) .setPositiveButton(mContext.getString(R.string.alert_agree), null) .show(); } @Override public boolean dispatchTouchEvent(MotionEvent event) { if (event.getAction() == MotionEvent.ACTION_UP) { View v = getCurrentFocus(); if (v instanceof EditText) { Rect outRect = new Rect(); v.getGlobalVisibleRect(outRect); if (!outRect.contains((int) event.getRawX(), (int) event.getRawY())) { v.clearFocus(); InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); if (imm != null) { imm.hideSoftInputFromWindow(v.getWindowToken(), 0); } } } } return super.dispatchTouchEvent(event); } }
package Composite; public class Main { public static void main(String[] args) { Folder root = new Folder("design pattern"); Folder d1= (Folder) root.addComponent(new Folder("structure")); Folder d2= (Folder) root.addComponent(new Folder("creation")); Folder d3= (Folder) root.addComponent(new Folder("update")); d1.addComponent(new File("strategy")); d1.addComponent(new File("Observer")); d2.addComponent(new File("Decorator")); d2.addComponent(new File("Composite")); d3.addComponent(new File("Singeloton")); d3.addComponent(new File("Builder")); d1.addComponent(new File("moaad")); root.show(); } }
package com.javawebtutor.Controllers.AdminControllers; import com.javawebtutor.Controllers.Controller; import javafx.event.ActionEvent; import java.io.IOException; public class AdminMainController extends Controller { public void users(ActionEvent event) throws IOException { this.changeScene(event, "/AdminUsersScene.fxml"); } public void cars(ActionEvent event) throws IOException { this.changeScene(event, "/AdminCarsScene.fxml"); } public void carMarks(ActionEvent event) throws IOException { this.changeScene(event, "/AdminCarMarksScene.fxml"); } }
package com.ut.healthelink.model; import com.ut.healthelink.validator.NoHtml; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; import org.hibernate.validator.constraints.NotEmpty; @Entity @Table(name = "UTSITEFEATURES") public class siteSections { @Id @GeneratedValue(strategy = GenerationType.AUTO) @Column(name = "ID", nullable = false) private int id; @NotEmpty @NoHtml @Column(name = "FEATURENAME", nullable = false) private String featureName; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getfeatureName() { return featureName; } public void setfeatureName(String featureName) { this.featureName = featureName; } public String getFeatureName() { return featureName; } public void setFeatureName(String featureName) { this.featureName = featureName; } }
package com.foodaholic.interfaces; import com.foodaholic.items.ItemPromo; public interface PromoCodeListener { void onStart(); void onEnd(String success, String result, String msg, ItemPromo promo); }
package com.example.vulnerabilitytester; import java.net.*; import java.io.*; import android.util.Log; public class SocketClass { private String serverName; private String serverIP=""; private static int port = 23; private Socket client; private OutputStream outToServer; private DataOutputStream out; private String inFromServer; private String connectedOrNot="Not Connected"; private boolean status = false; public SocketClass(String name, int portNumber, String ip) { serverName=name; port = portNumber; serverIP=ip; /////////////////////////////////////// try{ client = new Socket(serverIP,port); connectedOrNot="Connected"; Log.w("myApp", "Sockets Work!!! "); status = true; } catch(IOException e) { e.printStackTrace(); Log.w("myApp", "error in network File: "+ e.getMessage()+" CLIENT: "+serverIP); connectedOrNot="Connected ERROR"; } ////////////////////////////////////// } public boolean getConnectionStatus() { if(connectedOrNot.equals("Connected")) return true; return false; } public void sendMessage(String message) { ////////////////////////////////////// try { outToServer = client.getOutputStream(); out=new DataOutputStream(outToServer); out.write(message.getBytes("UTF-8")); Log.w("MyApp", "Socket succeded to send Message!!!"); } catch (IOException e) { Log.w("MyApp", "Socket Failed to send Message"); } /////////////////////////////////////// } public String receiveMessage() { /////////////////////////////////////// try { BufferedReader inFromClient = new BufferedReader(new InputStreamReader (client.getInputStream())); inFromServer = inFromClient.readLine(); Log.w("RECIEVED DATA",inFromServer); return inFromServer; } catch (IOException e) { Log.w("ERROR", e.toString()); return e.toString(); } } public String toString() { return "Connected to Server: "+serverName +" with IP address of "+serverIP+ " through port "+port+"."; } public String bannerGrab() { if(port == 80){ sendMessage("GET HTTP"); Log.w("SENT DATA ", "GET HTTP"); } else if(port == 22){ sendMessage("SSH"); Log.w("SENT DATA ", "SSH"); } else if(port == 21){ sendMessage("FTP"); Log.w("SENT DATA ", "FTP"); } else{ sendMessage("~:\"#$%^&*()!"); Log.w("SENT DATA ", "~:\"#$%^&*()!"); } return receiveMessage(); } }
package com.yeebar.aer; import android.app.Application; import android.content.SharedPreferences; import android.os.Bundle; import android.os.Message; import android.os.SystemClock; import android.support.design.widget.FloatingActionButton; import android.support.design.widget.NavigationView; import android.support.v4.view.GravityCompat; import android.support.v4.widget.DrawerLayout; import android.support.v7.app.ActionBarDrawerToggle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.Window; import android.widget.Button; import android.widget.ImageButton; import android.widget.TextView; import android.widget.Toast; import com.leancloud.util.MsgWhatValue; import com.leancloud.util.MyApplication; import com.leancloud.util.Utility; import java.io.File; import java.io.FileNotFoundException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.Map; import java.util.Set; import cn.sharesdk.framework.ShareSDK; import cn.sharesdk.onekeyshare.OnekeyShare; public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener ,RecyclerViewAdapter.Callbacks,FragmentInterface { public DBmanager dbHelper; private Bundle bundle; private SharedPreferences sp; private SharedPreferences.Editor editor; private SimpleDateFormat sdf; private volatile boolean isLogin=false;//判断账号是否已经登入 private boolean isRegister=false;//判断注册是否成功,主要验证手机是否验证成功 private boolean isAutoLogin=false; private Button login,qiandao; private ImageButton unLogin; private ActionBarDrawerToggle toggle; private DrawerLayout drawer; private Utility u;//自定义封装了一些手机客户端和leanCloud之间的数据通信 private String name; private Menu menu=null; private MenuItem menuItem=null; private NavigationView navigationView; private boolean drawerSlideStart=false,hasSlide=true; private float oldOffset=2,startOffset=0;//动态改变侧滑出现抽屉中的布局的数据,避免重复设置UI控件,造成手机卡顿 private long curTime=0,oldTime=0;//避免10分钟内重复发送验证码请求 private int verifed_flag=0;//flag=0表示是注册账号之后输入验证码,flag=1表示是敏感操作引起的需要输入验证码 private String phoneNO=null;//记录注册或者登入后的手机号 private String PSW=null;//记录登入后的密码; private File localFile; private resoureInterface resoureFragment; private boolean isPicLoad=false,isDbLoad=false; private MyApplication app; public final android.os.Handler handler=new android.os.Handler() { @Override public void handleMessage(Message msg) { bundle=msg.getData(); switch (msg.what) { case MsgWhatValue.DOWN: Toast.makeText(getApplicationContext(),bundle.getString("data"),Toast.LENGTH_LONG).show(); break; case MsgWhatValue.UNDOWN: Toast.makeText(getApplicationContext(),bundle.getString("data"),Toast.LENGTH_LONG).show(); break; case MsgWhatValue.QUERY_R: isLogin=true; name=bundle.getString("data"); phoneNO=bundle.getString("phoneNO"); PSW=bundle.getString("psw"); if(!isAutoLogin) { Set<String>set=new HashSet<>(); set.add("phoneNO"+bundle.getString("phoneNO")); set.add("psw"+bundle.getString("psw")); set.add("user"+name); set.add("money"+bundle.getInt("money")); editor.putStringSet("login",set); editor.commit(); LoginSuccess(); } isAutoLogin=false; break; case MsgWhatValue.QUERY_W: Toast.makeText(getApplicationContext(),bundle.getString("data"),Toast.LENGTH_LONG).show(); break; case MsgWhatValue.LOGIN_M: Toast.makeText(getApplicationContext(),bundle.getString("data"),Toast.LENGTH_LONG).show(); break; case MsgWhatValue.REGISTER_R: isRegister=true; verifed_flag=1; Toast.makeText(getApplicationContext(),bundle.getString("data"),Toast.LENGTH_LONG).show(); getSupportFragmentManager().beginTransaction().replace(R.id.include,new VerifiedFragment()).commit(); break; case MsgWhatValue.REGISTER_W: Toast.makeText(getApplicationContext(),bundle.getString("data"),Toast.LENGTH_LONG).show(); break; case MsgWhatValue.COMMIT_W: Toast.makeText(getApplicationContext(),bundle.getString("data"),Toast.LENGTH_LONG).show(); break; case MsgWhatValue.VALIDE_CODE_R: verifed_flag=0; Toast.makeText(getApplicationContext(),bundle.getString("data"),Toast.LENGTH_LONG).show(); if(!isRegister) { if(bundle.getInt("validCode")==1) { phoneNO=bundle.getString("phoneNO"); getSupportFragmentManager().beginTransaction().replace(R.id.include,new RegisterFragment()).commit(); } else getSupportFragmentManager().beginTransaction().replace(R.id.include,new MainFragment()).commit(); } else getSupportFragmentManager().beginTransaction().replace(R.id.include,new MainFragment()).commit(); isRegister=false; break; case MsgWhatValue.VALIDE_CODE_W: Toast.makeText(getApplicationContext(),bundle.getString("data"),Toast.LENGTH_LONG).show(); break; case MsgWhatValue.REQUSE_CODE: oldTime= SystemClock.elapsedRealtime(); break; case MsgWhatValue.DOWNLOAD_R: int flag=bundle.getInt("flag"); if(flag==0) { resoureFragment.UpdateResourec(bundle.getInt("flag")); Toast.makeText(getApplicationContext(),bundle.getString("data"),Toast.LENGTH_LONG).show(); } else if(flag==1) { String format=bundle.getString("format"); if(format.equals("png")) isPicLoad=true; else if(format.equals("db")) isDbLoad=true; } if(isDbLoad&&isPicLoad) { resoureFragment.UpdateResourec(bundle.getInt("flag")); Toast.makeText(getApplicationContext(),"下载完成",Toast.LENGTH_LONG).show(); } break; case MsgWhatValue.QIANDAO_R: /* noQiandao这个变量true表示此次调用qiandao这个方法是下载文件的时候查询金币 false表示此次调用qiandao这个方法是签到功能 */ boolean noQiandao=bundle.getBoolean("engough"); if(!noQiandao) { editor.putString(sdf.format(new Date()),"true"); editor.commit(); Toast.makeText(getApplicationContext(),bundle.getString("data"),Toast.LENGTH_LONG).show(); getSupportFragmentManager().beginTransaction().replace(R.id.include,new MainFragment()).commit(); } else { Map<String,String>downmap=new HashMap<>(); downmap.put("name",bundle.getString("name")); downmap.put("money","true"); try { u.downLoadFile(downmap,localFile,1,true); } catch (FileNotFoundException e) { e.printStackTrace(); } } break; case MsgWhatValue.QIANDAO_W: Toast.makeText(getApplicationContext(),bundle.getString("data"),Toast.LENGTH_LONG).show(); getSupportFragmentManager().beginTransaction().replace(R.id.include,new MainFragment()).commit(); break; case MsgWhatValue.QUERYURL_R: Map<String,String>urlMap=new HashMap<>(); urlMap.put("pic_url",bundle.getStringArray("url")[0]); urlMap.put("db_url",bundle.getStringArray("url")[1]); urlMap.put("name",bundle.getStringArray("url")[2]); try { u.downLoadFile(urlMap,localFile,bundle.getInt("flag"),false); } catch (FileNotFoundException e) { e.printStackTrace(); } break; case MsgWhatValue.QUERYURL_W: break; } } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.activity_main); ShareSDK.initSDK(this); sp=getSharedPreferences("app_info", Application.MODE_PRIVATE); editor=sp.edit(); app=(MyApplication)getApplication(); u=app.getUtility(); u.setHandler(handler); // u=new Utility(getApplicationContext(),handler); u.Initialize(); autoLogin(); sdf=new SimpleDateFormat("yyyy-MM-dd"); // u.isSdkRight(); if(savedInstanceState==null){ getSupportFragmentManager().beginTransaction() .add(R.id.include,new MainFragment()) .commit(); } Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); navigationView=(NavigationView)findViewById(R.id.nav_view); setSupportActionBar(toolbar); dbHelper = new DBmanager(this); // dbHelper.openDatabase(); // dbHelper.closeDatabase(); final FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab); fab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { getSupportFragmentManager().beginTransaction().replace(R.id.include,new ResourseFragment()).commit(); } }); drawer = (DrawerLayout) findViewById(R.id.drawer_layout); toggle = new ActionBarDrawerToggle( this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close) { @Override public void onDrawerSlide(View drawerView, float slideOffset) { startOffset=slideOffset; if(startOffset>oldOffset&&hasSlide) { drawerSlideStart=true; } else { oldOffset=startOffset; drawerSlideStart=false; } if(drawerSlideStart) { hasSlide=false; if(login==null) login=(Button)findViewById(R.id.draw_login_btn); if(isLogin&&name!=null) login.setText(name); else login.setText("未登入"); login.setTextSize(15); } if(qiandao==null) qiandao=(Button)findViewById(R.id.qiandao_btn); super.onDrawerSlide(drawerView, slideOffset); } @Override public void onDrawerOpened(View drawerView) { hasSlide=true; if(login==null) login=(Button)findViewById(R.id.draw_login_btn); else { if(!login.hasOnClickListeners()) { login.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(!isLogin) { getSupportFragmentManager().beginTransaction().replace(R.id.include,new LoginFragment()).commit(); drawer.closeDrawer(GravityCompat.START); } } }); } } if(unLogin==null) unLogin=(ImageButton)findViewById(R.id.tuichu); if(!unLogin.hasOnClickListeners()) { unLogin.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(isLogin) { isLogin=false; getSupportFragmentManager().beginTransaction().replace(R.id.include,new MainFragment()).commit(); drawer.closeDrawer(GravityCompat.START); } } }); } if(qiandao==null) qiandao=(Button)findViewById(R.id.qiandao_btn); else { if(!qiandao.hasOnClickListeners()) { if(sp.contains(sdf.format(new Date()))) { qiandao.setText("已签到"); qiandao.setBackgroundColor(0x727272); } qiandao.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(isLogin) { if(sp.contains(sdf.format(new Date()))) { Toast.makeText(MainActivity.this, "今天已经签到过了", Toast.LENGTH_LONG).show(); } else { Set<String>set=sp.getStringSet("login",null); String phoneNO=null; String psw=null; String sub=null; String money=null; int index=0; qiandao.setText("已签到"); qiandao.setBackgroundColor(0x727272); if(set!=null) { Iterator<String>it=set.iterator(); while (it.hasNext()) { sub=it.next(); if((index=sub.lastIndexOf("phoneNO"))!=-1) phoneNO=sub.substring(index+7); else if((index=sub.lastIndexOf("psw"))!=-1) psw=sub.substring(index+3); else if((index=sub.lastIndexOf("money"))!=-1) money=sub.substring(index+5); } } if(phoneNO!=null&&psw!=null) { Map<String,String>map=new HashMap<String, String>(); map.put("phoneNO",phoneNO); map.put("psw",psw); map.put("money",money); map.put("qiandao",sdf.format(new Date())); u.qiandao(map); } } } else Toast.makeText(MainActivity.this,"请先登入",Toast.LENGTH_LONG).show(); } }); } } super.onDrawerOpened(drawerView); } @Override public void onDrawerClosed(View drawerView) { super.onDrawerClosed(drawerView); ShareSDK.stopSDK(); } }; toggle.setToolbarNavigationClickListener(new View.OnClickListener() { @Override public void onClick(View v) { drawer.openDrawer(GravityCompat.START); } }); drawer.setDrawerListener(toggle); toggle.syncState(); navigationView = (NavigationView) findViewById(R.id.nav_view); navigationView.setNavigationItemSelectedListener(this); } public void autoLogin() { Set<String>set=sp.getStringSet("login",null); String phoneNO=null; String psw=null; String sub=null; String money=null; int index=0; if(set!=null) { Iterator<String>it=set.iterator(); while (it.hasNext()) { sub=it.next(); if((index=sub.lastIndexOf("phoneNO"))!=-1) phoneNO=sub.substring(index+7); else if((index=sub.lastIndexOf("psw"))!=-1) psw=sub.substring(index+3); else if((index=sub.lastIndexOf("money"))!=-1) money=sub.substring(index+5); } } if(phoneNO!=null&&psw!=null) { isAutoLogin=true; Map<String,String>map=new HashMap<>(); map.put("user",phoneNO); map.put("psw",psw); u.queryUserAndPsw(map); } } @Override public void onBackPressed() { DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); if (drawer.isDrawerOpen(GravityCompat.START)) { drawer.closeDrawer(GravityCompat.START); } else { super.onBackPressed(); } } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } else if(id==R.id.action_share) { showShare(); } return super.onOptionsItemSelected(item); } @SuppressWarnings("StatementWithEmptyBody") @Override public boolean onNavigationItemSelected(MenuItem item) { // Handle navigation view item clicks here. int id = item.getItemId(); if (id == R.id.nav_camera) { getSupportFragmentManager().beginTransaction().replace(R.id.include,new MainFragment()).commit(); } else if (id == R.id.nav_gallery) { getSupportFragmentManager().beginTransaction().replace(R.id.include,new ResourseFragment()).commit(); } else if (id == R.id.nav_slideshow) { getSupportFragmentManager().beginTransaction().replace(R.id.include,new PersonFragment()).commit(); } else if (id == R.id.nav_manage) { } else if (id == R.id.nav_send) { getSupportFragmentManager().beginTransaction().replace(R.id.include,new AboutFragment()).commit(); } else if(id== R.id.nav_share) { showShare(); } DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); drawer.closeDrawer(GravityCompat.START); return true; } @Override public void onTextViewUpdated(ArrayList<StudyTask> tasklist) { ArrayList list = TaskList.get(this).getmTaskList(); // TextView frontText = (TextView) findViewById(R.id.textView2); // frontText.setText(""+list.size()); } private void showShare() { // ShareSDK.initSDK(getApplicationContext(),"api20",true); OnekeyShare oks = new OnekeyShare(); //关闭sso授权 oks.disableSSOWhenAuthorize(); // 分享时Notification的图标和文字 2.5.9以后的版本不调用此方法 //oks.setNotification(R.drawable.ic_launcher, getString(R.string.app_name)); // title标题,印象笔记、邮箱、信息、微信、人人网和QQ空间使用 oks.setTitle("kaoyanruanjian"); // titleUrl是标题的网络链接,仅在人人网和QQ空间使用 oks.setTitleUrl("http://sharesdk.cn"); // text是分享文本,所有平台都需要这个字段 oks.setText("我是分享文本"); oks.setImageUrl("http://ac-un5psmpr.clouddn.com/4f5a547a670e04dd.png"); // imagePath是图片的本地路径,Linked-In以外的平台都支持此参数 //oks.setImagePath("/sdcard/test.jpg");//确保SDcard下面存在此张图片 // url仅在微信(包括好友和朋友圈)中使用 oks.setUrl("http://sharesdk.cn"); // comment是我对这条分享的评论,仅在人人网和QQ空间使用 oks.setComment("我是测试评论文本"); // site是分享此内容的网站名称,仅在QQ空间使用 oks.setSite(getString(R.string.app_name)); // siteUrl是分享此内容的网站地址,仅在QQ空间使用 oks.setSiteUrl("http://sharesdk.cn"); // 启动分享GUI oks.show(this); } @Override public void sendMsg(Message msg) { handler.sendMessage(msg); } @Override public void registerCommit(Map<String, String> map, int flag) { if(flag==0) { u.rigisterUser(map); } else if(flag==1) { Message msg=new Message(); Bundle data=new Bundle(); msg.what= MsgWhatValue.COMMIT_W; data.putString("data",map.get("err")); msg.setData(data); handler.sendMessage(msg); } } @Override public void registerBack() { getSupportFragmentManager().beginTransaction().replace(R.id.include,new MainFragment()).commit(); } @Override public void verifiedCode(String phone,String code,int flag) { //0代表验证码请求 //1代表敏感操作验证码验证 //2代表注册时候验证码验证 if(flag==0) { curTime=SystemClock.elapsedRealtime(); if(curTime>(oldTime+600000)) { u.verifiedCode(phone,code,0); } else Toast.makeText(getApplicationContext(),"验证码请求太频繁,稍后再请求",Toast.LENGTH_LONG).show(); } else { u.verifiedCode(phone,code,flag); } } @Override public int registerORverified() { return verifed_flag; } @Override public String getPhoneNO() { return phoneNO==null? null:phoneNO; } @Override public void downLoad(Map<String,String>map, File file, int flag) { if(isLogin) { isDbLoad=false; isPicLoad=false; map.put("phoneNO",phoneNO); map.put("psw",PSW); try { if(localFile==null||localFile!=file) localFile=file; u.downLoadFile(map,localFile,flag,true); } catch (FileNotFoundException e) { e.printStackTrace(); } } else { Toast.makeText(getApplicationContext(),"请先登入",Toast.LENGTH_LONG).show(); if(flag==0) resoureFragment.cancelRefresh(); } } @Override public void Login(String user, String psw) { Map<String,String>map=new HashMap<>(); map.put("user",user); map.put("psw",psw); u.queryUserAndPsw(map); } @Override public void Register() { getSupportFragmentManager().beginTransaction().replace(R.id.include,new VerifiedFragment()).commit(); } public void LoginSuccess() { getSupportFragmentManager().beginTransaction().replace(R.id.include,new MainFragment()).commit(); } @Override public void setResoureFragment(resoureInterface fragment) { this.resoureFragment=fragment; } @Override public boolean getIsLogin() { return isLogin; } }
import java.awt.*; public class Triangle { private points A; private points B; private points C; @Override public String toString() { return "Triangle{" + "A=" + A + ", B=" + B + ", C=" + C + '}'; } public points getA() { return A; } public void setA(points a) { A = a; } public points getB() { return B; } public void setB(points b) { B = b; } public points getC() { return C; } public void setC(points c) { C = c; } }
package io.shodo.banking.account.infra.renderer; import io.shodo.banking.account.domain.core.Account; import java.util.List; import java.util.function.Function; import java.util.stream.Collectors; class StatementsRenderer { private static final StatementRowData HEADER = new StatementRowData("Date", "Amount", "Operation"); private final StatementRowRenderer statementRowRenderer; private final List<StatementRowData> dataWithHeader; public StatementsRenderer(Account account) { dataWithHeader = prepareStatementsWithHeader(account); statementRowRenderer = createStatementRowRenderer(); } public String render() { StringBuilder sb = new StringBuilder(); for (StatementRowData statementRowData : dataWithHeader) { sb.append(statementRowRenderer.render(statementRowData)).append("\n"); } return sb.toString(); } private List<StatementRowData> prepareStatementsWithHeader(Account account) { List<StatementRowData> statements = account.transactions() .stream() .map(StatementRowData::new) .collect(Collectors.toList()); statements.add(0, HEADER); return statements; } private StatementRowRenderer createStatementRowRenderer() { return new StatementRowRenderer( new CellRenderer(getMaxSize(StatementRowData::getDate, 10), "| %s"), new CellRenderer(getMaxSize(StatementRowData::getAmount, 6), "| %s"), new CellRenderer(getMaxSize(StatementRowData::getOperation, 9), "| %s") ); } private Integer getMaxSize(Function<StatementRowData, String> fieldSupplier, int minimuSize) { return dataWithHeader.stream() .map(fieldSupplier) .map(String::length) .max(Integer::compareTo) .orElse(minimuSize); } }
package com.grocery.codenicely.vegworld_new.my_orders.model; import com.grocery.codenicely.vegworld_new.my_orders.OrderDetailsListCallback; /** * Created by ramya on 6/11/16. */ public interface OrderDetailsProvider { void getOrderDetails(String access_token, String order_id, OrderDetailsListCallback orderDetailsListCallback); }
package com.example.module1; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.context.ApplicationListener; import org.springframework.context.event.ApplicationContextEvent; import org.springframework.stereotype.Component; import java.net.InetAddress; import java.net.UnknownHostException; import java.util.concurrent.atomic.AtomicBoolean; /** * @author fengqi */ @Component public class Ip implements ApplicationListener<ApplicationContextEvent> { private AtomicBoolean start = new AtomicBoolean(false); private static final Logger log = LoggerFactory.getLogger(Ip.class); @Override public void onApplicationEvent(ApplicationContextEvent applicationContextEvent) { if (start.compareAndSet(false, true)) { try { InetAddress ip = InetAddress.getLocalHost(); String localName = ip.getHostName(); String localIp = ip.getHostAddress(); log.info("host name: {}", localName); log.info("host ip: {}" ,localIp); } catch (UnknownHostException e) { log.error("获取ip失败", e); } } } }
import java.util.HashMap; import java.util.Map; public class RandomPointer { public static void main(String[] args) { } public Node CopyRandomLit(Node head) { if (head == null) return null; Map<Node, Node> nodeMap = new HashMap<>(); Node resultHead = new Node(0, null, null); Node result = null; while (head != null) { resultHead.next = new Node(head.val, head.next, head.random); if (result == null) result = resultHead.next; nodeMap.put(head, resultHead.next); resultHead = resultHead.next; head = head.next; } resultHead = result; while (resultHead != null) { resultHead.random = nodeMap.get(resultHead.random); resultHead = resultHead.next; } return result; } // Definition for a Node. class Node { public int val; public Node next; public Node random; public Node() { } public Node(int _val, Node _next, Node _random) { val = _val; next = _next; random = _random; } } }
package com.product.controller; import com.product.model.ProductService; import com.product.model.ProductVO; import com.util.MyUtil; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.annotation.MultipartConfig; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.Part; import java.io.IOException; import java.util.LinkedList; import java.util.List; @MultipartConfig public class ProductServlet extends HttpServlet { public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { doPost(req, res); } public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { req.setCharacterEncoding("UTF-8"); String action = req.getParameter("action"); String getImg = req.getParameter("getImg"); if(getImg != null) { ProductService sc = new ProductService(); ProductVO vo = sc.getOneProduct(getImg); MyUtil.outputImg(getServletContext(),res, vo.getPic()); } if ("getOne_For_Display".equals(action)) { // 來自select_page.jsp的請求 List<String> errorMsgs = new LinkedList<String>(); // Store this set in the request scope, in case we need to // send the ErrorPage view. req.setAttribute("errorMsgs", errorMsgs); try { /***************************1.接收請求參數 - 輸入格式的錯誤處理**********************/ String str = req.getParameter("pro_no"); if (str == null || (str.trim()).length() == 0) { errorMsgs.add("請輸入產品編號"); } // Send the use back to the form, if there were errors if (!errorMsgs.isEmpty()) { RequestDispatcher failureView = req .getRequestDispatcher("/product/select_page.jsp"); failureView.forward(req, res); return;//程式中斷 } String pro_no = null; try { pro_no = new String(str); } catch (Exception e) { errorMsgs.add("產品編號格式不正確"); } // Send the use back to the form, if there were errors if (!errorMsgs.isEmpty()) { RequestDispatcher failureView = req .getRequestDispatcher("/product/select_page.jsp"); failureView.forward(req, res); return;//程式中斷 } /***************************2.開始查詢資料*****************************************/ ProductService productSvc = new ProductService(); ProductVO productVO = productSvc.getOneProduct(pro_no); if (productVO == null) { errorMsgs.add("查無資料"); } // Send the use back to the form, if there were errors if (!errorMsgs.isEmpty()) { RequestDispatcher failureView = req .getRequestDispatcher("/product/select_page.jsp"); failureView.forward(req, res); return;//程式中斷 } /***************************3.查詢完成,準備轉交(Send the Success view)*************/ req.setAttribute("productVO", productVO); // 資料庫取出的empVO物件,存入req String url = "/product/listOneProduct.jsp"; RequestDispatcher successView = req.getRequestDispatcher(url); // 成功轉交 listOneProduct.jsp successView.forward(req, res); /***************************其他可能的錯誤處理*************************************/ } catch (Exception e) { errorMsgs.add("無法取得資料:" + e.getMessage()); RequestDispatcher failureView = req .getRequestDispatcher("/product/select_page.jsp"); failureView.forward(req, res); } } if ("getSome_For_Display".equals(action)) { // 來自listSomeProduct.jsp的請求 List<String> errorMsgs = new LinkedList<String>(); // Store this set in the request scope, in case we need to // send the ErrorPage view. req.setAttribute("errorMsgs", errorMsgs); try { /***************************1.接收請求參數****************************************/ String product = req.getParameter("product"); String category_no = req.getParameter("category_no"); /***************************2.開始查詢資料*****************************************/ ProductService productSvc = new ProductService(); ProductVO productVO = new ProductVO(); productVO.setProduct(product); productVO.setCategory_no(category_no); List<ProductVO> list = productSvc.findByCompositeQuery(product,category_no); if (list.isEmpty()) { errorMsgs.add("查無資料,顯示全部商品"); } // Send the use back to the form, if there were errors if (!errorMsgs.isEmpty()) { RequestDispatcher failureView = req .getRequestDispatcher("/front-end/product/shop.jsp"); failureView.forward(req, res); return;//程式中斷 } /***************************3.查詢完成,準備轉交(Send the Success view)*************/ req.getSession().setAttribute("productVO", productVO); // 資料庫取出的productVO物件,存入req String url = "/front-end/product/getSomeProduct.jsp"; RequestDispatcher successView = req.getRequestDispatcher(url); // 成功轉交 listSomeProduct.jsp successView.forward(req, res); /***************************其他可能的錯誤處理*************************************/ } catch (Exception e) { errorMsgs.add("無法取得資料" + e.getMessage()); RequestDispatcher failureView = req .getRequestDispatcher("/front-end/product/shop.jsp"); failureView.forward(req, res); } } if ("getProduct_For_Display".equals(action)) { // 來自listSomeProduct.jsp的請求 List<String> errorMsgs = new LinkedList<String>(); // Store this set in the request scope, in case we need to // send the ErrorPage view. req.setAttribute("errorMsgs", errorMsgs); try { /***************************1.接收請求參數****************************************/ String str = req.getParameter("category_no"); if (str == null || (str.trim()).length() == 0) { errorMsgs.add("請輸入產品關鍵字"); } // Send the use back to the form, if there were errors if (!errorMsgs.isEmpty()) { RequestDispatcher failureView = req .getRequestDispatcher("/front-end/product/shop.jsp"); failureView.forward(req, res); return;//程式中斷_ } String product = null; try { product = new String(str); } catch (Exception e) { errorMsgs.add("產品編號格式不正確"); } // Send the use back to the form, if there were errors if (!errorMsgs.isEmpty()) { RequestDispatcher failureView = req .getRequestDispatcher("/front-end/product/shop.jsp"); failureView.forward(req, res); return;//程式中斷 } /***************************2.開始查詢資料*****************************************/ ProductService productSvc = new ProductService(); List<ProductVO> productVO = productSvc.findByCategory(product); if (productVO.isEmpty()) { errorMsgs.add("查無資料"); } // Send the use back to the form, if there were errors if (!errorMsgs.isEmpty()) { RequestDispatcher failureView = req .getRequestDispatcher("/front-end/product/shop.jsp"); failureView.forward(req, res); return;//程式中斷 } /***************************3.查詢完成,準備轉交(Send the Success view)*************/ req.setAttribute("productVO", productVO); // 資料庫取出的productVO物件,存入req String url = "/front-end/product/getSomeProduct.jsp"; RequestDispatcher successView = req.getRequestDispatcher(url); // 成功轉交 listSomeProduct.jsp successView.forward(req, res); /***************************其他可能的錯誤處理*************************************/ } catch (Exception e) { errorMsgs.add("無法取得資料" + e.getMessage()); RequestDispatcher failureView = req .getRequestDispatcher("/front-end/product/shop.jsp"); failureView.forward(req, res); } } if ("getOne_For_Update".equals(action)) { // 來自listAllProduct.jsp的請求 List<String> errorMsgs = new LinkedList<String>(); // Store this set in the request scope, in case we need to // send the ErrorPage view. req.setAttribute("errorMsgs", errorMsgs); String requestURL = req.getParameter("requestURL"); req.setAttribute("requestURL", requestURL); String whichPage = req.getParameter("whichPage"); req.setAttribute("whichPage", whichPage); try { /***************************1.接收請求參數****************************************/ String pro_no = new String(req.getParameter("pro_no")); /***************************2.開始查詢資料****************************************/ ProductService productSvc = new ProductService(); ProductVO productVO = productSvc.getOneProduct(pro_no); /***************************3.查詢完成,準備轉交(Send the Success view)************/ req.setAttribute("productVO", productVO); // 資料庫取出的productVO物件,存入req String url = "/back-end/product/update_product_input.jsp"; RequestDispatcher successView = req.getRequestDispatcher(url);// 成功轉交 update_product_input.jsp successView.forward(req, res); /***************************其他可能的錯誤處理**********************************/ } catch (Exception e) { errorMsgs.add("無法取得要修改的資料" + e.getMessage()); RequestDispatcher failureView = req .getRequestDispatcher("/back-end/product/listAllProduct.jsp"); failureView.forward(req, res); } } if ("update".equals(action)) { // 來自update_product_input.jsp的請求 List<String> errorMsgs = new LinkedList<String>(); // Store this set in the request scope, in case we need to // send the ErrorPage view. req.setAttribute("errorMsgs", errorMsgs); String requestURL = req.getParameter("requestURL"); req.setAttribute("requestURL", requestURL); String whichPage = req.getParameter("whichPage"); req.setAttribute("whichPage", whichPage); try { /***************************1.接收請求參數 - 輸入格式的錯誤處理**********************/ String pro_no = new String(req.getParameter("pro_no").trim()); String product = req.getParameter("product"); String productReg = "^[(\u4e00-\u9fa5)(a-zA-Z0-9_\\s)]{2,20}$"; if (product == null || product.trim().length() == 0) { errorMsgs.add("產品名稱: 請勿空白"); } else if(!product.trim().matches(productReg)) { //以下練習正則(規)表示式(regular-expression) errorMsgs.add("產品名稱: 只能是中、英文字母、數字和_ , 且長度必需在2到20之間"); } Integer price = new Integer(req.getParameter("price").trim()); if(price == null || price == 0) { errorMsgs.add("價錢請勿空白"); } Part part = req.getPart("pic"); String filename = MyUtil.getFileNameFromPart(part); byte[] pic = MyUtil.getPartPicture(part); if(filename == null) { ProductService productSvcPic = new ProductService(); ProductVO productVoPic = productSvcPic.getOneProduct(pro_no); pic = productVoPic.getPic(); } String message = req.getParameter("message"); Integer status = new Integer(req.getParameter("status")); Integer score = new Integer(req.getParameter("score")); Integer score_peo = new Integer(req.getParameter("score_peo")); String category_no = req.getParameter("category_no"); ProductVO productVO = new ProductVO(); productVO.setPro_no(pro_no); productVO.setProduct(product); productVO.setPrice(price); productVO.setPic(pic); productVO.setMessage(message); productVO.setStatus(status); productVO.setScore(score); productVO.setScore_peo(score_peo); productVO.setCategory_no(category_no); // Send the use back to the form, if there were errors if (!errorMsgs.isEmpty()) { req.setAttribute("productVO", productVO); // 含有輸入格式錯誤的productVO物件,也存入req RequestDispatcher failureView = req .getRequestDispatcher("/back-end/product/update_product_input.jsp"); failureView.forward(req, res); return; //程式中斷 } /***************************2.開始修改資料*****************************************/ ProductService productSvc = new ProductService(); productVO = productSvc.updateProduct(pro_no, product, price, pic, message, status, score, score_peo, category_no); /***************************3.修改完成,準備轉交(Send the Success view)*************/ String url = requestURL+"?whichPage="+whichPage; RequestDispatcher successView = req.getRequestDispatcher(url); // 修改成功後,轉交listOneProduct.jsp successView.forward(req, res); /***************************其他可能的錯誤處理*************************************/ } catch (Exception e) { errorMsgs.add("修改資料失敗"+e.getMessage()); RequestDispatcher failureView = req .getRequestDispatcher("/back-end/product/update_product_input.jsp"); failureView.forward(req, res); } } if ("insert".equals(action)) { // 來自addProduct.jsp的請求 List<String> errorMsgs = new LinkedList<String>(); // Store this set in the request scope, in case we need to // send the ErrorPage view. req.setAttribute("errorMsgs", errorMsgs); try { /***********************1.接收請求參數 - 輸入格式的錯誤處理*************************/ String product = req.getParameter("product"); String productReg = "^[(\u4e00-\u9fa5)(a-zA-Z0-9_)]{2,10}$"; if (product == null || product.trim().length() == 0) { errorMsgs.add("產品名稱: 請勿空白"); } else if(!product.trim().matches(productReg)) {//以下練習正則(規)表示式(regular-expression) errorMsgs.add("產品名稱: 只能是中、英文字母、數字和_ , 且長度必需在2到10之間"); } Integer price = new Integer(req.getParameter("price").trim()); if (price == null || price == 0) { errorMsgs.add("價錢請勿空白"); } Part part = req.getPart("pic"); String filename = MyUtil.getFileNameFromPart(part); if(filename == null) { errorMsgs.add("請選擇圖片"); }else if(!MyUtil.getMimeType().contains(getServletContext().getMimeType(part.getSubmittedFileName()))) { errorMsgs.add("圖片格式錯誤"); } byte[] pic = MyUtil.getPartPicture(part); String message = req.getParameter("message"); String category_no = req.getParameter("category_no"); ProductVO productVO = new ProductVO(); productVO.setProduct(product); productVO.setPrice(price); productVO.setPic(pic); productVO.setMessage(message); productVO.setCategory_no(category_no); // Send the use back to the form, if there were errors if (!errorMsgs.isEmpty()) { req.setAttribute("productVO", productVO); // 含有輸入格式錯誤的productVO物件,也存入req RequestDispatcher failureView = req .getRequestDispatcher("/back-end/product/addProduct.jsp"); failureView.forward(req, res); return; } /***************************2.開始新增資料***************************************/ ProductService productSvc = new ProductService(); productVO = productSvc.addProduct(product, price, pic, message, category_no); /***************************3.新增完成,準備轉交(Send the Success view)***********/ String url = "/back-end/product/listAllProduct.jsp?whichPage=100000"; RequestDispatcher successView = req.getRequestDispatcher(url); // 新增成功後轉交listAllProduct.jsp successView.forward(req, res); /***************************其他可能的錯誤處理**********************************/ } catch (Exception e) { errorMsgs.add(e.getMessage()); RequestDispatcher failureView = req .getRequestDispatcher("/back-end/product/addProduct.jsp"); failureView.forward(req, res); } } if ("delete".equals(action)) { // 來自listAllProduct.jsp List<String> errorMsgs = new LinkedList<String>(); // Store this set in the request scope, in case we need to // send the ErrorPage view. req.setAttribute("errorMsgs", errorMsgs); try { /***************************1.接收請求參數***************************************/ String pro_no = new String(req.getParameter("pro_no")); /***************************2.開始刪除資料***************************************/ ProductService productSvc = new ProductService(); productSvc.deleteProduct(pro_no); /***************************3.刪除完成,準備轉交(Send the Success view)***********/ String url = "/product/listAllProduct.jsp"; RequestDispatcher successView = req.getRequestDispatcher(url);// 刪除成功後,轉交回送出刪除的來源網頁 successView.forward(req, res); /***************************其他可能的錯誤處理**********************************/ } catch (Exception e) { errorMsgs.add("刪除資料失敗:"+e.getMessage()); RequestDispatcher failureView = req .getRequestDispatcher("/product/listAllProduct.jsp"); failureView.forward(req, res); } } if ("updateScore".equals(action)) { // 來自update_product_input.jsp的請求 List<String> errorMsgs = new LinkedList<String>(); // Store this set in the request scope, in case we need to // send the ErrorPage view. req.setAttribute("errorMsgs", errorMsgs); try { /***************************1.接收請求參數 - 輸入格式的錯誤處理**********************/ String pro_no = new String(req.getParameter("pro_no").trim()); Integer score = new Integer(req.getParameter("score")); Integer score_peo = new Integer(req.getParameter("score_peo")); ProductVO productVO = new ProductVO(); productVO.setPro_no(pro_no); productVO.setScore(score); productVO.setScore_peo(score_peo); // Send the use back to the form, if there were errors if (!errorMsgs.isEmpty()) { req.setAttribute("productVO", productVO); // 含有輸入格式錯誤的productVO物件,也存入req RequestDispatcher failureView = req .getRequestDispatcher("/back-end/product/update_product_input.jsp"); failureView.forward(req, res); return; //程式中斷 } /***************************2.開始修改資料*****************************************/ ProductService productSvc = new ProductService(); productVO = productSvc.updateScore(pro_no, score, score_peo); /***************************3.修改完成,準備轉交(Send the Success view)*************/ String url = "/front_end/product/order_detail.jsp"; RequestDispatcher successView = req.getRequestDispatcher(url); // 修改成功後,轉交listOneProduct.jsp successView.forward(req, res); /***************************其他可能的錯誤處理*************************************/ } catch (Exception e) { errorMsgs.add("修改資料失敗"+e.getMessage()); RequestDispatcher failureView = req .getRequestDispatcher("/back-end/product/update_product_input.jsp"); failureView.forward(req, res); } } } }
package br.edu.ifpr.consultacondutor.service; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.StringReader; import java.net.HttpURLConnection; import java.net.URL; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NodeList; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import com.google.gson.Gson; import br.edu.ifpr.consultacondutor.model.Placa; import br.edu.ifpr.consultacondutor.model.Veiculo; public class PlacaAPIService { public String getResponse(Placa placa) throws SAXException, IOException, ParserConfigurationException { String xmlResponse = "Veículo não encontrado."; String username = "git-tester"; String url = "http://www.placaapi.com/api/reg.asmx/CheckBrazil?" + "RegistrationNumber=" + placa.getPlaca() + "&username=" + username; URL obj = new URL(url); HttpURLConnection con = (HttpURLConnection) obj.openConnection(); BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); String inputLine; StringBuffer response = new StringBuffer(); while ((inputLine = in.readLine()) != null) response.append(inputLine); in.close(); Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder() .parse(new InputSource(new StringReader(response.toString()))); NodeList errNodes = doc.getElementsByTagName("Vehicle"); if (errNodes.getLength() > 0) { Element err = (Element) errNodes.item(0); xmlResponse = err.getElementsByTagName("vehicleJson").item(0).getTextContent(); } return xmlResponse; } public Veiculo fromJson(String xmlResponse) { Gson gson = new Gson(); Veiculo veiculo = gson.fromJson(xmlResponse, Veiculo.class); return veiculo; } }
/* GenericFilter.java Purpose: A generic class to help implementing servlet filter Description: History: 2001/11/13 14:46:46, Create, Tom M. Yeh. Copyright (C) 2001 Potix Corporation. All Rights Reserved. {{IS_RIGHT This program is distributed under LGPL Version 2.1 in the hope that it will be useful, but WITHOUT ANY WARRANTY. }}IS_RIGHT */ package org.zkoss.web.servlet; import java.util.Map; import java.util.Enumeration; import javax.servlet.Filter; import javax.servlet.FilterConfig; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.zkoss.web.servlet.http.Https; /** * A generic class to help implementing servlet filter. * Its role is like javax.servlet.GenericServlet to javax.servlet.Servlet. * * @author tomyeh */ public abstract class GenericFilter implements Filter { protected FilterConfig _config; protected GenericFilter() { } //-- extra API --// /** A convenience method which can be overridden so that there's * no need to call super.init(config). * @see #init(FilterConfig) */ protected void init() throws ServletException { } /** Returns a String containing the value of the named initialization * parameter, or null if the parameter does not exist. */ public final String getInitParameter(String name) { return _config.getInitParameter(name); } /** Returns a String containing the value of the named initialization * parameter, or null if the parameter does not exist. */ public final Enumeration getInitParameterNames() { return _config.getInitParameterNames(); } /** Returns the filter's name. */ public final String getFilterName() { return _config.getFilterName(); } /** Returns the servlet context in which this filter is running. */ public final ServletContext getServletContext() { return _config.getServletContext(); } /** * Redirects to another page. Note: it supports only HTTP. * * <p>It resolves "*" contained in URI, if any, to the proper Locale, * and the browser code. * Refer to {@link Servlets#locate(ServletContext, ServletRequest, String, Locator)} * for details. * * @param page the page's uri; null to denote the same request * @param mode one of {@link Servlets#OVERWRITE_URI}, {@link Servlets#IGNORE_PARAM}, * and {@link Servlets#APPEND_PARAM}. It defines how to handle if both uri * and params contains the same parameter. * mode is used only if both uri contains query string and params is * not empty. */ protected void sendRedirect(HttpServletRequest request, HttpServletResponse response, String page, Map params, int mode) throws ServletException, java.io.IOException { Https.sendRedirect(getServletContext(), request, response, page, params, mode); } /** Forward to the specified page. * * <p>It resolves "*" contained in URI, if any, to the proper Locale, * and the browser code. * Refer to {@link Servlets#locate(ServletContext, ServletRequest, String, Locator)} * for details. * @since 3.6.3 */ protected final void forward( ServletRequest request, ServletResponse response, String uri) throws ServletException, java.io.IOException { forward(getServletContext(), request, response, uri, null, 0); } /** Forward to the specified page with parameters. * * <p>It resolves "*" contained in URI, if any, to the proper Locale, * and the browser code. * Refer to {@link Servlets#locate(ServletContext, ServletRequest, String, Locator)} * for details. * @since 3.6.3 */ protected final void forward(ServletRequest request, ServletResponse response, String uri, Map params, int mode) throws ServletException, java.io.IOException { Https.forward(getServletContext(), request, response, uri, params, mode); } /** Includes the specified page. * * <p>It resolves "*" contained in URI, if any, to the proper Locale, * and the browser code. * Refer to {@link Servlets#locate(ServletContext, ServletRequest, String, Locator)} * for details. * @since 3.6.3 */ protected final void include(ServletRequest request, ServletResponse response, String uri) throws ServletException, java.io.IOException { include(getServletContext(), request, response, uri, null, 0); } /** Includes the specified page with parameters. * * <p>It resolves "*" contained in URI, if any, to the proper Locale, * and the browser code. * Refer to {@link Servlets#locate(ServletContext, ServletRequest, String, Locator)} * for details. * @since 3.6.3 */ protected final void include(ServletRequest request, ServletResponse response, String uri, Map params, int mode) throws ServletException, java.io.IOException { Https.include(getServletContext(), request, response, uri, params, mode); } /** @deprecated As of release 3.6.3, use {@link #forward(ServletRequest, ServletResponse, String)} * instead. */ protected final void forward(ServletContext ctx, ServletRequest request, ServletResponse response, String uri) throws ServletException, java.io.IOException { forward(ctx, request, response, uri, null, 0); } /** @deprecated As of release 3.6.3, use {@link #forward(ServletRequest, ServletResponse, String, Map, int)} * instead. */ protected final void forward(ServletContext ctx, ServletRequest request, ServletResponse response, String uri, Map params, int mode) throws ServletException, java.io.IOException { Https.forward(ctx, request, response, uri, params, mode); } /** @deprecated As of release 3.6.3, use {@link #include(ServletRequest, ServletResponse, String)} * instead. */ protected final void include(ServletContext ctx, ServletRequest request, ServletResponse response, String uri) throws ServletException, java.io.IOException { include(ctx, request, response, uri, null, 0); } /** @deprecated As of release 3.6.3, use {@link #include(ServletRequest, ServletResponse, String, Map, int)} * instead. */ protected final void include(ServletContext ctx, ServletRequest request, ServletResponse response, String uri, Map params, int mode) throws ServletException, java.io.IOException { Https.include(ctx, request, response, uri, params, mode); } //-- Filter --// /** Called by the web container to indicate to a filter that it is * being taken out of service. * * <p>This implementation does nothing. */ public void destroy() { } /** Called by the web container to indicate to a filter that it is * being placed into service. * However, deriving class usually doesn't override this method * but overriding {@link #init()}. */ public final void init(FilterConfig config) throws ServletException { _config = config; init(); } }
/* * Copyright (c) 2008-2021, Hazelcast, Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.hazelcast.internal.serialization.impl.compact; import com.hazelcast.internal.nio.BufferObjectDataInput; import com.hazelcast.internal.nio.IOUtil; import com.hazelcast.internal.serialization.impl.FieldOperations; import com.hazelcast.internal.serialization.impl.InternalGenericRecord; import com.hazelcast.nio.ObjectDataInput; import com.hazelcast.nio.serialization.FieldType; import com.hazelcast.nio.serialization.GenericRecord; import com.hazelcast.nio.serialization.GenericRecordBuilder; import com.hazelcast.nio.serialization.HazelcastSerializationException; import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.io.IOException; import java.lang.reflect.Array; import java.math.BigDecimal; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.LocalTime; import java.time.OffsetDateTime; import java.util.Set; import java.util.function.Function; import static com.hazelcast.internal.nio.Bits.INT_SIZE_IN_BYTES; import static com.hazelcast.internal.nio.Bits.NULL_ARRAY_LENGTH; import static com.hazelcast.internal.nio.Bits.SHORT_SIZE_IN_BYTES; import static com.hazelcast.internal.serialization.impl.compact.OffsetReader.BYTE_OFFSET_READER; import static com.hazelcast.internal.serialization.impl.compact.OffsetReader.BYTE_OFFSET_READER_RANGE; import static com.hazelcast.internal.serialization.impl.compact.OffsetReader.INT_OFFSET_READER; import static com.hazelcast.internal.serialization.impl.compact.OffsetReader.NULL_OFFSET; import static com.hazelcast.internal.serialization.impl.compact.OffsetReader.SHORT_OFFSET_READER; import static com.hazelcast.internal.serialization.impl.compact.OffsetReader.SHORT_OFFSET_READER_RANGE; import static com.hazelcast.internal.util.Preconditions.checkNotNegative; import static com.hazelcast.nio.serialization.FieldType.BOOLEAN; import static com.hazelcast.nio.serialization.FieldType.BOOLEAN_ARRAY; import static com.hazelcast.nio.serialization.FieldType.BYTE; import static com.hazelcast.nio.serialization.FieldType.BYTE_ARRAY; import static com.hazelcast.nio.serialization.FieldType.CHAR; import static com.hazelcast.nio.serialization.FieldType.CHAR_ARRAY; import static com.hazelcast.nio.serialization.FieldType.COMPOSED; import static com.hazelcast.nio.serialization.FieldType.COMPOSED_ARRAY; import static com.hazelcast.nio.serialization.FieldType.DATE; import static com.hazelcast.nio.serialization.FieldType.DATE_ARRAY; import static com.hazelcast.nio.serialization.FieldType.DECIMAL; import static com.hazelcast.nio.serialization.FieldType.DECIMAL_ARRAY; import static com.hazelcast.nio.serialization.FieldType.DOUBLE; import static com.hazelcast.nio.serialization.FieldType.DOUBLE_ARRAY; import static com.hazelcast.nio.serialization.FieldType.FLOAT; import static com.hazelcast.nio.serialization.FieldType.FLOAT_ARRAY; import static com.hazelcast.nio.serialization.FieldType.INT; import static com.hazelcast.nio.serialization.FieldType.INT_ARRAY; import static com.hazelcast.nio.serialization.FieldType.LONG; import static com.hazelcast.nio.serialization.FieldType.LONG_ARRAY; import static com.hazelcast.nio.serialization.FieldType.SHORT; import static com.hazelcast.nio.serialization.FieldType.SHORT_ARRAY; import static com.hazelcast.nio.serialization.FieldType.TIME; import static com.hazelcast.nio.serialization.FieldType.TIMESTAMP; import static com.hazelcast.nio.serialization.FieldType.TIMESTAMP_ARRAY; import static com.hazelcast.nio.serialization.FieldType.TIMESTAMP_WITH_TIMEZONE; import static com.hazelcast.nio.serialization.FieldType.TIMESTAMP_WITH_TIMEZONE_ARRAY; import static com.hazelcast.nio.serialization.FieldType.TIME_ARRAY; import static com.hazelcast.nio.serialization.FieldType.UTF; import static com.hazelcast.nio.serialization.FieldType.UTF_ARRAY; /** * A base class that has the capability of representing Compact serialized * objects as {@link InternalGenericRecord}s. This class is not instantiated * directly, but its subclass {@link DefaultCompactReader} is used in the * query system, as well as in returning a GenericRecord to the user. */ public class CompactInternalGenericRecord extends CompactGenericRecord implements InternalGenericRecord { private final OffsetReader offsetReader; private final Schema schema; private final BufferObjectDataInput in; private final int finalPosition; private final int dataStartPosition; private final int variableOffsetsPosition; private final CompactStreamSerializer serializer; private final boolean schemaIncludedInBinary; private final @Nullable Class associatedClass; public CompactInternalGenericRecord(CompactStreamSerializer serializer, BufferObjectDataInput in, Schema schema, @Nullable Class associatedClass, boolean schemaIncludedInBinary) { this.in = in; this.serializer = serializer; this.schema = schema; this.associatedClass = associatedClass; this.schemaIncludedInBinary = schemaIncludedInBinary; try { int numberOfVariableLengthFields = schema.getNumberOfVariableSizeFields(); if (numberOfVariableLengthFields != 0) { int dataLength = in.readInt(); dataStartPosition = in.position(); variableOffsetsPosition = dataStartPosition + dataLength; if (dataLength < BYTE_OFFSET_READER_RANGE) { offsetReader = BYTE_OFFSET_READER; finalPosition = variableOffsetsPosition + numberOfVariableLengthFields; } else if (dataLength < SHORT_OFFSET_READER_RANGE) { offsetReader = SHORT_OFFSET_READER; finalPosition = variableOffsetsPosition + (numberOfVariableLengthFields * SHORT_SIZE_IN_BYTES); } else { offsetReader = INT_OFFSET_READER; finalPosition = variableOffsetsPosition + (numberOfVariableLengthFields * INT_SIZE_IN_BYTES); } //set the position to final so that the next one to read something from `in` can start from //correct position in.position(finalPosition); } else { offsetReader = INT_OFFSET_READER; variableOffsetsPosition = 0; dataStartPosition = in.position(); finalPosition = dataStartPosition + schema.getFixedSizeFieldsLength(); } } catch (IOException e) { throw illegalStateException(e); } } @Nullable public Class getAssociatedClass() { return associatedClass; } public BufferObjectDataInput getIn() { return in; } @Override public Schema getSchema() { return schema; } @Override @Nonnull public GenericRecordBuilder newBuilder() { return serializer.createGenericRecordBuilder(schema); } @Override @Nonnull public GenericRecordBuilder cloneWithBuilder() { return serializer.createGenericRecordCloner(schema, this); } @Override @Nonnull public FieldType getFieldType(@Nonnull String fieldName) { return schema.getField(fieldName).getType(); } @Override public boolean hasField(@Nonnull String fieldName) { return schema.hasField(fieldName); } @Nonnull @Override public Set<String> getFieldNames() { return schema.getFieldNames(); } @Override public byte getByte(@Nonnull String fieldName) { try { return in.readByte(readFixedSizePosition(fieldName, BYTE)); } catch (IOException e) { throw illegalStateException(e); } } boolean isFieldExists(@Nonnull String fieldName, @Nonnull FieldType type) { FieldDescriptor field = schema.getField(fieldName); if (field == null) { return false; } return field.getType().equals(type); } @Override public short getShort(@Nonnull String fieldName) { try { return in.readShort(readFixedSizePosition(fieldName, SHORT)); } catch (IOException e) { throw illegalStateException(e); } } @Override public int getInt(@Nonnull String fieldName) { try { return in.readInt(readFixedSizePosition(fieldName, INT)); } catch (IOException e) { throw illegalStateException(e); } } @Override public long getLong(@Nonnull String fieldName) { try { return in.readLong(readFixedSizePosition(fieldName, LONG)); } catch (IOException e) { throw illegalStateException(e); } } @Override public float getFloat(@Nonnull String fieldName) { try { return in.readFloat(readFixedSizePosition(fieldName, FLOAT)); } catch (IOException e) { throw illegalStateException(e); } } @Override public double getDouble(@Nonnull String fieldName) { try { return in.readDouble(readFixedSizePosition(fieldName, DOUBLE)); } catch (IOException e) { throw illegalStateException(e); } } @Override public boolean getBoolean(@Nonnull String fieldName) { try { FieldDescriptor fd = getFieldDefinition(fieldName, BOOLEAN); int booleanOffset = fd.getOffset(); int bitOffset = fd.getBitOffset(); int getOffset = booleanOffset + dataStartPosition; byte lastByte = in.readByte(getOffset); return ((lastByte >>> bitOffset) & 1) != 0; } catch (IOException e) { throw illegalStateException(e); } } @Override public char getChar(@Nonnull String fieldName) { try { return in.readChar(readFixedSizePosition(fieldName, CHAR)); } catch (IOException e) { throw illegalStateException(e); } } @Override public String getString(@Nonnull String fieldName) { return getVariableLength(fieldName, UTF, BufferObjectDataInput::readString); } private <T> T getVariableLength(@Nonnull String fieldName, FieldType fieldType, Reader<T> reader) { int currentPos = in.position(); try { int pos = readVariableSizeFieldPosition(fieldName, fieldType); if (pos == NULL_OFFSET) { return null; } in.position(pos); return reader.read(in); } catch (IOException e) { throw illegalStateException(e); } finally { in.position(currentPos); } } @Override public BigDecimal getDecimal(@Nonnull String fieldName) { return getVariableLength(fieldName, DECIMAL, IOUtil::readBigDecimal); } @Override @Nonnull public LocalTime getTime(@Nonnull String fieldName) { int currentPos = in.position(); try { in.position(readFixedSizePosition(fieldName, TIME)); return IOUtil.readLocalTime(in); } catch (IOException e) { throw illegalStateException(e); } finally { in.position(currentPos); } } @Override @Nonnull public LocalDate getDate(@Nonnull String fieldName) { int currentPos = in.position(); try { in.position(readFixedSizePosition(fieldName, DATE)); return IOUtil.readLocalDate(in); } catch (IOException e) { throw illegalStateException(e); } finally { in.position(currentPos); } } @Override @Nonnull public LocalDateTime getTimestamp(@Nonnull String fieldName) { int currentPos = in.position(); try { in.position(readFixedSizePosition(fieldName, TIMESTAMP)); return IOUtil.readLocalDateTime(in); } catch (IOException e) { throw illegalStateException(e); } finally { in.position(currentPos); } } @Override @Nonnull public OffsetDateTime getTimestampWithTimezone(@Nonnull String fieldName) { int currentPos = in.position(); try { in.position(readFixedSizePosition(fieldName, TIMESTAMP_WITH_TIMEZONE)); return IOUtil.readOffsetDateTime(in); } catch (IOException e) { throw illegalStateException(e); } finally { in.position(currentPos); } } @Override public GenericRecord getGenericRecord(@Nonnull String fieldName) { return getVariableLength(fieldName, COMPOSED, in -> serializer.readGenericRecord(in, schemaIncludedInBinary)); } @Override public <T> T getObject(@Nonnull String fieldName) { return (T) getVariableLength(fieldName, COMPOSED, in -> serializer.read(in, schemaIncludedInBinary)); } @Override public byte[] getByteArray(@Nonnull String fieldName) { return getVariableLength(fieldName, BYTE_ARRAY, ObjectDataInput::readByteArray); } @Override public boolean[] getBooleanArray(@Nonnull String fieldName) { return getVariableLength(fieldName, BOOLEAN_ARRAY, CompactInternalGenericRecord::readBooleanBits); } @Override public char[] getCharArray(@Nonnull String fieldName) { return getVariableLength(fieldName, CHAR_ARRAY, ObjectDataInput::readCharArray); } @Override public int[] getIntArray(@Nonnull String fieldName) { return getVariableLength(fieldName, INT_ARRAY, ObjectDataInput::readIntArray); } @Override public long[] getLongArray(@Nonnull String fieldName) { return getVariableLength(fieldName, LONG_ARRAY, ObjectDataInput::readLongArray); } @Override public double[] getDoubleArray(@Nonnull String fieldName) { return getVariableLength(fieldName, DOUBLE_ARRAY, ObjectDataInput::readDoubleArray); } @Override public float[] getFloatArray(@Nonnull String fieldName) { return getVariableLength(fieldName, FLOAT_ARRAY, ObjectDataInput::readFloatArray); } @Override public short[] getShortArray(@Nonnull String fieldName) { return getVariableLength(fieldName, SHORT_ARRAY, ObjectDataInput::readShortArray); } @Override public String[] getStringArray(@Nonnull String fieldName) { return getVariableSizeArray(fieldName, UTF_ARRAY, String[]::new, ObjectDataInput::readString); } @Override public BigDecimal[] getDecimalArray(@Nonnull String fieldName) { return getVariableSizeArray(fieldName, DECIMAL_ARRAY, BigDecimal[]::new, IOUtil::readBigDecimal); } @Override public LocalTime[] getTimeArray(@Nonnull String fieldName) { return getVariableLength(fieldName, TIME_ARRAY, CompactInternalGenericRecord::getTimeArray); } @Override public LocalDate[] getDateArray(@Nonnull String fieldName) { return getVariableLength(fieldName, DATE_ARRAY, CompactInternalGenericRecord::getDateArray); } @Override public LocalDateTime[] getTimestampArray(@Nonnull String fieldName) { return getVariableLength(fieldName, TIMESTAMP_ARRAY, CompactInternalGenericRecord::getTimestampArray); } @Override public OffsetDateTime[] getTimestampWithTimezoneArray(@Nonnull String fieldName) { return getVariableLength(fieldName, TIMESTAMP_WITH_TIMEZONE_ARRAY, CompactInternalGenericRecord::getTimestampWithTimezoneArray); } @Override public GenericRecord[] getGenericRecordArray(@Nonnull String fieldName) { return getVariableSizeArray(fieldName, COMPOSED_ARRAY, GenericRecord[]::new, in -> serializer.readGenericRecord(in, schemaIncludedInBinary)); } @Override public <T> T[] getObjectArray(@Nonnull String fieldName, Class<T> componentType) { return (T[]) getVariableSizeArray(fieldName, COMPOSED_ARRAY, length -> (T[]) Array.newInstance(componentType, length), in -> serializer.read(in, schemaIncludedInBinary)); } protected interface Reader<R> { R read(BufferObjectDataInput t) throws IOException; } private <T> T[] getVariableSizeArray(@Nonnull String fieldName, FieldType fieldType, Function<Integer, T[]> constructor, Reader<T> reader) { int currentPos = in.position(); try { int position = readVariableSizeFieldPosition(fieldName, fieldType); if (position == NULL_ARRAY_LENGTH) { return null; } in.position(position); int itemCount = in.readInt(); int dataLength = in.readInt(); int dataStartPosition = in.position(); T[] values = constructor.apply(itemCount); OffsetReader offsetReader = getOffsetReader(dataLength); int offsetsPosition = dataStartPosition + dataLength; for (int i = 0; i < itemCount; i++) { int offset = offsetReader.getOffset(in, offsetsPosition, i); if (offset != NULL_ARRAY_LENGTH) { in.position(offset + dataStartPosition); values[i] = reader.read(in); } } return values; } catch (IOException e) { throw illegalStateException(e); } finally { in.position(currentPos); } } private static OffsetReader getOffsetReader(int dataLength) { if (dataLength < BYTE_OFFSET_READER_RANGE) { return BYTE_OFFSET_READER; } else if (dataLength < SHORT_OFFSET_READER_RANGE) { return SHORT_OFFSET_READER; } else { return INT_OFFSET_READER; } } private int readFixedSizePosition(@Nonnull String fieldName, FieldType fieldType) { FieldDescriptor fd = getFieldDefinition(fieldName, fieldType); int primitiveOffset = fd.getOffset(); return primitiveOffset + dataStartPosition; } @Nonnull private FieldDescriptor getFieldDefinition(@Nonnull String fieldName, FieldType fieldType) { FieldDescriptor fd = schema.getField(fieldName); if (fd == null) { throw throwUnknownFieldException(fieldName); } if (fd.getType() != fieldType) { throw new HazelcastSerializationException("Not a '" + fieldType + "' field: " + fieldName); } return fd; } private int readVariableSizeFieldPosition(@Nonnull String fieldName, FieldType fieldType) { try { FieldDescriptor fd = getFieldDefinition(fieldName, fieldType); int index = fd.getIndex(); int offset = offsetReader.getOffset(in, variableOffsetsPosition, index); return offset == NULL_OFFSET ? NULL_OFFSET : offset + dataStartPosition; } catch (IOException e) { throw illegalStateException(e); } } private HazelcastSerializationException throwUnknownFieldException(@Nonnull String fieldName) { return new HazelcastSerializationException("Unknown field name: '" + fieldName + "' for " + schema); } //indexed methods// private int readLength(int beginPosition) { try { return in.readInt(beginPosition); } catch (IOException e) { throw illegalStateException(e); } } public Byte getByteFromArray(@Nonnull String fieldName, int index) { return getFixedSizeFieldFromArray(fieldName, BYTE_ARRAY, ObjectDataInput::readByte, index); } public Boolean getBooleanFromArray(@Nonnull String fieldName, int index) { int position = readVariableSizeFieldPosition(fieldName, BOOLEAN_ARRAY); if (position == NULL_OFFSET) { return null; } if (readLength(position) <= index) { return null; } int currentPos = in.position(); try { int booleanOffsetInBytes = index / Byte.SIZE; int booleanOffsetWithinLastByte = index % Byte.SIZE; byte b = in.readByte(INT_SIZE_IN_BYTES + position + booleanOffsetInBytes); return ((b >>> booleanOffsetWithinLastByte) & 1) != 0; } catch (IOException e) { throw illegalStateException(e); } finally { in.position(currentPos); } } public Character getCharFromArray(@Nonnull String fieldName, int index) { return getFixedSizeFieldFromArray(fieldName, CHAR_ARRAY, ObjectDataInput::readChar, index); } public Integer getIntFromArray(@Nonnull String fieldName, int index) { return getFixedSizeFieldFromArray(fieldName, INT_ARRAY, ObjectDataInput::readInt, index); } public Long getLongFromArray(@Nonnull String fieldName, int index) { return getFixedSizeFieldFromArray(fieldName, LONG_ARRAY, ObjectDataInput::readLong, index); } public Double getDoubleFromArray(@Nonnull String fieldName, int index) { return getFixedSizeFieldFromArray(fieldName, DOUBLE_ARRAY, ObjectDataInput::readDouble, index); } public Float getFloatFromArray(@Nonnull String fieldName, int index) { return getFixedSizeFieldFromArray(fieldName, FLOAT_ARRAY, ObjectDataInput::readFloat, index); } public Short getShortFromArray(@Nonnull String fieldName, int index) { return getFixedSizeFieldFromArray(fieldName, SHORT_ARRAY, ObjectDataInput::readShort, index); } private <T> T getFixedSizeFieldFromArray(@Nonnull String fieldName, FieldType fieldType, Reader<T> reader, int index) { checkNotNegative(index, "Array indexes can not be negative"); int position = readVariableSizeFieldPosition(fieldName, fieldType); if (position == NULL_OFFSET) { return null; } if (readLength(position) <= index) { return null; } int currentPos = in.position(); try { FieldType singleType = fieldType.getSingleType(); int typeSize = FieldOperations.fieldOperations(singleType).typeSizeInBytes(); in.position(INT_SIZE_IN_BYTES + position + index * typeSize); return reader.read(in); } catch (IOException e) { throw illegalStateException(e); } finally { in.position(currentPos); } } @Override public String getStringFromArray(@Nonnull String fieldName, int index) { return getVarSizeFromArray(fieldName, UTF_ARRAY, BufferObjectDataInput::readString, index); } @Override public GenericRecord getGenericRecordFromArray(@Nonnull String fieldName, int index) { return getVarSizeFromArray(fieldName, COMPOSED_ARRAY, in -> serializer.readGenericRecord(in, schemaIncludedInBinary), index); } @Override public BigDecimal getDecimalFromArray(@Nonnull String fieldName, int index) { return getVarSizeFromArray(fieldName, DECIMAL_ARRAY, IOUtil::readBigDecimal, index); } @Override public LocalTime getTimeFromArray(@Nonnull String fieldName, int index) { return getFixedSizeFieldFromArray(fieldName, TIME_ARRAY, IOUtil::readLocalTime, index); } @Override public LocalDate getDateFromArray(@Nonnull String fieldName, int index) { return getFixedSizeFieldFromArray(fieldName, DATE_ARRAY, IOUtil::readLocalDate, index); } @Override public LocalDateTime getTimestampFromArray(@Nonnull String fieldName, int index) { return getFixedSizeFieldFromArray(fieldName, TIMESTAMP_ARRAY, IOUtil::readLocalDateTime, index); } @Override public OffsetDateTime getTimestampWithTimezoneFromArray(@Nonnull String fieldName, int index) { return getFixedSizeFieldFromArray(fieldName, TIMESTAMP_WITH_TIMEZONE_ARRAY, IOUtil::readOffsetDateTime, index); } @Override public Object getObjectFromArray(@Nonnull String fieldName, int index) { return getVarSizeFromArray(fieldName, COMPOSED_ARRAY, in -> serializer.read(in, schemaIncludedInBinary), index); } private <T> T getVarSizeFromArray(@Nonnull String fieldName, FieldType fieldType, Reader<T> reader, int index) { int currentPos = in.position(); try { int pos = readVariableSizeFieldPosition(fieldName, fieldType); if (pos == NULL_OFFSET) { return null; } int itemCount = in.readInt(pos); checkNotNegative(index, "Array index can not be negative"); if (itemCount <= index) { return null; } int dataLength = in.readInt(pos + INT_SIZE_IN_BYTES); int dataStartPosition = pos + (2 * INT_SIZE_IN_BYTES); OffsetReader offsetReader = getOffsetReader(dataLength); int offsetsPosition = dataStartPosition + dataLength; int indexedItemOffset = offsetReader.getOffset(in, offsetsPosition, index); if (indexedItemOffset != NULL_OFFSET) { in.position(indexedItemOffset + dataStartPosition); return reader.read(in); } return null; } catch (IOException e) { throw illegalStateException(e); } finally { in.position(currentPos); } } @Override protected Object getClassIdentifier() { return schema.getTypeName(); } protected IllegalStateException illegalStateException(IOException e) { return new IllegalStateException("IOException is not expected since we get from a well known format and position"); } private static LocalDate[] getDateArray(ObjectDataInput in) throws IOException { int len = in.readInt(); if (len == NULL_ARRAY_LENGTH) { return null; } LocalDate[] values = new LocalDate[len]; for (int i = 0; i < len; i++) { values[i] = IOUtil.readLocalDate(in); } return values; } private static LocalTime[] getTimeArray(ObjectDataInput in) throws IOException { int len = in.readInt(); if (len == NULL_ARRAY_LENGTH) { return null; } LocalTime[] values = new LocalTime[len]; for (int i = 0; i < len; i++) { values[i] = IOUtil.readLocalTime(in); } return values; } private static LocalDateTime[] getTimestampArray(ObjectDataInput in) throws IOException { int len = in.readInt(); if (len == NULL_ARRAY_LENGTH) { return null; } LocalDateTime[] values = new LocalDateTime[len]; for (int i = 0; i < len; i++) { values[i] = IOUtil.readLocalDateTime(in); } return values; } private static OffsetDateTime[] getTimestampWithTimezoneArray(ObjectDataInput in) throws IOException { int len = in.readInt(); if (len == NULL_ARRAY_LENGTH) { return null; } OffsetDateTime[] values = new OffsetDateTime[len]; for (int i = 0; i < len; i++) { values[i] = IOUtil.readOffsetDateTime(in); } return values; } private static boolean[] readBooleanBits(BufferObjectDataInput input) throws IOException { int len = input.readInt(); if (len == NULL_ARRAY_LENGTH) { return null; } if (len == 0) { return new boolean[0]; } boolean[] values = new boolean[len]; int index = 0; byte currentByte = input.readByte(); for (int i = 0; i < len; i++) { if (index == Byte.SIZE) { index = 0; currentByte = input.readByte(); } boolean result = ((currentByte >>> index) & 1) != 0; index++; values[i] = result; } return values; } @Override public String toString() { return "CompactGenericRecord{" + "schema=" + schema + ", finalPosition=" + finalPosition + ", offset=" + dataStartPosition + '}'; } }
package com.miyatu.tianshixiaobai.activities.mine.XiaoBaiSpace; import android.graphics.Color; import android.location.Location; import android.os.Bundle; import android.view.View; import android.widget.Toast; import androidx.core.widget.NestedScrollView; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import androidx.swiperefreshlayout.widget.SwipeRefreshLayout; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import com.hjq.toast.ToastUtils; import com.miyatu.tianshixiaobai.R; import com.miyatu.tianshixiaobai.activities.BaseFragment; import com.miyatu.tianshixiaobai.activities.Community.XiaoBaiReleaseDetailsActivity; import com.miyatu.tianshixiaobai.activities.mine.XiaoBaiUserReleaseFragment; import com.miyatu.tianshixiaobai.adapter.XiaoBaiSpaceAdapter; import com.miyatu.tianshixiaobai.adapter.XiaoBaiUserAdapter; import com.miyatu.tianshixiaobai.custom.GPSLocationListener; import com.miyatu.tianshixiaobai.custom.GPSLocationManager; import com.miyatu.tianshixiaobai.custom.GPSProviderStatus; import com.miyatu.tianshixiaobai.custom.InputTextMsgDialog; import com.miyatu.tianshixiaobai.entity.BaseResultEntity; import com.miyatu.tianshixiaobai.entity.XiaoBaiReleaseEntity; import com.miyatu.tianshixiaobai.http.api.ForumApi; import com.miyatu.tianshixiaobai.utils.LogUtils; import com.trello.rxlifecycle.components.support.RxAppCompatActivity; import com.wzgiceman.rxretrofitlibrary.retrofit_rx.exception.ApiException; import com.wzgiceman.rxretrofitlibrary.retrofit_rx.http.HttpManager; import com.wzgiceman.rxretrofitlibrary.retrofit_rx.listener.HttpOnNextListener; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class XiaoBaiSpaceReleaseFragment extends BaseFragment implements HttpOnNextListener { private String businessID; private double longitude = 0.0; //经度 private double latitude = 0.0; //维度 private GPSLocationManager gpsLocationManager; private boolean isFindLocation; private RecyclerView recyclerView; private XiaoBaiUserAdapter adapter; private XiaoBaiReleaseEntity.ListBean changeBean; private int changePosition; private SwipeRefreshLayout refreshLayout; private InputTextMsgDialog inputTextMsgDialog; private String strCommentContent = ""; private String forumID = ""; private HttpManager manager; private ForumApi forumApi; private Map<String, Object> params; private void initRequest(String businessID) { params = new HashMap<>(); params.put("map", longitude + "," + latitude); params.put("business_id", businessID); params.put("member_id", getUserBaseInfo().getMember_id()); params.put("page", page); params.put("limit", limit); forumApi = new ForumApi(ForumApi.XIAO_BAI_RELEASE); manager = new HttpManager(this, (RxAppCompatActivity)getActivity()); forumApi.setParams(params); manager.doHttpDeal(forumApi); } private void initZanRequest(String forumID) { params = new HashMap<>(); params.put("forum_id", forumID); forumApi = new ForumApi(ForumApi.XIAO_BAI_RELEASE_ZAN); manager = new HttpManager(this, (RxAppCompatActivity)getActivity()); forumApi.setParams(params); manager.doHttpDeal(forumApi); } private void initAddCommentRequest(String forumID, String content) { params = new HashMap<>(); params.put("forum_id", forumID); params.put("content", content); forumApi = new ForumApi(ForumApi.ADD_COMMENT_XIAO_BAI_RELEASE_COMMENT); manager = new HttpManager(this, (RxAppCompatActivity)getActivity()); forumApi.setParams(params); manager.doHttpDeal(forumApi); } public XiaoBaiSpaceReleaseFragment(String businessID) { this.businessID = businessID; } @Override protected int getLayout() { return R.layout.frag_xiao_bai_user_release; } @Override protected void initView(View view) { recyclerView = view.findViewById(R.id.recyclerView); refreshLayout = view.findViewById(R.id.refreshLayout); initRefreshLayout(); initContentRecyclerView(); // 初始化评论框 inputTextMsgDialog = new InputTextMsgDialog(getActivity(), R.style.dialog_center); inputTextMsgDialog.setMaxNumber(200); //设置最大字数 initInputEvent(); } @Override protected void initData() { gpsLocationManager = GPSLocationManager.getInstances(getActivity()); //开启定位 gpsLocationManager.start(new GPSListener()); } @Override protected void initEvent() { } @Override protected void updateView() { } private void showInputView(String content) { content = content.equals(getString(R.string.custom_input_hint)) ? "" : content; inputTextMsgDialog.setEditHint(getString(R.string.custom_input_hint)); inputTextMsgDialog.setEditContent(content); inputTextMsgDialog.show(); } private void initInputEvent() { inputTextMsgDialog.setmOnTextSendListener(new InputTextMsgDialog.OnTextSendListener() { @Override public void onTextSend(String msg) { // 点击发送 initAddCommentRequest(forumID, msg); } }); inputTextMsgDialog.setOnInputViewDismissListener(new InputTextMsgDialog.OnInputViewDismissListener() { @Override public void onDismissListener(boolean isNeedShow, String msg) { if (isNeedShow) { strCommentContent = msg; } } }); } //初始化刷新控件 private void initRefreshLayout() { refreshLayout.setColorSchemeColors(Color.parseColor("#f39800")); refreshLayout.setOnRefreshListener(() -> { isRefreshing = true; page = 1; initRequest(businessID); }); } private void initContentRecyclerView() { adapter = new XiaoBaiUserAdapter(R.layout.item_information_xiao_bai_release, null, XiaoBaiUserAdapter.TYPE_RELEASE); recyclerView.setNestedScrollingEnabled(false); recyclerView.setLayoutManager(new LinearLayoutManager(getActivity())); recyclerView.setAdapter(adapter); adapter.setOnLoadMoreListener(() -> { isLoadMore = true; initRequest(businessID); }, recyclerView); adapter.setOnItemChildClickListener((adapter, view, position) -> { XiaoBaiReleaseEntity.ListBean listBean = (XiaoBaiReleaseEntity.ListBean) adapter.getData().get(position); switch (view.getId()) { case R.id.ivPortrait: XiaoBaiSpaceActivity.startActivity(getActivity(), listBean.getBusiness_id()); break; case R.id.linLike: changeBean = listBean; changePosition = position; initZanRequest(listBean.getForum_id()); break; case R.id.linComment: changeBean = listBean; changePosition = position; forumID = listBean.getForum_id(); showInputView(strCommentContent); break; case R.id.linViewDetails: XiaoBaiReleaseDetailsActivity.startActivity(getActivity(), listBean.getForum_id(), listBean); // XiaoBaiSpaceActivity.startActivity(getActivity(), 0); break; } }); } private void initContent(List<XiaoBaiReleaseEntity.ListBean> dataBeanList) { if (isLoadMore) { isLoadMore = false; adapter.loadMoreComplete(); if (dataBeanList.size() < limit) { adapter.loadMoreEnd(); } adapter.addData(dataBeanList); } else { refreshLayout.setRefreshing(false); isRefreshing = false; adapter.setNewData(dataBeanList); } page ++; } @Override public void onNext(String resulte, String mothead) { if (mothead.equals(ForumApi.XIAO_BAI_RELEASE_ZAN)) { //点赞 BaseResultEntity<Integer> baseResultEntity = new Gson().fromJson(resulte, new TypeToken<BaseResultEntity<Integer>>(){}.getType()); if (baseResultEntity.getStatus().equals("200")) { //成功 changeBean.setIs_zan(changeBean.getIs_zan().equals("0") ? "1" : "0"); changeBean.setZan_count(String.valueOf(baseResultEntity.getData())); adapter.notifyItemChanged(changePosition, changeBean); } ToastUtils.show(baseResultEntity.getMsg()); } if (mothead.equals(ForumApi.XIAO_BAI_RELEASE)) { BaseResultEntity<XiaoBaiReleaseEntity> baseResultEntity = new Gson().fromJson(resulte, new TypeToken<BaseResultEntity<XiaoBaiReleaseEntity>>(){}.getType()); if (baseResultEntity.getStatus().equals("200")) { //成功 initContent(baseResultEntity.getData().getList()); return; } ToastUtils.show(baseResultEntity.getMsg()); } if (mothead.equals(ForumApi.ADD_COMMENT_XIAO_BAI_RELEASE_COMMENT)) { BaseResultEntity<XiaoBaiReleaseEntity.ListBean.ReplyBean> baseResultEntity = new Gson().fromJson(resulte, new TypeToken<BaseResultEntity<XiaoBaiReleaseEntity.ListBean.ReplyBean>>(){}.getType()); if (baseResultEntity.getStatus().equals("200")) { //成功 if (changeBean.getReply().size() == 3) { changeBean.getReply().remove(2); } changeBean.getReply().add(0, baseResultEntity.getData()); adapter.notifyItemChanged(changePosition, changeBean); return; } ToastUtils.show(baseResultEntity.getMsg()); } } @Override public void onError(ApiException e) { } public class GPSListener implements GPSLocationListener { @Override public void UpdateLocation(final Location location) { if (location != null) { longitude = location.getLongitude(); latitude = location.getLatitude(); LogUtils.i("longitude:"+longitude); LogUtils.i("latitude:"+latitude); gpsLocationManager.stop(); if (!isFindLocation) { page = 1; isFindLocation = true; initRequest(businessID); } } } @Override public void UpdateStatus(String provider, int status, Bundle extras) { if ("gps" == provider) { Toast.makeText(getActivity(), "定位类型:" + provider, Toast.LENGTH_SHORT).show(); } } @Override public void UpdateGPSProviderStatus(int gpsStatus) { switch (gpsStatus) { case GPSProviderStatus.GPS_ENABLED: Toast.makeText(getActivity(), "GPS开启", Toast.LENGTH_SHORT).show(); break; case GPSProviderStatus.GPS_DISABLED: Toast.makeText(getActivity(), "GPS关闭", Toast.LENGTH_SHORT).show(); break; case GPSProviderStatus.GPS_OUT_OF_SERVICE: Toast.makeText(getActivity(), "GPS不可用", Toast.LENGTH_SHORT).show(); break; case GPSProviderStatus.GPS_TEMPORARILY_UNAVAILABLE: Toast.makeText(getActivity(), "GPS暂时不可用", Toast.LENGTH_SHORT).show(); break; case GPSProviderStatus.GPS_AVAILABLE: Toast.makeText(getActivity(), "GPS可用", Toast.LENGTH_SHORT).show(); break; } } } }
/** * This hand consists of five cards with consecutive ranks and the same suit. For the sake of simplicity, 2 and A can only form a straight flush with K but not with 3. The card with the highest rank in a straight flush is referred to as the top card of this straight flush. A straight flush always beats any straights, flushes, full houses and quads. A straight flush having a top card with a higher rank beats a straight flush having a top card with a lower rank. For straight flushes having top cards with the same rank, the one having a top card with a higher suit beats one having a top card with a lower suit. * @author Marco Brian * */ public class StraightFlush extends Hand { /** * Constructs the StraightFlush object * @param player player having this hand * @param cards cards to be made into a hand */ public StraightFlush(CardGamePlayer player, CardList cards) { super(player,cards); } public String getType() { return "StraightFlush"; } /** * Using the same logic when building a Straight class and a Flush Class. * * We check whether is it is a Flush and if also a Straight. * Return true only if it is a flush and a straight, * if we find that either one is false we can directly return false. * */ public boolean isValid() { boolean is_flush=false; boolean is_straight=false; if(this.size()==5) { //Check if hand is a flush if(getCard(0).suit==getCard(1).suit && getCard(1).suit==getCard(2).suit && getCard(2).suit==getCard(3).suit && getCard(3).suit==getCard(4).suit) { is_flush=true; } else { return false; } // Check if hand is a straight if( getCard(0).getRank() == 9 && getCard(1).getRank() == 10 && getCard(2).getRank() == 11 && getCard(3).getRank() == 12 && getCard(4).getRank() == 0) { is_straight=true; } else if( getCard(0).getRank() == 10 && getCard(1).getRank() == 11 && getCard(2).getRank() == 12 && getCard(3).getRank() == 0 && getCard(4).getRank() == 1 ) { is_straight=true; } else if(getCard(0).getRank() == 0 && getCard(1).getRank() == 1 && getCard(2).getRank() == 2 && getCard(3).getRank() == 3 && getCard(4).getRank() == 4) { return false; } else if (getCard(0).getRank() == 1 && getCard(1).getRank() == 2 && getCard(2).getRank() == 3 && getCard(3).getRank() == 4 && getCard(4).getRank() == 5) { return false; } else { for(int i=0;i<4;i++) { if(getCard(i).getRank()+1 != getCard(i+1).getRank()) { return false; } } is_straight=true; } return (is_straight && is_flush); } else { return false; } } /** * If hand argument is also a straight flush then we have to compare the top card of each hand.Else * if the hands are of other size 5 cards, we return true because StraightFlush is the highest rank among * the size 5 cards. Else we return false. */ public boolean beats(Hand hand) { String hand_type= hand.getType(); if(getType()==hand_type) { if(this.getTopCard().compareTo(hand.getTopCard()) == 1) { return true; } else { return false; } } else if(hand_type=="Straight" || hand_type=="Flush" || hand_type=="FullHouse" || hand_type=="Quad") { return true; } else { return false; } } }
package se.rtz.csvtool.command; import java.io.IOException; import java.io.PrintStream; import java.util.HashMap; import java.util.List; import java.util.Map; import com.google.common.base.Strings; import com.google.common.collect.Ordering; import se.rtz.csvtool.commonArgs.CsvInputExtractor; import se.rtz.tool.arg.Param; import se.rtz.tool.arg.common.IntegerExtractor; import se.rtz.tool.arg.freetextoutput.FreeTextPrintStreamExtractor; import se.rtz.tool.commands.Command; import se.rtz.tool.commands.CommandDoc; import se.rtz.tool.util.csv.CsvReader; import se.rtz.tool.util.csv.impl.CsvReaderImpl; import se.rtz.tool.util.matrix.HashMatrix; @CommandDoc(author = "Daniel Schwartz, schw@rtz.se", description = "Displays a csv more human friendly. Useful together with 'less -S'", name = "view") public class View implements Command { private Integer height; private Integer width; private Integer line; private CsvReader csvReader; private PrintStream outputStream; private HashMatrix<Integer, Integer, String> dataMatrix = new HashMatrix<>(); private Map<Integer, Integer> columnIndexToColumnWidth = new HashMap<>(); @Override public void execute() { int[] recordIndex = { 1 }; csvReader.forEach(csvRecord -> { int[] columnIndex = { 1 }; csvRecord.forEach(csvCell -> { insertData(columnIndex[0], recordIndex[0], csvCell); insertData(0, recordIndex[0], Integer.toString(recordIndex[0])); insertData(columnIndex[0], 0, Integer.toString(columnIndex[0])); columnIndex[0]++; }); recordIndex[0]++; }); List<se.rtz.tool.util.matrix.Row<Integer, Integer, String>> rows = Ordering.natural().sortedCopy(dataMatrix.getRows()); if (line > 0) drawLine(); int rowCount = 0; for (se.rtz.tool.util.matrix.Row<Integer, Integer, String> row: rows) { HashMap<Integer, String> data = new HashMap<>(row.getRowValues()); int linesWrittenForThisRecord = 0; while (!data.isEmpty() && linesWrittenForThisRecord < height) { data = writeLine(data); linesWrittenForThisRecord++; } if (line > 0 && rowCount % line == 0) { drawLine(); } rowCount++; } } private HashMap<Integer, String> writeLine(HashMap<Integer, String> data) { HashMap<Integer, String> remainder = new HashMap<>(); Integer lastCol = Ordering.natural().max(data.keySet()); for (int columnIndex = 0; columnIndex <= lastCol; columnIndex++) { String restForThisColumn = writeCell(data, columnIndex); if (restForThisColumn != null) remainder.put(columnIndex, restForThisColumn); } outputStream.println(); return remainder; } private String writeCell(HashMap<Integer, String> data, int columnIndex) { String restForThisColumn = null; int widthOfThisColumn = columnIndexToColumnWidth.get(columnIndex); if (data.containsKey(columnIndex)) { String value = data.get(columnIndex); if (0 <= value.indexOf("\n") && value.indexOf("\n") < widthOfThisColumn) { outputStream.print(Strings.padEnd(value.substring(0, value.indexOf("\n")), widthOfThisColumn, ' ')); restForThisColumn = value.substring(value.indexOf("\n") + 1); } else if (value.length() > widthOfThisColumn) { outputStream.print(value.substring(0, widthOfThisColumn)); restForThisColumn = value.substring(widthOfThisColumn).trim(); } else { outputStream.print(Strings.padEnd(value, widthOfThisColumn, ' ')); } } else { outputStream.print(Strings.repeat(" ", widthOfThisColumn)); } outputStream.print(" "); return restForThisColumn; } private void drawLine() { Integer maxCol = Ordering.natural().max(columnIndexToColumnWidth.keySet()); for (int i = 0; i <= maxCol; i++) { outputStream.print(Strings.repeat("-", columnIndexToColumnWidth.get(i))); outputStream.print(" "); } outputStream.println(); } private void insertData(int x, int y, String z) { dataMatrix.put(x, y, z); int length = 1; if (!columnIndexToColumnWidth.containsKey(x)) columnIndexToColumnWidth.put(x, length); Integer longestWidth = columnIndexToColumnWidth.get(x); longestWidth = Math.max(Math.min(width, z.length()), longestWidth); columnIndexToColumnWidth.put(x, longestWidth); } @Override public void close() throws IOException { csvReader.close(); outputStream.close(); } @Param(description = "Max height of each row. Default 1", exampleValues = "2", token = "-h", extractor = IntegerExtractor.class) public void setHeight(Integer height) { if (height == null) this.height = 1; else this.height = height; } @Param(description = "Width of each column, Default 20.", exampleValues = "34", token = "-w", extractor = IntegerExtractor.class) public void setWidth(Integer width) { if (width == null) this.width = 20; else this.width = width; } @Param(description = "Draw a separator line to separate groups of records.", exampleValues = "5", token = "-line", extractor = IntegerExtractor.class, moreInfo = "If not given, no lines will be printed.") public void setLine(Integer line) { if (line == null) this.line = 0; else this.line = line; } @Param(description = "Csv input. If not given, std in will be used", // exampleValues = "./aFile.csv ',+UTF-8'", extractor = CsvInputExtractor.class, // token = "-csvIn") public void setCsvReader(CsvReader csvReader) { this.csvReader = CsvReaderImpl.orStandardReader(csvReader); } @Param(description = "Free text output.", exampleValues = "./anOutputFile.txt", token = "-out", moreInfo = "If omitted or if ':out:' is passed as value, then std out will be used.", extractor = FreeTextPrintStreamExtractor.class) public void setPrintStream(PrintStream outputStream) { this.outputStream = outputStream; } }
package rs2.util.constants; /** * * @author Jake Bellotti * @since 1.0 */ public class DialogueConstants { public static final int[] NPC_IDS = {4882, 4887, 4893, 4900}; public static final int[] PLAYER_IDS = {968, 973, 979, 986}; public static final int[] OPTION_IDS = {2459, 2469, 2480, 2492}; public static final int[] STATEMENT_IDS = {356, 359, 363, 368, 374}; }
package com.trump.auction.activity.service.impl; import com.cf.common.util.mapping.BeanMapper; import com.trump.auction.activity.dao.ActivityShareDao; import com.trump.auction.activity.model.ActivityShareModel; import com.trump.auction.activity.service.ActivityShareService; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; /** * @description: 分享活动 * @author: zhangqingqiang * @date: 2018-03-20 15:08 **/ @Service @Slf4j public class ActivityShareServiceImpl implements ActivityShareService { @Autowired private ActivityShareDao activityShareDao; @Autowired private BeanMapper beanMapper; /** * 获取活动信息 * @param activityId 活动id(非主键) * @return 一条活动信息 */ @Override public ActivityShareModel getActivityInfo(String activityId) { return beanMapper.map(activityShareDao.getActivityInfo(activityId),ActivityShareModel.class); } /** * 根据不同入口获取活动信息 * @param entrance 活动入口 * @return */ @Override public ActivityShareModel getActivityByEntrance(Integer entrance) { return beanMapper.map(activityShareDao.getActivityByEntrance(entrance),ActivityShareModel.class); } }
package com.gestion.entity; import java.io.Serializable; import javax.persistence.*; import java.util.Date; import java.util.List; /** * The persistent class for the inventaire_client database table. * */ @Entity @Table(name="inventaire_client") public class InventaireClient implements Serializable { private static final long serialVersionUID = 1L; @Id @Column(name="id_inventaire") private int idInventaire; @Temporal( TemporalType.DATE) @Column(name="date_inventaire") private Date dateInventaire; @OneToOne @JoinColumn(name="id_service") private ServiceSiteClient serviceSiteClient; @OneToMany(mappedBy="inventaireClient") private List<FirRouteurClient> firRouteurClient; @OneToMany(mappedBy="inventaireClient") private List<MaterielClient> materielClient; @OneToMany(mappedBy="inventaireClient") private List<ImprimantesClient> imprimantesClient; @OneToMany(mappedBy="inventaireClient") private List<PhotocopieurClient> photocopieurClient; @OneToMany(mappedBy="inventaireClient") private List<ScannerClient> scannerClient; @OneToMany(mappedBy="inventaireClient") private List<ServeursClient> serveursClient; @OneToMany(mappedBy="inventaireClient") private List<StockageClient> stockageClient; @OneToMany(mappedBy="inventaireClient") private List<SwitchClient> switchClient; @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; InventaireClient other = (InventaireClient) obj; if (dateInventaire == null) { if (other.dateInventaire != null) return false; } else if (!dateInventaire.equals(other.dateInventaire)) return false; if (idInventaire != other.idInventaire) return false; if (serviceSiteClient == null) { if (other.serviceSiteClient != null) return false; } else if (!serviceSiteClient.equals(other.serviceSiteClient)) return false; return true; } @Override public String toString() { return "InventaireClient [idInventaire=" + idInventaire + ", dateInventaire=" + dateInventaire + ", serviceSiteClient=" + serviceSiteClient + "]"; } public InventaireClient() { } public int getIdInventaire() { return this.idInventaire; } public void setIdInventaire(int idInventaire) { this.idInventaire = idInventaire; } public Date getDateInventaire() { return this.dateInventaire; } public void setDateInventaire(Date dateInventaire) { this.dateInventaire = dateInventaire; } public ServiceSiteClient getServiceSiteClient() { return serviceSiteClient; } public void setServiceSiteClient(ServiceSiteClient serviceSiteClient) { this.serviceSiteClient = serviceSiteClient; } public List<MaterielClient> getMaterielClient() { return materielClient; } public void setMaterielClient(List<MaterielClient> materielClient) { this.materielClient = materielClient; } public List<FirRouteurClient> getFirRouteurClient() { return firRouteurClient; } public void setFirRouteurClient(List<FirRouteurClient> firRouteurClient) { this.firRouteurClient = firRouteurClient; } public List<ImprimantesClient> getImprimantesClient() { return imprimantesClient; } public void setImprimantesClient(List<ImprimantesClient> imprimantesClient) { this.imprimantesClient = imprimantesClient; } public List<PhotocopieurClient> getPhotocopieurClient() { return photocopieurClient; } public void setPhotocopieurClient(List<PhotocopieurClient> photocopieurClient) { this.photocopieurClient = photocopieurClient; } public List<ScannerClient> getScannerClient() { return scannerClient; } public void setScannerClient(List<ScannerClient> scannerClient) { this.scannerClient = scannerClient; } public List<ServeursClient> getServeursClient() { return serveursClient; } public void setServeursClient(List<ServeursClient> serveursClient) { this.serveursClient = serveursClient; } public List<StockageClient> getStockageClient() { return stockageClient; } public void setStockageClient(List<StockageClient> stockageClient) { this.stockageClient = stockageClient; } public List<SwitchClient> getSwitchClient() { return switchClient; } public void setSwitchClient(List<SwitchClient> switchClient) { this.switchClient = switchClient; } }
package com.yidatec.weixin.dao.security; import java.sql.ResultSet; import java.sql.SQLException; import java.util.List; import org.springframework.jdbc.core.RowMapper; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority; import com.yidatec.weixin.dao.DataBase; import com.yidatec.weixin.entity.PlatformUserEntity; import com.yidatec.weixin.entity.ResourceTreeEntity; public class SecurityDao extends DataBase { /** * 提取系统中的所有权限 * @return List<String> * @throws Exception */ public List<String> loadAuthorities() throws Exception { String sql = "select auth_name from " + getTableName("authorities"); @SuppressWarnings("unchecked") List<String> authorities = jdbcTemplate.query(sql, new RowMapper() { public Object mapRow(ResultSet rs, int arg1) throws SQLException { return rs.getString("auth_name"); } }); return authorities; } /** * 根据权限获取资源 * @param auth_name * @return * @throws Exception */ public List<String> loadResourcesByAuthorityName(String auth_name) throws Exception { String sql = " select b.resource_string from " + getTableName("authorities_resources") + " a, " + getTableName("resources") + " b, " + getTableName("authorities") + " c " + " where a.resource_id = b.id and a.authority_id = c.id and c.auth_name = ? "; @SuppressWarnings("unchecked") List<String> resources = jdbcTemplate.query(sql, new Object[]{ auth_name }, new RowMapper() { public Object mapRow(ResultSet rs, int arg1) throws SQLException { return rs.getString("resource_string"); } }); return resources; } /** * 根据帐号获取权限 * @param username * @return * @throws Exception */ public List<GrantedAuthority> loadUserAuthoritiesByName(String username) throws Exception { /* String sql = " select a.auth_name " + " from " + getTableName("authorities") + " a, " + getTableName("roles_authorities") + " b, " + getTableName("platform_users_roles") + " c, " + getTableName("platform_users") + " d " + " where a.id = b.authority_id and b.role_id = c.role_id and c.user_id = d.id " + " and d.account = ? "; */ String sql = " select a.auth_name " + " from " + getTableName("authorities") + " a, " + getTableName("platform_users_auths") + " b, " + getTableName("platform_users") + " c " + " where a.id = b.auth_id and b.user_id = c.id and c.account = ? "; SimpleGrantedAuthority authority = null; @SuppressWarnings("unchecked") List<GrantedAuthority> authorities = jdbcTemplate.query(sql, new Object[]{ username }, new RowMapper() { public Object mapRow(ResultSet rs, int arg1) throws SQLException { SimpleGrantedAuthority authority = new SimpleGrantedAuthority(rs.getString("auth_name")); return authority; } }); return authorities; } /** * 获取用户实体 * @param account * @return * @throws Exception */ public PlatformUserEntity loadUserByAccount(String account) throws Exception { String sql = "select * from " + getTableName("platform_users") + " where account = ?"; @SuppressWarnings("unchecked") List<PlatformUserEntity> users = jdbcTemplate.query(sql, new Object[]{ account }, new RowMapper() { public Object mapRow(ResultSet rs, int arg1) throws SQLException { PlatformUserEntity userEntity = new PlatformUserEntity(); userEntity.setId(rs.getString("id")); userEntity.setUser_id(rs.getString("user_id")); userEntity.setAccount(rs.getString("account")); userEntity.setPassword(rs.getString("password")); userEntity.setName(rs.getString("name")); userEntity.setMail(rs.getString("mail")); userEntity.setMobile_phone(rs.getString("mobile_phone")); userEntity.setIssys(rs.getInt("issys")); userEntity.setEnabled(rs.getInt("enabled")); userEntity.setType(rs.getInt("type")); userEntity.setAccountNonLocked(rs.getInt("locked") == 0); userEntity.setAccountNonExpired(rs.getInt("expired") == 0); userEntity.setCredentialsNonExpired(rs.getInt("credentialsexpired") == 0); userEntity.setCreate_user(rs.getString("create_user")); userEntity.setCreate_date(rs.getString("create_date")); userEntity.setModify_user(rs.getString("modify_user")); userEntity.setModify_date(rs.getString("modify_date")); userEntity.setWeichat_type(rs.getString("weichat_type")); if(null != rs.getObject("sex")){ userEntity.setSex(rs.getInt("sex")); } return userEntity; } }); if (null != users && users.size() > 0) return users.get(0); return null; } /** * 获取资源树 * @return * @throws Exception */ public List<ResourceTreeEntity> loadResourceTree() throws Exception { String sql = " select b.parentId, b.parentName, b.parentPriority, " + " id 'childId', resource_name 'childName', resource_priority 'childPriority' " + " from " + getTableName("resources") + " a, " + " (select id 'parentId', resource_name 'parentName', resource_priority 'parentPriority' from o2o_resources where pid IS NULL) b " + " WHERE a.pid = b.parentId order by parentPriority, childPriority "; @SuppressWarnings("unchecked") List<ResourceTreeEntity> resourceTree = jdbcTemplate.query(sql, new RowMapper() { public Object mapRow(ResultSet rs, int arg1) throws SQLException { ResourceTreeEntity resource = new ResourceTreeEntity(); resource.setParentId(rs.getString("parentId")); resource.setParentName(rs.getString("parentName")); resource.setParentPriority(rs.getInt("parentPriority")); resource.setChildId(rs.getString("childId")); resource.setChildName(rs.getString("childName")); resource.setChildPriority(rs.getInt("childPriority")); return resource; } }); return resourceTree; } }
package de.omikron.server; import java.io.IOException; import java.net.ServerSocket; import java.net.Socket; import java.util.ArrayList; public class ServerConnection { private ServerSocket server; private int port; private ArrayList<ClientHandler> clientList; private boolean isWaitingForClients; public ServerConnection(int port) { this.port = port; this.isWaitingForClients = true; this.clientList = new ArrayList<>(); } @SuppressWarnings("resource") protected void init() { try { System.out.println("Starting server .."); server = new ServerSocket(port); System.out.println("Server started."); System.out.println("Waiting for clients .."); while(isWaitingForClients) { Socket connection = server.accept(); System.out.println("Client connected."); ClientHandler client = new ClientHandler(this, connection); System.out.println("Client connected."); Thread t1 = new Thread(client); t1.start(); clientList.add(client); } } catch (IOException e) { e.printStackTrace(); } } protected synchronized void sendToAllClients(String msg) { for(ClientHandler ch : clientList) { ch.sendMsg(msg); } } }
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.topica.vn.baitap_thaytrungnt9.JDBC; import java.sql.Connection; import java.sql.DriverManager; import java.util.ArrayList; import java.util.List; import java.util.Queue; /** * * @author khong */ public class PoolConnect { List<Connection> lisConnection = new ArrayList<>(); static final Config config = new Config("root","12345", "jdbc:mysql://localhost:3306/testdb","com.mysql.jdbc.Driver", 5); public PoolConnect() { System.out.println("den day"); while(CheckPoolFull()){ lisConnection.add(createConnection()); } } private synchronized boolean CheckPoolFull(){ final int POOLMAXSIZE = config.getMaxConnection(); if(lisConnection.size() < POOLMAXSIZE) return true; return false; } private Connection createConnection(){ try { Class.forName(config.getDriver()); Connection con = DriverManager.getConnection(config.getUrl(),config.getUsername(), config.getPassword()); if(con != null) System.out.println("Creadted connection"); else System.out.println("missCreated"); return con; } catch (Exception e) { e.printStackTrace(); } return null; } public synchronized Connection getConnection(){ Connection con = null; if(lisConnection.size() > 0){ con = lisConnection.get(0); lisConnection.remove(0); } return con; } public synchronized void returnConnection(Connection con){ lisConnection.add(con); } }
package org.sunshinelibrary.turtle; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import org.sunshinelibrary.turtle.init.InitService; import org.sunshinelibrary.turtle.syncservice.AppSyncService; import org.sunshinelibrary.turtle.utils.Logger; import org.sunshinelibrary.turtle.webservice.RestletWebService; /** * Created with IntelliJ IDEA. * User: fengxiaoping * Date: 10/14/13 * Time: 10:32 PM * To change this template use File | Settings | File Templates. */ public class SyncTriggerReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { Logger.i("trigger sync"); if(intent.getAction().equals(Intent.ACTION_BOOT_COMPLETED) && !InitService.isRunning){ Intent initIntent = new Intent(context, InitService.class); context.startService(initIntent); }else{ try{ TurtleManagers.userManager.login(); }catch (NullPointerException e){ e.printStackTrace(); Logger.e("-=-=-=-=-=-=-> Current userManager is Null !!"); } } } }
package com.example.todolist; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; public class dbHelper extends SQLiteOpenHelper { public dbHelper(Context context) { super(context, db.DB_NAME, null , db.DB_VERSION); } @Override public void onCreate(SQLiteDatabase sqLiteDatabase) { String createTable = "CREATE TABLE " + db.TaskEntry.TABLE + " ( " + db.TaskEntry._ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + db.TaskEntry.COL_TASK_TITLE + " TEXT NOT NULL);"; sqLiteDatabase.execSQL(createTable); } @Override public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) { sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + db.TaskEntry.TABLE); onCreate(sqLiteDatabase); } }
package com.trump.auction.goods.model; import lombok.Data; import lombok.ToString; import java.io.Serializable; import java.util.Date; /** * 商品图片model * @author zhangqingqiang * @since 2017-12-21 */ @Data @ToString public class ProductPicModel implements Serializable{ private Integer id; private String picUrl; private Integer skuId; private Integer colorId; private Integer productId; private Date createTime; private Date updateTime; private String picType; private String userId; private String userIp; }
package com.jigurd.trashrss; import android.content.Context; import android.content.SharedPreferences; import android.os.AsyncTask; import android.widget.TextView; import android.widget.Toast; import com.sun.syndication.feed.synd.SyndFeed; import com.sun.syndication.io.SyndFeedInput; import com.sun.syndication.io.XmlReader; import java.net.URL; import static android.content.Context.MODE_PRIVATE; import static com.jigurd.trashrss.MainActivity.USERPREFS; public class RSSReader extends AsyncTask<Void, Void, Boolean> { private String mURL; private Context mContext; RSSReader(Context iContext){ mContext = iContext; } @Override protected Boolean doInBackground(Void... voids) { SharedPreferences uPrefs = mContext.getSharedPreferences(USERPREFS, MODE_PRIVATE); mURL = uPrefs.getString("URL", ""); getFeed(mURL); return null; } private void getFeed(String iURL){ URL feedUrl; try { feedUrl = new URL(iURL); SyndFeedInput input = new SyndFeedInput(); SyndFeed feed = input.build(new XmlReader(feedUrl)); Toast.makeText(mContext, feed.toString(), Toast.LENGTH_SHORT).show(); } catch (Exception e) { e.printStackTrace(); System.out.println("Parse error: "+e.getMessage()); } System.out.println("test"); } }
package com.example.ren95.lab1_shakurov; import android.inputmethodservice.ExtractEditText; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.text.Layout; import android.view.View; import android.view.ViewGroup; import android.widget.CompoundButton; import android.widget.EditText; import android.widget.RadioButton; import android.widget.Switch; import android.widget.TextView; import java.util.ArrayList; import java.util.List; import java.util.ResourceBundle; public class MainActivity extends AppCompatActivity { private ArrayList<String> L_gramma = new ArrayList<String>(); private ArrayList<String> R_gramma = new ArrayList<String>(); private ArrayList<String> L_gramma_e = new ArrayList<String>(); private ArrayList<String> R_gramma_e = new ArrayList<String>(); private String[] str = {"0", "1", "e", "::=", " | "}; private int n = 4; EditText neterm0; EditText neterm1; EditText neterm2; EditText neterm3; EditText edit1; EditText edit2; EditText edit3; EditText edit4; EditText edit5; EditText edit6; EditText edit7; EditText edit8; EditText edit9; EditText edit10; EditText edit11; EditText edit12; ArrayList<View> layoutList; View layout1, layout2, layout3, layout4, layout; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); neterm0 = (EditText) findViewById(R.id.netrem0); neterm1 = (EditText) findViewById(R.id.neterm1); neterm2 = (EditText) findViewById(R.id.neterm2); neterm3 = (EditText) findViewById(R.id.neterm3); edit1 = (EditText) findViewById(R.id.edit1); edit2 = (EditText) findViewById(R.id.edit2); edit3 = (EditText) findViewById(R.id.edit3); edit4 = (EditText) findViewById(R.id.edit4); edit5 = (EditText) findViewById(R.id.edit5); edit6 = (EditText) findViewById(R.id.edit6); edit7 = (EditText) findViewById(R.id.edit7); edit8 = (EditText) findViewById(R.id.edit8); edit9 = (EditText) findViewById(R.id.edit9); edit10 = (EditText) findViewById(R.id.edit10); edit11 = (EditText) findViewById(R.id.edit11); edit12 = (EditText) findViewById(R.id.edit12); layout1 = (View) findViewById(R.id.view1); layout2 = (View) findViewById(R.id.view2); layout3 = (View) findViewById(R.id.view3); layout4 = (View) findViewById(R.id.view4); layout = (View) findViewById(R.id.view); Switch sw = (Switch)findViewById(R.id.switch1); sw.setChecked(true); sw.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if(isChecked==false){ n=3; layout4.setVisibility(View.INVISIBLE); } else { n=4; layout4.setVisibility(View.VISIBLE); } } }); } private void MatrToR_Gram(int[][] matr, int k, String[] noterm) { String temp = ""; for (int i = 0; i < n; i++) { temp += noterm[i] + str[3]; for (int j = 0; j < k; j++) { if (matr[i][j] != -1) { if (j != k - 1) temp += str[j] + noterm[matr[i][j]] + str[4]; else temp += str[j] + str[4]; } } if (temp.charAt(temp.length() - 2) == '|') temp = temp.substring(0, temp.length() - 3); R_gramma.add(temp); temp = ""; } } private void MatrToR_Gram_e(int[][] matr, int k, String[] noterm) { String temp = ""; for (int i = 0; i < n; i++) { temp += noterm[i] + str[3]; for (int j = 0; j < k - 1; j++) { if (matr[i][j] != -1) { temp += str[j] + noterm[matr[i][j]] + str[4]; if (matr[matr[i][j]][k - 1] == 1) temp += str[j] + str[4]; } } if (temp.charAt(temp.length() - 2) == '|') temp = temp.substring(0, temp.length() - 3); R_gramma_e.add(temp); temp = ""; } } private void MatrToL_Gram(int[][] matr, int k, String[] noterm) { String temp = ""; for (int i = 0; i < n; i++) { temp += noterm[i] + str[3]; L_gramma.add(temp); temp = ""; } for (int i = 0; i < n; i++) { for (int j = 0; j < k - 1; j++) { if (matr[i][j] != -1) { L_gramma.set(matr[i][j], L_gramma.get(matr[i][j]) + noterm[i] + str[j] + str[4]); } } } L_gramma.set(0, L_gramma.get(0) + str[k - 1]); for (int i = 0; i < n; i++)//удаление последней черты { int j = L_gramma.get(i).length(); if (L_gramma.get(i).charAt(j - 2) == '|') L_gramma.set(i, L_gramma.get(i).substring(0, j - 3)); } } private void MatrToL_Gram_e(int[][] matr, int k, String[] noterm)//без е { String temp = ""; for (int i = 0; i < n; i++) { temp += noterm[i] + str[3]; L_gramma_e.add(temp); temp = ""; } for (int i = 0; i < n; i++) { for (int j = 0; j < k - 1; j++) { if (matr[i][j] != -1) { if (i != 0) { L_gramma_e.set(matr[i][j], L_gramma_e.get(matr[i][j]) + noterm[i] + str[j] + str[4]); } else { L_gramma_e.set(matr[i][j], L_gramma_e.get(matr[i][j]) + noterm[i] + str[j] + str[4] + str[j] + str[4]); } } } } for (int i = 0; i < n; i++)//удаление последней черты { int j = L_gramma_e.get(i).length(); if (L_gramma_e.get(i).charAt(j - 2) == '|') L_gramma_e.set(i, L_gramma_e.get(i).substring(0, j - 3)); } } private ArrayList<View> getAllChildren(View v) { if (!(v instanceof ViewGroup)) { ArrayList<View> viewArrayList = new ArrayList<View>(); viewArrayList.add(v); return viewArrayList; } ArrayList<View> result = new ArrayList<View>(); ViewGroup vg = (ViewGroup) v; for (int i = 1; i < vg.getChildCount(); i++) { View child = vg.getChildAt(i); if (child instanceof EditText) { ArrayList<View> viewArrayList = new ArrayList<View>(); viewArrayList.addAll(getAllChildren(child)); result.addAll(viewArrayList); } else { if (child instanceof ViewGroup) { ArrayList<View> viewArrayList = new ArrayList<View>(); viewArrayList.addAll(getAllChildren(child)); result.addAll(viewArrayList); } } } return result; } public void getgramma(View view) { int k = 3; int[][] matr; String str_temp = ""; matr = new int[n][k]; layoutList = new ArrayList<>(); String[] neterm = {neterm0.getText().toString(), neterm1.getText().toString(), neterm2.getText().toString(), neterm3.getText().toString()}; ArrayList<View> layoutList = new ArrayList<>(); layoutList = this.getAllChildren(layout); int index=1; for (int j = 0; j < 12; j++) // считывание данных, создание матрицы { TextView ctrl = (TextView) findViewById(layoutList.get(j).getId()); str_temp = ctrl.getText().toString(); if (n * k >= index) { if ((index - 1) % k == k - 1) { if (str_temp.equals("1")) matr[(index - 1) / k][(index - 1) % k] = 1; else { matr[(index - 1) / k][(index - 1) % k] = -1; } } else { int f=0; if (str_temp.equals("")) {//добавил f = -1; } if(f==0){ for ( int i = 0; i < n;i++) { if (str_temp.equals(neterm[i])) { f = i; break; } } } if (f < n) matr[(index - 1) / k][(index - 1) % k] = f; /* else { matr[(index - 1) / k][(index - 1) % k] = -1; }*/ } } index++; } R_gramma.clear(); L_gramma.clear(); R_gramma_e.clear(); L_gramma_e.clear(); MatrToR_Gram(matr, k, neterm); MatrToL_Gram(matr, k, neterm); MatrToL_Gram_e(matr, k, neterm); MatrToR_Gram_e(matr, k, neterm); TextView textL = (TextView) findViewById(R.id.textView); textL.append("Левостороння грамматика\n"); for (int g = 0; g < n; g++)//Вывод { textL.append(L_gramma.get(g) + "\n"); } textL.append("\n"); for (int g = 0; g < n; g++)//Вывод { textL.append(L_gramma_e.get(g) + "\n"); } textL.append("Правосторонняя грамматика\n"); for (int g = 0; g < n; g++)//Вывод без e { textL.append(R_gramma.get(g) + "\n"); } textL.append("\n"); for (int g = 0; g < n; g++)//Вывод без e { textL.append(R_gramma_e.get(g) + "\n"); } } public void pressButtonClear(View view) { TextView l=(TextView)findViewById(R.id.textView); l.setText(""); ArrayList<View> layoutList = new ArrayList<>(); layoutList = this.getAllChildren(layout); for(int i=0;i<12;i++){ TextView ctrl = (TextView) findViewById(layoutList.get(i).getId()); ctrl.setText(""); } } }
//Name: Surbhi Goel //USC loginid: surbhigo@usc.edu //CS 455 PA2 //Fall 2016 import java.util.ArrayList; import java.util.Arrays; import java.util.Scanner; import java.util.StringTokenizer; public class PolynomialCalculator { /** Return a Polynomial version * As user enter Create command the prompt will ask for coeff-power pairs * If user missed the last exponent (i.e., odd number of values). For that ignores the last value entered (i.e., the term that had a coefficient given, but no corresponding exponent). * If a negative exponent is entered. For this uses the absolute value. For the last two items listed above, where you are taking corrective action, you should label your message with the string "WARNING:" instead. */ private static Polynomial UserInput(Scanner in) { ArrayList<Double> userList = new ArrayList<Double>(); Polynomial poly = new Polynomial(); double coeff = 0.0; int exponent = 0; System.out.println("Enter a space-separated sequence of coeff-power pairs terminated by <nl>" ); String input = in.nextLine(); Scanner lineScanner = new Scanner(input); while(lineScanner.hasNextDouble()) { userList.add(lineScanner.nextDouble()); } if(userList.size()%2!= 0) { System.out.println("WARNING: missing the last exponent (i.e., odd number of values)"); } for(int i = 0; i < userList.size()-1; i+=2) { if(userList.get(i+1) < 0) { System.out.println("WARNING: A negative exponent is found"); } coeff = userList.get(i); exponent = Math.abs(userList.get(i+1).intValue()); poly = poly.add(new Polynomial(new Term(coeff,exponent))); } return poly; } /** Return a Polynomial version * Assignment of polynomial to Polynomial Array * Checks for illegal polynomial index (for the array of polynomials) */ private static void createInput(int value, Polynomial polyArr[], Scanner in) { if(value > polyArr.length-1) { System.out.println("ERROR: illegal index for a poly. must be between 0 and 9, inclusive"); } else { Polynomial p2 = UserInput(in); polyArr[value]=p2; } } /** As user enter Print command then: Prints a String version of the polynomial. Polynomial is in a simplified form (only one term for any exponent), with no zero-coefficient terms, and terms are shown in decreasing order by exponent. */ private static void printPoly(int value , Polynomial polyArr[]) { if(value > polyArr.length-1) { System.out.println("ERROR: illegal index for a poly. must be between 0 and 9, inclusive"); } else { System.out.println(polyArr[value].toFormattedString()); } } /** As user enter eval command then the prompt will ask for floating point value for x and evaluates value of the polynomial at value for x. */ private static void evalPoly(int value, Polynomial polyArr[], Scanner in) { if(value > polyArr.length-1) { System.out.println("ERROR: illegal index for a poly. must be between 0 and 9, inclusive"); } else { System.out.print("Enter a floating point value for x: "); Double x = in.nextDouble(); System.out.println(polyArr[value].eval(x)); } } /** * As user enter add command then add two polynomials (neither poly is modified) */ private static void addPoly(Polynomial polyArr[], StringTokenizer st) { String check = st.nextToken(); String token = st.nextToken(); String nextToken = st.nextToken(); try { value = Integer.parseInt(check); int nextValue = Integer.parseInt(token); int lastValue = Integer.parseInt(nextToken); if((value > polyArr.length-1) || (nextValue > polyArr.length-1) || (lastValue > polyArr.length-1)) { System.out.println("ERROR: illegal index for a poly. must be between 0 and 9, inclusive"); } else { Polynomial poly1= polyArr[Integer.parseInt(token)]; Polynomial poly2= polyArr[Integer.parseInt(nextToken)]; Polynomial poly3= new Polynomial(); poly3 = poly2.add(poly1); polyArr[value] = poly3; } } catch(NumberFormatException e) { System.out.println("ERROR: Illegal command. Type 'help' for command options."); } } /* * As user enter help command then it will provide a command summary. */ private static void helpPoly() { System.out.println("create: To build a Polynomial"); System.out.println("print: To print a Polynomial"); System.out.println("eval: To evaluate value of Polynomial"); System.out.println("quit: To quit from running inputs"); } private static final int size = 10; //size of Polynomial array private static int value = 0; public static void main(String[] args) { boolean flag = true; Polynomial polyArr [] = new Polynomial[size]; //Initialize an array of 10 polynomials with zero value for(int i = 0; i < polyArr.length; i++) { polyArr[i] = new Polynomial(); } System.out.println("Press help to see all command options: "); Scanner in = new Scanner(System.in); while(flag) { String scan = in.nextLine(); String command = ""; StringTokenizer st = new StringTokenizer(scan, " "); while(st.hasMoreTokens()) { command = st.nextToken().toLowerCase(); if(command.equals("create") || command.equals("print") || command.equals("eval") || command.equals("add") || command.equals("quit") || command.equals("help")) { if(command.equals("create")) { String check = st.nextToken(); try { value = Integer.parseInt(check); createInput(value,polyArr,in); } catch(NumberFormatException e) { System.out.println("ERROR: Illegal command. Type 'help' for command options."); } } if(command.equals("print")) { String check = st.nextToken(); try { value = Integer.parseInt(check); printPoly(value, polyArr); } catch(NumberFormatException e) { System.out.println("ERROR: Illegal command. Type 'help' for command options."); } } if(command.equals("eval")) { String check = st.nextToken(); try { value = Integer.parseInt(check); evalPoly(value,polyArr,in); } catch(NumberFormatException e) { System.out.println("ERROR: Illegal command. Type 'help' for command options."); } } if(command.equals("add")) { addPoly(polyArr,st); } if(command.equals("help")) { if(st.hasMoreTokens()) { System.out.println("ERROR: Illegal command. Type 'help' for command options."); break; } else { helpPoly(); break; } } if(command.equals("quit")) { if(st.hasMoreTokens()) { System.out.println("ERROR: Illegal command. Type 'help' for command options."); break; } else { flag = false; break; } } } else { System.out.println("ERROR: Illegal command. Type 'help' for command options."); break; } } } } }
package com.aoharkov.soapproducing.endpoint; import com.aoharkov.soapproducing.GetTicketRequest; import com.aoharkov.soapproducing.GetTicketResponse; import com.aoharkov.soapproducing.ObjectFactory; import com.aoharkov.soapproducing.SaveTicketRequest; import com.aoharkov.soapproducing.SaveTicketResponse; import com.aoharkov.soapproducing.Ticket; import com.aoharkov.soapproducing.entity.TicketEntity; import com.aoharkov.soapproducing.mapper.Mapper; import com.aoharkov.soapproducing.repository.TicketRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.ws.server.endpoint.annotation.Endpoint; import org.springframework.ws.server.endpoint.annotation.PayloadRoot; import org.springframework.ws.server.endpoint.annotation.RequestPayload; import org.springframework.ws.server.endpoint.annotation.ResponsePayload; import java.util.NoSuchElementException; import java.util.Optional; @Endpoint public class TicketEndpoint { private static final String NAMESPACE_URI = "http://soapproducing.aoharkov.com"; private static final ObjectFactory OBJECT_FACTORY = new ObjectFactory(); private final TicketRepository ticketRepository; private final Mapper<TicketEntity, Ticket> ticketMapper; @Autowired public TicketEndpoint(TicketRepository ticketRepository, Mapper<TicketEntity, Ticket> ticketMapper) { this.ticketRepository = ticketRepository; this.ticketMapper = ticketMapper; } @PayloadRoot(namespace = NAMESPACE_URI, localPart = "getTicketRequest") @ResponsePayload public GetTicketResponse getTicket(@RequestPayload GetTicketRequest request) { GetTicketResponse response = OBJECT_FACTORY.createGetTicketResponse(); Optional<TicketEntity> ticketFromDB = ticketRepository.findById(request.getId()); if (!ticketFromDB.isPresent()) { throw new NoSuchElementException(); } Ticket ticketDto = ticketMapper.mapEntityToDto(ticketFromDB.get()); response.setTicket(ticketDto); return response; } @PayloadRoot(namespace = NAMESPACE_URI, localPart = "saveTicketRequest") @ResponsePayload public SaveTicketResponse saveTicket(@RequestPayload SaveTicketRequest request) { SaveTicketResponse response = OBJECT_FACTORY.createSaveTicketResponse(); TicketEntity ticketEntity = ticketMapper.mapDtoToEntity(request.getTicket()); response.setId(ticketRepository.save(ticketEntity)); return response; } }
package com.example.paindairy.entity; import androidx.annotation.NonNull; import androidx.room.ColumnInfo; import androidx.room.Entity; import androidx.room.Ignore; import androidx.room.PrimaryKey; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; @Entity public class PainRecord { @PrimaryKey(autoGenerate = true) public int uid; @ColumnInfo(name = "email_id") @NonNull public String emailId; @ColumnInfo(name = "pain_intensity_level") @NonNull public int painIntensityLevel; @ColumnInfo(name = "pain_location") @NonNull public String painLocation; @ColumnInfo(name = "moode_level") @NonNull public String moodLevel; @ColumnInfo(name = "steps_per_day") @NonNull public int stepsPerDay; @ColumnInfo(name = "step_goal", defaultValue = "10000") @NonNull public int stepGoal; @ColumnInfo(name = "current_date") @NonNull public Date currentDate; @NonNull public double temperature; @NonNull public double humidity; @NonNull public double pressure; @Ignore public PainRecord(@NonNull int painIntensityLevel, @NonNull String painLocation, @NonNull String moodLevel) { this.painIntensityLevel = painIntensityLevel; this.painLocation = painLocation; this.moodLevel = moodLevel; } @Ignore public PainRecord(@NonNull String emailId, @NonNull int painIntensityLevel, @NonNull String painLocation, @NonNull String moodLevel) { this.emailId = emailId; try { // SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy"); // this.currentDate = formatter.parse(formatter.format(new Date())); this.currentDate = new Date(); this.painIntensityLevel = painIntensityLevel; this.painLocation = painLocation; this.moodLevel = moodLevel; } catch (Exception e) { } } @Ignore public PainRecord(@NonNull String emailId, @NonNull int painIntensityLevel, @NonNull String painLocation, @NonNull String moodLevel, @NonNull int stepsPerDay) { try { SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy"); this.currentDate = formatter.parse(formatter.format(new Date())); this.emailId = emailId; this.painIntensityLevel = painIntensityLevel; this.painLocation = painLocation; this.moodLevel = moodLevel; this.stepsPerDay = stepsPerDay; } catch (Exception exception) { exception.printStackTrace(); } } @Ignore public PainRecord(@NonNull String emailId, int painIntensityLevel, @NonNull String painLocation, @NonNull String moodLevel, int stepsPerDay, double temperature, double humidity, double pressure) { try { SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy"); this.currentDate = formatter.parse(formatter.format(new Date())); this.emailId = emailId; this.painIntensityLevel = painIntensityLevel; this.painLocation = painLocation; this.moodLevel = moodLevel; this.stepsPerDay = stepsPerDay; this.temperature = temperature; this.humidity = humidity; this.pressure = pressure; } catch (Exception exception) { exception.printStackTrace(); } } public PainRecord(@NonNull String emailId, int painIntensityLevel, @NonNull String painLocation, @NonNull String moodLevel, int stepsPerDay, int stepGoal, @NonNull Date currentDate, @NonNull double temperature, @NonNull double humidity, @NonNull double pressure) { this.emailId = emailId; this.painIntensityLevel = painIntensityLevel; this.painLocation = painLocation; this.moodLevel = moodLevel; this.stepsPerDay = stepsPerDay; this.currentDate = currentDate; this.temperature = temperature; this.humidity = humidity; this.pressure = pressure; this.stepGoal = stepGoal; } }
package net.sduhsd.royr6099.unit11.gradebooklists; //© A+ Computer Science - www.apluscompsci.com //Name - //Date - //Class - //Lab - import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Scanner; import static java.lang.System.*; import static java.util.Arrays.*; import java.util.ArrayList; public class Class { private String name; private List<Student> studentList; public Class() { name=""; studentList = new ArrayList<Student>(); } public Class(String name, int stuCount) { this.name = name; studentList = new ArrayList<Student>(); } public void addStudent(int stuNum, Student s) { while (stuNum >= studentList.size()) { studentList.add(null); } studentList.set(stuNum, s); } public String getClassName() { return name; } public void sort() { Collections.sort(studentList); } public double getClassAverage() { double classAverage=0.0; for (Student s : studentList) { classAverage += s.getAverage(); } return classAverage / studentList.size(); } public double getStudentAverage(int stuNum) { return studentList.get(stuNum).getAverage(); } public double getStudentAverage(String stuName) { for (Student s : studentList) { if (s.getName().equals(stuName)) { return s.getAverage(); } } return 0.0; } public String getStudentName(int stuNum) { return studentList.get(stuNum).getName(); } public String getStudentWithHighestAverage() { return Collections.max(studentList).getName(); } public String getStudentWithLowestAverage() { return Collections.min(studentList).getName(); } public String getFailureList(double failingGrade) { String output=""; for (Student s : studentList) { if (s.getAverage() <= failingGrade) { output += s.getName() + " "; } } return output; } public String toString() { String output=""+getClassName()+"\n"; for (Student s : studentList) { output += s + "\t" + String.format("%.2f", s.getAverage()) + "\n"; } return output; } }
package funciones; import org.testng.ITestResult; public class SoutTest { //mostrar el resultado : pass / fall /bloqued public static void SouTest(ITestResult result) { System.out.println("El test" + result.getMethod().getDescription() + " resulto: " + result.getStatus()); } }
package com.zafkiel.Aspect; import com.zafkiel.POJO.AroundServiceReqVO; import com.zafkiel.POJO.AroundServiceRspVO; import com.zafkiel.Utils.AopTargetUtils; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Pointcut; import org.aspectj.lang.reflect.MethodSignature; import org.springframework.aop.framework.AopContext; import org.springframework.stereotype.Component; @Component @Aspect public class AroundAspect { @Pointcut("execution(* com.zafkiel.Service.IAroundService.*(*,String,*))") public void pointcut() { } @Around("pointcut()") public void aroundAdvice(ProceedingJoinPoint joinPoint) throws Throwable { System.out.println("---------------------"); System.out.println("执行目标方法前"); Object proxy = AopContext.currentProxy(); System.out.println("proxy:" + proxy.getClass().getName()); System.out.println("proxy:" + proxy); Object target= AopTargetUtils.getCglibProxyTargetObject(proxy); System.out.println("target:"+target.getClass().getName()); System.out.println("target:"+target); System.out.println(proxy==target); System.out.println(proxy.equals(target)); MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature(); Object returnType = methodSignature.getReturnType(); System.out.println("methodSignature:" + methodSignature.toString()); System.out.println("目标对象:" + joinPoint.getTarget()); System.out.println("目标方法:" + methodSignature.getDeclaringTypeName() + "." + methodSignature.getName()); Object[] args = joinPoint.getArgs(); if (null != args && args.length > 0) { if (args[0] instanceof AroundServiceReqVO) { AroundServiceReqVO arg0 = (AroundServiceReqVO) args[0]; System.out.println("入参0:" + arg0); System.out.println("arg0.nero:" + arg0.getNero()); System.out.println("arg0.saber:" + arg0.getSaber()); } if (args[1] instanceof String) { System.out.println("入参1:" + (String) args[1]); System.out.println("我将会改变入参1,改变为:" + "homula"); args[1] = "homula"; } if (args[2] instanceof Integer) { System.out.println("入参2:" + (Integer) args[2]); } } System.out.println("---------------------"); System.out.println("开始执行目标方法"); Object returnValue = joinPoint.proceed(args); System.out.println("执行目标方法结束"); System.out.println("---------------------"); System.out.println("改变参数1后执行返回的结果为:" + returnValue.toString()); AroundServiceRspVO returnObject = (AroundServiceRspVO) returnValue; System.out.println("returnObject.alterNero:" + returnObject.getAlterNero()); System.out.println("returnObject.alterSaber:" + returnObject.getAlterSaber()); System.out.println("---------------------"); } }
/* * Copyright 2002-2023 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 * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.expression.spel.ast; /** * Captures primitive types and their corresponding class objects, plus one special * {@link #OBJECT} entry that represents all reference (non-primitive) types. * * @author Andy Clement * @author Sam Brannen */ public enum TypeCode { /** * An {@link Object}. */ OBJECT(Object.class), /** * A {@code boolean}. */ BOOLEAN(Boolean.TYPE), /** * A {@code char}. */ CHAR(Character.TYPE), /** * A {@code byte}. */ BYTE(Byte.TYPE), /** * A {@code short}. */ SHORT(Short.TYPE), /** * An {@code int}. */ INT(Integer.TYPE), /** * A {@code long}. */ LONG(Long.TYPE), /** * A {@code float}. */ FLOAT(Float.TYPE), /** * A {@code double}. */ DOUBLE(Double.TYPE); private final Class<?> type; TypeCode(Class<?> type) { this.type = type; } public Class<?> getType() { return this.type; } public static TypeCode forName(String name) { for (TypeCode typeCode : values()) { if (typeCode.name().equalsIgnoreCase(name)) { return typeCode; } } return OBJECT; } public static TypeCode forClass(Class<?> clazz) { for (TypeCode typeCode : values()) { if (typeCode.getType() == clazz) { return typeCode; } } return OBJECT; } }
package com.androidcookbook.sensorupordown; import android.content.Context; import android.hardware.Sensor; import android.hardware.SensorEvent; import android.hardware.SensorEventListener; import android.hardware.SensorManager; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.widget.TextView; import java.util.*; public class MainActivity extends AppCompatActivity { private TextView mFace; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mFace = (TextView) findViewById(R.id.faceTextView); SensorManager sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE); List<android.hardware.Sensor> sensorList = sensorManager.getSensorList(Sensor.TYPE_ACCELEROMETER); sensorManager.registerListener(accelerometerListener, sensorList.get(0), 0, null); } private SensorEventListener accelerometerListener = new SensorEventListener() { @Override public void onSensorChanged(SensorEvent event) { float z = event.values[2]; if (z >9 && z < 10) mFace.setText("FACE UP"); else if (z > -10 && z < -9) mFace.setText("FACE DOWN"); } @Override public void onAccuracyChanged(Sensor arg0, int arg1) { // empty } }; }
package me.kpali.wolfflow.core.exception; /** * 任务中断异常 * * @author kpali */ public class TaskInterruptedException extends Exception { public TaskInterruptedException() { super(); } public TaskInterruptedException(String message) { super(message); } public TaskInterruptedException(Throwable cause) { super(cause); } }
import java.io.*; import java.util.*; class baek__14697 { static int[] dx = new int[3]; public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String[] temp = br.readLine().split(" "); for (int i = 0; i < 3; i++) { dx[i] = Integer.parseInt(temp[i]); } int n = Integer.parseInt(temp[3]); boolean[] check = new boolean[301]; Queue<Integer> q = new LinkedList<>(); for (int i = 0; i < 3; i++) { q.add(dx[i]); check[dx[i]] = true; } while (!q.isEmpty()) { int x = q.poll(); for (int k = 0; k < 3; k++) { int nx = x + dx[k]; if (nx > n) continue; if (check[nx]) continue; q.add(nx); check[nx] = true; } } System.out.print(check[n] ? 1 : 0); } }
public class UserDaoFactory { public UserDao createUserDao() { return new UserDaoImpl(); } }
package com.revature.web; import javax.naming.AuthenticationException; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; /** * Created by achen on 12/8/2016. */ public class FrontController { public void login(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException, ServletException, IOException { new MainController().login(request, response); } public void checkLogin(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { new MainController().checkLogin(request, response); } public void logout(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { new MainController().logout(request, response); } public void doMain(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { new MainController().doMain(request, response); } public void updateStatus(HttpServletRequest request, HttpServletResponse response) throws IOException { new MainController().updateStatus(request, response); } public void updateType(HttpServletRequest request, HttpServletResponse response) throws IOException { new MainController().updateType(request, response); } public void addReimbursement(HttpServletRequest request, HttpServletResponse response) throws IOException { new MainController().addReimbursement(request, response); } public void validateAmount(HttpServletRequest request, HttpServletResponse response) throws IOException { new MainController().validateAmount(request, response); } }
package md.tx.materialdesigndemo.complexCoordinatorLayout; import android.content.Context; import android.content.Intent; import android.support.design.widget.CollapsingToolbarLayout; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.Toolbar; import android.view.View; import md.tx.materialdesigndemo.R; public class IOExampleActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_ioexample); CollapsingToolbarLayout collapsingToolbarLayout = (CollapsingToolbarLayout) findViewById(R.id.collapsingToolbarLayout); collapsingToolbarLayout.setTitle("CollapsingToolbarLayout"); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); toolbar.setNavigationOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { onBackPressed(); } }); } public static void start(Context context) { context.startActivity(new Intent(context, IOExampleActivity.class)); } }
package com.kaka.blog.service; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.mail.javamail.JavaMailSender; import org.springframework.mail.javamail.MimeMessageHelper; import org.springframework.stereotype.Service; import javax.mail.MessagingException; import javax.mail.internet.MimeMessage; /** * @author Kaka */ @Service public class MailServiceImpl implements MailService{ private final Logger logger = LoggerFactory.getLogger(this.getClass()); @Autowired JavaMailSender javaMailSender; @Value("${spring.mail.username}") private String from; /** * 發送驗證信 * @param sendTo * @param mailTitle * @param mailContent */ @Override public void sendMail(String sendTo, String mailTitle, String mailContent) { logger.info("開始寫入驗證信..."); MimeMessage message = javaMailSender.createMimeMessage(); try { MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(message, true); mimeMessageHelper.setFrom(from); mimeMessageHelper.setSubject(mailTitle); mimeMessageHelper.setTo(sendTo); mimeMessageHelper.setText(mailContent, true); javaMailSender.send(message); logger.info("驗證信寄出..."); } catch (MessagingException e) { logger.error("驗證信寄出錯誤...", e); } } }
package com.mtl.hulk.bench.model; public class OrderEntry { String orderNum; public OrderEntry(String orderNum) { this.orderNum = orderNum; } }
package prueba.test; import static org.junit.Assert.*; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; import org.springframework.boot.test.autoconfigure.orm.jpa.TestEntityManager; import org.springframework.test.context.junit4.SpringRunner; import prueba.modelo.ClienteVO; import prueba.modelo.dao.IClienteDao; @RunWith(SpringRunner.class) @DataJpaTest public class ListarTodos { @Autowired TestEntityManager entityManager; @Autowired IClienteDao dao; @Before public void setUp() throws Exception { ClienteVO cliente1=new ClienteVO("1111", "juan apablo", "figueroa", "figueroa@gmail.com", "654654"); ClienteVO cliente2=new ClienteVO("2222", "Matias", "Alvares", "matias@gmail.com", "654656"); ClienteVO cliente3=new ClienteVO("3333", "Jaime", "Rodriguez", "jaime@gmail.com", "987654"); this.entityManager.persist(cliente1); this.entityManager.persist(cliente2); this.entityManager.persist(cliente3); } @Test public void cuandoFindAllEntonces3() { int cuantos=this.dao.findAll().size(); assertTrue("DEBERIAN SER 3 PERO SON : " + cuantos, cuantos==3); } }
package scripting; import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.HashMap; import java.util.Map; import world.Climate; import world.Worldhandler; import com.badlogic.gdx.graphics.Texture; import com.badlogic.gdx.graphics.g2d.TextureRegion; import com.rapplebob.ArmsAndArmorChampions.AAA_C; import com.rapplebob.ArmsAndArmorChampions.State; import static com.rapplebob.ArmsAndArmorChampions.AAA_C.*; import com.rapplebob.ArmsAndArmorChampions.*; import containers.Activator; import containers.ConHand; import containers.Container; import containers.Content; import containers.ContentType; import containers.Menu; import editor.Editorhandler; public class Scripthandler { //Spara pointers till alla variabler man kan ändra på i ett hashtable. //Låt en metod ställa in dessa variabler ifall variabeln finns i listan och se att värdet blir av korrekt typ. private static InputStreamReader inputStreamReader = new InputStreamReader(System.in); private static BufferedReader reader = new BufferedReader(inputStreamReader); private static boolean initialized = false; private static HashMap<String, Integer> genInts = new HashMap<String, Integer>(); public static void initialize(){ loadGenericVariables(); initialized = true; } public static void update() { try { if (reader.ready()) { handleScript(reader.readLine()); } } catch (Exception ex) { ex.printStackTrace(); } } public static void loadGenericVariables(){ genInts.put("BRUSHCLIMATE", Editorhandler.brush.CELL.CLIMATE); genInts.put("BRUSHTERRAIN", Editorhandler.brush.CELL.TERRAIN); } public static void handleScript(String script) { // Ta bort kommentarer, mellanrum o.s.v script = cleanupScript(script); // Kolla efter metoder såsom GET_ och fyll i variabler. script = fillScript(script); // Loopa igenom olika kommandon och utför dem. while (script.contains("#")) { activateScript(script); script = script.substring(script.indexOf("#") + 1); } activateScript(script); //System.out.println(script); } public static void activateScript(String script) { if (script.length() > 0) { if (script.length() > 1) { if (script.contains("#")) { readLine(script.substring(0, script.indexOf("#"))); } else { readLine(script); } } else { if (!script.contains("#")) { readLine(script); } } } } public static String cleanupScript(String script) { while (script.contains(" ")) { script = script.substring(0, script.indexOf(" ")) + script.substring(script.indexOf(" ") + 1); } return script; } public static String fillScript(String script) { while (script.contains("GET_")) { script = script.substring(0, script.indexOf("GET_")) + getVar(script.substring(script.indexOf("GET_") + 4, script.indexOf("_TEG"))) + script.substring(script.indexOf("_TEG") + 4); } return script; } public static String getVar(String id) { //Skriv kodfanskapet. String value = "[GET-ERROR]"; if(id.substring(0, 4).equals("loc_")){ value += "[LOC]"; id = id.substring(4); //Hämta en lokal variabel såsom titeln på den activator som kommandot skickades från. if(id.substring(0, 15).equals("activatorTitle_")){ id = id.substring(15); value = getActivatorTitleById(id); }else if(id.substring(0, 12).equals("activatorId_")){ id = id.substring(12); value = getActivatorIdByTitle(id); } }else{ if(genInts.containsKey(id)){ value = genInts.get(id).toString(); } } return value; } public static void readLine(String line) { String cmd = line.substring(0, line.indexOf("_") + 1); if (line.length() == 5) { if (cmd.equals("exit_")) { exit(); } } if (line.length() == 5) { if (cmd.equals("test_")) { System.out.println("Test successful!"); } } if (line.length() > 9) { if (cmd.equals("openMenu_")) { openMenu(line); } } if (line.length() > 6) { if (cmd.equals("setAA_")) { ConHand.getActiveMenu().activeAct = Integer.parseInt(line.substring(6)); } } if (line.length() == 9) { if (cmd.equals("activate_")) { handleScript(ConHand.getActiveAct().script); } } if (line.length() > 6) { if (cmd.equals("print_")) { System.out.println(line.substring(6)); } } if (line.length() == 10) { if (cmd.equals("startgame_")) { setStage(); newState = State.GAME; } } if (line.length() == 8) { if (cmd.equals("endgame_")) { save(); newState = State.MENU; } } if (line.length() == 9) { if (cmd.equals("continue_")) { gamePaused = false; } } if (line.length() == 14) { if (cmd.equals("unpauseEditor_")) { editorPaused = false; } } if (line.length() > 9) { if (cmd.equals("setState_")) { setState(line.substring(9)); } } if (line.length() > 10) { if (cmd.equals("switchCon_")) { switchContainer(line.substring(10)); } } if (line.length() > 12) { if (cmd.equals("setActImage_")) { setActImage(line.substring(12)); } } if (line.length() > 12) { if (cmd.equals("setActTitle_")) { setActTitle(line.substring(12)); } } } public static String getActivatorIdByTitle(String title){ String id = ""; String script = ""; Menu m = ConHand.getActiveMenu(); boolean found = false; for(int i = 0; i < m.acts.size(); i++){ if(m.acts.get(i).title.equals(title)){ id = m.acts.get(i).ID; found = true; break; } } if(!found){ for(Map.Entry<String, Container> entry : ConHand.cons.entrySet()){ Container C = ConHand.cons.get(entry.getKey()); for(int i = 0; i < C.CONTENT.size(); i++){ Content CT = C.CONTENT.get(i); if(CT.TYPE == ContentType.MENU){ m = (Menu) CT; for(int mi = 0; mi < m.acts.size(); mi++){ if(m.acts.get(i).title.equals(title)){ id = m.acts.get(i).ID; found = true; break; } } if(found){ break; } } } if(found){ break; } } } return title; } public static String getActivatorTitleById(String id){ String title = ""; String script = ""; Menu m = ConHand.getActiveMenu(); boolean found = false; for(int i = 0; i < m.acts.size(); i++){ if(m.acts.get(i).ID.equals(id)){ title = m.acts.get(i).title; found = true; break; } } if(!found){ for(Map.Entry<String, Container> entry : ConHand.cons.entrySet()){ Container C = ConHand.cons.get(entry.getKey()); for(int i = 0; i < C.CONTENT.size(); i++){ Content CT = C.CONTENT.get(i); if(CT.TYPE == ContentType.MENU){ m = (Menu) CT; for(int mi = 0; mi < m.acts.size(); mi++){ if(m.acts.get(i).ID.equals(id)){ title = m.acts.get(i).title; found = true; break; } } if(found){ break; } } } if(found){ break; } } } return title; } public static void setState(String state){ State temp = State.parseState(state); AAA_C.newState = State.parseState(state); System.out.println(state + " - " + temp.toString()); } public static void openMenu(String cmd) { String id = cmd.substring(cmd.indexOf("_") + 1); ConHand.getActiveMenuholder().openMenuByID(id); } public static void switchContainer(String ID){ if(ConHand.getContainer(ID).ACTIVE){ ConHand.getContainer(ID).ACTIVE = false; }else{ ConHand.getContainer(ID).ACTIVE = true; } } public static void setActImage(String cmd){ Activator A = ConHand.getActById(cmd.substring(0, cmd.indexOf("_"))); cmd = cmd.substring(cmd.indexOf("_") + 1); String type = cmd.substring(0, cmd.indexOf("_")); cmd = cmd.substring(cmd.indexOf("_") + 1); boolean useTex = false; Texture tex = AAA_C.getActiveRenderer().actBack; TextureRegion reg = new TextureRegion(); switch(type){ case "Climate":reg = Worldhandler.getClimateImage(Worldhandler.getClimateIdByString(cmd)); useTex = false; break; case "Terrain":reg = Worldhandler.getTerrainImage(Worldhandler.getTerrainIdByString(cmd)); useTex = false; break; case "Image":reg = ConHand.getSharedTexture(cmd); useTex = false; break; } if(useTex){ A.TEX = new TextureRegion(tex, tex.getWidth(), tex.getHeight()); }else{ A.TEX = reg; } } //setActTitle_EDICON01_Climate_GET_BRUSHCLIMATE_TEG public static void setActTitle(String cmd){ String aid = cmd.substring(0, cmd.indexOf("_")); cmd = cmd.substring(cmd.indexOf("_") + 1); String type = cmd.substring(0, cmd.indexOf("_")); cmd = cmd.substring(cmd.indexOf("_") + 1); String title = cmd; switch(type){ case "Climate": title = Worldhandler.climates.get(Integer.parseInt(cmd)).CLIMATE; break; case "Terrain": title = Worldhandler.terrains.get(Integer.parseInt(cmd)).TERRAIN; break; } String cid = ConHand.getContainerByAct(aid).ID; for(Map.Entry<String, Content> entry : ConHand.cons.get(cid).CONTENT.entrySet()){ Menu m = (Menu) ConHand.cons.get(cid).CONTENT.get(entry.getKey()); if(m.TYPE == ContentType.MENU){ if(m.acts.containsKey(aid)){ ConHand.cons.get(cid).CONTENT.get(entry.getKey()). = cmd; } } } } }
package com.example.elearning.repositories; import com.example.elearning.entities.Apprenant; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; public interface ApprenantRepository extends JpaRepository<Apprenant,Integer> { @Query("select aa from Apprenant aa") Page<Apprenant> listapprenants(Pageable pageable); @Query("select aa from Apprenant aa where aa.nom like :mc") Page<Apprenant> findByDesignationApprenant(@Param("mc") String mc, Pageable pageable); }
package top.lvjp.rabbitmqconsumer.config; import org.springframework.amqp.core.*; import org.springframework.amqp.rabbit.connection.CachingConnectionFactory; import org.springframework.amqp.rabbit.connection.ConnectionFactory; import org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer; import org.springframework.amqp.rabbit.listener.api.ChannelAwareMessageListener; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import top.lvjp.rabbitmqmodel.entity.TOrder; import java.io.ByteArrayInputStream; import java.io.InputStream; import java.io.ObjectInputStream; import static top.lvjp.rabbitmqmodel.constant.Constants.*; /** * 手动配置 rabbitmq 消息接受 * @author lvjp * @date 2019/5/4 */ @Configuration public class RabbitMQConfig { @Bean public ConnectionFactory connectionFactory() { CachingConnectionFactory connectionFactory = new CachingConnectionFactory("127.0.0.1", 5672); connectionFactory.setUsername("guest"); connectionFactory.setPassword("guest"); connectionFactory.setVirtualHost("/"); connectionFactory.setPublisherConfirms(true); connectionFactory.setPublisherReturns(true); return connectionFactory; } @Bean public TopicExchange orderExchange() { return new TopicExchange(ORDER_EXCHANGE, true, false); } @Bean public Queue orderQueue() { return new Queue(ORDER_QUEUE, true); } @Bean(name = "orderBinding") public Binding orderBinding() { return BindingBuilder.bind(orderQueue()) .to(orderExchange()) .with(ROUTING_KEY); } @Bean public SimpleMessageListenerContainer messageListenerContainer() { SimpleMessageListenerContainer container = new SimpleMessageListenerContainer(connectionFactory()); container.setQueues(orderQueue()); container.setExposeListenerChannel(true); container.setMaxConcurrentConsumers(5); container.setConcurrentConsumers(1); container.setAcknowledgeMode(AcknowledgeMode.MANUAL); container.setMessageListener((ChannelAwareMessageListener) (message, channel) -> { byte[] body = message.getBody(); InputStream in = new ByteArrayInputStream(body); TOrder order = (TOrder) new ObjectInputStream(in).readObject(); System.out.println("orderQueue 收到消息: " + order); channel.basicAck(message.getMessageProperties().getDeliveryTag(), false); }); return container; } }
package com.example.cam.timetable; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import java.util.ArrayList; public class ModuleViewActivity extends AppCompatActivity { public static ArrayList<String> ArrayofModule = new ArrayList<>(); @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.content_module_view); ListView listView = (ListView) findViewById(R.id.listView1); DatabaseHandler db = new DatabaseHandler(this); db.getAllModules(); ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, ArrayofModule); listView.setAdapter(adapter); listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { public void onItemClick(AdapterView<?> parent, View v, int position, long id) { Toast.makeText(getApplicationContext(), ((TextView) v).getText(), Toast.LENGTH_SHORT).show(); } }); } }
package emp.entidades; import java.io.Serializable; import java.util.List; import java.util.Date; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.JoinColumn; import javax.persistence.Lob; import javax.persistence.ManyToOne; import javax.persistence.OneToMany; import javax.persistence.Table; import javax.persistence.Temporal; import javax.persistence.TemporalType; import javax.persistence.Transient; import org.junit.Ignore; import com.axcessfinancial.domain.*; import com.sun.org.apache.xml.internal.security.c14n.helper.C14nHelper; @Entity @Table(name="tb_solicitud_documento") public class TipoSolicitudDocumento extends com.axcessfinancial.domain.BaseEntity implements Serializable{ private DocumentoAdjuntar documento; private TipoSolicitud tipoSolicitud; @ManyToOne @JoinColumn(name = "idDocumentoAdjuntar", insertable = true, updatable = true) public DocumentoAdjuntar getDocumento() { return documento; } public void setDocumento(DocumentoAdjuntar documento) { this.documento = documento; } @ManyToOne @JoinColumn(name = "idTipoSolicitud", insertable = true, updatable = true) public TipoSolicitud getTipoSolicitud() { return tipoSolicitud; } public void setTipoSolicitud(TipoSolicitud tipoSolicitud) { this.tipoSolicitud = tipoSolicitud; } }
package com.entities; public class Product { String id; String name; public Product(String id, String name) { // TODO Auto-generated constructor stub this.id = id; this.name=name; } @Override public String toString() { // TODO Auto-generated method stub return super.toString(); } @Override public int hashCode() { // TODO Auto-generated method stub return super.hashCode(); } 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; } }
package web.viewhelper.impl; import java.io.IOException; import java.util.ArrayList; import java.util.List; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import classes.util.Resultado; import dominio.evento.Evento; import dominio.evento.IDominio; import dominio.participantes.Participante; import dominio.viewmodels.ParticipanteEventoVM; import web.viewhelper.IViewHelper; public class ParticipantesEventoVH implements IViewHelper { @Override public IDominio getData(HttpServletRequest request) { String operacao = request.getParameter("operacao"); ParticipanteEventoVM participantes = new ParticipanteEventoVM(); String requestIds = request.getParameter("id"); if(operacao.equals("SALVAR") || operacao.equals("ATUALIZAR") || operacao.equals("EXCLUIR")) { String[] strId = requestIds.split(","); int[] ids = new int[strId.length]; int idEvento = Integer.parseInt(request.getParameter("evt-id")); Evento evento = new Evento(); evento.setId(idEvento); participantes.setEvento(evento); ArrayList<Participante> listaParticipantes = new ArrayList<Participante>(); for(int i = 0; i < strId.length; i++) { ids[i] = Integer.parseInt(strId[i]); Participante p = new Participante(); p.setId(ids[i]); listaParticipantes.add(p); } participantes.setParticipantes(listaParticipantes); } else if(operacao.equals("CONSULTAR")) { int idEvento = Integer.parseInt(request.getParameter("evtid")); boolean listaIncluidos = request.getParameter("incluidos").equals("true") ? true : false; System.out.println("Incluidos: " + listaIncluidos); Evento evento = new Evento(); evento.setId(idEvento); participantes.setEvento(evento); participantes.setIncluidos(listaIncluidos); } return participantes; } @Override public void formataView(Resultado resultado, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { String operacao = request.getParameter("operacao"); String uri = request.getRequestURI(); List<IDominio> recebido = null; List<Participante> ptcRecebidos = null; String msgErro = ""; if(resultado != null) { msgErro = resultado.getMensagem(); recebido = resultado.getEntidades(); ptcRecebidos = (List<Participante>) (Object) recebido; } if(msgErro != null && msgErro != "") { request.setAttribute("mensagem", msgErro); request.getRequestDispatcher("erro.jsp").forward(request, response); } else { if(recebido == null || recebido.size() <= 0) { request.setAttribute("erro", "Não há participantes"); request.getRequestDispatcher("sucesso.jsp").forward(request, response); } else { if(operacao.equals("CONSULTAR")) { if(uri.equals("/gestao-eventos-web/evento/consultar-participantes")) { System.out.println("CONSULTAR PARTICIPANTES"); request.setAttribute("resultado", ptcRecebidos); request.getRequestDispatcher("seleciona-participantes.jsp").forward(request, response); } else { request.setAttribute("resultado", ptcRecebidos); request.getRequestDispatcher("participantes-evento.jsp").forward(request, response); } } else { request.getRequestDispatcher("sucesso.jsp").forward(request, response); } } } // caso não tenha mensagem de erro } // final do método }
/** * $Id: Roster.java,v 1.19 2005/09/13 15:15:44 nicks Exp nicks $ * * Container class form maintaining information about singers, conductors, * directors and other production participants. * * Originally part of the AMATO application. * * @author Nick Seidenman <nick@seidenman.net> * @version $Revision: 1.19 $ * * $Log: Roster.java,v $ * Revision 1.19 2005/09/13 15:15:44 nicks * "changed" flag is now set for any add or delete operation. * * Revision 1.18 2005/09/07 18:02:00 nicks * Got rid of clueless nullArray construct. * * Revision 1.17 2005/08/21 19:28:03 nicks * Added conductor selector combobox. * * Revision 1.16 2005/08/15 14:26:28 nicks * Changed as_* to to* (more java-esque) * * Revision 1.15 2005/08/15 13:52:19 nicks * Several mods to support DnD, AddPerformanceFrame. * Changed as_* to to* (more java-esque) * * Revision 1.14 2005/08/08 19:09:53 nicks * Comments modified to comply with javadoc stds. * * Revision 1.13 2005/08/03 18:33:53 nicks * Now able to add Singers, Musicians, Conductors, Directors, Staff on RosterPanel pop-up menu. * * Revision 1.12 2005/07/22 22:12:39 nicks * Started work on Drag-n-Drop within RosterPanel. * Cleaned up nearly all warnings. Only a few left in Opera.java, Operas.java, * and Performance.java and these pertain to strict type-checking ala 1.5. * Just wanted to check everything in now as a check point. I'll continue * to work on getting a totally clean compilation. * * Revision 1.11 2005/07/19 18:14:36 nicks * Retired PerformerList objects. Now working on a Population * object class that will become the base class for objects * that can return lists of constituents according to all * sorts of criteria. Stay tuned ... * * Revision 1.10 2005/07/18 03:26:43 nicks * Save function was broken due to re-wiring of the Roster tree. * Fixed. * * Revision 1.9 2005/07/17 11:48:35 nicks * toJPanel instead of as_JLabel (instead of toHTML). * * Revision 1.8 2005/06/30 15:39:39 nicks * Added serialVersionUID to keep the 5.0 compiler happy. * (sheesh!) * * Revision 1.7 2005/06/29 19:51:37 nicks * Added conductor(s) to performance(s). * * Revision 1.6 2005/06/27 20:55:45 nicks * voice attribute of Singer is now an ArrayList. This lets one define a * singer who can sing a range of voices, not just one. For example, * Some sopranos can also sing mezzo, or some baritones can also do (low) * tenor roles. Voices are specified as a comma-separated list. * * Revision 1.5 2005/06/25 19:07:17 nicks * Fixed a nullpointer situation that would arise when the role * called for a voice for which there were no singers in the roster. * * Revision 1.4 2005/06/23 15:22:39 nicks * Cleaned up a few minor problems. * * Revision 1.3 2005/06/22 21:41:53 nicks * Cheap, demo version of cast selection working. (Will use real * java stuff, not this crappy html vaporware.) * Had to make the AmatoDB object globally visible for this * sort of thing to work. I hate doing it, but I guess there's no * harm for the moment since this is a self-contained application. * * Revision 1.2 2005/06/18 04:19:02 nicks * Have OperaPanel and RosterPanel (cheesy versions) working. * This should be suitable for demo to Irene sometime soon. * I just want to more or less dummy up a SeasonPanel and I'll * be ready to demo. * * Revision 1.1 2005/06/15 14:51:08 nicks * Initial revision * */ import java.io.*; import java.util.*; import javax.swing.*; import javax.swing.tree.*; import javax.swing.event.*; import java.awt.*; import java.awt.datatransfer.*; import java.awt.dnd.*; public class Roster extends DefaultMutableTreeNode { private static final long serialVersionUID = 20050630112720L; private DefaultTreeModel treeModel; private DefaultMutableTreeNode singers = null; private DefaultMutableTreeNode conductors = null; private DefaultMutableTreeNode musicians = null; private DefaultMutableTreeNode directors = null; private DefaultMutableTreeNode staff = null; public Roster () { super ("Roster"); treeModel = new DefaultTreeModel (this); singers = new DefaultMutableTreeNode ("Singers"); conductors = new DefaultMutableTreeNode ("Conductors"); musicians = new DefaultMutableTreeNode ("Musicians"); directors = new DefaultMutableTreeNode ("Directors"); staff = new DefaultMutableTreeNode ("Staff"); treeModel.insertNodeInto (staff, this, 0); treeModel.insertNodeInto (directors, this, 0); treeModel.insertNodeInto (musicians, this, 0); treeModel.insertNodeInto (conductors, this, 0); treeModel.insertNodeInto (singers, this, 0); } public void add (Constituent c) { int i = 0; int[] j = new int[1]; DefaultMutableTreeNode subtree = determineSubtree (c); int nodeCount = subtree.getChildCount (); while (i < nodeCount) { Constituent kid = (Constituent) subtree.getChildAt (i); //System.out.println ("Roster.add: kid(" + i + "): " + kid); if (kid.toString().compareTo (c.toString()) >= 0) { break; } ++i; } treeModel.insertNodeInto (c, subtree, i); if (Amato.db != null) Amato.db.setChanged(true); } public void remove (Constituent c) { for (Performance p: c.getPerformances()) { p.removeCast (c); } c.setValid (false); treeModel.removeNodeFromParent ((MutableTreeNode) c); Amato.db.setChanged(true); } private DefaultMutableTreeNode determineSubtree (Constituent c) { if (c instanceof Singer) return singers; else if (c instanceof Musician) return musicians; else if (c instanceof Director) return directors; else if (c instanceof Conductor) return conductors; else return staff; } public String toXML () { String result; int nodeCount = getChildCount(); result = "<roster>\n"; // Emit the constituents // This will work for now. If we go with more levels within // the tree (e.g. voice subtree under singers) then this will // have to be rewritten. for (int i = 0; i < nodeCount; i++) { DefaultMutableTreeNode tn = (DefaultMutableTreeNode) getChildAt (i); int subtreeNodeCount = tn.getChildCount(); for (int j = 0; j < subtreeNodeCount; j++) { DefaultMutableTreeNode tn2 = (DefaultMutableTreeNode) tn.getChildAt (j); Constituent c = (Constituent) tn2; result += c.toXML (); result += "\n"; } } // Emit the end tag result += "</roster>"; return result; } final public String toHTML () { String result = "<html><h1>Roster</h1>\n<hr>\n</html>"; return result; } public JPanel toJPanel () { JPanel p = new JPanel (new FlowLayout ()); p.setBorder (BorderFactory.createEmptyBorder (10, 10, 10, 10)); JLabel l = new JLabel (toHTML(), JLabel.LEFT); p.add (l); p.setBorder (BorderFactory.createTitledBorder (toString())); return p; } final public JLabel getSubtreeJLabel (String stName) { JLabel l = new JLabel ("<html><h1>" + stName + "</h1><hr></html>", JLabel.CENTER); l.setBorder (BorderFactory.createTitledBorder (stName)); return l; } final public Object[] findCastMember (Cast c) { return findByName (c.getFirstName(), c.getLastName()); } final public Object[] getVoice (String voice) { Vector<Singer> v = new Vector<Singer>(); int i = 0; int nodeCount = 0; // System.out.println ("voice: " + voice); nodeCount = singers.getChildCount (); for (i = 0; i < nodeCount; i++) { Singer s = (Singer) singers.getChildAt (i); if (s.hasVoice (voice)) { v.add (s); } } return (Object[]) v.toArray(); } final public Object[] getConductors () { Vector<Conductor> v = new Vector<Conductor>(); int i = 0; int nodeCount = 0; nodeCount = conductors.getChildCount (); for (i = 0; i < nodeCount; i++) { v.add ((Conductor) conductors.getChildAt (i)); } return v.toArray(); } final public DefaultComboBoxModel createConductorComboBoxModel () { DefaultComboBoxModel ccbm = new DefaultComboBoxModel (getConductors()); String tba = new String ("TBA"); ccbm.addElement (tba); ccbm.setSelectedItem (tba); return ccbm; } final public Object[] findByName (String lastName) { Vector<Constituent> v = new Vector<Constituent>(); int i = 0; int nodeCount = 0; // Return a zero-length array. if (lastName == null) return new Object[0]; nodeCount = singers.getChildCount (); for (i = 0; i < nodeCount; i++) { Constituent m = (Constituent) singers.getChildAt (i); if (lastName.equals (m.getLastName())) { v.add (m); } } nodeCount = musicians.getChildCount (); for (i = 0; i < nodeCount; i++) { Constituent m = (Constituent) musicians.getChildAt (i); if (lastName.equals (m.getLastName())) { v.add (m); } } nodeCount = conductors.getChildCount (); for (i = 0; i < nodeCount; i++) { Constituent m = (Constituent) conductors.getChildAt (i); if (lastName.equals (m.getLastName())) { v.add (m); } } nodeCount = directors.getChildCount (); for (i = 0; i < nodeCount; i++) { Constituent m = (Constituent) directors.getChildAt (i); if (lastName.equals (m.getLastName())) { v.add (m); } } nodeCount = staff.getChildCount (); for (i = 0; i < nodeCount; i++) { Constituent m = (Constituent) staff.getChildAt (i); if (lastName.equals (m.getLastName())) { v.add (m); } } return v.toArray(); } final public Object[] findByName (String firstName, String lastName) { Object[] cArray = findByName (lastName); Vector<Constituent> v = new Vector<Constituent>(); for (int i = 0; i < cArray.length; i++ ) { Constituent m = (Constituent) cArray[i]; if (lastName.equals (m.getLastName()) && firstName.equals (m.getFirstName())) { v.add (m); } } return v.toArray (); } public void addTreeModelListener (TreeModelListener tml) { treeModel.addTreeModelListener (tml); } final public boolean isLeaf() { return false; } public DefaultMutableTreeNode getSingers () { return singers; } }
package algorithm._19; public class Solution { public static void main(String[] args) { ListNode listNode = new ListNode(1); ListNode listNode1 = new ListNode(2); ListNode listNode2 = new ListNode(3); ListNode listNode3 = new ListNode(4); ListNode listNode4 = new ListNode(5); listNode.next = listNode1; listNode1.next = listNode2; listNode2.next = listNode3; listNode3.next = listNode4; System.out.println(new Solution().removeNthFromEnd(listNode, 1)); } public ListNode removeNthFromEnd(ListNode head, int n) { ListNode tmpNode = new ListNode(0); tmpNode.next = head; int size = 0; ListNode cursor = head; while (cursor != null) { cursor = cursor.next; size++; } cursor = tmpNode; size -= n; while (size > 0) { cursor = cursor.next; size--; } cursor.next = cursor.next.next; return tmpNode.next; } } class ListNode { int val; ListNode next; ListNode(int x) { val = x; } @Override public String toString() { return String.format("ListNode val : %d , next : %s", val, next != null ? next.toString() : "null"); } }
package tal.com.orders.entities; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.Table; @Entity @Table(name = "items") public class Item { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "item_id") private Integer id; @Column(name = "description") private String description; @Column(name = "price") private int price; @ManyToOne(optional = false) @JoinColumn(referencedColumnName = "id", name = "order_id") private Order order; public Item() { } public Item(int id, String description, int price, Order order) { super(); this.id = id; this.description = description; this.price = price; this.order = order; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public int getPrice() { return price; } public void setPrice(int price) { this.price = price; } public Order getOrder() { return order; } public void setOrder(Order order) { this.order = order; } }
package domain; import java.time.LocalDate; public interface KanVervallen { LocalDate getVervaldatum(); boolean isVervallen(); }
/** */ package mmodelb.impl; import mmodela.impl.ItemImpl; import mmodelb.ItemB; import mmodelb.MmodelbPackage; import org.eclipse.emf.ecore.EClass; /** * <!-- begin-user-doc --> * An implementation of the model object '<em><b>Item B</b></em>'. * <!-- end-user-doc --> * <p> * </p> * * @generated */ public class ItemBImpl extends ItemImpl implements ItemB { /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected ItemBImpl() { super(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override protected EClass eStaticClass() { return MmodelbPackage.Literals.ITEM_B; } } //ItemBImpl
/* * Copyright 2010 mathieuancelin. * * 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. * under the License. */ package com.buzybeans.core.proxy; import com.buzybeans.core.beans.Bean; import java.lang.reflect.Method; import javassist.util.proxy.MethodFilter; import javassist.util.proxy.MethodHandler; /** * * @author Mathieu ANCELIN */ public class DynamicProxy<T> implements MethodFilter, MethodHandler { private final Bean<T> bean; private final Class<T> type; public static <R> DynamicProxy<R> getDynamicProxy(Class<R> type, Bean<R> bean) { return new DynamicProxy<R>(type, bean); } private DynamicProxy(Class<T> type, Bean<T> bean) { this.bean = bean; this.type = type; } public Class<T> getType() { return type; } @Override public boolean isHandled(Method method) { return true; } @Override public Object invoke(Object self, Method method, Method proceed, Object[] args) throws Throwable { return bean.localCall(method, args); } }
/*********************************************************************** * Module: PayInfoEnd.java * Author: djl * Purpose: Defines the Class PayDetail ***********************************************************************/ package com.lenovohit.ebpp.bill.model; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Table; import javax.persistence.Transient; import org.apache.commons.lang3.builder.EqualsBuilder; import org.apache.commons.lang3.builder.HashCodeBuilder; import org.apache.commons.lang3.builder.ToStringBuilder; import com.lenovohit.core.model.BaseIdModel; @Entity @Table(name = "IH_EBPP_END_PAYINFO") public class PayInfoEnd extends BaseIdModel { private static final long serialVersionUID = 2656939416556528121L; @Transient public static final String VALID_FLAG_TRUE = "1"; @Transient public static final String VALID_FLAG_FALSE = "0"; @Transient public static final String INVALID_TYPE_EMPTY_ORIBIZNO = "1"; @Transient public static final String INVALID_TYPE_EMPTY_PAYNO = "2"; @Transient public static final String INVALID_TYPE_EMPTY_WAY = "3"; @Transient public static final String INVALID_TYPE_NOT_FOUND_BILL = "4"; // @Transient // public static final String INVALID_TYPE_NOT_UNIQUE = "5"; private String no; private String oriBizNo; private String payNo;//SEQUENCENO private String status; private float amt; private String payedTime;//TRAN_TIME private String way;//TRAN_WAY private int quantity;//TRAN_QUANTITY private String payChannel;//TRAN_CHANEL private String createdOn; private String updatedOn; private String insertTime; private String validFlag; private String invalidType; private String invalidInfo; private String syncDate; private String syncType; private String syncFlag; @Column(name = "SEQUENCENO", length = 30) public String getPayNo() { return payNo; } public void setPayNo(String payNo) { this.payNo = payNo; } @Column(name = "STATUS", length = 2) public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } @Column(name="NO", length=30) public String getNo() { return no; } public void setNo(String no) { this.no = no; } @Column(name = "AMT") public float getAmt() { return amt; } public void setAmt(float amt) { this.amt = amt; } @Column(name = "TRAN_CHANEL") public String getPayChannel() { return payChannel; } public void setPayChannel(String payChannel) { this.payChannel = payChannel; } @Column(name = "TRAN_WAY",length = 2) public String getWay() { return way; } public void setWay(String way) { this.way = way; } // @Column(name = "TRAN_QUALITY") // public float getQuality() { // return quality; // } // // public void setQuality(float quality) { // this.quality = quality; // } @Column(name = "TRAN_QUANTITY") public int getQuantity() { return quantity; } public void setQuantity(int quantity) { this.quantity = quantity; } @Column(name = "TRAN_TIME",length=19) public String getPayedTime() { return payedTime; } public void setPayedTime(String payedTime) { this.payedTime = payedTime; } @Column(name = "ORIBIZNO", length = 50) public String getOriBizNo() { return oriBizNo; } public void setOriBizNo(String oriBizNo) { this.oriBizNo = oriBizNo; } public String getValidFlag() { return validFlag; } public void setValidFlag(String validFlag) { this.validFlag = validFlag; } public String getInvalidType() { return invalidType; } public void setInvalidType(String invalidType) { this.invalidType = invalidType; } public String getInvalidInfo() { return invalidInfo; } public void setInvalidInfo(String invalidInfo) { this.invalidInfo = invalidInfo; } public String getCreatedOn() { return createdOn; } public void setCreatedOn(String createdOn) { this.createdOn = createdOn; } public String getUpdatedOn() { return updatedOn; } public void setUpdatedOn(String updatedOn) { this.updatedOn = updatedOn; } public String getInsertTime() { return insertTime; } public void setInsertTime(String insertTime) { this.insertTime = insertTime; } public String getSyncDate() { return syncDate; } public void setSyncDate(String syncDate) { this.syncDate = syncDate; } public String getSyncType() { return syncType; } public void setSyncType(String syncType) { this.syncType = syncType; } public String getSyncFlag() { return syncFlag; } public void setSyncFlag(String syncFlag) { this.syncFlag = syncFlag; } /** * 重载toString; */ public String toString() { return ToStringBuilder.reflectionToString(this); } /** * 重载hashCode; */ public int hashCode() { return new HashCodeBuilder().append(this.getId()).toHashCode(); } /** * 重载equals */ public boolean equals(Object obj) { return EqualsBuilder.reflectionEquals(this, obj); } // @Transient // public String getbID() { // return bID; // } // // public void setbID(String bID) { // this.bID = bID; // } }
/* * Author: Adam Liszka * License: See LICENSE.txt * Description: Listens for clocks that have "[gameclock]" or * "[realclock]" on the first line of the sign. There is no * listener for block destroyed events because clocks check * if they are still valid in the ClockUpdater loop and remove * themselves if they are no longer attached to a sign. It may * be the case that the clock is improperly read from file or * otherwise directed to a non sign block. The sign formats * are as follows: * * [gameclock] * ClockLabel * -unused at this time- * ClockFormat * * [realclock] * ClockLabel * TimeZone * ClockFormat * * ClockLabel becomes "as is" line 2 on the clock * TimeZone affects the timezone of SystemClock clocks * ClockFormat changes the format of the clock (i.e. "hh:mm") * * Lines 1-3 are entirely optional. * * Todo: Permissions... */ package com.bobcat00.wallclock; import com.bobcat00.wallclock.Clocks.GameClock; import com.bobcat00.wallclock.Clocks.SystemClock; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.block.SignChangeEvent; public class SignListener implements Listener { protected WallClockPlugin plugin; public SignListener(WallClockPlugin plugin) { this.plugin = plugin; } @EventHandler public void blockEvent(SignChangeEvent event) { String[] lines = event.getLines(); if (lines[0].equals("[gameclock]")) { GameClock clock = new GameClock(event.getBlock()); clock.setLabel(lines[1]); clock.setFormat(lines[3]); plugin.addClock(clock); } else if (lines[0].equals("[realclock]")) { SystemClock clock = new SystemClock(event.getBlock()); clock.setLabel(lines[1]); clock.setTimeZone(lines[2]); clock.setFormat(lines[3]); plugin.addClock(clock); } } }
package com.example.dailymaple; import androidx.annotation.Nullable; import androidx.appcompat.app.AppCompatActivity; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.util.DisplayMetrics; import android.view.View; import android.view.Window; import android.widget.Button; public class DeletePopupActivity extends Activity implements View.OnClickListener { Button button_cancel; Button button_delete; Intent intent; Intent intent2; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.activity_delete_popup); DisplayMetrics dm = getApplicationContext().getResources().getDisplayMetrics(); int width = (int) (dm.widthPixels * 0.9); // Display 사이즈의 90% int height = (int) (dm.heightPixels * 0.4); // Display 사이즈의 50% getWindow().getAttributes().width = width; getWindow().getAttributes().height = height; button_cancel = findViewById(R.id.button_cancel); button_cancel.setOnClickListener(this); button_delete = findViewById(R.id.button_delete); button_delete.setOnClickListener(this); intent2 = getIntent(); } @Override public void onClick(View v) { switch (v.getId()){ case R.id.button_cancel: finish(); case R.id.button_delete: intent = new Intent(); intent.putExtra("btn_id",intent2.getIntExtra("btn_id",0)); setResult(RESULT_OK, intent); finish(); } } }
package android.transitions.everywhere.utils; import android.animation.LayoutTransition; import android.annotation.TargetApi; import android.os.Build.VERSION; import android.os.Build.VERSION_CODES; import android.view.ViewGroup; import java.lang.reflect.Field; @TargetApi(VERSION_CODES.HONEYCOMB) public class ViewGroupUtils { interface ViewGroupUtilsImpl { void suppressLayout(ViewGroup group, boolean suppress); } @TargetApi(VERSION_CODES.JELLY_BEAN) static class BaseViewGroupUtilsImpl implements ViewGroupUtilsImpl { private static Field sFieldLayoutSuppressed; static LayoutTransition mLayoutTransition = new LayoutTransition() { @Override public boolean isChangingLayout() { return true; } }; static { mLayoutTransition.setAnimator(LayoutTransition.APPEARING, null); mLayoutTransition.setAnimator(LayoutTransition.CHANGE_APPEARING, null); mLayoutTransition.setAnimator(LayoutTransition.CHANGE_DISAPPEARING, null); mLayoutTransition.setAnimator(LayoutTransition.DISAPPEARING, null); mLayoutTransition.setAnimator(LayoutTransition.CHANGING, null); } @Override public void suppressLayout(ViewGroup group, boolean suppress) { if (suppress) { group.setLayoutTransition(mLayoutTransition); } else { group.setLayoutTransition(null); if (sFieldLayoutSuppressed == null) { sFieldLayoutSuppressed = ReflectionUtils.getPrivateField(ViewGroup.class, "mLayoutSuppressed"); } Boolean suppressed = (Boolean) ReflectionUtils.getFieldValue(group, Boolean.FALSE, sFieldLayoutSuppressed); if (!Boolean.FALSE.equals(suppressed)) { ReflectionUtils.setFieldValue(group, sFieldLayoutSuppressed, false); group.requestLayout(); } } } } @TargetApi(VERSION_CODES.JELLY_BEAN_MR2) static class JellyBeanMr2ViewGroupUtilsImpl extends BaseViewGroupUtilsImpl { @Override public void suppressLayout(ViewGroup group, boolean suppress) { ViewGroupUtilsJellyBeanMr2.suppressLayout(group, suppress); } } private static final ViewGroupUtilsImpl IMPL; static { if (VERSION.SDK_INT >= VERSION_CODES.JELLY_BEAN_MR2) { IMPL = new JellyBeanMr2ViewGroupUtilsImpl(); } else { IMPL = new BaseViewGroupUtilsImpl(); } } public static void suppressLayout(ViewGroup group, boolean suppress) { if (group != null) { IMPL.suppressLayout(group, suppress); } } }
package com.chao.wifiscaner.action; import java.util.ArrayList; import android.app.Activity; import com.chao.wifiscaner.controller.Controller; import com.chao.wifiscaner.controller.PutController; import com.chao.wifiscaner.model.PutItem; import com.chao.wifiscaner.model.WifiItem; import com.chao.wifiscaner.ui.PutActivity; import com.chao.wifiscaner.view.LoadingDialog; public abstract class PutAction extends Action { protected Activity activity; protected PutController controller; protected ArrayList<WifiItem> wifiItems; protected ArrayList<PutItem> putItems; protected final LoadingDialog dialog; public PutAction(Controller controller) { super(controller); this.controller=(PutController)controller; this.activity=this.controller.getActivity(); wifiItems=((PutActivity)activity).wifiItems; putItems=((PutActivity)activity).putItems; dialog=new LoadingDialog(activity); } }
package final_G22; import static spark.Spark.*; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.URLDecoder; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Comparator; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.math.BigDecimal; import java.util.regex.Matcher; import java.util.regex.Pattern; import spark.ModelAndView; import spark.template.velocity.VelocityTemplateEngine; import org.apache.log4j.Logger; import org.json.simple.parser.JSONParser; import org.json.simple.parser.ParseException; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import com.amazonaws.AmazonClientException; import com.amazonaws.auth.profile.ProfileCredentialsProvider; import com.amazonaws.regions.Regions; import com.amazonaws.services.dynamodbv2.AmazonDynamoDB; import com.amazonaws.services.dynamodbv2.AmazonDynamoDBClientBuilder; import com.amazonaws.services.dynamodbv2.document.DynamoDB; import com.amazonaws.services.dynamodbv2.document.Item; import com.amazonaws.services.dynamodbv2.document.Table; import com.amazonaws.services.s3.AmazonS3; import com.amazonaws.services.s3.AmazonS3ClientBuilder; import com.amazonaws.services.s3.model.S3Object; import com.amazonaws.services.s3.model.S3ObjectInputStream; public class FrontendApp { static final int NUM_OF_THREADS = 20; static final Logger logger = Logger.getLogger(FrontendApp.class); static AmazonDynamoDB client; static JSONParser parser = new JSONParser(); static int totalFiles; static Map<String, Double> pageRank = new HashMap<>(); static boolean isDebug = false; public static void main(String[] args) { staticFiles.location("/public"); port(8081); threadPool(NUM_OF_THREADS); System.out.println("Indexer Main starts!"); if(args.length < 1) { System.err.println("You need to provide the total number of files."); System.exit(1); } totalFiles = Integer.parseInt(args[0]); if (args.length == 2) { isDebug = true; } File pageRankDir = new File("pagerankscores"); File[] pageRankFiles = pageRankDir.listFiles(); // System.out.println(pageRankFiles.length); for (int i = 0; i < pageRankFiles.length; i++) { try(FileReader fr = new FileReader(pageRankFiles[i]); BufferedReader br = new BufferedReader(fr);) { String line; while ((line = br.readLine()) != null) { line = line.substring(1, line.length()-1); String[] pair = line.split(","); double val = 1; try { val = Double.parseDouble(pair[1]); } catch (NumberFormatException e) { // System.out.println(line); } pageRank.put(pair[0], val); } } catch (IOException e) { e.printStackTrace(); } } // System.out.println("PageRank size: " + pageRank.size()); // get("/", (request,response) -> { // return "<html><body>" // + "<form action=\"/tfidf\" method=\"POST\">" // + "<label for=\"name\">Search: </label>" // + "<input type=\"text\" name=\"query\" required/><br>" // + "<input type=\"submit\" value=\"Search\"/>" // + "</form></body></html>"; // }); // get("/tfidf", (request,response) -> { // String query = request.queryParams("query"); // String [] keys = query.split(" "); // System.out.println("query:"+query); // System.out.println("key number:"+keys.length); // Map<String, String> invertedlist = getDataFromDynamo(keys); // // HashMap<String, Double> ret = comupteTFIDF(invertedlist); // return ret.toString(); // }); get("/", (req, res) -> { Map<String, Object> model = new HashMap<>(); return new VelocityTemplateEngine().render( new ModelAndView(model, "public/splash.vm") ); }); get("/search", (req, res) -> { String key = req.queryParams("key"); String page = req.queryParams("page"); if (key == null || key.isEmpty()) { res.redirect("/"); return null; } boolean isFirstPage = false; boolean isLastPage = false; int pageNum; if (page == null || page.isEmpty()) { pageNum = 1; } else { pageNum = Integer.parseInt(page); } List<String> keys = new ArrayList<String>(); try { Pattern pattern = Pattern.compile("[\\p{Alnum}]+"); Matcher matcher = pattern.matcher(key); while(matcher.find()) { String keyItem = matcher.group().toLowerCase(); keys.add(keyItem); } System.out.println("query:"+key); System.out.println("key number:"+keys.size()); } catch (Exception e) { e.printStackTrace(); } Map<String, String> invertedlist = getDataFromDynamo(keys); // System.out.println(ret.toString()); Map<String, Double> urlDfidfMap = comupteTFIDF(invertedlist); // try { // for (Entry<String, String> entry : invertedlist.entrySet()) { // String map = entry.getValue(); // map = map.substring(1, map.length()-1); // String[] pairs = map.split(","); // for (String pair : pairs) { // String[] tuple = pair.split(":"); // String url = tuple[0]; // url = url.substring(1, url.length()-1); // url = URLDecoder.decode(url, "UTF-8"); // String tfidfStr = tuple[1]; // // System.out.println(tfidfStr); // double tfidf = (new BigDecimal(tfidfStr)).doubleValue(); // if (urlDfidfMap.containsKey(url)) { // urlDfidfMap.put(url, urlDfidfMap.get(url) + tfidf); // } else { // urlDfidfMap.put(url, tfidf); // } // } // } // } catch (Exception e) { // e.printStackTrace(); // } if ((urlDfidfMap.size() < (pageNum -1) * 10) || pageNum < 1) { pageNum = 1; } List<String> ranked = getRanked(urlDfidfMap, pageNum); List<LinkInfo> rankedLinks = new LinkedList<>(); try { for (String link : ranked) { double tfidf = urlDfidfMap.get(link); LinkInfo info = new LinkInfo(link, tfidf); double pageRankScore = 1; if (pageRank.containsKey(link)) { pageRankScore = pageRank.get(link); } info.setPageRank(pageRankScore); double weightTfidf = 0.99; double weightPageRank = 0.01; double harmonic = ((weightTfidf + weightPageRank) / ((weightTfidf/tfidf) + (weightPageRank/pageRankScore))); info.setHarmonic(harmonic); Document doc = Jsoup.connect(link).get(); info.setTitle(doc.title()); info.setBody(doc.body().text().substring(0, 70) + "..."); rankedLinks.add(info); } } catch (Exception e) { e.printStackTrace(); } if (pageNum == 1) { isFirstPage = true; } if (ranked.size() != 10) { isLastPage = true; } Map<String, Object> model = new HashMap<>(); model.put("ranked", rankedLinks); model.put("isFirstPage", isFirstPage); model.put("isLastPage", isLastPage); model.put("key", key); model.put("page", pageNum); model.put("isDebug", isDebug); model.put("prev", pageNum - 1); model.put("next", pageNum + 1); return new VelocityTemplateEngine().render( new ModelAndView(model, "public/search.vm") ); }); } private static List<String> getRanked(Map<String, Double> map, int page) { List<String> ranked = new LinkedList<>(); Map<String, Double> copy = new HashMap<>(); for (Entry<String, Double> mapEntry : map.entrySet()) { String link = mapEntry.getKey(); double tfidf = mapEntry.getValue(); double pageRankScore = 1; if (pageRank.containsKey(link)) { pageRankScore = pageRank.get(link); } double weightTfidf = 0.99; double weightPageRank = 0.01; double harmonic = ((weightTfidf + weightPageRank) / ((weightTfidf/tfidf) + (weightPageRank/pageRankScore))); // System.out.println("tfidf: " + tfidf + ", pageRank: " + pageRankScore + ", harmonic: " + harmonic); copy.put(link, harmonic); } //Use Comparator.reverseOrder() for reverse ordering copy.entrySet() .stream() .sorted(Map.Entry.comparingByValue(Comparator.reverseOrder())) .forEachOrdered(x -> ranked.add(x.getKey())); List<String> partitionedRanked = ranked.subList((page-1)*10, Math.min(page*10, ranked.size())); return partitionedRanked; } public static Map<String,String> getDataFromDynamo(List<String> keys) { //load credential ProfileCredentialsProvider credentialsProvider = new ProfileCredentialsProvider(); try { credentialsProvider.getCredentials(); } catch (Exception e) { System.out.println("Update Credential"); throw new AmazonClientException( "Cannot load the credentials from the credential profiles file. " + "Please make sure that your credentials file is at the correct " + "location (~/.aws/credentials), and is in valid format.", e); } try { //create client client = AmazonDynamoDBClientBuilder.standard() .withCredentials(credentialsProvider) .withRegion("us-east-1") .build(); } catch (Exception e) { e.printStackTrace(); } DynamoDB dynamoDB = new DynamoDB(client); Table table = dynamoDB.getTable("InvertedIndex"); //word, {doc:tf, doc:tf} Map<String,String> invertedlist = new HashMap<String,String>(); PorterStemmer s = new PorterStemmer(); for(String key : keys) { //stem search key boolean allLetters = true; for(int i=0; i<key.length(); i++) { char ch = key.charAt(i); if(Character.isLetter(ch)) { s.add(ch); } else { s.reset(); allLetters = false; break; } } if(allLetters){ s.stem(); key = s.toString(); s.reset(); } Item item = null; try { item = table.getItem("word", key); } catch (Exception e) { e.printStackTrace(); } if(item == null) { System.out.println("Item " + key + " does not exsit"); continue; } String json = item.toJSON(); try { Object obj = parser.parse(json); HashMap<String, String> map = (HashMap<String, String>)obj; String info = map.get("info"); System.out.println(key+" "+info); invertedlist.put(key, info); } catch (ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } } // // return invertedlist; } public static HashMap<String, Double> comupteTFIDF( Map<String,String> invertedlist) throws IOException { //docid: scores HashMap<String, Double> scorings = new HashMap<String, Double>(); for(String word: invertedlist.keySet()) { String info = invertedlist.get(word); //read large info from s3 files if(info.startsWith("s3://")) { String bucket_name = "testmyindexer";//this can be changed final AmazonS3 s3 = AmazonS3ClientBuilder.standard().withRegion(Regions.US_EAST_1).build(); S3Object o = s3.getObject(bucket_name, "storage/"+word); if(o == null) { System.out.println("Cannot find object in s3"); continue; } S3ObjectInputStream s3is = o.getObjectContent(); InputStreamReader streamReader = new InputStreamReader(s3is); BufferedReader reader = new BufferedReader(streamReader); info = ""; String line; if((line=reader.readLine())!=null) { info = line; } } Object obj; try { obj = parser.parse(info); HashMap<String, Double> map = (HashMap<String, Double>)obj; for(String docid: map.keySet()) { String link = URLDecoder.decode(docid, "UTF-8"); double tf = (0.4+(1-0.4)* map.get(docid)); double idf = Math.log((double)totalFiles/(double)map.size()); double score = scorings.getOrDefault(docid, (double) 0); score += tf*idf; scorings.put(link,score); } } catch (ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return scorings; } }
package view.insuranceSystemView.developView.developer.showInsurance; import java.awt.Color; import java.awt.event.ActionListener; import model.data.insuranceData.AbsInsuranceData; import model.dataList.IntDataList; import view.aConstant.InsuranceSystemViewConstant; import view.component.BasicLabel; import view.component.SeparateLine; import view.component.TitledRadioButtonGroup; import view.component.button.LinkButton; import view.component.button.SelectButton; import view.component.group.DynamicGroup; import view.component.textArea.InputTextArea; import view.insuranceSystemView.absInsuranceSystemView.InsuranceSystemView; @SuppressWarnings("serial") public class SelectInsuranceToWatchView extends InsuranceSystemView { // Static public enum EActionCommands {InsuranceDesign, WatchInsuranceData} // Component private InputTextArea nameTTA, contentTTA, insuranceRateInfoTTA, lossPercentTTA; private TitledRadioButtonGroup diseaseTRBG; // Constructor public SelectInsuranceToWatchView(ActionListener actionListener, IntDataList<AbsInsuranceData> insuranceList) { this.addComponent(new BasicLabel("보험 선택")); this.addComponent(new SeparateLine(Color.black)); DynamicGroup selectBtnGroup = new DynamicGroup(); for(AbsInsuranceData insuranceData : insuranceList.getList()) { selectBtnGroup.addGroupComponent(new SelectButton(insuranceData.getName(), Integer.toString(insuranceData.getID()), actionListener)); } this.addComponent(selectBtnGroup); this.addToLinkPanel( new LinkButton(InsuranceSystemViewConstant.SomeThingLookGreat, "", null), new LinkButton(InsuranceSystemViewConstant.SomeThingLookNide, "", null), new LinkButton("보험 설계", EActionCommands.InsuranceDesign.name(), actionListener), new LinkButton("보험 정보 확인", EActionCommands.WatchInsuranceData.name(), actionListener) ); } // Getter & Setter public String getName() {return this.nameTTA.getContent();} public String getContent() {return this.contentTTA.getContent();} public String getInsuranceRateInfo() {return this.insuranceRateInfoTTA.getContent();} public String getLossPercent() {return this.lossPercentTTA.getContent();} public String getDisease() {return this.diseaseTRBG.getSelectedOptionNames().get(0);} }
//program to demonstrate to promation rule class promation { public static void main(String args[]) { byte a,b=2; short s,k=5; int i,m=2,k=5; a=b; Systm.out.println("Value of var a="+a); a=b*10; s=k*b; i=k*10+b; i=m*k; s=m*2+k; }//close of main }//close of class
import java.util.Scanner; public class Runner { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.println("write word1 in 2^ :"); String word1 =scanner.nextLine(); System.out.println("write word2:"); String word2 =scanner.nextLine(); CreateArray createArray = new CreateArray(); char[][] arrayWord1 = createArray.fillTheArray(word1); createArray.printArray(arrayWord1); SimileWords simileWords = new SimileWords(); simileWords.matchSearch(arrayWord1,word2); } }
import java.util.*; public class Ch19_05 { public static enum Color {WHITE, BLACK}; public static class GraphVertex { Color color; List<GraphVertex> edges; GraphVertex(Color color, List<GraphVertex> edges) { this.color = color; this.edges = edges; } } //assumes vertex inputted is within a connected graph public static boolean isMinimallyConnected(GraphVertex vertex) { if (vertex == null) { return false; } return !hasCycle(vertex); } public static boolean hasCycle(GraphVertex vertex) { if (vertex.color == Color.BLACK) { return true; } vertex.color = Color.BLACK; boolean isCycle = false; for (GraphVertex adjVertex : vertex.edges) { if (!isCycle) { isCycle = hasCycle(adjVertex); } } return isCycle; } public static void main(String[] args) { //create graph GraphVertex A = new GraphVertex(Color.WHITE, new LinkedList<GraphVertex>()); GraphVertex B = new GraphVertex(Color.WHITE, new LinkedList<GraphVertex>()); GraphVertex C = new GraphVertex(Color.WHITE, new LinkedList<GraphVertex>()); GraphVertex D = new GraphVertex(Color.WHITE, new LinkedList<GraphVertex>()); GraphVertex E = new GraphVertex(Color.WHITE, new LinkedList<GraphVertex>()); GraphVertex F = new GraphVertex(Color.WHITE, new LinkedList<GraphVertex>()); A.edges.addAll(Arrays.asList(B, C, D)); B.edges.add(E); C.edges.add(F); E.edges.add(A); //outputs if graph is minimally connected System.out.println(isMinimallyConnected(A)); } }
package com.esum.comp.dbc.template; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Map; import org.apache.commons.lang.StringUtils; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import com.esum.comp.dbc.jdbc.common.OrderedRecord; import com.esum.comp.dbc.job.JobExecutor; import com.esum.comp.dbc.template.impl.JdbcAction; import com.esum.comp.dbc.template.impl.JdbcReader; import com.esum.comp.dbc.template.impl.JdbcTrigger; import com.esum.comp.dbc.template.impl.JdbcWriter; import com.esum.comp.dbc.template.impl.Query; import com.esum.comp.dbc.utils.BatchUtils; import com.esum.framework.common.util.SysUtil; /** * @author kim.ryeowon * * Copyright(c) eSum Technologies., Inc. All rights reserved. */ public class Template { private Entity trigger; private Entity reader; private Entity writer; private List<Entity> actions; private String keyField; private String description; public void load(Document document) throws Exception { Element docElement = document.getDocumentElement(); NamedNodeMap map = docElement.getAttributes(); if(map!=null && map.getLength()> 0) { Node childNode = map.getNamedItem("keyField"); if (childNode != null && childNode.getNodeValue() != null) { keyField = childNode.getNodeValue().trim(); } } actions = new ArrayList<Entity>(); NodeList childList = docElement.getChildNodes(); if(childList!=null && childList.getLength()!=0){ for(int i=0;i<childList.getLength();i++){ Node childNode = childList.item(i); if(childNode.getNodeType()!=Node.ELEMENT_NODE) continue; String nodeName = childNode.getNodeName(); if(nodeName.equals("jdbcTrigger")){ trigger = new JdbcTrigger(childNode); } else if(nodeName.equals("jdbcReader")){ reader = new JdbcReader(childNode); } else if(nodeName.equals("jdbcWriter")){ writer = new JdbcWriter(childNode); } else if(nodeName.equals("jdbcAction")){ Entity action = new JdbcAction(childNode); actions.add(action); } else if(nodeName.equals("description")){ description = childNode.getTextContent(); } else throw new Exception("Invalid document element name : "+nodeName); } } if(actions!=null) { for(Entity entity : actions) { JdbcAction action = (JdbcAction)entity; if(action.getReader()!=null) initReader(action.getReader()); if(action.getWriter()!=null) initWriter(action.getWriter()); } } if(reader!=null) { initReader((JdbcReader)reader); } if(writer!=null) { initWriter((JdbcWriter)writer); } } private void initReader(JdbcReader jdbcReader) { Map<String, Query> queries = jdbcReader.getQueries(); Iterator<String> i = queries.keySet().iterator(); while(i.hasNext()) { String id = i.next(); Query query = queries.get(id); if(StringUtils.isNotEmpty(query.getAckQuery())) { Query ackQuery = getQueryById(query.getAckQuery()); if(ackQuery!=null) ackQuery.setQueryType(Query.QUERY_ACK); } if(StringUtils.isNotEmpty(query.getErrorQuery())) { Query errQuery = getQueryById(query.getErrorQuery()); if(errQuery!=null) errQuery.setQueryType(Query.QUERY_ERROR); } } } private void initWriter(JdbcWriter jdbcWriter) { List<Query> queries = jdbcWriter.getQueries(); Iterator<Query> i = queries.iterator(); while(i.hasNext()) { Query query = i.next(); if(StringUtils.isNotEmpty(query.getAckQuery())) { Query ackQuery = getQueryById(query.getAckQuery()); if(ackQuery!=null) ackQuery.setQueryType(Query.QUERY_ACK); } if(StringUtils.isNotEmpty(query.getErrorQuery())) { Query errQuery = getQueryById(query.getErrorQuery()); if(errQuery!=null) errQuery.setQueryType(Query.QUERY_ERROR); } } } public Entity getTrigger() { return trigger; } public Entity getReader() { return reader; } public Entity getWriter() { return writer; } public String getDescription() { return description; } public List<String> getKeyFields() { return BatchUtils.getTokenList(keyField, JobExecutor.SEP_COMMA); } public String getKeyField(OrderedRecord item) { if (keyField == null) { return null; } List<String> keyFields = BatchUtils.getTokenList(keyField, JobExecutor.SEP_COMMA); StringBuffer sb = new StringBuffer(); if (item != null && (keyFields != null && !keyFields.isEmpty())) { for(String key : keyFields) { Object value = item.get(key); if (value != null) { sb.append(String.valueOf(value)); sb.append(JobExecutor.SEP_PIPE); } } sb.setLength((sb.length()>1)? sb.length()-1 : 0); } return sb.toString(); } public List<Entity> getActions() { return actions; } public Query getQueryById(String queryId) { Query query = null; if(actions!=null) { for(Entity entity : actions) { JdbcAction action = (JdbcAction)entity; if(action.getReader()!=null) { query = searchQueryInReader(action.getReader(), queryId); if(query!=null) return query; } if(action.getWriter()!=null) { query = searchQueryInWriter(action.getWriter(), queryId); if(query!=null) return query; } } } query = searchQueryInReader(getReader(), queryId); if(query!=null) return query; query = searchQueryInWriter(getWriter(), queryId); if(query!=null) return query; return null; } private Query searchQueryInReader(Entity reader, String queryId) { JdbcReader jdbcReader = (JdbcReader)reader; if(jdbcReader!=null) { return jdbcReader.getQueryById(queryId); } return null; } private Query searchQueryInWriter(Entity writer, String queryId) { JdbcWriter jdbcWriter = (JdbcWriter)writer; if(jdbcWriter!=null) { return jdbcWriter.getQueryById(queryId); } return null; } public String toString() { StringBuffer sb = new StringBuffer(); sb.append("Template ["); sb.append("description="); sb.append(getDescription()); sb.append(", keyField="); sb.append(keyField); sb.append(SysUtil.LINE_SEPARATOR); if(trigger!=null) { sb.append(trigger); sb.append(SysUtil.LINE_SEPARATOR); } if(reader!=null) { sb.append(reader); sb.append(SysUtil.LINE_SEPARATOR); } if(writer!=null) { sb.append(writer); sb.append(SysUtil.LINE_SEPARATOR); } if(actions!=null) { for(Entity action : actions) { sb.append(action); sb.append(SysUtil.LINE_SEPARATOR); } } sb.append("]"); return sb.toString(); } }
package xyz.mcallister.seth.HG.scoreboard; import xyz.mcallister.seth.HG.Main; /** * Created by sethm on 30/05/2016. */ public class Manager { private Main plugin; public Manager(Main plugin) { this.plugin = plugin; } public void init() {} public void tear() {} public void reload() {} public Main getPlugin() { return this.plugin; } }
package com.gaby.exception; /** * @Description: 自定义的异常父类 * @Author: wengzhongjie * @CreateDate: 2019-03-14 14:05 */ public class BaseException extends RuntimeException{ public BaseException() { } public BaseException(Throwable cause) { super(cause); } public BaseException(String message) { super(message); } public BaseException(String message, Throwable cause) { super(message, cause); } }
package cn.edu.nju.software.timemachine.service; import cn.edu.nju.software.timemachine.entity.Picture; public interface IPictureService<T extends Picture> extends IService<T> { public long addPicture(T picture); public T getPicture(long id); }
package pp; import org.apache.log4j.Logger; import pp.model.Btl; import pp.model.Fighter; import pp.model.xml.CGlad; import pp.service.GlRuService; import java.io.IOException; import java.util.Calendar; import java.util.Collections; import java.util.TimeZone; /** * Created by alsa on 09.08.2016. */ public class ChampGuildActivity extends Activity { public static final Logger LOGGER = Logger.getLogger(TournamentActivity.class); private static final long MIN = 60 * 1000; private static final long HOUR = MIN * 60; public long counter; private StuffManager stuffManager = new StuffManagerImpl(service); private Fighter fighter; protected ChampGuildActivity(final GlRuService service) { super(service); this.fighter = new FighterImpl(service, stuffManager); } public void doSome() { try { Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("GMT")); if (counter++ % 5 == 1) { service.updateGlads(); service.updateStuff(); stuffManager.spendPriest(80); stuffManager.spendMasseur(90); for (CGlad glad : service.getGlads().values()) { if (glad.getMorale() < 10 && glad.getStamina() >= TournamentActivity.moneyHealStamina(glad) && glad.getStamina() < 100) { service.healMoney(glad); } } stuffManager.spendDoctor(Collections.<CGlad>emptyList(), true); int hh = calendar.get(Calendar.HOUR_OF_DAY); int mm = calendar.get(Calendar.MINUTE); if (hh == 1 && (mm >= 50 && mm <= 59) && !TournamentActivity.fullHP(service.getGlads().values()) && (service.getStuff().getRstGld() != null && service.getStuff().getRstGld() > 0)) { service.restoreGlads(); } } service.champGuild(); Btl incomingBtl = service.getIncomingBtl(); if (incomingBtl != null && incomingBtl.getId() != 0L) { service.updateGlads(); fighter.battle(incomingBtl, null); } } catch (IOException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } Utils.sleep(11000); } }
package com.pelephone_mobile.songwaiting.ui.fragments; import android.graphics.Typeface; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.FrameLayout; import android.widget.ImageButton; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.TextView; import com.pelephone_mobile.R; import com.pelephone_mobile.songwaiting.global.SWGlobal; import com.pelephone_mobile.songwaiting.service.SWService; import com.pelephone_mobile.songwaiting.service.interfaces.ISWServiceResponceListener; import com.pelephone_mobile.songwaiting.service.pojos.Category; import com.pelephone_mobile.songwaiting.service.pojos.Pojo; import com.pelephone_mobile.songwaiting.service.pojos.Songs; import com.pelephone_mobile.songwaiting.ui.adapters.DropDownAdapter; import com.pelephone_mobile.songwaiting.ui.adapters.SWArtistsAdaper; import com.pelephone_mobile.songwaiting.ui.interfaces.ISWOnSubCategoryClickListener; import com.pelephone_mobile.songwaiting.utils.SWLogger; import com.nineoldandroids.animation.Animator; import com.nineoldandroids.animation.Animator.AnimatorListener; import com.nineoldandroids.animation.ObjectAnimator; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; public class ArtistsListFragment extends SWBaseWithMenu { private Category category; private ListView mLvArtists; private static final String tag = "ArtistsListFragment"; private boolean isStartLoadingData = false; private SWArtistsAdaper mArtistsAdapter = null; private ISWOnSubCategoryClickListener subCategoryClickListener = null; private LinearLayout mSubCategories ; private boolean mIsDropOpen = false; private TextView mTxtSort; private LinearLayout mDropDownLayout; private ImageButton ibDropDown; private TextView tvTitle; private ListView listDropDown; private ArrayList<Category> mArtists = new ArrayList<Category>(); public static ArtistsListFragment getInstance( ISWOnSubCategoryClickListener subCategoryListener, Category category) { ArtistsListFragment artistsListFragment = new ArtistsListFragment(); artistsListFragment.setCategory(category); artistsListFragment.setSubCategoryListener(subCategoryListener); return artistsListFragment; } private void setSubCategoryListener( ISWOnSubCategoryClickListener subCategoryListener) { this.subCategoryClickListener = subCategoryListener; } @Override public void onServiceConnected(SWService service) { super.onServiceConnected(service); isStartLoadingData = true; initArtistsList(); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // TODO Auto-generated method stub mContentView = inflater.inflate(R.layout.artist_list_layout, container, false); if (mContentView != null) { mSubCategories = (LinearLayout) mContentView .findViewById(R.id.subCategoryLayout); mTransperent = (FrameLayout)mContentView.findViewById(R.id.transperentView); tvTitle = (TextView) mContentView .findViewById(R.id.tvTitle); tvTitle.setText(category.categoryName); Typeface font = Typeface.createFromAsset(SWGlobal.getAppResources().getAssets(), "arialbd.ttf"); tvTitle.setTypeface(font); mLvArtists = (ListView) mContentView.findViewById(R.id.lvArtists); ibDropDown = (ImageButton)mContentView.findViewById(R.id.ibDropDown); mDropDownLayout = (LinearLayout)mContentView.findViewById(R.id.dropDownLinear); if(android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB) { mDropDownLayout.setAlpha(0); } else { mDropDownLayout.setVisibility(View.INVISIBLE); } mTxtSort = (TextView)mContentView.findViewById(R.id.txtSort); ibDropDown.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { if(mIsDropOpen == true) { if(android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB) { ObjectAnimator objetc = ObjectAnimator.ofFloat(mDropDownLayout, "alpha", 1,0); objetc.addListener(new AnimatorListener() { @Override public void onAnimationStart(Animator animation) { // TODO Auto-generated method stub } @Override public void onAnimationRepeat(Animator animation) { // TODO Auto-generated method stub } @Override public void onAnimationEnd(Animator animation) { mDropDownLayout.setVisibility(View.GONE); } @Override public void onAnimationCancel(Animator animation) { // TODO Auto-generated method stub } }); objetc.start(); } else { mDropDownLayout.setVisibility(View.INVISIBLE); } mIsDropOpen = false; } else { if(android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB) { ObjectAnimator objetct = ObjectAnimator.ofFloat(mDropDownLayout, "alpha", 0,1); objetct.addListener(new AnimatorListener() { @Override public void onAnimationStart(Animator animation) { // TODO Auto-generated method stub mDropDownLayout.setVisibility(View.VISIBLE); mDropDownLayout.setAlpha(0); } @Override public void onAnimationRepeat(Animator animation) { // TODO Auto-generated method stub } @Override public void onAnimationEnd(Animator animation) { } @Override public void onAnimationCancel(Animator animation) { // TODO Auto-generated method stub } }); objetct.start(); } else { mDropDownLayout.setVisibility(View.VISIBLE); } mIsDropOpen = true; } } }); final String options[] = new String[] { getResources().getString(R.string.sort_general), getResources().getString(R.string.sort_artist_name) }; mTxtSort.setText(options[0]); Typeface fontArial = Typeface.createFromAsset(SWGlobal.getAppResources().getAssets(), "arial.ttf"); mTxtSort.setTypeface(fontArial); listDropDown = (ListView)mContentView.findViewById(R.id.listSortOptions); listDropDown.setAdapter(new DropDownAdapter(getActivity(), options)); listDropDown.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { if(android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB) { ObjectAnimator objetc = ObjectAnimator.ofFloat(mDropDownLayout, "alpha", 1,0); objetc.addListener(new AnimatorListener() { @Override public void onAnimationStart(Animator animation) { // TODO Auto-generated method stub } @Override public void onAnimationRepeat(Animator animation) { // TODO Auto-generated method stub } @Override public void onAnimationEnd(Animator animation) { mDropDownLayout.setVisibility(View.GONE); } @Override public void onAnimationCancel(Animator animation) { // TODO Auto-generated method stub } }); objetc.start(); } else { mDropDownLayout.setVisibility(View.INVISIBLE); } mIsDropOpen = false; mTxtSort.setText(options[position]); if(position == 1) { sortByArtist(); } else { sorGeneral(); } } }); return mContentView; } return super.onCreateView(inflater, container, savedInstanceState); } @Override public void onActivityCreated(Bundle savedInstanceState) { // TODO Auto-generated method stub if (mSWService != null && !isStartLoadingData && mArtistsAdapter == null) { initArtistsList(); } super.onActivityCreated(savedInstanceState); mLvArtists.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { if(hasInternetConnection()) { if (mSWService != null) { final int tempPosition = position; mSWService.getSongsController().getSongsBySubCategory( new ISWServiceResponceListener() { @Override public void onResponce(Pojo data) { // TODO Auto-generated method stub if (data != null && getActivity() != null && data instanceof Songs) { /* * Log.i(tag, category.subCategories * .getAndParse(tempPosition).categoryName); * String picture = * ((Songs)data).allSongs * .getAndParse(tempPosition).picture; * Log.i(tag,picture); picture = * picture.replace(".jpg", ""); picture * = picture + ".jpg"; * Log.i(tag,picture); */ int subCategoryId = mArtists.get(tempPosition).categoryId; String subCategoryName = mArtists.get(tempPosition).categoryName; subCategoryClickListener.onSubCategoryClickListener(category.categoryId, subCategoryId, subCategoryName); } } @Override public void onError(ErrorsTypes error) { // TODO Auto-generated method stub } }, category.categoryId, category.subCategories.get(position).categoryId); } } else { mPopNoInternet.show(); } } }); } public class CustomComparator implements Comparator<Category> { @Override public int compare(Category o1, Category o2) { int compare = o1.categoryName.compareToIgnoreCase(o2.categoryName); return compare; } } private void sortByArtist() { Collections.sort(mArtists, new CustomComparator()); mArtistsAdapter.setmArtistsList(mArtists); mArtistsAdapter.notifyDataSetChanged(); } private void sorGeneral() { mArtists = new ArrayList<Category>(); mArtists.addAll(category.subCategories); mArtistsAdapter.setmArtistsList(mArtists); mArtistsAdapter.notifyDataSetChanged(); } private void initArtistsList() { for (Category cat : category.subCategories) { SWLogger.print(tag, "category id : " + cat.categoryId + ", category name : " + cat.categoryName + ", subCategorySize : " + cat.subCategories.size()); } mArtists = new ArrayList<Category>(); mArtists.addAll(category.subCategories); mArtistsAdapter = new SWArtistsAdaper(getActivity(), mArtists); mLvArtists.setAdapter(mArtistsAdapter); } public void setCategory(Category category) { this.category = category; } }
/** * *大智慧股份有限公司 * Copyright (c) 2006-2015 DZH,Inc.All Rights Reserved. */ package com.gw.steel.steel.util.common; import java.util.Map; import org.apache.commons.lang.StringUtils; /** * * @author log.yin * @version $Id: Md5ParamsGenerator.java, v 0.1 2015年2月3日 下午7:25:16 log.yin Exp $ */ public class Md5ParamsGenerator { /** * key1value1key2value2key3value3... * only append the key-value is not blank * @param map * @return */ public static String generateMd5Params(Map<String, String> map) { return generateMd5Params(map, false); } /** * key1value1key2value2key3value3... * * @param map * @param containsEmptyString: if or not the value is blank, also append the key and value * @return */ public static String generateMd5Params(Map<String, String> map, boolean containsEmptyString) { StringBuilder signString = new StringBuilder(); for (Map.Entry<String, String> entry : map.entrySet()) { if (StringUtils.isNotBlank(entry.getValue())) { signString.append(entry.getKey()).append(entry.getValue()); continue; } if (containsEmptyString) { signString.append(entry.getKey()).append(""); } } return signString.toString(); } /** * key1=value1&key2=value2&key3=value3... * * @param map * @param keyLable: key-name * @return */ public static String generateHttpGetParams(Map<String, String> map) { StringBuilder requstParams = new StringBuilder(); for (Map.Entry<String, String> entry : map.entrySet()) { requstParams.append(entry.getKey()).append("=") .append(entry.getValue() == null ? "" : entry.getValue()).append("&"); } return requstParams.toString().substring(0, requstParams.toString().length() - 1); } }
package org.apress.prospark; import java.nio.charset.StandardCharsets; import org.apache.log4j.LogManager; import org.apache.log4j.Logger; import org.eclipse.paho.client.mqttv3.MqttClient; import org.eclipse.paho.client.mqttv3.MqttException; import org.eclipse.paho.client.mqttv3.MqttMessage; import org.eclipse.paho.client.mqttv3.MqttTopic; import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence; public class MqttDriver extends AbstractDriver { private static final Logger LOG = LogManager.getLogger(MqttDriver.class); private final String brokerUrl; private final String topic; private MqttClient client; private MqttTopic mqttTopic; public MqttDriver(String path, String brokerUrl, String topic) { super(path); this.brokerUrl = brokerUrl; this.topic = topic; } @Override public void init() throws Exception { client = new MqttClient(brokerUrl, MqttClient.generateClientId(), new MemoryPersistence()); LOG.info(String.format("Attempting to connect to broker %s", brokerUrl)); client.connect(); mqttTopic = client.getTopic(topic); LOG.info(String.format("Connected to broker %s", brokerUrl)); } @Override public void close() throws Exception { if (client != null) { client.disconnect(); } } @Override public void sendRecord(String record) throws Exception { try { mqttTopic.publish(new MqttMessage(record.getBytes(StandardCharsets.UTF_8))); } catch (MqttException e) { if (e.getReasonCode() == MqttException.REASON_CODE_MAX_INFLIGHT) { Thread.sleep(10); } } } public static void main(String[] args) throws Exception { if (args.length != 3) { System.err.println("Usage:MqttDriver <path_to_input_folder> <broker_url> <topic>"); System.exit(-1); } String path = args[0]; String brokerUrl = args[1]; String topic = args[2]; MqttDriver driver = new MqttDriver(path, brokerUrl, topic); try { driver.execute(); } finally { driver.close(); } } }
package Ventas; import java.sql.Connection; import java.sql.SQLException; import java.sql.Statement; import javax.swing.JOptionPane; import javax.swing.JTable; import javax.swing.JTextField; import javax.swing.table.DefaultTableModel; import Conexion.Conectar; public class GuardarVenta { public void guardarventa(String folio, JTextField txtefectivo,JTextField txtCliente,JTextField txtSubtotal,JTextField txtTotal, String fecha ){ String efectivo2=txtefectivo.getText(); String subtotal2=txtSubtotal.getText(); String total2=txtTotal.getText(); float efectivo1=Float.parseFloat(efectivo2); float subtotal=Float.parseFloat(subtotal2); float total=Float.parseFloat(total2); Conectar cx=new Conectar(); Connection cn=cx.conexion(null); String sql="INSERT INTO ventas (folio,cliente,importe,total_pv,total,fecha)VALUES('"+folio+"','"+txtCliente.getText()+"'," + "'"+efectivo1+"','"+subtotal+"','"+total+"','"+fecha+"')"; System.out.println(sql); try { Statement comando = (Statement) cn.createStatement(); comando.execute(sql); } catch (SQLException e) { // TODO Auto-generated catch block JOptionPane.showMessageDialog(null, e); } } public void detalleVenta(DefaultTableModel modelo1,JTable table_1,String fecha, String folio,JTextField txtCliente){ try{ Conectar cx=new Conectar(); Connection cn= cx.conexion(null); for(int i=0;i<modelo1.getRowCount();i++){ Statement comando; comando = cn.createStatement(); String id1=(table_1.getValueAt(i, 0).toString()); String nombre =(table_1.getValueAt(i, 1).toString()); String Precio1=(table_1.getValueAt(i, 2).toString()); float precio=Float.parseFloat(Precio1); String PrecioIva1=(table_1.getValueAt(i, 3).toString()); float precioIva=Float.parseFloat(PrecioIva1); String cantidad1=(table_1.getValueAt(i, 4).toString()); int cantidad = Integer.parseInt(cantidad1); String sql="INSERT INTO ventas_has_productos (folio,clave,nombre,precio,total_pv,cantidad,fecha, cliente)" + "VALUES('"+folio+"','"+id1+"','"+nombre+"','"+precio+"','"+precioIva+"','"+cantidad+"','"+fecha+"','"+txtCliente.getText()+"')"; comando.execute(sql); System.out.println(sql); } }catch(SQLException e){ JOptionPane.showMessageDialog(null, e); } } public void vaciar(JTable table_1){ try { DefaultTableModel modelo1=(DefaultTableModel) table_1.getModel(); int filas=table_1.getRowCount(); for (int i = 0;filas>i; i++) { modelo1.removeRow(0); } } catch (Exception e) { //JOptionPane.showMessageDialog(null, "Seleccione la fila que desea quitar."); } } }