text stringlengths 10 2.72M |
|---|
package ua.training.controller.commands.action.statement;
import lombok.extern.log4j.Log4j2;
import ua.training.constant.Attributes;
import ua.training.constant.Mess;
import ua.training.constant.Pages;
import ua.training.controller.commands.Command;
import ua.training.controller.commands.utility.CommandsUtil;
import ua.training.model.entity.User;
import javax.servlet.http.HttpServletRequest;
/**
* Description: This class log out user
*
* @author Zakusylo Pavlo
*/
@Log4j2
public class LogOut implements Command {
@Override
public String execute(HttpServletRequest request) {
User user = (User) request.getSession().getAttribute(Attributes.REQUEST_USER);
CommandsUtil.deleteUsersFromContext(request, user.getEmail());
request.getSession().setAttribute(Attributes.REQUEST_USER, null);
request.getSession().setAttribute(Attributes.PAGE_NAME, Attributes.PAGE_DEMONSTRATION);
log.info(Mess.LOG_USER_LOGGED_OUT + "[" + user.getEmail() + "]");
return Pages.SIGN_OR_REGISTER_REDIRECT;
}
}
|
/*
* 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 latihanarray;
/**
*
* @author IRMA
*/
public class LatihanArray {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
int a = 5;
int [] b = new int[5];
b[0]=100;
b[1]=200;
b[2]=300;
b[3]=400;
b[4]=500;
System.out.println(a);
System.out.println(b[0]);
System.out.println(b.length);
String [] c = new String [10];
c[0]="1.apel";
c[1]="2.jeruk";
c[2]="3.mangga";
c[3]="4.nanas";
c[4]="5.durian";
c[5]="6.kedondong";
c[6]="7.pir";
c[7]="8.dukuh";
c[8]="9.pisang";
c[9]="10.anggur";
System.out.println(c[0]);
System.out.println(c[1]);
System.out.println(c[2]);
System.out.println(c[3]);
System.out.println(c[4]);
System.out.println(c[5]);
System.out.println(c[6]);
System.out.println(c[7]);
System.out.println(c[8]);
System.out.println(c[9]);
}
}
|
package Main;
import Client.Client;
public class main {
public static void main(String args[]){
if(args.length == 2){
int delay = -1;
try{
delay = Integer.parseInt(args[0]);
}catch(Exception e){
System.out.println("Could not parse delay.");
return;
}
if(delay >= 0){
Client client1 = new Client();
client1.start(delay, args[1]);
}
else{
System.out.println("Enter valid delay.");
}
}
else{
System.out.println("Arguments: [delay, hostIP]");
}
}
}
|
package utd.aos.utils;
import java.io.Serializable;
public class Resource implements Serializable {
private static final long serialVersionUID = 1L;
public String filename;
public int seek = 0;
public int writeOffset = 0;
public String fileContent;
public String getFilename() {
return filename;
}
public void setFilename(String filename) {
this.filename = filename;
}
public int getSeek() {
return seek;
}
public void setSeek(int seek) {
this.seek = seek;
}
public String getFileContent() {
return fileContent;
}
public void setFileContent(String fileContent) {
this.fileContent = fileContent;
}
public int getWriteOffset() {
return writeOffset;
}
public void setWriteOffset(int writeOffset) {
this.writeOffset = writeOffset;
}
}
|
package common;
import java.util.concurrent.TimeUnit;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import pubsub.JSub;
import pubsub.JTopic;
import queueworker.JQueue;
import queueworker.JWorker;
import scala.concurrent.duration.Duration;
import akka.actor.ActorRef;
import akka.actor.ActorSystem;
import akka.remote.Ack;
import akka.testkit.JavaTestKit;
import akka.testkit.TestActorRef;
import akka.testkit.TestProbe;
import common.JMessageProtocol.NewsMessage;
import common.JMessageProtocol.Subscribe;
public class JPubSubTest {
static ActorSystem actorSystem;
@BeforeClass
public static void initActorSystem() {
actorSystem = ActorSystem.apply();
}
@AfterClass
public static void terminateActorSystem() {
actorSystem.shutdown();
actorSystem.awaitTermination();
}
@Test
public void testPub_must_publish_in_a_certain_interval() throws Exception {
JavaTestKit testTarget = new JavaTestKit(actorSystem);
ActorRef testactor = TestActorRef.apply(JPub.props("test", testTarget.getRef(), Duration.create(1, TimeUnit.SECONDS)), actorSystem);
// give 50 millis delay for the first shot and 10 millis for poor laptop performance
testTarget.expectMsgClass(Duration.create(1050, TimeUnit.MILLISECONDS), NewsMessage.class);
testTarget.expectMsgClass(Duration.create(1010, TimeUnit.MILLISECONDS), NewsMessage.class);
testTarget.expectMsgClass(Duration.create(1010, TimeUnit.MILLISECONDS), NewsMessage.class);
actorSystem.stop(testTarget.getRef());
actorSystem.stop(testactor);
}
@Test
public void testTopic_must_receive_from_Pub_and_publish_to_Subribers() throws Exception{
JavaTestKit testTarget = new JavaTestKit(actorSystem);
ActorRef testactor = TestActorRef.apply(JTopic.props(), actorSystem);
testactor.tell(new Subscribe(testTarget.getRef()), testTarget.getRef());
testactor.tell(new NewsMessage("Hello World"), testTarget.getRef());
testTarget.expectMsgClass(NewsMessage.class);
actorSystem.stop(testactor);
actorSystem.stop(testTarget.getRef());
}
@Test
public void testTopic_must_recognize_and_cleanup_subscriber_termination() throws Exception{
TestProbe testworker = new TestProbe(actorSystem);
ActorRef testactor = TestActorRef.apply(JTopic.props(), actorSystem);
testactor.tell(new Subscribe(testworker.ref()), testworker.ref());
testactor.tell(new NewsMessage("Hello World"), testworker.ref());
testworker.expectMsgClass(NewsMessage.class);
actorSystem.stop(testworker.ref());
Thread.sleep(20);
testactor.tell(new NewsMessage("Hello World"), testworker.ref());
testworker.expectNoMsg();
actorSystem.stop(testactor);
}
@Test
public void testQueue_must_receive_from_Pub_and_publish_to_Workers() throws Exception{
TestProbe testworker = new TestProbe(actorSystem);
ActorRef testactor = TestActorRef.apply(JQueue.props(), actorSystem);
testactor.tell(new Subscribe(testworker.ref()), testworker.ref());
testactor.tell(new NewsMessage("Hello World"), testworker.ref());
testworker.expectMsgClass(NewsMessage.class);
actorSystem.stop(testactor);
actorSystem.stop(testworker.ref());
}
@Test
public void testQueue_must_receive_from_Pub_queue_the_msg_and_publish_then_later_to_registered_Workers() throws Exception{
TestProbe testworker = new TestProbe(actorSystem);
ActorRef testactor = TestActorRef.apply(JQueue.props(), actorSystem);
testactor.tell(new NewsMessage("Hello World"), testworker.ref());
testactor.tell(new Subscribe(testworker.ref()), testworker.ref());
testworker.expectMsgClass(NewsMessage.class);
actorSystem.stop(testactor);
actorSystem.stop(testworker.ref());
}
@Test
public void testQueue_must_recognize_and_cleanup_subscriber_termination() throws Exception{
TestProbe testworker = new TestProbe(actorSystem);
ActorRef testactor = TestActorRef.apply(JQueue.props(), actorSystem);
testactor.tell(new Subscribe(testworker.ref()), testworker.ref());
testactor.tell(new NewsMessage("Hello World"), testworker.ref());
testworker.expectMsgClass(NewsMessage.class);
actorSystem.stop(testworker.ref());
testactor.tell(new NewsMessage("Hello World"), testworker.ref());
testworker.expectNoMsg();
actorSystem.stop(testactor);
}
@Test
public void testQueue_must_take_back_unprocessed_msg_into_the_queue() throws Exception{
TestProbe testworker = new TestProbe(actorSystem);
TestProbe testworkerFallback = new TestProbe(actorSystem);
ActorRef testactor = TestActorRef.apply(JQueue.props(), actorSystem);
NewsMessage msg1 = new NewsMessage("Hello World1");
NewsMessage msg2 = new NewsMessage("Hello World2");
testactor.tell(msg1, testworker.ref());
testactor.tell(msg2, testworker.ref());
testactor.tell(new Subscribe(testworker.ref()), testworker.ref());
testworker.expectMsg(msg1);
testworker.send(testactor, JMessageProtocol.MESSAGE_PROCESSED);
testworker.expectMsg(msg2);
// do not send MessageProcessed and test, if it will be taken back to the queue
actorSystem.stop(testworker.ref());
testworker.expectNoMsg();
testactor.tell(new Subscribe(testworkerFallback.ref()), testworkerFallback.ref());
testworkerFallback.expectMsg(msg2);
actorSystem.stop(testworkerFallback.ref());
actorSystem.stop(testactor);
}
@Test
public void testSub_must_receive() throws Exception{
TestProbe testworker = new TestProbe(actorSystem);
ActorRef testactor = TestActorRef.apply(JSub.props(), actorSystem);
testactor.tell(new NewsMessage("Hello World"), testworker.ref());
testworker.expectMsg(Ack.class);
actorSystem.stop(testactor);
actorSystem.stop(testworker.ref());
}
@Test
public void testWorker_must_receive_and_acknnowledge_Wieth_MessageProcessed() throws Exception{
TestProbe testworker = new TestProbe(actorSystem);
ActorRef testactor = TestActorRef.apply(JWorker.props(), actorSystem);
testactor.tell(new NewsMessage("Hello World"), testworker.ref());
testworker.expectMsg(JMessageProtocol.MESSAGE_PROCESSED);
actorSystem.stop(testactor);
actorSystem.stop(testworker.ref());
}
}
|
package com.mal.movieapp.database;
import java.io.Serializable;
/**
* Created by souidan on 8/27/16.
*/
public class Movie implements Serializable {
public long id;
public String title;
public String overview;
public double rating;
public int movieId;
public String date;
public String posterPath;
public String backdrop;
public Movie() {
super();
}
public Movie(Long id, String title, String overview, double rating, int movieId, String date, String posterPath, String backdrop) {
super();
this.id = id;
this.title = title;
this.overview = overview;
this.rating = rating;
this.movieId = movieId;
this.date = date;
this.posterPath = posterPath;
this.backdrop = backdrop;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public double getRating() {
return rating;
}
public void setRating(double rating) {
this.rating = rating;
}
public int getMovieId() {
return movieId;
}
public void setMovieId(int movieId) {
this.movieId = movieId;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getPosterPath() {
return posterPath;
}
public void setPosterPath(String posterPath) {
this.posterPath = posterPath;
}
public String getBackdrop() {
return backdrop;
}
public void setBackdrop(String backdrop) {
this.backdrop = backdrop;
}
public String getOverview() {
return overview;
}
public void setOverview(String overview) {
this.overview = overview;
}
}
|
package com.careme;
import android.graphics.Rect;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.FrameLayout;
import com.facebook.react.ReactActivity;
/**
* Created based on https://stackoverflow.com/questions/7417123/android-how-to-adjust-layout-in-full-screen-mode-when-softkeyboard-is-visible/19494006#answer-42261118
*/
public class AndroidBug5497Workaround extends ReactActivity {
// For more information, see https://issuetracker.google.com/issues/36911528
// To use this class, simply invoke assistActivity() on an Activity that already has its content view set.
private View rootView;
private ViewGroup contentContainer;
private ViewTreeObserver viewTreeObserver;
private ViewTreeObserver.OnGlobalLayoutListener listener = () -> possiblyResizeChildOfContent();
private Rect contentAreaOfWindowBounds = new Rect();
private FrameLayout.LayoutParams rootViewLayout;
private int usableHeightPrevious = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
contentContainer = (ViewGroup) findViewById(android.R.id.content);
rootView = contentContainer.getChildAt(0);
rootViewLayout = (FrameLayout.LayoutParams) rootView.getLayoutParams();
}
@Override
protected void onPause() {
super.onPause();
if (viewTreeObserver.isAlive()) {
viewTreeObserver.removeOnGlobalLayoutListener(listener);
}
}
@Override
protected void onResume() {
super.onResume();
if (viewTreeObserver == null || !viewTreeObserver.isAlive()) {
viewTreeObserver = rootView.getViewTreeObserver();
}
viewTreeObserver.addOnGlobalLayoutListener(listener);
}
@Override
protected void onDestroy() {
super.onDestroy();
rootView = null;
contentContainer = null;
viewTreeObserver = null;
}
private void possiblyResizeChildOfContent() {
contentContainer.getWindowVisibleDisplayFrame(contentAreaOfWindowBounds);
int usableHeightNow = contentAreaOfWindowBounds.height();
if (usableHeightNow != usableHeightPrevious) {
rootViewLayout.height = usableHeightNow;
rootView.layout(contentAreaOfWindowBounds.left, contentAreaOfWindowBounds.top, contentAreaOfWindowBounds.right, contentAreaOfWindowBounds.bottom);
rootView.requestLayout();
usableHeightPrevious = usableHeightNow;
}
}
} |
package com.cinema.biz.model;
import com.cinema.biz.model.base.TSimMaintenance;
public class SimMaintenance extends TSimMaintenance {
} |
import java.util.Scanner;
public class UsaFormula{
public static void main(String[]arg){
Scanner Lee=new Scanner(System.in);
Formula f=new Formula();
System.out.print("Ingresa valor para x: ");
f.setX(Lee.nextInt());
System.out.print("Ingresa valor para y: ");
f.setY(Lee.nextInt());
f.Resultado();
}
} |
package saga.repositories;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import saga.entities.Cliente;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.*;
class ClienteRepositorioTest {
private ClienteRepositorio clienteRepositorio;
private Cliente cliente1;
private Cliente cliente2;
@BeforeEach
void init() {
this.clienteRepositorio = new ClienteRepositorio();
this.cliente1 = new Cliente("00023827490", "Victor Emanuel", "vitao@ccc.ufcg.edu.br", "Labarc");
this.cliente2 = new Cliente("64269141198", "Ana Amari", "ana_amari@ccc.ufcg.edu.br", "SPG");
this.clienteRepositorio.adicionaCliente("00023827490", cliente1);
this.clienteRepositorio.adicionaCliente("64269141198", cliente2);
}
@Test
void testAdicionaCliente() {
Cliente cliente3 = new Cliente("58217738123", "Lucio Correia", "lucio_correia@ccc.ufcg.edu.br", "SPLab");
this.clienteRepositorio.adicionaCliente("58217738123", cliente3);
assertEquals(cliente3, this.clienteRepositorio.consultaCliente("58217738123"));
}
@Test
void testConsultaCliente() {
assertEquals(this.cliente1, this.clienteRepositorio.consultaCliente("00023827490"));
}
@Test
void testConsultaClienteInexistente() {
assertNull(this.clienteRepositorio.consultaCliente("01123827490"));
}
@Test
void testConsultaClientes() {
Map<String, Cliente> clientes = new HashMap<>();
clientes.put("00023827490", this.cliente1);
clientes.put("64269141198", this.cliente2);
List<Cliente> clientes1 = new ArrayList<>(clientes.values());
assertEquals(clientes1, this.clienteRepositorio.consultaClientes());
}
@Test
void testRemoveCliente() {
this.clienteRepositorio.removeCliente("64269141198");
assertEquals(1, this.clienteRepositorio.consultaClientes().size());
}
} |
/*
* 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.davivienda.sara.dto;
/**
*
* @author jmcastel
*/
public class CajerosSinTransmisionDTO {
private Integer idRegistro;
private String codigoCajero;
private String nombreCajero;
/**
* @return the idRegistro
*/
public Integer getIdRegistro() {
return idRegistro;
}
/**
* @param idRegistro the idRegistro to set
*/
public void setIdRegistro(Integer idRegistro) {
this.idRegistro = idRegistro;
}
/**
* @return the codigoCajero
*/
public String getCodigoCajero() {
return codigoCajero;
}
/**
* @param codigoCajero the codigoCajero to set
*/
public void setCodigoCajero(String codigoCajero) {
this.codigoCajero = codigoCajero;
}
/**
* @return the nombreCajero
*/
public String getNombreCajero() {
return nombreCajero;
}
/**
* @param nombreCajero the nombreCajero to set
*/
public void setNombreCajero(String nombreCajero) {
this.nombreCajero = nombreCajero;
}
}
|
package kirbyandfriends;
public class Reference {
public static int Spawn_Gui_ID = -1;
}
|
package gov.nysenate.opendirectory.servlets;
import gov.nysenate.opendirectory.ldap.Ldap;
import gov.nysenate.opendirectory.models.Person;
import gov.nysenate.opendirectory.utils.Request;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.TreeSet;
import javax.naming.NamingException;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.solr.client.solrj.SolrServerException;
@SuppressWarnings("serial")
public class SolrControllerServlet extends BaseServlet {
public static void main(String[] args) {
try {
Collection<Person> people = new SolrControllerServlet().replaceDepartments(new Ldap().connect().getPeople());
} catch (NamingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Request self = new Request(this,request,response);
try {
ServletOutputStream out = response.getOutputStream();
String command = urls.getCommand(request);
if (command != null) {
if(command.equals("removeAll")) {
removeAll(self);
out.println("Removed all documents");
} else if (command.equals("reindexAll")) {
reindexAll(self);
out.println("Reindexed all ldap values");
}
else if (command.equals("resetPermissions")){
resetPermissions(self);
out.println("Reset all permissions");
}
else {
out.println("Unknown command: "+command);
out.println("Recognized Commands are: removeAll,reindexAll, and resetPermissions");
}
} else {
out.println("Available commands are: ");
out.println("\tRemoveAll - /solr/removeAll");
out.println("\tIndexAll - /solr/indexAll");
out.println("\tReindexAll - /solr/reindexAll");
}
} catch (SolrServerException e) {
e.printStackTrace();
} catch (NamingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void resetPermissions(Request self) throws NamingException, SolrServerException, IOException {
Collection<Person> people = self.solrSession.loadPeople();
ArrayList<Person> toAdd = new ArrayList<Person>();
for(Person ldapPerson: people) {
ldapPerson.setPermissions(Person.getDefaultPermissions());
ldapPerson.setCredentials(null);
toAdd.add(ldapPerson);
}
self.solrSession.savePeople(toAdd);
}
private void reindexAll(Request self) throws NamingException, SolrServerException, IOException {
Collection<Person> people = replaceDepartments(new Ldap().connect().getPeople());
HashMap<String,Person> solrPeople = getUidPersonMap(self.solrSession.loadPeople());
ArrayList<Person> toAdd = new ArrayList<Person>();
for(Person ldapPerson: people) {
Person solrPerson = solrPeople.get(ldapPerson.getUid());
//pretty awful merge
if(solrPerson != null) {
solrPerson.setDepartment(ldapPerson.getDepartment());
solrPerson.setEmail(ldapPerson.getEmail());
solrPerson.setFirstName(ldapPerson.getFirstName());
solrPerson.setLastName(ldapPerson.getLastName());
solrPerson.setLocation(ldapPerson.getLocation());
solrPerson.setPhone(ldapPerson.getPhone());
solrPerson.setState(ldapPerson.getState());
solrPerson.setTitle(ldapPerson.getTitle());
solrPerson.setUid(ldapPerson.getUid());
toAdd.add(solrPerson);
solrPeople.remove(solrPerson.getUid());
}
else {
toAdd.add(ldapPerson);
}
}
self.solrSession.savePeople(toAdd);
//no longer in ldap
for(String uid:solrPeople.keySet()) {
self.solrSession.deleteByUid(uid);
}
}
private Collection<Person> replaceDepartments(Collection<Person> people) {
for(Person p : people) {
String department = p.getDepartment();
if(department==null || department.isEmpty()) {
continue;
}
department = department.replaceAll("ARRC", "Agriculture and Rural Resources");
department = department.replaceAll("dev","Development");
department = department.replaceAll("DO","District Office");
department = department.replaceAll("M&O", "Maintenance and Operations");
department = department.replaceAll("CS","Creative Services");
department = department.replaceAll("LC","Legislative Committee");
department = department.replaceAll("Maj\\.", "Majority");
department = department.replaceAll("Prog\\.", "Program");
department = department.replaceAll("SC", "Select Committee");
department = department.replaceAll("SS", "Senate Services");
department = department.replaceAll("STS", "Senate Technology Services");
department = department.replaceAll("Sess\\. Asst\\.", "Session Assistant");
department = department.replaceAll("TF", "Task Force");
department = department.replaceAll("^Senator","Senators/Senator");
if(department.equals("Senate Technology Services")) {
department = "Senate Technology Services/STS General";
}
if(department.contains("Senatorial District")) {
department = "Senators/" + department;
}
if(department.equals("NYS Black PR Hisp & Asian Leg Cau")) {
department = "NYS Black, Puerto Rican, Hispanic & Legislative Caucus";
}
else if(department.equals("Task Force/Demographic Research & Reapp.")) {
department = "Task Force/Demographic Research & Reapportionment";
}
if(department.contains("Caucus")) {
department = "Caucuses/" + department;
}
p.setDepartment(department);
}
return people;
}
private HashMap<String,Person> getUidPersonMap(Collection<Person> people) {
HashMap<String,Person> map = new HashMap<String,Person>();
for(Person person:people) {
map.put(person.getUid(), person);
}
return map;
}
private void removeAll(Request self) throws SolrServerException, IOException {
self.solrSession.deleteAll();
}
private void indexExtras(Request self) throws SolrServerException, IOException {
}
}
|
package org.kuali.ole.describe.form;
/**
* Created with IntelliJ IDEA.
* User: Srinivasane
* Date: 12/11/12
* Time: 2:57 PM
* To change this template use File | Settings | File Templates.
*/
import org.kuali.ole.docstore.model.xmlpojo.work.einstance.oleml.EHoldings;
import org.kuali.ole.docstore.model.xmlpojo.work.einstance.oleml.EInstance;
import org.kuali.ole.select.document.OLEEResourceLicense;
import java.util.ArrayList;
import java.util.List;
/**
* InstanceEditorForm is the form class for Instance Editor
*/
public class WorkEInstanceOlemlForm extends EditorForm {
public EInstance selectedEInstance;
private List<OLEEResourceLicense> license = new ArrayList<>();
private List<String> accessLocation = new ArrayList<String>();
private EHoldings selectedEHoldings;
public EHoldings getSelectedEHoldings() {
return selectedEHoldings;
}
public void setSelectedEHoldings(EHoldings selectedEHoldings) {
this.selectedEHoldings = selectedEHoldings;
}
public EInstance getSelectedEInstance() {
return selectedEInstance;
}
public void setSelectedEInstance(EInstance selectedEInstance) {
this.selectedEInstance = selectedEInstance;
}
public List<OLEEResourceLicense> getLicense() {
return license;
}
public void setLicense(List<OLEEResourceLicense> license) {
this.license = license;
}
public List<String> getAccessLocation() {
return accessLocation;
}
public void setAccessLocation(List<String> accessLocation) {
this.accessLocation = accessLocation;
}
}
|
/*
* Copyright (c) 2019, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.wso2.carbon.identity.tenant.resource.manager.util;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.event.publisher.core.config.EventPublisherConfiguration;
import org.wso2.carbon.event.publisher.core.exception.EventPublisherConfigurationException;
import org.wso2.carbon.event.stream.core.EventStreamConfiguration;
import org.wso2.carbon.event.stream.core.exception.EventStreamConfigurationException;
import org.wso2.carbon.identity.core.util.IdentityTenantUtil;
import org.wso2.carbon.identity.tenant.resource.manager.constants.TenantResourceConstants;
import org.wso2.carbon.identity.tenant.resource.manager.exception.TenantResourceManagementServerException;
import org.wso2.carbon.identity.tenant.resource.manager.internal.TenantResourceManagerDataHolder;
import org.wso2.carbon.utils.multitenancy.MultitenantConstants;
import java.util.List;
import static org.wso2.carbon.identity.tenant.resource.manager.constants.TenantResourceConstants.ErrorMessages.ERROR_CODE_ERROR_WHEN_CREATING_TENANT_EVENT_PUBLISHER_CONFIGURATION_USING_SUPER_TENANT_CONFIG;
/**
* Utility methods for tenant resource management.
*/
public class ResourceUtils {
private static final Log log = LogFactory.getLog(ResourceUtils.class);
/**
* This method can be used to generate a TenantResourceManagementServerException from
* TenantResourceConstants.ErrorMessages object when no exception is thrown.
*
* @param error TenantResourceConstants.ErrorMessages.
* @param data data to replace if message needs to be replaced.
* @return TenantResourceManagementServerException.
*/
public static TenantResourceManagementServerException handleServerException(
TenantResourceConstants.ErrorMessages error, String... data) {
String message = populateMessageWithData(error, data);
return new TenantResourceManagementServerException(message, error.getCode());
}
public static TenantResourceManagementServerException handleServerException(
TenantResourceConstants.ErrorMessages error, Throwable e, String... data) {
String message = populateMessageWithData(error, data);
return new TenantResourceManagementServerException(message, error.getCode(), e);
}
public static String populateMessageWithData(TenantResourceConstants.ErrorMessages error, String... data) {
String message;
if (data.length != 0) {
message = String.format(error.getMessage(), data);
} else {
message = error.getMessage();
}
return message;
}
/**
* This method creates event publisher configurations tenant wise by using super tenant publisher configurations.
*
* @param activeEventPublisherConfigurations list of active super tenant publisher configurations.
*/
public static void loadTenantPublisherConfigurationFromSuperTenantConfig(
List<EventPublisherConfiguration> activeEventPublisherConfigurations) {
for (EventPublisherConfiguration eventPublisherConfiguration : activeEventPublisherConfigurations) {
try {
if (TenantResourceManagerDataHolder.getInstance().getCarbonEventPublisherService()
.getActiveEventPublisherConfiguration(eventPublisherConfiguration.getEventPublisherName())
== null) {
if (log.isDebugEnabled()) {
log.debug("Super tenant event publisher configuration for the: " + eventPublisherConfiguration
.getEventPublisherName() + " will be used for the tenant domain: "
+ PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain());
}
TenantResourceManagerDataHolder.getInstance().getCarbonEventPublisherService()
.addEventPublisherConfiguration(eventPublisherConfiguration);
}
} catch (EventPublisherConfigurationException e) {
log.error(populateMessageWithData(
ERROR_CODE_ERROR_WHEN_CREATING_TENANT_EVENT_PUBLISHER_CONFIGURATION_USING_SUPER_TENANT_CONFIG,
eventPublisherConfiguration.getEventPublisherName(),
PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain()), e);
}
}
}
/**
* This method returns super tenant event publisher configurations.
*
* @return list of event publisher configurations.
*/
public static List<EventPublisherConfiguration> getSuperTenantEventPublisherConfigurations() {
List<EventPublisherConfiguration> activeEventPublisherConfigurations = null;
try {
activeEventPublisherConfigurations = TenantResourceManagerDataHolder.getInstance()
.getCarbonEventPublisherService().getAllActiveEventPublisherConfigurations();
} catch (EventPublisherConfigurationException e) {
log.error(populateMessageWithData(
TenantResourceConstants.ErrorMessages.ERROR_CODE_ERROR_WHEN_FETCHING_SUPER_TENANT_EVENT_PUBLISHER_CONFIGURATION,
PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain()), e);
}
return activeEventPublisherConfigurations;
}
public static void startTenantFlow(int tenantId) {
PrivilegedCarbonContext.startTenantFlow();
PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantId(tenantId);
PrivilegedCarbonContext.getThreadLocalCarbonContext()
.setTenantDomain(IdentityTenantUtil.getTenantDomain(tenantId));
}
public static void startSuperTenantFlow() {
PrivilegedCarbonContext.startTenantFlow();
PrivilegedCarbonContext carbonContext = PrivilegedCarbonContext.getThreadLocalCarbonContext();
carbonContext.setTenantId(MultitenantConstants.SUPER_TENANT_ID);
carbonContext.setTenantDomain(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME);
}
}
|
package commonwealth.constitution;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import commonwealth.game.BufferedImageLoader;
import commonwealth.game.Map;
import commonwealth.issues.Issues;
import commonwealth.nations.ID;
import commonwealth.nations.Nations;
public class judgeClause extends Issues{
Map map;
BufferedImageLoader loader = new BufferedImageLoader();
BufferedImage character = null;
public judgeClause(Map map){
this.map = map;
try{
character = loader.loadImage("/tex/President.png");
}catch(Exception e){
e.printStackTrace();
}
}
public void tick() {
}
public void render(Graphics g) {
g.setColor(Color.black);
g.fillRect(88, 88, 132, 132);
g.drawImage(character, 90, 90, 128, 128, null);
g.setFont(new Font("Arial", Font.BOLD, 40));
g.drawString("The Judiciary Clause", 250, 100);
g.setFont(new Font("Arial", 0, 20));
g.drawString("Good morning, good leader. Glad you decided to adopt a constitution.", 75, 250);
g.drawString("As you know, we will need someone to interpret the constitution. I propose", 75, 275);
g.drawString("we make a court of five people, chosen by yourself, who will serve for", 75, 300);
g.drawString("life and can overturn any legislation you try to pass that they believe to be", 75, 325);
g.drawString("unconstitutional. Do you want to adopt the Judiciary Clause?", 75, 350);
}
public void effects() {
map.judicialClause = true;
for(int i = 0; i < map.nationList.size(); i++){
Nations tempNation = map.nationList.get(i);
if(tempNation.getAffiliation() == ID.fanatic){
}
if(tempNation.getAffiliation() == ID.tribal){
tempNation.setHappiness(tempNation.getHappiness() - 10);
}
if(tempNation.getAffiliation() == ID.order){
}
if(tempNation.getAffiliation() == ID.democrat){
tempNation.setHappiness(tempNation.getHappiness() + 10);
}
}
}
public void negEffects() {
}
}
|
package org.itachi.cms.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
/**
* Created by yangz on 2017/5/4.
*/
@Controller
@RequestMapping("/")
public class ViewController {
@RequestMapping(method = RequestMethod.GET)
public String index(Model model) throws Exception {
return "index";
}
}
|
public class Jitomate extends IngredienteDecorator{
public Jitomate (Sandwich s){
super(s);
}
public double getPrecio(){
return sandwich.getPrecio() + 2;
}
public String getDescripcion(){
return sandwich.getDescripcion() + ", Jitomate";
}
}
|
@Local
public interface gestionMecanicienLocal {
public void identifyMeca(int idMeca, string psw, int idStation) throws stationNotFoundException, usagerNotFoundException, wrongStationForMecaException
public int[] navettesAreviser(int idStation);
//au choix de la navette (alé de la liste int[] navettesAreviser, ça return le numéro de quai ou se trouve cette navette
public int chooseNavette(int[] navettes);
}
|
package com.nanyin.entity;
import lombok.Data;
import javax.persistence.*;
import java.util.Date;
/**
* 工单下的一页中有多个任务组成
*/
@Data
@Entity
public class Task {
@Id
@Column(columnDefinition = "INT(11)")
@GeneratedValue(strategy= GenerationType.IDENTITY)
private Integer id;
/**
* Task名称
*/
@Column(length = 2048)
String name;
/**
* Task内容
*/
@Column(columnDefinition = "TEXT")
String comment;
@Column(length = 11)
Integer ord;
@Temporal(value=TemporalType.TIMESTAMP)
Date gmtCreate;
@Temporal(value=TemporalType.TIMESTAMP)
Date gmtModify;
@Temporal(value=TemporalType.TIMESTAMP)
Date gmtEnd;
@OneToOne
@JoinColumn
Priority priority;
@ManyToOne
@JoinColumn(name = "paper_id")
Paper paper;
}
|
/*
* 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 task2;
import java.util.ArrayList;
/**
* an abstract base class with all attributes
* to be inherited by the MemoryGame class
*
* @author sohailgsais
*/
public abstract class Base {
// declaring String vaariables that will store game data
static String firstInput, secondInput, makeGuess, activeFile;
// pos list stores the 2d array indexes
// matchedWords stores the position of all matched words
static ArrayList<String> pos = new ArrayList<>();
static ArrayList<String> matchedWords = new ArrayList<>();
static String[][] Board;
static int row, colm;
static boolean userQuit = false;
static int matches = 0, numOfTries = 0;
static int firstrowPos, firstcolmPos, secondrowPos, secondcolmPos;
// brdRow and brdColm are used to displays row and colm positions of the board
static int brdRow = 0, brdColm = 0;
}
|
/*
* 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 ClasesNormales;
import java.util.ArrayList;
import java.util.Arrays;
/**
*
* @author Danil
*/
public class Carta implements Comparable<Carta>{
private String palo,figura;
/**
*
* @param palo
* @param figura
*/
public Carta(String palo, String figura) { //La clase carta consta de un constructor que une palo y figura en un Objeto de tipo Carta
this.palo = palo;
this.figura = figura;
}
/**
*
* @return
*/
public String getPalo() {
return palo;
}
/**
*
* @param palo
*/
public void setPalo(String palo) {
this.palo = palo;
}
/**
*
* @return
*/
public String getFigura() {
return figura;
}
/**
*
* @param figura
*/
public void setFigura(String figura) {
this.figura = figura;
}
@Override
public int compareTo(Carta c){
String[] figuras={"As","Dos","Tres","Cuatro","Cinco","Seis","Siete","Ocho","Nueve","Sota","Caballo","Rey"};
ArrayList<String> f= new ArrayList<>();
f.addAll(Arrays.asList(figuras));
int figComp=f.indexOf(this.figura)-f.indexOf(c.figura);
return figComp;
}
@Override
public String toString() {
return figura + " de " + palo+ ".jpg"; //.jpg para mostrar la imagen directamente
}
}
|
package com.corycharlton.bittrexapi.request;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import com.corycharlton.bittrexapi.internal.constants.Url;
import com.corycharlton.bittrexapi.internal.util.StringUtils;
import com.corycharlton.bittrexapi.response.WithdrawResponse;
import static com.corycharlton.bittrexapi.internal.util.Ensure.isNotNullOrWhitespace;
import static com.corycharlton.bittrexapi.internal.util.Ensure.isTrue;
/**
* Used to withdraw funds from your account.
*/
public class WithdrawRequest extends Request<WithdrawResponse> {
/**
* Used to withdraw funds from your account.
* @param currency A string literal for the currency (ie. BTC)
* @param quantity The quantity of coins to withdraw
* @param address The address where to send the funds
*/
public WithdrawRequest(@NonNull String currency, double quantity, @NonNull String address) {
this(currency, quantity, address, null);
}
/**
* Used to withdraw funds from your account.
* @param currency A string literal for the currency (ie. BTC)
* @param quantity The quantity of coins to withdraw
* @param address The address where to send the funds
* @param paymentId An optional string used for CryptoNotes/BitShareX/Nxt optional field (memo/paymentid)
*/
public WithdrawRequest(@NonNull String currency, double quantity, @NonNull String address, @Nullable String paymentId) {
super(Url.WITHDRAW, true, WithdrawResponse.class);
isNotNullOrWhitespace("address", address);
isNotNullOrWhitespace("currency", currency);
isTrue("quantity", quantity > 0.0);
addParameter("address", address);
addParameter("currency", currency);
addParameter("quantity", quantity);
if (!StringUtils.isNullOrWhiteSpace(paymentId)) {
addParameter("paymentid", paymentId);
}
}
}
|
package stephen.ranger.ar.materials;
import java.awt.Color;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.vecmath.Vector3f;
import stephen.ranger.ar.Camera;
import stephen.ranger.ar.IntersectionInformation;
import stephen.ranger.ar.PBRTMath;
import stephen.ranger.ar.RTStatics;
public class BRDFMaterial extends ColorInformation {
/**
* http://www1.cs.columbia.edu/CAVE/software/curet/html/brdfm.html<br/>
* <br/>
* Contains:<br/>
* ------------------------<br/>
* - theta_v (polar angle of the viewing direction) (pitch),<br/>
* - phi_v (azimuthal angle of the viewing direction) (yaw),<br/>
* - theta_i (polar angle of the illumination direction) (pitch),<br/>
* - and phi_i (the azimuthal angle of the illumination direction) (yaw).<br/>
* <br/>
* major array: entry for the 205 sample directions<br/>
* minor array: theta/phi values
*/
public static final float[][] brdfDirections = remapDirections(parseBRDFFile("resources/table.txt"));
/**
* http://www1.cs.columbia.edu/CAVE/software/curet/html/brdfm.html<br/>
* <br/>
* Contains:<br/>
* ------------------------<br/>
* major array: entry for the 61 materials<br/>
* minor array: weights for the 205 sample directions that correspond to the major array in 'brdfDirections'
*/
public static final float[][] brdfWeights = parseBRDFFile("resources/abrdf.dat");
private final float[] material;
public BRDFMaterial(final int materialID, final Color color) {
super(color);
this.material = brdfWeights[materialID];
}
public float getBRDFLuminocity(final IntersectionInformation info, final Camera camera) {
float luminocity = 0f;
float weight = 0f;
int ctr = 0;
final Vector3f negRay = new Vector3f(info.ray.direction);
negRay.scale(-1f);
negRay.normalize();
final Vector3f tempDir = new Vector3f();
tempDir.sub(camera.light.origin, info.intersection);
tempDir.normalize();
final Vector3f tangent = PBRTMath.getNormalTangent(info.normal);
for (int i = 0; i < camera.brdfSamples; i++) {
final float[] remapped = PBRTMath.getRemappedDirection(info.normal, tangent, negRay, RTStatics.getReflectionDirection(info.normal, tempDir));
float lastMaxDist2 = 0.001f;
while ((ctr < 4) && (lastMaxDist2 < 1.5f)) {
for (int j = 0; j < brdfDirections.length; j++) {
final float dist2 = PBRTMath.getDistance2(remapped, brdfDirections[j]);
if (dist2 < lastMaxDist2) {
final float temp = (float) Math.exp(-100.0 * dist2);
luminocity += this.material[j] * temp;
weight += temp;
ctr++;
}
}
lastMaxDist2 *= 2f;
}
}
if (ctr == 0) {
return 0f;
}
return luminocity / weight * 6f;
}
/**
* parse BRDF file (either abrdf.dat or table.txt).
* @param file
* @return
*/
private static float[][] parseBRDFFile(final String file) {
final List<float[]> values = new ArrayList<float[]>();
float[][] valuesAsArray = null;
try {
final BufferedReader fin = new BufferedReader(new FileReader(new File(file)));
String temp = null;
String[] split = null;
final List<Float> tempValues = new ArrayList<Float>();
while ((temp = fin.readLine()) != null) {
split = temp.split(" ");
for (int j = 1; j < split.length; j++) {
if (!split[j].replaceAll("\\D", "").equals("")) {
tempValues.add(Float.parseFloat(split[j]));
}
}
final float[] buffer = new float[tempValues.size()];
for (int i = 0; i < buffer.length; i++) {
buffer[i] = tempValues.get(i);
}
values.add(buffer);
tempValues.clear();
}
valuesAsArray = new float[values.size()][];
for (int i = 0; i < values.size(); i++) {
valuesAsArray[i] = values.get(i);
}
} catch (final IOException e) {
e.printStackTrace();
}
return valuesAsArray;
}
/**
* PBRT page 465.
*
* Remaps viewing/light directions to sin(theta-i) * sin(theta-o), delta-phi / PI, cos(theta-i) * cos(theta-o)
*
* @param directions
* @return
*/
private static float[][] remapDirections(final float[][] directions) {
final float[][] remapedDirections = new float[directions.length][];
for (int i = 0; i < directions.length; i++) {
remapedDirections[i] = PBRTMath.getRemappedDirection(new float[] { directions[i][0], directions[i][1] }, new float[] { directions[i][2], directions[i][3] });
}
return remapedDirections;
}
@Override
public float[] getMaterialColor(final Camera camera, final IntersectionInformation info, final int depth) {
float[] returnColor = this.diffuse.getColorComponents(new float[3]);
final float luminance = this.getBRDFLuminocity(info, camera);
final float[] hsv = RTStatics.convertRGBtoHSV(returnColor);
hsv[2] = luminance;
returnColor = RTStatics.convertHSVtoRGB(hsv);
return returnColor;
}
}
|
package TST_teamproject.Board.controller;
import java.security.Principal;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import TST_teamproject.Board.model.BoardReplyVo;
import TST_teamproject.Board.model.BoardVo;
import TST_teamproject.Board.service.BoardReplyService;
import TST_teamproject.Board.service.BoardService;
@Controller
@EnableAutoConfiguration
public class BoardController {
@Autowired
private BoardService service;
@Autowired
private BoardReplyService replyService;
// 11.03 수정
@RequestMapping(value="/BoardList" , method = RequestMethod.GET)
public String listBoard(Model model, BoardVo vo, Principal principal) throws Exception{
model.addAttribute("BoardList", service.boardList(vo.getTst_board_category()));
model.addAttribute("category", vo.getTst_board_category());
//이거 닉네임으로 바꿔야됨
model.addAttribute("userId",principal.getName());
return "board.list";
}
// 12.05 유진 수정
//10.26
@RequestMapping(value="/BoardInsert" , method = RequestMethod.GET)
public String insertBoard(Model model, BoardVo vo, Principal cipal) throws Exception{
vo.setTst_user_nickname(cipal.getName());
model.addAttribute("BoardVo", vo);
return "board.insert";
}
//10.26
//10.27 수정
@RequestMapping(value="/BoardInsertPage" , method = RequestMethod.GET)
public String insertBoardPage(Model model ,BoardVo vo,RedirectAttributes redirectAttributes) throws Exception{
service.boardInsert(vo);
// redirectAttributes.addAttribute 값이 깨지지 않고 전송 값으로 활용
redirectAttributes.addAttribute("tst_board_category", vo.getTst_board_category());
return "redirect:/BoardList";
}
//10.27
//11.29 유진 수정
@ResponseBody
@RequestMapping(value="/BoardDetail" , method = RequestMethod.GET)
public BoardVo detailBoard(Model model , BoardVo vo, BoardReplyVo reVo) throws Exception{
vo =service.boardDetail(vo.getTst_board_no());
vo.setTst_reply_count(replyService.boardReplyCount(reVo.getTst_board_no()));
model.addAttribute("reply", reVo);
return vo;
}
//10.27
@ResponseBody
@RequestMapping(value = "/BoardDelete", method = RequestMethod.GET)
public String deleteBoard(Model mode, BoardVo vo) throws Exception {
String category = service.boardDetail(vo.getTst_board_no()).getTst_board_category();
service.boardDelete(vo.getTst_board_no());
return category;
}
//10.28
@RequestMapping(value="/BoardModify" , method = RequestMethod.GET)
public String modifyBoard(Model model, BoardVo vo, Principal cipal) throws Exception{
vo.setTst_user_nickname(cipal.getName());
// model.addAttribute("BoardVo", vo);
model.addAttribute("detail", service.boardDetail(vo.getTst_board_no()));
return "board.modify";
}
//10.28
@ResponseBody
@RequestMapping(value="/BoardModifyPage" , method = RequestMethod.GET)
public String modifyPage(Model model ,BoardVo vo, RedirectAttributes redirectAttributes) throws Exception{
service.boardModify(vo);
return service.boardDetail(vo.getTst_board_no()).getTst_board_category();
}
// 11.04
@RequestMapping(value="/BoardReplyList" , method = RequestMethod.GET)
@ResponseBody
public List<BoardReplyVo> listReplyBoard(BoardReplyVo vo) throws Exception{
return replyService.boardReplyList(vo.getTst_board_no());
}
// 11.05
// @RequestMapping(value="/BoardReplyInsert" , method = RequestMethod.GET)
// public String insertReplyBoard(Model model, BoardReplyVo reVo, BoardVo vo, Principal cipal, RedirectAttributes redirectAttributes) throws Exception{
// reVo.setTst_user_nickname(cipal.getName());
// System.out.println(reVo.toString());
// System.out.println(vo.toString());
//// replyService.boardReplyInsert(reVo);
// redirectAttributes.addAttribute("tst_board_no", vo.getTst_board_no());
// return "redirect:/BoardDetail";
// }
// 11.05
//11.10 수정
@RequestMapping(value="/BoardReplyInsert" , method = RequestMethod.GET)
@ResponseBody
public String insertReplyBoard(Model model, BoardReplyVo reVo, Principal cipal, BoardVo vo) throws Exception{
reVo.setTst_user_nickname(cipal.getName());
replyService.boardReplyInsert(reVo);
return "ㅋㅋㅋㅋㅋㅋㅋㅋㅋㅋㅋㅋㅋ";
}
// 11.10
@ResponseBody
@RequestMapping(value = "/BoardReplyDelete", method = RequestMethod.GET)
public String deleteReplyBoard(Model mode, BoardReplyVo reVo) throws Exception {
replyService.boardReplyDelete(reVo.getTst_board_reply_no());
return "hjj";
}
} |
package GUIController;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.time.LocalDate;
//Kommentieren
public class CreateAccount
{
private static final String DBURL = "jdbc:postgresql://localhost:5432/postgres";
private static final String LOGIN = "postgres";
private static final String PASSWORD = "test";
static {
try {
con = DriverManager.getConnection(DBURL, LOGIN, PASSWORD);
} catch (SQLException e) {
e.printStackTrace();
}
}
public static Connection con;
public static void createAccount(int cardnumber,String name, String surname, String email, LocalDate birthday, String street, String postCode, String place, String password, String gender, String kontoart) {
try
{
PreparedStatement statement = con.prepareStatement("INSERT INTO customer VALUES (" + "'" + cardnumber + "'" + "," + "'" + name + "'" + "," + "'" + surname + "'" + "," + "'" + email + "'" + "," + "'" + birthday + "'" + "," + "'" + street + "'" + "," + "'" + Integer.parseInt(postCode) + "'" + "," + "'" + place + "'" + "," + "'" + password + "'" + "," + "'" + gender + "'" + "," + "'" + kontoart+ "');");
statement.execute();
}catch(Exception e){
e.printStackTrace();
}
}
}
|
package common.util.web;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringReader;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.ext.MessageBodyReader;
import org.apache.commons.io.IOUtils;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.SerializationConfig.Feature;
import com.sun.jersey.api.core.HttpContext;
//@Provider
//@Consumes("application/json")
public class JsonReader implements MessageBodyReader {
private @Context
HttpContext hc;
private @Context
ServletContext servletContext;
private @Context
ThreadLocal<HttpServletRequest> requestInvoker;
private @Context
ThreadLocal<HttpServletResponse> responseInvoker;
public boolean isReadable(Class type, Type genericType, Annotation[] annotations, MediaType mediaType) {
return mediaType.getType().equalsIgnoreCase("application") && mediaType.getSubtype().equalsIgnoreCase("json");
}
public Object readFrom(Class type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap httpHeaders, InputStream entityStream)
throws IOException, WebApplicationException {
try {
String data = IOUtils.toString(entityStream);
StringReader sr = new StringReader(data);
ObjectMapper jsonProcessor = new ObjectMapper();
jsonProcessor.configure(Feature.WRITE_NULL_PROPERTIES, false);
jsonProcessor.configure(
org.codehaus.jackson.map.DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES,
false);
return jsonProcessor.readValue(sr, type);
} catch (Exception e) {
throw new WebApplicationException(e);
}
}
}
|
package logic;
import board.Field;
import board.FieldValue;
import components.Counter;
import components.Images;
import javafx.scene.paint.ImagePattern;
import javafx.scene.shape.Rectangle;
import java.util.List;
import java.util.Map;
public class NewGame extends KolkoAndKrzyzyk {
public static void restartGame(List<Rectangle> fields, Map<Integer, Field> rectangleFields) {
emptyField(fields);
rectangleFields.forEach((key, value) -> value.setValue(FieldValue.EMPTY));
Counter.movCounter = 0;
Counter.playerClicked = false;
Counter.gameOver = false;
}
public static void emptyField(List<Rectangle> fields) {
for (int i = 0; i < 9; i++) {
fields.get(i).setFill(new ImagePattern(Images.imgEmpty));
}
}
} |
/*
* #%L
* Diana UI Core
* %%
* Copyright (C) 2014 Diana UI
* %%
* 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.
* #L%
*/
package com.dianaui.universal.core.client.ui;
import com.dianaui.universal.core.client.ui.base.ComplexWidget;
import com.dianaui.universal.core.client.ui.base.mixin.HTMLMixin;
import com.dianaui.universal.core.client.ui.base.mixin.TextMixin;
import com.dianaui.universal.core.client.ui.constants.Styles;
import com.google.gwt.dom.client.Document;
import com.google.gwt.user.client.ui.HasText;
import com.google.gwt.user.client.ui.HasWidgets;
/**
* @author Joshua Godi
* @author <a href='mailto:donbeave@gmail.com'>Alexey Zhokhov</a>
*/
public class LinkedGroupItemText extends ComplexWidget implements HasWidgets, HasText {
public LinkedGroupItemText() {
setElement(Document.get().createPElement());
setStyleName(Styles.LIST_GROUP_ITEM_TEXT);
}
/**
* {@inheritDoc}
*/
@Override
public String getText() {
return TextMixin.getText(this);
}
/**
* {@inheritDoc}
*/
@Override
public void setText(final String text) {
TextMixin.setText(this, text);
}
public String getHTML() {
return HTMLMixin.getHTML(this);
}
public void setHTML(final String html) {
HTMLMixin.setHTML(this, html);
}
}
|
package com.dungkk.gasorder.passingObjects;
public class User {
private static String firstName;
private String lastName;
private static String username = null;
private String password;
private String phoneNumber;
private String email;
public User(String name){
username = name;
}
public String getEmail() {
return email;
}
public String getFirstName() {
return firstName;
}
public static void setFirstName(String firstName) {
User.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public String getPassword() {
return password;
}
public String getPhoneNumber() {
return phoneNumber;
}
public static String getUsername() {
return username;
}
public static void setUsername(String username) {
User.username = username;
}
}
|
/*
* 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 interfazGrafica;
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import javax.swing.table.DefaultTableModel;
/**
*
* @author Oscar
* Esta clase se encarga de gestionar los datos mediante una tabla
*/
public class MenuTabla extends JFrame{
private String[][] datos;
private String[] nombreColumnas;
/**
* El constructor inicializa la tabla con los datos entregados por parámetro
*
* @param datos
* @param nombreColumnas
*/
public MenuTabla(String[][] datos, String[] nombreColumnas){
super("SIVU");
this.datos=datos;
this.nombreColumnas= nombreColumnas;
generarTabla();
super.setLocationRelativeTo(null);
super.setResizable(false);
this.pack();
this.setVisible(true);
}
public boolean isCellEditable (int row, int column)
{
return false;
}
public void generarTabla() {
String[] nombreColumnas = {"N°", "Nombre", "Posición", "Salud"};
DefaultTableModel dtm = new DefaultTableModel(this.datos, this.nombreColumnas){
@Override
public boolean isCellEditable(int row, int column) {
return false;
}
};
final JTable tabla = new JTable(dtm);
tabla.setPreferredScrollableViewportSize(new Dimension(500, 200));
JScrollPane scrollPane = new JScrollPane(tabla);
getContentPane().add(scrollPane, BorderLayout.CENTER);
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
cerrarVentana();
}
});
}
private void cerrarVentana(){
this.dispose();}
}
|
package com.esum.hotdeploy.util;
public class ElementUpdatedEvent extends ElementEvent {
public ElementUpdatedEvent(Object source, Object oldValue, Object newValue, int index) {
super(source, oldValue, newValue, index, ElementEvent.UPDATED);
}
}
|
package com.example.sample.test;
import org.junit.Test;
import org.hamcrest.Matchers;
import io.restassured.RestAssured;
public class SampleRESTAssuredTest {
@Test
public void checkStatus() {
RestAssured.given()
.when().log().all().get("http://www.marklogic.com")
.then().log().all().statusCode(200);
}
@Test
public void checkContent() {
RestAssured.given()
.when().get("http://localhost:8184/sample")
.then().body("result", Matchers.equalTo("success"));
}
}
|
package com.example.demo;
import java.util.ArrayList;
public class test {
public static void main(String[] args) {
test test=new test();
/* int[][] a={{1,2,8,9},{2,4,9,12},{4,7,10,13},{6,8,11,15}};
StringBuffer str=new StringBuffer();
str.append("Hellow World");
System.out.println(test.replaceSpace(str));*/
}
public boolean Find(int target, int [][] array) {
boolean flag=false;
ok:for(int i=array.length-1;i>0;i--){
for(int j=array[i].length-1;j>0;j--){
if(array[i][j]==target){
flag=true;
break ok;
}
}
}
return flag;
}
public String replaceSpace(StringBuffer str) {
/* String a=String.valueOf(str).replace(" ","%20");
return a;*/
int length=str.length();
StringBuffer newStr=new StringBuffer();
for(int i=0;i<length;i++){
if(!String.valueOf(str.charAt(i)).equals(" ")){
newStr.append(str.charAt(i));
}else{
newStr.append("%20");
}
}
return newStr.toString();
}
public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
return null;
}
}
|
package com.decorator.common.example;
/**
* 抽象装饰者
*/
public abstract class Decorator extends Component {
private Component component = null;
//通过构造函数传递被修饰者
public Decorator(Component _component) {
this.component = _component;
}
public void operate() {
this.component.operate();
}
}
|
package org.jaxws.integrationtest.exampleWebService;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlType;
/**
*
* @author chenjianjx
*
*/
@XmlType
@XmlAccessorType(XmlAccessType.FIELD)
public class VoidResponse extends AbstractResponse {
}
|
package de.hofuniversity.ejbbean.bean;
import javax.ejb.Remote;
import de.hofuniversity.ejbbean.data.MatchDetailsSummaryData;
/**
*
* @author Markus Exner
*
*/
@Remote
public interface MatchDetailsRemote {
public final String MAPPED_NAME = "ejb/MatchDetails";
public MatchDetailsSummaryData getMatchDetails(int matchId);
}
|
package com.github.charlieboggus.sgl.utility;
import org.joml.Vector3f;
import org.joml.Vector4f;
public class Color
{
public static final Color Clear = new Color(0.0f, 0.0f, 0.0f, 0.0f);
public static final Color Black = new Color(0.0f, 0.0f, 0.0f, 1.0f);
public static final Color White = new Color(1.0f, 1.0f, 1.0f, 1.0f);
public static final Color Gray = new Color(0.5f, 0.5f, 0.5f, 1.0f);
public static final Color Gray10 = new Color(0.1f, 0.1f, 0.1f, 1.0f);
public static final Color Gray20 = new Color(0.2f, 0.2f, 0.2f, 1.0f);
public static final Color Gray30 = new Color(0.3f, 0.3f, 0.3f, 1.0f);
public static final Color Gray40 = new Color(0.4f, 0.4f, 0.4f, 1.0f);
public static final Color Gray50 = new Color(0.5f, 0.5f, 0.5f, 1.0f);
public static final Color Gray60 = new Color(0.6f, 0.6f, 0.6f, 1.0f);
public static final Color Gray70 = new Color(0.7f, 0.7f, 0.7f, 1.0f);
public static final Color Gray80 = new Color(0.8f, 0.8f, 0.8f, 1.0f);
public static final Color Gray90 = new Color(0.9f, 0.9f, 0.9f, 1.0f);
public static final Color LightGray = new Color(0.75f, 0.75f, 0.75f, 1.0f);
public static final Color DarkGray = new Color(0.25f, 0.25f, 0.25f, 1.0f);
public static final Color Red = new Color(1.0f, 0.0f, 0.0f, 1.0f);
public static final Color Green = new Color(0.0f, 1.0f, 0.0f, 1.0f);
public static final Color Blue = new Color(0.0f, 0.0f, 1.0f, 1.0f);
public static final Color Cyan = new Color(0.0f, 1.0f, 1.0f, 1.0f);
public static final Color Magenta = new Color(1.0f, 0.0f, 1.0f, 1.0f);
public static final Color Yellow = new Color(1.0f, 1.0f, 0.0f, 1.0f);
public static final Color Orange = new Color(1.0f, 0.6f, 0.0f, 1.0f);
public static final Color RoyalBlue = fromRGBA8888(0x4169E1FF);
public static final Color SlateBlue = fromRGBA8888(0x7B68EEFF);
public static final Color SkyBlue = fromRGBA8888(0x87CEEBFF);
public static final Color Chartreuse = fromRGBA8888(0x7FFF00FF);
public static final Color Lime = fromRGBA8888(0x32CD32FF);
public static final Color SeaGreen = fromRGBA8888(0x20B2AAFF);
public static final Color Forest = fromRGBA8888(0x228B22FF);
public static final Color Olive = fromRGBA8888(0x6B8E23FF);
public static final Color Goldenrod = fromRGBA8888(0xDAA520FF);
public static final Color Brown = fromRGBA8888(0xA52A2AFF);
public static final Color Tan = fromRGBA8888(0xD2B48CFF);
public static final Color Firebrick = fromRGBA8888(0xB22222FF);
public static final Color Scarlet = fromRGBA8888(0x560319FF);
public static final Color Coral = fromRGBA8888(0xFF7F50FF);
public static final Color Salmon = fromRGBA8888(0xFA8072FF);
public static final Color Tomato = fromRGBA8888(0xFF6347FF);
public static final Color Pink = fromRGBA8888(0xFFC0CBFF);
public static final Color Purple = fromRGBA8888(0xA020F0FF);
public static final Color Violet = fromRGBA8888(0x9400D3FF);
public static final Color Maroon = fromRGBA8888(0xB03060FF);
public static final Color Plum = fromRGBA8888(0xDDA0DDFF);
public static Color fromRGB565(int rgb565)
{
float r = ((rgb565 & 0x0000F800) >>> 11) / 31.0f;
float g = ((rgb565 & 0x000007E0) >>> 5) / 63.0f;
float b = (rgb565 & 0x0000001F) / 31.0f;
return new Color(r, g, b, 1.0f);
}
public static Color fromRGBA4444(int rgba4444)
{
float r = ((rgba4444 & 0x0000F000) >>> 12) / 15.0f;
float g = ((rgba4444 & 0x00000F00) >>> 8) / 15.0f;
float b = ((rgba4444 & 0x000000F0) >>> 4) / 15.0f;
float a = (rgba4444 & 0x0000000F) / 15.0f;
return new Color(r, g, b, a);
}
public static Color fromRGB888(int rgb888)
{
float r = ((rgb888 & 0x00FF0000) >>> 16) / 255.0f;
float g = ((rgb888 & 0x0000FF00) >>> 8) / 255.0f;
float b = (rgb888 & 0x000000FF) / 255.0f;
return new Color(r, g, b, 1.0f);
}
public static Color fromRGBA8888(int rgba8888)
{
float r = ((rgba8888 & 0xFF000000) >>> 24) / 255.0f;
float g = ((rgba8888 & 0x00FF0000) >>> 16) / 255.0f;
float b = ((rgba8888 & 0x0000FF00) >>> 8) / 255.0f;
float a = (rgba8888 & 0x000000FF) / 255.0f;
return new Color(r, g, b, a);
}
public static Color fromARGB8888(int argb8888)
{
float a = ((argb8888 & 0xFF000000) >>> 24) / 255.0f;
float r = ((argb8888 & 0x00FF0000) >>> 16) / 255.0f;
float g = ((argb8888 & 0x0000FF00) >>> 8) / 255.0f;
float b = (argb8888 & 0x000000FF) / 255.0f;
return new Color(r, g, b, a);
}
public static Color fromABGR8888(int abgr8888)
{
float a = ((abgr8888 & 0xFF000000) >>> 24) / 255.0f;
float b = ((abgr8888 & 0x00FF0000) >>> 16) / 255.0f;
float g = ((abgr8888 & 0x0000FF00) >>> 8) / 255.0f;
float r = (abgr8888 & 0x000000FF) / 255.0f;
return new Color(r, g, b, a);
}
public static Color fromString(String str)
{
try {
return fromRGBA8888((int) Long.parseLong(str.substring(2), 16));
}
catch (Exception e) {
return Color.Clear;
}
}
// -----------------------------------------------------------------------------------------------------------------
private float r;
private float g;
private float b;
private float a;
public Color(float r, float g, float b, float a)
{
this.r = r;
this.g = g;
this.b = b;
this.a = a;
this.clamp();
}
private void clamp()
{
if(this.r < 0.0f)
this.r = 0.0f;
else if(this.r > 1.0f)
this.r = 1.0f;
if(this.g < 0.0f)
this.g = 0.0f;
else if(this.g > 1.0f)
this.g = 1.0f;
if(this.b < 0.0f)
this.b = 0.0f;
else if(this.b > 1.0f)
this.b = 1.0f;
if(this.a < 0.0f)
this.a = 0.0f;
else if(this.a > 1.0f)
this.a = 1.0f;
}
public float r()
{
return this.r;
}
public float g()
{
return this.g;
}
public float b()
{
return this.b;
}
public float a()
{
return this.a;
}
public int redByte()
{
return (int)((this.toRGBA8888() >>> 24) & 0xFF);
}
public int greenByte()
{
return (int)((this.toRGBA8888() >>> 16) & 0xFF);
}
public int blueByte()
{
return (int)((this.toRGBA8888() >>> 8) & 0xFF);
}
public int alphaByte()
{
return (int)(this.toRGBA8888() & 0xFF);
}
public Color mul(Color c)
{
this.r *= c.r();
this.g *= c.g();
this.b *= c.b();
this.a *= c.a();
this.clamp();
return this;
}
public Color mul(float scalar)
{
this.r *= scalar;
this.g *= scalar;
this.b *= scalar;
this.a *= scalar;
this.clamp();
return this;
}
public Color add(Color c)
{
this.r += c.r();
this.g += c.g();
this.b += c.b();
this.a += c.a();
this.clamp();
return this;
}
public Color sub(Color c)
{
this.r -= c.r();
this.g -= c.g();
this.b -= c.b();
this.a -= c.a();
this.clamp();
return this;
}
public Color lerp(Color target, float t)
{
this.r += t * (target.r() - this.r());
this.g += t * (target.g() - this.g());
this.b += t * (target.b() - this.b());
this.a += t * (target.a() - this.a());
this.clamp();
return this;
}
public Color lerp(float r, float g, float b, float a, float t)
{
this.r += t * (r - this.r());
this.g += t * (g - this.g());
this.b += t * (b - this.b());
this.a += t * (a - this.a());
this.clamp();
return this;
}
public int toRGB565()
{
return ((int)(this.r() * 31) << 11) | ((int)(this.g() * 63) << 5) | ((int)(this.b() * 31));
}
public int toRGBA4444()
{
return ((int)(this.r() * 15) << 12) | ((int)(this.g() * 15) << 8) | ((int)(this.b() * 15) << 4) | ((int)(this.a() * 15));
}
public int toRGB888()
{
return ((int)(this.r() * 255) << 16) | ((int)(this.g() * 255) << 8) | ((int)(this.b() * 255));
}
public int toRGBA8888()
{
return ((int)(this.r() * 255) << 24) | ((int)(this.g() * 255) << 16) | ((int)(this.b() * 255) << 8) | ((int)(this.a() * 255));
}
public float toRGBA8888_float()
{
return Float.intBitsToFloat(this.toRGBA8888());
}
public int toARGB8888()
{
return ((int)(this.a() * 255) << 24) | ((int)(this.r() * 255) << 16) | ((int)(this.g() * 255) << 8) | ((int)(this.b() * 255));
}
public int toABGR8888()
{
return ((int)(this.a() * 255) << 24) | ((int)(this.b() * 255) << 16) | ((int)(this.g() * 255) << 8) | ((int)(this.r() * 255));
}
public Vector3f toVector3()
{
return new Vector3f(this.r(), this.g(), this.b());
}
public Vector4f toVector4()
{
return new Vector4f(this.r(), this.g(), this.b(), this.a());
}
@Override
public String toString()
{
return "0x" + Integer.toHexString(this.toRGBA8888()).toUpperCase();
}
}
|
package com.example.demo.ServiceImp;
import com.example.demo.DO.CourseDO;
import com.example.demo.DO.ScDO;
import com.example.demo.Exception.ErrorCodeAndMsg;
import com.example.demo.Exception.StudentException;
import com.example.demo.Input.getMessageInout;
import com.example.demo.Output.getMessageOutput;
import com.example.demo.Service.StudentService;
import com.example.demo.Input.createInout;
import com.example.demo.Output.createOutput;
import com.example.demo.Utils.checkUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.example.demo.DAO.StudentMapper;
import com.example.demo.DO.StudentDO;
import javax.annotation.Resource;
import java.util.*;
/**
* @author qianchen
* @date 2019/12/26 11:52
*/
@Service
@Slf4j
@Api(tags = "学生信息操作接口")
@Transactional(rollbackFor = Exception.class)
public class StudentServiceImp implements StudentService {
@Resource StudentMapper studentMapper;
@Override
@ApiOperation(httpMethod = "POST", value = "新增学生信息接口")
public createOutput create(createInout request) {
StudentDO student = studentMapper.selectByPrimaryKey(request.getSno());
if (student != null) {
throw new StudentException(ErrorCodeAndMsg.student_is_exist);
}
/** 入参格式校验 */
// 年龄校验
if (request.getSage() != null) {
if (!checkUtils.AgeValid(request.getSage())) {
throw new StudentException(ErrorCodeAndMsg.age_is_error);
}
}
// 姓名校验
if (checkUtils.NameValid(request.getSname())) {
throw new StudentException(ErrorCodeAndMsg.name_is_error);
}
// 性别校验
if (!checkUtils.SexValid(request.getSex())) {
throw new StudentException(ErrorCodeAndMsg.sex_is_error);
}
// 班级校验
if (request.getSdept() != null) {
if (checkUtils.NameValid(request.getSdept())) {
throw new StudentException(ErrorCodeAndMsg.dept_is_error);
}
}
StudentDO student1 = new StudentDO();
student1.setSno(request.getSno());
student1.setSname(request.getSname());
student1.setSage(request.getSage());
student1.setSex(request.getSex());
student1.setSdept(request.getSdept());
student1.setSdate(new Date());
studentMapper.insert(student1);
createOutput result = new createOutput();
result.setSno(student1.getSno());
result.setSdate(student1.getSdate());
return result;
}
@Override
public getMessageOutput getMessage(getMessageInout request) {
getMessageOutput result = new getMessageOutput();
Map<String, String> map = new HashMap<>();
StudentDO studentDO = studentMapper.selectByPrimaryKey(request.getSno());
if (studentDO == null) {
throw new StudentException(ErrorCodeAndMsg.student_number_does_not_exist);
}
List<ScDO> scDOS = studentMapper.findscoreById(request.getSno());
Map<String, String> map1 = new HashMap<>();
Map<String, String> map2 = new HashMap<>();
List<String> cnos = new ArrayList<>();
// 建立课程号与课程成绩的map2
for (ScDO sc : scDOS) {
map2.put(sc.getCno(), sc.getScore());
cnos.add(sc.getCno());
}
List<CourseDO> courseDOS = studentMapper.findcourseByIds(cnos);
// 建立课程号与课程名称的map1
for (CourseDO courseDO : courseDOS) {
for (String cno : cnos) {
if (cno.equals(courseDO.getCno())) {
map1.put(cno, courseDO.getCname());
}
}
}
for (String cno : cnos) {
map.put(map1.get(cno), map2.get(cno));
}
result.setMap(map);
return result;
}
}
|
/**
* Copyright (C) 2016 - 2030 youtongluan.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.yx.redis;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.yx.common.Host;
import org.yx.util.Asserts;
import redis.clients.jedis.Protocol;
public class RedisParamter {
static final int DEFAULT_TRY_COUNT = 3;
static final int DEFAULT_TIMEOUT = 3000;
public static RedisParamter create(String host) {
return new RedisParamter(host);
}
private int timeout = DEFAULT_TIMEOUT;
private String password = null;
private int db = 0;
private int tryCount = DEFAULT_TRY_COUNT;
private final List<Host> hosts;
private String masterName;
public RedisParamter(String host) {
Asserts.notEmpty(host, "redis host cannot be empty");
host = host.replace(' ', ' ').replace(',', ',').replace(':', ':').replaceAll("\\s", "");
int index = host.indexOf('-');
if (index > -1) {
this.masterName = host.substring(0, index);
host = host.substring(index + 1);
}
String h = host;
String[] hs = h.split(",");
List<Host> hosts = new ArrayList<>(hs.length);
for (String addr : hs) {
if (addr.isEmpty()) {
continue;
}
if (!addr.contains(":")) {
hosts.add(Host.create(addr, Protocol.DEFAULT_PORT));
continue;
}
hosts.add(Host.create(addr));
}
if (hosts.size() == 1) {
this.hosts = Collections.singletonList(hosts.get(0));
} else {
hosts.sort(null);
this.hosts = Collections.unmodifiableList(hosts);
}
}
public String masterName() {
return this.masterName;
}
public List<Host> hosts() {
return hosts;
}
public int getTimeout() {
return timeout;
}
public RedisParamter setTimeout(int timeout) {
this.timeout = timeout;
return this;
}
public String getPassword() {
return password;
}
public RedisParamter setPassword(String password) {
this.password = password;
return this;
}
public int getDb() {
return db;
}
public RedisParamter setDb(int db) {
this.db = db;
return this;
}
public int getTryCount() {
return tryCount;
}
public RedisParamter setTryCount(int tryCount) {
this.tryCount = tryCount;
return this;
}
@Override
public String toString() {
return "RedisParamter [masterName=" + masterName + ", hosts=" + hosts + ", db=" + db + ", password=" + password
+ ", timeout=" + timeout + ", tryCount=" + tryCount + "]";
}
}
|
package CATChinaRetail.TestAutomation.Core;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class ReadExcel {
static int ActualRowNum = 0;
static String SheetName = null;
public static void SheetName(String InputSheetName) {
SheetName = InputSheetName;
}
@SuppressWarnings("resource")
public static int TestCaseName(String TestCaseName) throws IOException
{
File file = new File("./src/main/resources/DataSheet.xlsx");
FileInputStream inputStream = new FileInputStream(file);
Workbook currentWorkbook = null;
currentWorkbook = new XSSFWorkbook(inputStream);
Sheet currentSheet = currentWorkbook.getSheet(SheetName);
int rowCount = currentSheet.getLastRowNum() - currentSheet.getFirstRowNum();
int i = 1;
for (i = 1; i < rowCount + 1; i++) {
Row row = currentSheet.getRow(i);
if (row.getCell(0).getStringCellValue().equals(TestCaseName)) {
ActualRowNum = i;
break;
} else {
continue;
}
}
inputStream.close();
return ActualRowNum;
}
@SuppressWarnings("resource")
public static String ReadColumn(String ColumnName) throws IOException {
File file = new File("./src/main/resources/DataSheet.xlsx");
FileInputStream inputStream = new FileInputStream(file);
Workbook currentWorkbook = null;
currentWorkbook = new XSSFWorkbook(inputStream);
Sheet currentSheet = currentWorkbook.getSheet(SheetName);
Row row = currentSheet.getRow(0);
int j = 0;
for (j = 0; j < row.getLastCellNum(); j++) {
if (row.getCell(j).getStringCellValue().equals(ColumnName)) {
break;
}
}
row = currentSheet.getRow(ActualRowNum);
String rowValue = row.getCell(j).getStringCellValue();
inputStream.close();
return rowValue;
}
}
|
/*
package com.androidcodefinder.loginapp;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;
import com.androidcodefinder.loginapp.R;
import com.epicodus.mshauri.model.chat;
import com.firebase.ui.database.FirebaseListAdapter;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.ArrayList;
import butterknife.BindView;
import butterknife.ButterKnife;
public class chatActivity extends AppCompatActivity {
ArrayList<String> chatsArray = new ArrayList<>();
@BindView(R.id.chatusernamee) TextView mUsername;
@BindView(R.id.listview) ListView mList;
private FirebaseAuth mAuth;
private ListView mListView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_chat);
ButterKnife.bind(this);
mAuth = FirebaseAuth.getInstance();
loadchat();
displaychats();
}
// Firebase ref = new Firebase("https://<yourapp>.firebaseio.com");
public void displaychats(){
String[] arrayy = chatsArray.toArray( new String[chatsArray.size()]);
ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, arrayy);
mList.setAdapter(adapter);
}
public void loadchat(){
FirebaseUser current = mAuth.getCurrentUser();
String uid = current.getUid();
DatabaseReference myRef = FirebaseDatabase.getInstance().getReference("users").child(uid).child("chat");
myRef.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange( DataSnapshot dataSnapshot) {
String email = dataSnapshot.getValue(String.class);
chatsArray.add(email);
mListView = (ListView) findViewById(R.id.listview);
for(int i=0; i < chatsArray.size(); i++){
mUsername.setText(mUsername.getText() + " " + chatsArray.get(i) + " , ");
}
}
@Override
public void onCancelled( DatabaseError databaseError) {
}
});
}
}*/
|
/*
* 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 taiga.mcmods.buildguide;
import cpw.mods.fml.client.FMLClientHandler;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.NumberFormat;
import java.util.logging.Logger;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFormattedTextField;
import javax.swing.JLabel;
import javax.swing.border.TitledBorder;
import net.minecraftforge.common.MinecraftForge;
public class GuidePanel extends Box {
public static final int GUI_SPACING = 5;
public GuidePanel() {
super(BoxLayout.LINE_AXIS);
xlab = new JLabel("X:");
ylab = new JLabel("Y:");
zlab = new JLabel("Z:");
xent = new JFormattedTextField(NumberFormat.getIntegerInstance());
yent = new JFormattedTextField(NumberFormat.getIntegerInstance());
zent = new JFormattedTextField(NumberFormat.getIntegerInstance());
Dimension size = new Dimension(100, 0);
xent.setMinimumSize(size);
yent.setMinimumSize(size);
zent.setMinimumSize(size);
grabcoord = new JButton("Player Position");
grabcoord.setFocusable(false);
grabcoord.setAlignmentX(CENTER_ALIGNMENT);
grabcoord.setDefaultCapable(false);
setupOrigin();
grabcoord.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
int x = (int) FMLClientHandler.instance().getClient().h.s;
int y = (int) FMLClientHandler.instance().getClient().h.t;
int z = (int) FMLClientHandler.instance().getClient().h.u;
xent.setValue(x);
yent.setValue(y);
zent.setValue(z);
}
});
}
protected int getOriginX() {
return ((Number)xent.getValue()).intValue();
}
protected int getOriginY() {
return ((Number)yent.getValue()).intValue();
}
protected int getOriginZ() {
return ((Number)zent.getValue()).intValue();
}
private void setupOrigin() {
Box left = Box.createVerticalBox();
Box right = Box.createVerticalBox();
left.add(xlab);
left.add(Box.createVerticalStrut(GUI_SPACING));
right.add(xent);
right.add(Box.createVerticalStrut(GUI_SPACING));
left.add(ylab);
left.add(Box.createVerticalStrut(GUI_SPACING));
right.add(yent);
right.add(Box.createVerticalStrut(GUI_SPACING));
left.add(zlab);
left.add(Box.createVerticalStrut(GUI_SPACING));
right.add(zent);
right.add(Box.createVerticalStrut(GUI_SPACING));
Box orig = Box.createHorizontalBox();
orig.add(left);
orig.add(Box.createHorizontalStrut(GUI_SPACING));
orig.add(right);
Box panel = Box.createVerticalBox();
panel.add(orig);
panel.add(grabcoord);
panel.setBorder(new TitledBorder("Origin"));
add(panel);
}
private final JLabel xlab;
private final JLabel ylab;
private final JLabel zlab;
private final JFormattedTextField xent;
private final JFormattedTextField yent;
private final JFormattedTextField zent;
private final JButton grabcoord;
private static final long serialVersionUID = 1L;
private static final String locprefix = GuidePanel.class.getName().toLowerCase();
private static final Logger log = Logger.getLogger(locprefix,
System.getProperty("taiga.code.logging.text"));
}
|
package oo.abstraction;
public class StudentTester {
public static void main(String[] args) {
Student s1 = new Student("輔仁大學", "醫資學程", 405570173, "林芸妗", "女", 1);
Student s2 = new Student("輔仁大學", "醫資學程", 405570202, "蔡德蓉", "女", 1);
Student s3 = new Student("輔仁大學", "醫資學程", 405570214, "張芳菽", "女", 1);
Student[] ss = new Student[3];
ss[0] = new Student("輔仁大學", "醫資學程", 405570173, "林芸妗", "女", 1);
ss[1] = new Student("輔仁大學", "醫資學程", 405570202, "蔡德蓉", "女", 1);
ss[2] = new Student("輔仁大學", "醫資學程", 405570214, "張芳菽", "女", 1);
ss[0].seatnumber = 17;
ss[1].seatnumber = 20;
ss[2].seatnumber = 21;
}
}
|
package com.reptile.dao;
import java.util.List;
import org.apache.commons.dbutils.QueryRunner;
import com.reptile.bean.Book;
import com.reptile.util.constants.ReptileConstants;
import com.reptile.util.db.DataSourceUtil;
public class ReptileDao {
/**
* get data base
**/
private static QueryRunner queryRunner = new QueryRunner();
/**
* save book batch
*
* @param data
* the data get from html page
* @throws Exception
**/
public static void saveBookBatch(List<Book> data) throws Exception {
/*
* define an object array,
*
*/
Object[][] params = new Object[data.size()][3];
for (int i = 0; i < params.length; i++) {
params[i][0] = data.get(i).getBookId();
params[i][1] = data.get(i).getBookName();
params[i][2] = data.get(i).getBookPrice();
}
queryRunner.batch(DataSourceUtil.getDataSource().getConnection(), ReptileConstants.SQL_INSERT, params);
System.out.print("执行数据库完毕!" + "成功插入数据:" + data.size() + "条");
DataSourceUtil.releaseConnection();
}
}
|
package com.sevael.lgtool.service;
import java.io.InputStream;
import java.util.List;
import org.bson.Document;
import com.google.gson.JsonObject;
public interface EmailRequestService {
String emailRequest(JsonObject requestDetails);
List<Document> getAllRequeter();
String uploadPdfFile(InputStream inputStream, String filename, String certificationid);
}
|
package pers.lyr.demo.common.mapper;
import org.springframework.jdbc.core.RowMapper;
import pers.lyr.demo.pojo.po.Teacher;
import java.sql.ResultSet;
import java.sql.SQLException;
/**
* @Author lyr
* @create 2020/9/13 14:37
*/
public class TeacherTableMapper implements RowMapper<Teacher> {
public static final TeacherTableMapper INSTANCE = new TeacherTableMapper();
@Override
public Teacher mapRow(ResultSet resultSet, int i) throws SQLException {
Teacher teacher = new Teacher();
teacher.setTeacherId(resultSet.getInt("teacher_id"))
.setDeleted(resultSet.getInt("is_deleted"))
.setSex(resultSet.getInt("sex"))
.setTeacherName(resultSet.getString("teacher_name"))
.setTeacherPassword(resultSet.getString("teacher_password"))
.setGmtCreate(resultSet.getDate("gmt_create"))
.setGmtModified(resultSet.getDate("gmt_modified"));
return teacher;
}
}
|
package com.wb.welfare.dominio;
import java.io.Serializable;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
@Entity
public class Cliente implements Serializable{
private static final long serialVersionUID=1L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String nome;
private String sobrenome;
private String cpf;
private String nascimento;
public String telefone;
public String genero;
private String tratamento;
private String pagamento;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public String getSobrenome() {
return sobrenome;
}
public void setSobrenome(String sobrenome) {
this.sobrenome = sobrenome;
}
public String getCpf() {
return cpf;
}
public void setCpf(String cpf) {
this.cpf = cpf;
}
public String getNascimento() {
return nascimento;
}
public void setNascimento(String nascimento) {
this.nascimento = nascimento;
}
public String getTelefone() {
return telefone;
}
public void setTelefone(String telefone) {
this.telefone = telefone;
}
public String getGenero() {
return genero;
}
public void setGenero(String genero) {
this.genero = genero;
}
public String getTratamento() {
return tratamento;
}
public void setTratamento(String tratamento) {
this.tratamento = tratamento;
}
public String getPagamento() {
return pagamento;
}
public void setPagamento(String pagamento) {
this.pagamento = pagamento;
}
public static long getSerialversionuid() {
return serialVersionUID;
}
} |
package com.isg.ifrend.wrapper.mli.request.account;
import java.util.Date;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement(name="GetPayoutFigure")
public class GetPayoutFigure {
private String accountNumber;
private String customerNumber;
private String cardNumber;
@XmlElement(name="payoutDate")
private Date payoutDate;
public String getAccountNumber() {
return accountNumber;
}
public void setAccountNumber(String accountNumber) {
this.accountNumber = accountNumber;
}
public String getCustomerNumber() {
return customerNumber;
}
public void setCustomerNumber(String customerNumber) {
this.customerNumber = customerNumber;
}
public String getCardNumber() {
return cardNumber;
}
public void setCardNumber(String cardNumber) {
this.cardNumber = cardNumber;
}
public Date getPayoutDate() {
return payoutDate;
}
public void setPayoutDate(Date payoutDate) {
this.payoutDate = payoutDate;
}
}
|
package interfazDelJuego;
import java.awt.Color;
import javax.swing.JFrame;
import clienteLogica.Cliente;
import clienteLogica.VentanaChat;
import clienteLogica.VentanaLobby;
import hilosDelJuego.HiloBuffos;
import hilosDelJuego.IA;
import hilosDelJuego.Movimiento;
import hilosDelJuego.MovimientoLocal;
import hilosDelJuego.Repintar;
import logicaJuego.Mapa;
public class JVentanaGrafica extends JFrame {
/**
*
*/
private static final long serialVersionUID = 1L;
private JPanelGrafico contentPane;
private JPanelGraficoLocal contentPaneLocal;
private Repintar hiloDibujado;
private Movimiento mov1;
private MovimientoLocal mov2;
private Mapa nuevo;
private Cliente cliente;
private int idSala;
private boolean dueño;
private VentanaChat chat;
private VentanaLobby lobby;
private HiloBuffos debuff1;
private HiloBuffos debuff2;
private IA HiloIA;
public JVentanaGrafica(Mapa mapa, Cliente cliente) {
super("Bomberman");
setResizable(false);
this.cliente = cliente;
this.nuevo = mapa;
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
setBounds(0, 0, 443, 820);
contentPane = new JPanelGrafico(nuevo);
setBackground(Color.GREEN);
setContentPane(contentPane);
setLocationRelativeTo(null);
hiloDibujado = new Repintar(this, contentPane);
hiloDibujado.start();
mov1 = new Movimiento(this, cliente);
mov1.start();
}
public JVentanaGrafica(Mapa mapa) {
super("Bomberman");
setResizable(false);
this.nuevo = mapa;
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
setBounds(0, 0, 443, 820);
contentPaneLocal = new JPanelGraficoLocal(nuevo);
setBackground(Color.GREEN);
setContentPane(contentPaneLocal);
setLocationRelativeTo(null);
hiloDibujado = new Repintar(this);
hiloDibujado.start();
mov2 = new MovimientoLocal(this);
mov2.start();
if(nuevo.getCantJug()==1) {
HiloIA = new IA(this);
HiloIA.start();
}
debuff1=new HiloBuffos(contentPaneLocal.getTest().getJugadoresLocal().get(0));
debuff1.start();
debuff2=new HiloBuffos(contentPaneLocal.getTest().getJugadoresLocal().get(1));
debuff2.start();
}
public JPanelGrafico getContentPane() {
return contentPane;
}
public Mapa getNuevo() {
return nuevo;
}
public void setNuevo(Mapa nuevo) {
this.nuevo = nuevo;
contentPane.setTest(nuevo);
contentPane.actualizarJugadores();
}
public Repintar getHiloDibujado() {
return hiloDibujado;
}
public void setHiloDibujado(Repintar hiloDibujado) {
this.hiloDibujado = hiloDibujado;
}
public Movimiento getMov1() {
return mov1;
}
public void setMov1(Movimiento mov1) {
this.mov1 = mov1;
}
public int getIdSala() {
return idSala;
}
public void setIdSala(int idSala) {
this.idSala = idSala;
}
public void setDueño(boolean dueño) {
this.dueño = dueño;
}
public VentanaChat getChat() {
return chat;
}
public void setChat(VentanaChat chat) {
this.chat = chat;
}
public VentanaLobby getLobby() {
return lobby;
}
public void setLobby(VentanaLobby lobby) {
this.lobby = lobby;
}
public JPanelGraficoLocal getContentPaneLocal() {
return contentPaneLocal;
}
public void setContentPaneLocal(JPanelGraficoLocal contentPaneLocal) {
this.contentPaneLocal = contentPaneLocal;
}
@Override
public void dispose() {
this.setVisible(false);
if(cliente!=null) {
if (dueño)
cliente.enviar("eliminarSala" + "/" + ((Integer) (idSala)).toString());
else
cliente.enviar("salirSala" + "/" + ((Integer) (idSala)).toString());
chat.dispose();
lobby.habilitarCamposTexto();
}
}
}
|
/*
* Copyright (c) TIKI Inc.
* MIT license. See LICENSE file in root directory.
*/
package com.mytiki.blockchain.config;
import com.mytiki.blockchain.features.latest.address.AddressConfig;
import com.mytiki.blockchain.features.latest.block.BlockConfig;
import org.springframework.context.annotation.Import;
@Import({
AddressConfig.class,
BlockConfig.class
})
public class ConfigFeatures {
}
|
package com.next.pojo.vo;
public class UserVO {
private String id;
private String username;
private String password;
private String nickname;
private String mpWxOpenId;
private String appQqOpenId;
private String appWxOpenId;
private String appWeiboUid;
private Integer sex;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getNickname() {
return nickname;
}
public void setNickname(String nickname) {
this.nickname = nickname;
}
public String getMpWxOpenId() {
return mpWxOpenId;
}
public void setMpWxOpenId(String mpWxOpenId) {
this.mpWxOpenId = mpWxOpenId;
}
public String getAppQqOpenId() {
return appQqOpenId;
}
public void setAppQqOpenId(String appQqOpenId) {
this.appQqOpenId = appQqOpenId;
}
public String getAppWxOpenId() {
return appWxOpenId;
}
public void setAppWxOpenId(String appWxOpenId) {
this.appWxOpenId = appWxOpenId;
}
public String getAppWeiboUid() {
return appWeiboUid;
}
public void setAppWeiboUid(String appWeiboUid) {
this.appWeiboUid = appWeiboUid;
}
public Integer getSex() {
return sex;
}
public void setSex(Integer sex) {
this.sex = sex;
}
public String getBirthday() {
return birthday;
}
public void setBirthday(String birthday) {
this.birthday = birthday;
}
public String getFaceImage() {
return faceImage;
}
public void setFaceImage(String faceImage) {
this.faceImage = faceImage;
}
public String getToken() {
return token;
}
public void setToken(String token) {
this.token = token;
}
private String birthday;
private String faceImage;
private String token;
}
|
package com.fwo.hp.fwo;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;
public class About extends AppCompatActivity {
TextView txt1,txt2,txt3;
boolean check = false;
RelativeLayout relativeLayout;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_data);
txt1=(TextView)findViewById(R.id.txt);
txt2=(TextView)findViewById(R.id.txt1);
txt3=(TextView)findViewById(R.id.txt2);
relativeLayout=(RelativeLayout)findViewById(R.id.activity_about);
relativeLayout.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if(check==false) {
check = true;
txt1.setText("ہمارے بارے میں");
txt2.setText("اسمارٹ مووم ویز ملٹی لیشنز مفت فلو (ایم ایل ایف) ٹریفک اور انٹیلجنٹ ٹرانسمیشن سسٹم کا حتمی مستقبل ہیں. مکمل، محفوظ، محفوظ اور آرام دہ اور پرسکون سفر کے تجربے کے ساتھ ہمارے قیمتی ہموار سفر ٹول پلازاس کے ذریعے عمدہ سفر کی عمدہ اور اہم دیکھ بھال کی تلاش میں.");
txt3.setText("نجی گاڑیاں: تمام قسم کی گاڑیاں مفت کی جا رہی ہیں. 30 جنوری 2018 تک 30 جنوری کو رجسٹریشن کریں گے، ابتدائی چارج / 300 روپے کے توازن کے ساتھ اور ہر 5000 کلو میٹر سفر کے بعد 500 روپے کے ریچارج کا حوصلہ افزائی کریں.");
}
else {
txt1.setText("About Us :");
txt2.setText("Smart Motorways are the ultimate future of Multi Lanes Free Flow(MLFF) traffic and Intelligent Transport System.In the quest of Excellence and prime care of our valuable seamless travel through toll plazas with complete,Safe,Secure and Comfortable travelling experience.");
txt3.setText("Private Vehicles : All such type of vehicles are being offered free.M.Tag registration till 30th of January 2018 , with initial charge/balance of Rs.300 and incentive of recharge Rs.500 after every 5000 km travelling.");
check=false;
}
}
});
/* if (check == true) {
txt1.setText("About Us :");
txt2.setText("Smart Motorways are the ultimate future of Multi Lanes Free Flow(MLFF) traffic and Intelligent Transport System.In the quest of Excellence and prime care of our valuable seamless travel through toll plazas with complete,Safe,Secure and Comfortable travelling experience.");
txt3.setText("Private Vehicles : All such type of vehicles are being offered free.M.Tag registration till 30th of January 2018 , with initial charge/balance of Rs.300 and incentive of recharge Rs.500 after every 5000 km travelling.");
}
else {
}*/
}
}
|
import java.util.*;
public class TaxiRank
{
public static void main(String[] args)
{
Queue q = new Queue();
Scanner kybd = new Scanner(System.in);
System.out.print("Join (j), leave (l) or end (e)? ");
String action = kybd.nextLine();
while (!action.equalsIgnoreCase("e"))
{
if (action.equalsIgnoreCase("j"))
{
System.out.print("Enter car registration: ");
String registration = kybd.nextLine();
q.add(registration);
System.out.println(registration + " joined queue");
}
else if (action.equalsIgnoreCase("l"))
{
if (!q.isEmpty())
{
System.out.println(q.remove() + " left queue");
}
else
{
System.out.println("Queue empty");
}
}
else
{
System.out.println("Invalid operation");
}
System.out.print("Join (j), leave (l) or end (e)? ");
action = kybd.nextLine();
}
}
}
|
import javax.swing.JOptionPane;
import java.util.*;
public class Alphabetize
{
public static void main(String[] args)
{
int optionsInt = Integer.parseInt(JOptionPane.showInputDialog("How many words would you like to alphabetize?"));
int[] alphaInts = new int[optionsInt];
String[] alphaChoices = new String[optionsInt];
String[] alphaChars = new String[optionsInt];
String[] alphabet = { "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"};
for (int i = 0; i < optionsInt; i++)
{
alphaChoices[i] = JOptionPane.showInputDialog("Enter your words");
}
for (int i = 0; i < alphaChoices.length; i++)
{
alphaChars[i] = alphaChoices[i].substring(0, 1);
}
for (int i = 0; i < alphaChars.length; i++)
{
for (int o = 0; o < alphabet.length; o++)
{
if (alphaChars[i].equalsIgnoreCase(alphabet[o]))
{
alphaInts[i] = o;
}
}
}
for (int i = 0; i < alphaInts.length; i++)
{
for (int o = i + 1; o < alphaInts.length; o++)
{
if (alphaInts[i] > alphaInts[o])
{
int holder = alphaInts[i];
alphaInts[i] = alphaInts[o];
alphaInts[o] = holder;
String holderString = alphaChoices[i];
alphaChoices[i] = alphaChoices[o];
alphaChoices[o] = holderString;
}
}
}
for (int i = 0; i < alphaChars.length; i++)
{
System.out.print(alphaChoices[i] + " ");
}
}
}
|
package pe.edu.sise.ejemplosqlitatareas;
import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.SQLException;
import android.support.annotation.LayoutRes;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends ListActivity {
public static final int NEW_ITEM = 1;
public static final int EDIT_ITEM = 2;
public static final int SHOW_ITEM = 3;
// Elemento Seleccionado
public static DataBaseHelper mDbHelper = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Abrir Base de Datos:
mDbHelper = new DataBaseHelper(this);
try{
fillData();
}catch (SQLException e){
e.printStackTrace();
showMessage(e.getLocalizedMessage());
}
}
public void showMessage(String message){
Context context = getApplicationContext();
CharSequence text = message.toString();
int duration = Toast.LENGTH_LONG;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
private void fillData(){
mDbHelper.open();
Cursor itemCursor = mDbHelper.getItems();
ListEntry item = null;
ArrayList<ListEntry> resultList = new ArrayList<ListEntry>();
// Procesamos el Resultado
while (itemCursor.moveToNext()){
int id = itemCursor.getInt(itemCursor.getColumnIndex(DataBaseHelper.SL_ID));
String task = itemCursor.getString(itemCursor.getColumnIndex(DataBaseHelper.SL_ITEM));
String place = itemCursor.getString(itemCursor.getColumnIndex(DataBaseHelper.SL_PLACE));
int importance = itemCursor.getInt(itemCursor.getColumnIndex(DataBaseHelper.SL_IMPORTANCE));
item = new ListEntry();
item.id = id;
item.task = task;
item.place = place;
item.importance = importance;
resultList.add(item);
}
itemCursor.close();
mDbHelper.close();
// Se genera el adaptador
TaskAdapter items = new TaskAdapter(this, R.layout.row_list, resultList, getLayoutInflater());
//ListView lista = (ListView) findViewById(R.id.list);
//lista.setAdapter(items);
setListAdapter(items);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.item_list, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case R.id.new_item:
Intent intent = new Intent(this, Item.class);
startActivityForResult(intent, NEW_ITEM);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private class TaskAdapter extends ArrayAdapter<ListEntry> {
private LayoutInflater mInfalter;
private List<ListEntry> mObjects;
public TaskAdapter(Context context, int resource, List<ListEntry> objects, LayoutInflater mInfalter){
super(context, resource, objects);
this.mInfalter = mInfalter;
this.mObjects = objects;
}
@Override
public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
ListEntry listEntry = mObjects.get(position);
// Obtenciónde la vista de la línea de la tabla
View row = mInfalter.inflate(R.layout.row_list, null);
//rellenamos datos
TextView place = (TextView) row.findViewById(R.id.row_place);
TextView item = (TextView) row.findViewById(R.id.row_item);
place.setText(listEntry.place);
item.setText(listEntry.task);
ImageView icon = (ImageView) row.findViewById(R.id.row_importance);
icon.setTag(new Integer(listEntry.id));
switch (listEntry.importance){
case 1:
icon.setImageResource(R.drawable.ic_green);
break;
case 2:
icon.setImageResource(R.drawable.ic_yellow);
break;
case 3:
icon.setImageResource(R.drawable.ic_red);
break;
}
return row;
}
}
private class ListEntry {
int id;
String task;
String place;
int importance;
}
}
|
package com.example.expensemanager;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import androidx.cardview.widget.CardView;
public class Main5Activity extends AppCompatActivity implements View.OnClickListener {
private CardView addexpense,viewexpense;
DatabaseHelper db;
int sumexpenses;
private TextView sumexpense;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main5);
sumexpense = (TextView)findViewById(R.id.textView9);
getSupportActionBar().setTitle("Expenses");
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
db= new DatabaseHelper(this);
sumexpenses=db.sumExpenses();
String sum= Integer.toString(sumexpenses);
sumexpense.setText(sum);
addexpense = (CardView) findViewById(R.id.id1);
viewexpense = (CardView) findViewById(R.id.id2);
addexpense.setOnClickListener(this);
viewexpense.setOnClickListener(this);
}
@Override
public void onClick(View view) {
Intent i;
switch (view.getId()) {
case R.id.id1:
i= new Intent(this, Main2Activity.class );
startActivity(i);
break;
case R.id.id2:
i= new Intent(this, ViewListContents.class );
startActivity(i);
break;
default: break;
}
}
}
|
package com.coleapps.wgucoursetracker3;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.Notification;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.text.InputType;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Random;
public class EditOrViewCourse extends AppCompatActivity {
private String[] alertArray;
private String alertTitle;
private String alertBody;
private NotificationHelper helper;
private Notification.Builder notifBuilder;
private String[] termsArray;
private String action;
private String courseFilter;
private String courseId;
private String courseName;
private String courseNum;
private String startDate;
private String endDate;
private String termName;
private String status;
private String mentorName;
private String mentorTel;
private String mentorEmail;
private String notes;
private String[] statusArray;
private TextView tvCourseName;
private TextView tvCourseStart;
private TextView tvCourseEnd;
private TextView tvCourseTerm;
private TextView tvCourseNum;
private TextView tvMentorName;
private TextView tvMentorTel;
private TextView tvMentorEmail;
private TextView tvStatus;
private TextView tvNotes;
private Button btnSetAlert;
private Button btnSaveChanges;
private Button btnDeleteCourse;
private Button btnShareNotes;
private final int NUM_INDEX = 5;
private final int STATUS_INDEX = 8;
private final int EDITOR_REQUEST_CODE = 1008;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_course);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
btnSaveChanges = findViewById(R.id.saveChanges);
btnDeleteCourse = findViewById(R.id.deleteCourse);
btnShareNotes = findViewById(R.id.shareNotes);
btnSetAlert = findViewById(R.id.btnSetAlert);
Intent intent = getIntent();
Uri uri = intent.getParcelableExtra(DBProvider.CONTENT_ITEM_TYPE_COURSE);
if (uri == null) {
action = Intent.ACTION_INSERT;
tvCourseTerm = (TextView) findViewById(R.id.tvCourseTermName);
tvCourseNum = (TextView) findViewById(R.id.tvCourseNum);
tvCourseName = (TextView) findViewById(R.id.tvCourseName);
tvCourseStart = (TextView) findViewById(R.id.tvCourseStart);
tvCourseEnd = (TextView) findViewById(R.id.tvCourseEnd);
tvStatus = (TextView) findViewById(R.id.tvStatus);
tvMentorName = (TextView) findViewById(R.id.tvMentorName);
tvMentorTel = (TextView) findViewById(R.id.tvMentorTel);
tvMentorEmail = (TextView) findViewById(R.id.tvMentorEmail);
tvNotes = (TextView) findViewById(R.id.tvNotes);
setUpDialogs();
setUpButtons();
setUpDatePickers();
} else {
action = Intent.ACTION_EDIT;
courseFilter = DBOpenHelper.COURSES_ID + "=" + uri.getLastPathSegment();
//query the db for the specific ID of the clicked on item
Cursor cursor = getContentResolver().query(uri,
DBOpenHelper.ALL_COURSES_COLUMNS, courseFilter, null, null);
cursor.moveToFirst();
//pull all values from the db
courseId = cursor.getString(cursor.getColumnIndex(DBOpenHelper.COURSES_ID));
courseName = cursor.getString(cursor.getColumnIndex(DBOpenHelper.COURSES_COURSENAME));
courseNum = cursor.getString(cursor.getColumnIndex(DBOpenHelper.COURSES_COURSENUM));
startDate = cursor.getString(cursor.getColumnIndex(DBOpenHelper.COURSES_STARTDATE));
endDate = cursor.getString(cursor.getColumnIndex(DBOpenHelper.COURSES_ENDDATE));
termName = cursor.getString(cursor.getColumnIndex(DBOpenHelper.COURSES_TERMNAME));
status = cursor.getString(cursor.getColumnIndex(DBOpenHelper.COURSES_STATUS));
mentorName = cursor.getString(cursor.getColumnIndex(DBOpenHelper.COURSES_MENTOR_NAME));
mentorTel = cursor.getString(cursor.getColumnIndex(DBOpenHelper.COURSES_MENTOR_TEL));
mentorEmail = cursor.getString(cursor.getColumnIndex(DBOpenHelper.COURSES_MENTOR_EMAIL));
notes = cursor.getString(cursor.getColumnIndex(DBOpenHelper.COURSES_NOTES));
//acquire text views on the screen
tvCourseTerm = (TextView) findViewById(R.id.tvCourseTermName);
tvCourseNum = (TextView) findViewById(R.id.tvCourseNum);
tvCourseName = (TextView) findViewById(R.id.tvCourseName);
tvCourseStart = (TextView) findViewById(R.id.tvCourseStart);
tvCourseEnd = (TextView) findViewById(R.id.tvCourseEnd);
tvStatus = (TextView) findViewById(R.id.tvStatus);
tvMentorName = (TextView) findViewById(R.id.tvMentorName);
tvMentorTel = (TextView) findViewById(R.id.tvMentorTel);
tvMentorEmail = (TextView) findViewById(R.id.tvMentorEmail);
tvNotes = (TextView) findViewById(R.id.tvNotes);
//create strings to populate text views
String termString = "Term " + termName;
String statusString = "Status: " + status;
//pass strings to text views
tvCourseTerm.setText(termString);
tvCourseNum.setText(courseNum);
tvCourseName.setText(courseName);
tvCourseStart.setText(startDate);
tvCourseEnd.setText(endDate);
tvStatus.setText(statusString);
tvMentorName.setText(mentorName);
tvMentorTel.setText(mentorTel);
tvMentorEmail.setText(mentorEmail);
tvNotes.setText(notes);
setUpDatePickers();
setUpButtons();
setUpDialogs();
cursor.close();
}
}
private void setUpDialogs() {
//Dialog for changing the course name, activated on click of tvCourseName object
tvCourseName.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
AlertDialog.Builder builder = new AlertDialog.Builder(EditOrViewCourse.this);
builder.setTitle("Set Course Name");
String oldCourseName = String.valueOf(tvCourseName.getText());
// Set up the input
final EditText input = new EditText(EditOrViewCourse.this);
// Specify the type of input expected; this sets the input as plain text
input.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_NORMAL);
input.setText(oldCourseName);
builder.setView(input);
// Set up the buttons
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String newCourseName = input.getText().toString();
tvCourseName.setText(newCourseName);
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
btnSaveChanges.setVisibility(View.VISIBLE);
builder.show();
}
});
tvCourseNum.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
AlertDialog.Builder builder = new AlertDialog.Builder(EditOrViewCourse.this);
builder.setTitle("Set Course Number");
String oldCourseNum = String.valueOf(tvCourseNum.getText());
// Set up the input
final EditText input = new EditText(EditOrViewCourse.this);
// Specify the type of input expected; this sets the input as plain text
input.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_NORMAL);
input.setText(oldCourseNum);
builder.setView(input);
// Set up the buttons
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String newCourseNum = input.getText().toString();
tvCourseNum.setText(newCourseNum);
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
btnSaveChanges.setVisibility(View.VISIBLE);
builder.show();
}
});
tvCourseTerm.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
ArrayList<String> terms = new ArrayList<>();
String fieldToAdd = null;
Cursor termCursor = getContentResolver().query(DBProvider.CONTENT_URI_TERMS, DBOpenHelper.ALL_TERM_COLUMNS,
null, null, null);
while (termCursor.moveToNext()) {
fieldToAdd = termCursor.getString(termCursor.getColumnIndex(DBOpenHelper.TERMS_TERMNAME));
terms.add(fieldToAdd);
}
termsArray = new String[terms.size()];
for (int i = 0; i < terms.size(); i++) {
termsArray[i] = terms.get(i);
}
if(termsArray.length == 0) {
Toast.makeText(EditOrViewCourse.this, "No terms available to add course, please create at least 1 term", Toast.LENGTH_SHORT).show();
} else {
AlertDialog.Builder builder = new AlertDialog.Builder(EditOrViewCourse.this);
builder.setTitle("Select Term to Add Course to");
builder.setItems(termsArray, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
String newCourseTerm = "Term " + termsArray[i];
tvCourseTerm.setText(newCourseTerm);
}
});
btnSaveChanges.setVisibility(View.VISIBLE);
builder.show();
}
}
});
tvStatus.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
statusArray = new String[] {"In Progress", "Not Started", "Completed", "Dropped"};
AlertDialog.Builder builder = new AlertDialog.Builder(EditOrViewCourse.this);
builder.setTitle("Select Status");
builder.setItems(statusArray, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
String status = "Status: " + statusArray[i];
tvStatus.setText(status);
}
});
btnSaveChanges.setVisibility(View.VISIBLE);
builder.show();
}
});
tvMentorName.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
AlertDialog.Builder builder = new AlertDialog.Builder(EditOrViewCourse.this);
builder.setTitle("Set Mentor's Name");
String oldMentorName = String.valueOf(tvMentorName.getText());
// Set up the input
final EditText input = new EditText(EditOrViewCourse.this);
// Specify the type of input expected; this sets the input as plain text
input.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_NORMAL);
input.setText(oldMentorName);
builder.setView(input);
// Set up the buttons
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String newMentorName = input.getText().toString();
tvMentorName.setText(newMentorName);
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
btnSaveChanges.setVisibility(View.VISIBLE);
builder.show();
}
});
tvMentorTel.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
AlertDialog.Builder builder = new AlertDialog.Builder(EditOrViewCourse.this);
builder.setTitle("Set Mentor's Phone Number");
String oldMentorName = String.valueOf(tvMentorTel.getText());
// Set up the input
final EditText input = new EditText(EditOrViewCourse.this);
// Specify the type of input expected; this sets the input as plain text
input.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_NORMAL);
input.setText(oldMentorName);
builder.setView(input);
// Set up the buttons
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String newMentorTel = input.getText().toString();
tvMentorTel.setText(newMentorTel);
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
btnSaveChanges.setVisibility(View.VISIBLE);
builder.show();
}
});
tvMentorEmail.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
AlertDialog.Builder builder = new AlertDialog.Builder(EditOrViewCourse.this);
builder.setTitle("Set Mentor's Email Address");
String oldMentorName = String.valueOf(tvMentorEmail.getText());
// Set up the input
final EditText input = new EditText(EditOrViewCourse.this);
// Specify the type of input expected; this sets the input as plain text
input.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_NORMAL);
input.setText(oldMentorName);
builder.setView(input);
// Set up the buttons
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String newMentorEmail = input.getText().toString();
tvMentorEmail.setText(newMentorEmail);
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
btnSaveChanges.setVisibility(View.VISIBLE);
builder.show();
}
});
tvNotes.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
AlertDialog.Builder builder = new AlertDialog.Builder(EditOrViewCourse.this);
builder.setTitle("Additional Notes");
String oldNotes = String.valueOf(tvNotes.getText());
// Set up the input
final EditText input = new EditText(EditOrViewCourse.this);
// Specify the type of input expected; this sets the input as plain text
input.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_NORMAL);
input.setText(oldNotes);
builder.setView(input);
// Set up the buttons
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String newNotes = input.getText().toString();
tvNotes.setText(newNotes);
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
btnSaveChanges.setVisibility(View.VISIBLE);
builder.show();
}
});
}
private void setUpButtons() {
//Save changes button click listener, does not appear until values on page have changed
btnSaveChanges.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String newTermNumString = String.valueOf(tvCourseTerm.getText());
//Requires substring to parse out label "Term "
String newTermNum = newTermNumString.substring(NUM_INDEX);
String newCourseNum = String.valueOf(tvCourseNum.getText());
String newCourseName = String.valueOf(tvCourseName.getText());
String newCourseStart = String.valueOf(tvCourseStart.getText());
String newCourseEnd = String.valueOf(tvCourseEnd.getText());
String newStatusString = String.valueOf(tvStatus.getText());
//Requires substring to parse out label "Status: "
String newStatus = newStatusString.substring(STATUS_INDEX);
String newMentorName = String.valueOf(tvMentorName.getText());
String newMentorTel = String.valueOf(tvMentorTel.getText());
String newMentorEmail = String.valueOf(tvMentorEmail.getText());
String newNotes = String.valueOf(tvNotes.getText());
//get action based on Edit or Create new term
if(action == Intent.ACTION_EDIT) {
updateCourse(newCourseNum, newCourseName, newCourseStart, newCourseEnd, newStatus, newTermNum, newMentorName, newMentorTel, newMentorEmail, newNotes);
Intent intent = new Intent(EditOrViewCourse.this, CourseList.class);
startActivityForResult(intent, EDITOR_REQUEST_CODE);
} else if (action == Intent.ACTION_INSERT) {
insertCourse(newCourseNum, newCourseName, newCourseStart, newCourseEnd, newStatus, newTermNum, newMentorName, newMentorTel, newMentorEmail, newNotes);
Intent intent = new Intent(EditOrViewCourse.this, CourseList.class);
startActivityForResult(intent, EDITOR_REQUEST_CODE);
}
}
});
btnDeleteCourse.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
deleteCourse();
Intent intent = new Intent(EditOrViewCourse.this, CourseList.class);
startActivityForResult(intent, EDITOR_REQUEST_CODE);
}
});
btnShareNotes.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String shareBody = String.valueOf(tvNotes.getText());
String subject = "Notes for Course " + String.valueOf(tvCourseNum.getText());
Intent shareIntent = new Intent(android.content.Intent.ACTION_SEND);
shareIntent.setType("text/plain");
shareIntent.putExtra(Intent.EXTRA_SUBJECT, subject);
shareIntent.putExtra(Intent.EXTRA_TEXT, shareBody);
startActivity(Intent.createChooser(shareIntent, "Share"));
}
});
btnSetAlert.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
alertArray = new String[] {"Start Date", "End Date"};
AlertDialog.Builder builder = new AlertDialog.Builder(EditOrViewCourse.this);
builder.setTitle("Which alert would you like to set?");
builder.setItems(alertArray, new DialogInterface.OnClickListener() {
@RequiresApi(api = Build.VERSION_CODES.O)
@Override
public void onClick(DialogInterface dialogInterface, int i) {
if (alertArray[i].equals("Start Date")) {
alertTitle = "Course Start";
alertBody = "Course " + courseNum + " " + courseName + " will start on " +startDate;
} else if (alertArray[i].equals("End Date")) {
alertTitle = "Course End";
alertBody = "Course " + courseNum + " " + courseName + " will end on " + endDate;
}
helper = new NotificationHelper(EditOrViewCourse.this);
notifBuilder = helper.getWguCourseChannelNotification(alertTitle, alertBody);
helper.getManager().notify(new Random().nextInt(), notifBuilder.build());
}
});
builder.show();
}
});
}
private void setUpDatePickers() {
tvCourseStart.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Calendar cal = Calendar.getInstance();
int year = cal.get(Calendar.YEAR);
int month = cal.get(Calendar.MONTH);
int dayOfMonth = cal.get(Calendar.DAY_OF_MONTH);
DatePickerDialog startDateDialog = new DatePickerDialog(EditOrViewCourse.this, android.R.style.Theme_Holo_Light_Dialog_MinWidth, startDateSetListener, year, month, dayOfMonth);
startDateDialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
startDateDialog.show();
}
DatePickerDialog.OnDateSetListener startDateSetListener = new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker datePicker, int year, int month, int dayOfMonth) {
month = month++;
String startDateString = month + "/" + dayOfMonth + "/" + year;
tvCourseStart.setText(startDateString);
btnSaveChanges.setVisibility(View.VISIBLE);
}
};
});
tvCourseEnd.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Calendar cal2 = Calendar.getInstance();
int year = cal2.get(Calendar.YEAR);
int month = cal2.get(Calendar.MONTH);
int dayOfMonth = cal2.get(Calendar.DAY_OF_MONTH);
DatePickerDialog startDateDialog = new DatePickerDialog(EditOrViewCourse.this, android.R.style.Theme_Holo_Light_Dialog_MinWidth, endDateSetListener, year, month, dayOfMonth);
startDateDialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
startDateDialog.show();
}
DatePickerDialog.OnDateSetListener endDateSetListener = new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker datePicker, int year, int month, int dayOfMonth) {
month = month++;
String endDateString = month + "/" + dayOfMonth + "/" + year;
tvCourseEnd.setText(endDateString);
btnSaveChanges.setVisibility(View.VISIBLE);
}
};
});
}
private void updateCourse(String courseNum, String courseName, String startDate, String endDate, String status,
String termName, String mentorName, String mentorTel, String mentorEmail, String notes) {
ContentValues values = new ContentValues();
values.put(DBOpenHelper.COURSES_COURSENUM, courseNum);
values.put(DBOpenHelper.COURSES_COURSENAME, courseName);
values.put(DBOpenHelper.COURSES_STARTDATE, startDate);
values.put(DBOpenHelper.COURSES_ENDDATE, endDate);
values.put(DBOpenHelper.COURSES_STATUS, status);
values.put(DBOpenHelper.COURSES_TERMNAME, termName);
values.put(DBOpenHelper.COURSES_MENTOR_NAME, mentorName);
values.put(DBOpenHelper.COURSES_MENTOR_TEL, mentorTel);
values.put(DBOpenHelper.COURSES_MENTOR_EMAIL, mentorEmail);
values.put(DBOpenHelper.COURSES_NOTES, notes);
String where = DBOpenHelper.COURSES_ID + "= ?";
String[] selectionArg = {courseId};
getContentResolver().update(DBProvider.CONTENT_URI_COURSES, values, where, selectionArg);
}
private void insertCourse(String courseNum, String courseName, String startDate, String endDate, String status,
String termName, String mentorName, String mentorTel, String mentorEmail, String notes) {
ContentValues values = new ContentValues();
values.put(DBOpenHelper.COURSES_COURSENUM, courseNum);
values.put(DBOpenHelper.COURSES_COURSENAME, courseName);
values.put(DBOpenHelper.COURSES_STARTDATE, startDate);
values.put(DBOpenHelper.COURSES_ENDDATE, endDate);
values.put(DBOpenHelper.COURSES_STATUS, status);
values.put(DBOpenHelper.COURSES_TERMNAME, termName);
values.put(DBOpenHelper.COURSES_MENTOR_NAME, mentorName);
values.put(DBOpenHelper.COURSES_MENTOR_TEL, mentorTel);
values.put(DBOpenHelper.COURSES_MENTOR_EMAIL, mentorEmail);
values.put(DBOpenHelper.COURSES_NOTES, notes);
getContentResolver().insert(DBProvider.CONTENT_URI_COURSES, values);
}
private void deleteCourse() {
String where = DBOpenHelper.COURSES_ID + "= ?";
String[] selectionArg = {courseId};
getContentResolver().delete(DBProvider.CONTENT_URI_COURSES, where, selectionArg);
}
public void openAssessmentList(View view) {
Intent intent = new Intent(this, AssessmentList.class);
startActivityForResult(intent, EDITOR_REQUEST_CODE);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
switch (id) {
case R.id.go_home:
Intent intent = new Intent(EditOrViewCourse.this, MainScreen.class);
startActivityForResult(intent, EDITOR_REQUEST_CODE);
break;
}
return super.onOptionsItemSelected(item);
}
private void setAlert() {
}
}
|
package cn.itcast.dao;
import org.springframework.jdbc.core.JdbcTemplate;
public class OrdersDao {
//注入jdbcTemplate
private JdbcTemplate jdbcTemplate;
public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
/**
* 做对数据库操作的方法,不写业务逻辑
*/
//小王少钱的方法
public void lessMoney(){
String sql = "update account set salary = salary - ? where username = ?";
jdbcTemplate.update(sql, 1000,"小王");
}
//小马多钱的方法
public void moreMoney(){
String sql = "update account set salary = salary + ? where username = ?";
jdbcTemplate.update(sql, 1000,"小马");
}
}
|
package com.andreldm.report.pojo;
import java.time.LocalDateTime;
public class Purchase {
private String product;
private Double value;
private Integer quantity;
private LocalDateTime date;
public String getProduct() {
return product;
}
public void setProduct(String product) {
this.product = product;
}
public Double getValue() {
return value;
}
public void setValue(Double value) {
this.value = value;
}
public Integer getQuantity() {
return quantity;
}
public void setQuantity(Integer quantity) {
this.quantity = quantity;
}
public LocalDateTime getDate() {
return date;
}
public void setDate(LocalDateTime date) {
this.date = date;
}
}
|
package com.rcorchero.hastensports.data.network;
import com.rcorchero.hastensports.BuildConfig;
import java.util.concurrent.TimeUnit;
import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.converter.jackson.JacksonConverterFactory;
public class NetworkServiceFactory {
private static final String BASE_URL = " https://api.myjson.com/";
private static final int HTTP_READ_TIMEOUT = 10000;
private static final int HTTP_CONNECT_TIMEOUT = 6000;
public static NetworkService makeNetworkService() {
return makeNetworkService(makeOkHttpClient());
}
private static NetworkService makeNetworkService(OkHttpClient okHttpClient) {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(JacksonConverterFactory.create())
.client(okHttpClient)
.build();
return retrofit.create(NetworkService.class);
}
private static OkHttpClient makeOkHttpClient() {
OkHttpClient.Builder httpClientBuilder = new OkHttpClient().newBuilder();
httpClientBuilder.connectTimeout(HTTP_CONNECT_TIMEOUT, TimeUnit.SECONDS);
httpClientBuilder.readTimeout(HTTP_READ_TIMEOUT, TimeUnit.SECONDS);
httpClientBuilder.addInterceptor(makeLoggingInterceptor());
return httpClientBuilder.build();
}
private static HttpLoggingInterceptor makeLoggingInterceptor() {
HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
logging.setLevel(BuildConfig.DEBUG ? HttpLoggingInterceptor.Level.BODY
: HttpLoggingInterceptor.Level.NONE);
return logging;
}
}
|
package test.xitikit.examples.java.mysql.logwatch.simple;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestInstance;
import org.mockito.Mockito;
import org.xitikit.examples.java.mysql.logwatch.simple.*;
import java.nio.file.Path;
import static java.util.Arrays.*;
import static org.mockito.Mockito.*;
/**
* Copyright ${year}
*
* @author J. Keith Hoopes
*/
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
class LogWatchCliTest{
@Test
void emptyCommand(){
LogEntryRepository logEntryRepository = Mockito.mock(LogEntryRepository.class);
AccessLogLoader accessLogLoader = Mockito.mock(AccessLogLoader.class);
BlockedIpv4Repository blockedIpv4Repository = Mockito.mock(BlockedIpv4Repository.class);
doReturn(blockedIpv4())
.when(blockedIpv4Repository)
.save(any());
doReturn(asList(ipv4SearchResult()))
.when(logEntryRepository)
.findAllByDateRangeAndThreshold(any(), any(), any());
new LogWatchCli(logEntryRepository, accessLogLoader, blockedIpv4Repository).run(args());
verify(logEntryRepository, times(1)).findAllByDateRangeAndThreshold(any(), any(), any());
verify(accessLogLoader, times(1)).parseAndSaveAccessLogEntries(any(Path.class));
}
private static AccessLogSearchResult ipv4SearchResult(){
return new AccessLogSearchResult("10.150.10.1", 110);
}
private static String[] args(){
return new String[]{
"--accessLog=src/test/resources/access.log",
"--startDate=2017-01-01.13:00:00",
"--duration=hourly",
"--threshold=100"};
}
private static BlockedIpv4 blockedIpv4(){
BlockedIpv4 blockedIpv4 = new BlockedIpv4("whatever", "cuz");
blockedIpv4.setId(1);
return blockedIpv4;
}
} |
/*
Copyright (C) 2013-2014, Securifera, Inc
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of Securifera, Inc nor the names of its contributors may be
used to endorse or promote products derived from this software without specific
prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS
OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
================================================================================
Pwnbrew is provided under the 3-clause BSD license above.
The copyright on this package is held by Securifera, Inc
*/
/*
* ServerHttpWrapper.java
*
* Created on July 8, 2013
*/
package pwnbrew.network.http;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.security.SecureRandom;
import java.util.Arrays;
import java.util.logging.Level;
import java.util.logging.Logger;
import pwnbrew.log.Log;
import pwnbrew.log.LoggableException;
import pwnbrew.manager.ConnectionManager;
import pwnbrew.manager.DataManager;
import pwnbrew.misc.DebugPrinter;
import pwnbrew.network.Message;
import pwnbrew.network.RegisterMessage;
import pwnbrew.network.ServerPortRouter;
import pwnbrew.utilities.SocketUtilities;
import pwnbrew.utilities.Utilities;
import pwnbrew.selector.SocketChannelHandler;
/**
*
*
*/
public class ServerHttpWrapper extends HttpWrapper {
private static final String NAME_Class = ServerHttpWrapper.class.getSimpleName();
private static final int STEALTH_COOKIE_B64 = 5;
//Random number gen for age
private final SecureRandom aSR = new SecureRandom();
private volatile boolean staging = false;
//==========================================================================
/**
* Constructor
*
*/
public ServerHttpWrapper(){
};
//===============================================================
/**
* Process the HTTP header, extract the data from it, and pass the message
* on to the message handler.
*
* @param aLine
*/
@Override
void processHeader( SocketChannelHandler passedHandler ) {
if( currentHeader != null ){
//Get the accept language
String langField = currentHeader.getOption( Http.ACCEPT_LANGUAGE );
if( langField != null ){
//Split on the semi-colon separater
String[] langArr = langField.split(";");
if( langArr.length > 1){
//Get the q field
String[] qArr = langArr[1].split("\\.");
if( qArr.length > 1){
//Try an parse the field
try {
int stealthNum = Integer.parseInt( qArr[1] );
byte[] ctrlMsg = getMessageBytes( stealthNum);
//Create a control message
if( ctrlMsg != null ){
//Handle the message
ByteBuffer msgBB = ByteBuffer.wrap(ctrlMsg);
byte currMsgType = msgBB.get();
if( DataManager.isValidType( currMsgType ) ){
//Get the length
byte[] msgLenArr = new byte[ Message.MSG_LEN_SIZE ];
msgBB.get(msgLenArr);
//Verify that it matches
int msgLen = SocketUtilities.byteArrayToInt(msgLenArr);
if( msgLen == msgBB.remaining()){
byte[] msgByteArr = new byte[msgLen];
msgBB.get(msgByteArr);
//Get the id If the client is already registered then return
if( msgByteArr.length > Message.MSG_LEN_SIZE + 1 ){
//Register the handler
if( currMsgType == Message.REGISTER_MESSAGE_TYPE ){
RegisterMessage aMsg = RegisterMessage.getMessage( ByteBuffer.wrap( msgByteArr ));
int srcId = aMsg.getSrcHostId();
int chanId = aMsg.getChannelId();
if( passedHandler.registerId(srcId, chanId) ){
Log.log( Level.SEVERE,ServerHttpWrapper.class.getSimpleName(), "processHeader()", "Registered host: " + Integer.toString(srcId) + " channel: " + Integer.toString(chanId), null );
passedHandler.setRegisteredFlag(true);
RegisterMessage retMsg = new RegisterMessage(RegisterMessage.REG_ACK, aMsg.getStlth(), srcId, chanId);
DataManager.send(passedHandler.getPortRouter().getPortManager(), retMsg);
//Turn off wrapping if not stlth
if( !aMsg.keepWrapping() )
passedHandler.setWrapping( srcId, false);
} else {
Log.log( Level.SEVERE,ServerHttpWrapper.class.getSimpleName(), "processHeader()", "Host registration failed: "+ Integer.toString(srcId) + " channel: " + Integer.toString(chanId), null);
}
return;
} else {
if( currMsgType == Message.STAGING_MESSAGE_TYPE ){
//Get src id
byte[] srcHostIdArr = Arrays.copyOfRange(msgByteArr, 0, 4);
int srcHostId = SocketUtilities.byteArrayToInt(srcHostIdArr);
//Register the relay
int parentId = passedHandler.getRootHostId();
if( srcHostId != parentId ){
ServerPortRouter aSPR = (ServerPortRouter)passedHandler.getPortRouter();
aSPR.registerHandler(srcHostId, parentId, ConnectionManager.STAGE_CHANNEL_ID, passedHandler);
}
}
//Get dest id
byte[] dstHostId = Arrays.copyOfRange(msgByteArr, 4, 8);
int dstId = SocketUtilities.byteArrayToInt(dstHostId);
try{
DataManager.routeMessage( passedHandler.getPortRouter(), currMsgType, dstId, msgByteArr );
} catch(Exception ex ){
Log.log( Level.SEVERE, NAME_Class, "processHeader()", ex.toString(), ex);
}
return;
}
}
} else {
}
}
}
} catch ( NumberFormatException ex){
//Do nothing because it doesn't fit the criteria
ex = null;
} catch (IOException ex) {
//Do nothing because it doesn't fit the criteria
ex = null;
} catch (LoggableException ex) {
Logger.getLogger(ServerHttpWrapper.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
//Send redirect
ByteBuffer reply = wrapBytes( new byte[0]);
passedHandler.queueBytes( Arrays.copyOf(reply.array(), reply.position()));
}
}
//===============================================================
/**
* Returns a ByteBuffer with the necessary bytes in it.
*
* @param msgBytes
* @return
*/
@Override
public ByteBuffer wrapBytes( byte[] msgBytes ) {
//Allocate and add the bytes from the message
if( staging )
return wrapStager( msgBytes );
else {
Http aHttpMsg = Http.getGeneric( Http._302 );
//XOR the bytes
if( msgBytes.length > 0 ){
//Have to add 1 because this call is between 0 and n which means the check on the other
//side will fail if the number returns 0
int exp = aSR.nextInt( 9 ) + 1;
int ageVal = (int) Math.pow(STEALTH_COOKIE_B64, exp);
//XOR the bytes
byte[] encodedBytes = Utilities.xorData(msgBytes, XOR_STRING.getBytes());
//Get a hex string representation
String encodedByteStr = SocketUtilities.toString(encodedBytes).replace(" ", "");
StringBuilder aSB = new StringBuilder()
.append(COOKIE_REF).append("=").append( encodedByteStr );
aHttpMsg.setOption(Http.SET_COOKIE, aSB.toString());
aHttpMsg.setOption(Http.AGE, Integer.toString(ageVal));
}
//Allocate enough space
int httpLen = aHttpMsg.getLength();
ByteBuffer aByteBuffer = ByteBuffer.allocate( httpLen );
//Add the bytes
aHttpMsg.append(aByteBuffer);
return aByteBuffer;
}
}
//======================================================================
/**
*
* @param classBytes
* @return
*/
private ByteBuffer wrapStager( byte[] classBytes ){
//Allocate and add the bytes from the message
Http aHttpMsg = Http.getGeneric( Http._200 );
//Set the bytes
if( classBytes.length > 0 ){
aHttpMsg.setPayloadBytes( classBytes );
aHttpMsg.setOption( Http.CONTENT_LENGTH, Integer.toString(classBytes.length) );
}
//Allocate enough space
int httpLen = aHttpMsg.getLength();
ByteBuffer aByteBuffer = ByteBuffer.allocate( httpLen );
//Add the bytes
aHttpMsg.append(aByteBuffer);
return aByteBuffer;
}
//===============================================================
/**
* Return the message bytes.
*
* @param aLine
*/
private byte[] getMessageBytes(int stealthNum) throws IOException {
byte[] msgBytes = null;
switch( stealthNum ){
case STEALTH_COOKIE_B64:
//Get the cookie
String cookieVal = currentHeader.getOption( Http.COOKIE );
if( cookieVal != null && cookieVal.startsWith(COOKIE_REF) ){
String[] cookieArr = cookieVal.split("=");
if( cookieArr.length > 1 ){
//Convert the hexstring to bytes
String hexString = cookieArr[1];
try {
byte[] xorBytes = SocketUtilities.hexStringToByteArray(hexString);
//XOR the bytes
msgBytes = Utilities.xorData(xorBytes, XOR_STRING.getBytes());
} catch (LoggableException ex) {
Log.log( Level.SEVERE, NAME_Class, "getMessageBytes()", ex.getMessage(), ex);
}
}
}
break;
default:
break;
}
return msgBytes;
}
//===================================================================
/**
* Set the staging flag
*
* @param passedBool
*/
public synchronized void setStaging( boolean passedBool ) {
staging = passedBool;
}
//===================================================================
/**
* Check if the handler is managing a staged connection
*
* @return
*/
public synchronized boolean isStaged() {
return staging;
}
}
|
package com.strategy;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Configuration;
@SpringBootApplication
@Configuration
public class AccountStrategyApplication {
public static void main(String[] args) {
SpringApplication.run(AccountStrategyApplication.class, args);
}
public static void getRules()
{
}
}
|
package org.maple.jdk8.stream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
/**
* @Author Mapleins
* @Date 2019-04-05 14:14
* @Description 演示流转集合
*/
public class Test4 {
public static void main(String[] args) {
Stream<String> stream = Stream.of("hello", "world", "hello world");
//将上面的流转换为字符数组
// String[] arr = stream.toArray(length -> new String[length]);
String[] arr = stream.toArray(String[]::new);
Arrays.asList(arr).forEach(System.out::println);
System.out.println("---------------------------------");
// 将流转换为 list
Stream<String> stream2 = Stream.of("hello", "world", "hello world");
// api 方法 只能转换成 ArrayList
// List<String> list = stream2.collect(Collectors.toList());
/**
* 上面的 collect()方法的原始实现如下
* collect((Supplier<A> supplier, 提供者:提供容器,来将流放入容器
* BiConsumer<A, T> accumulator, 消费者:传入两个参数,不返回值,这里的两个参数是:1.集合 2.流中的元素
* BinaryOperator<A> combiner, 合并者:Function:传入两个一样参数类型,返回一个结果,把流中产生的集合,加入到 new 出的 list 当中
* Set<Characteristics> characteristics)
*
*/
// List list = stream2.collect(() -> new ArrayList<>(), (list1, item) -> list1.add(item),(newList,list1) -> newList.addAll(list1) );
// List list = stream2.collect(ArrayList::new, ArrayList::add, ArrayList::addAll);
List list = stream2.collect(LinkedList::new, LinkedList::add, LinkedList::addAll);
list.forEach(System.out::println);
}
}
|
package cn.tedu.test;
import java.util.Scanner;
/**
* 要求用户从控制台输入一个email地址,然后获取该email的用户名(@之前的内容)
* @author Xiloer
*
*/
public class TestDay0104 {
public static void main(String[] args) {
String regex="[0-9a-zA-Z]*[@][0-9a-zA-Z]*[.][c][o][m]";
String input;
do{
System.out.println("请输入您的邮箱:");
input =new Scanner(System.in).nextLine();
if(input.matches(regex)){
System.out.println("您的邮箱输入正确");
}else{
System.out.println("你的邮箱输入有误");
}
}while(!input.matches(regex));
int i=input.indexOf("@");
System.out.println("您的用户名为:"+input.substring(0,i));
}
}
|
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
PrintWriter out = new PrintWriter(System.out);
int n = scanner.nextInt();
Integer[] a = new Integer[n];
for (int i = 0; i < n; i++) {
a[i] = scanner.nextInt();
}
Arrays.sort(a);
for (int i = 0; i < n; i += 2) {
out.print(a[i] + " ");
}
int k = n - 1;
if (k % 2 == 0) {
k--;
}
for (int i = k; i >= 1; i -= 2) {
out.print(a[i] + " ");
}
out.flush();
}
} |
package com.example.BSD;
public class CursusListItem
{
private String cursusTitel;
private String cursusOmschrijving;
private String aanmaakDatum;
private String vakgebied;
private String inschrijfDatum;
private String maxAantalDeelnemers;
private String prijs;
public CursusListItem(String CursusTitel, String CursusOmschrijving, String datum, String prijs, String inschrijfdatum, String vakgebied, String maxAantalDeelnemers)
{
this.cursusTitel = CursusTitel;
this.cursusOmschrijving = CursusOmschrijving;
this.aanmaakDatum = datum;
this.prijs = prijs;
this.inschrijfDatum = inschrijfdatum;
this.vakgebied = vakgebied;
this.maxAantalDeelnemers = maxAantalDeelnemers;
}
public void setTitel( String titel )
{
this.cursusTitel = titel;
}
public String getTitel()
{
return cursusTitel;
}
public void setOmschrijving( String omschrijving )
{
this.cursusOmschrijving = omschrijving;
}
public String getOmschrijving()
{
return cursusOmschrijving;
}
public void setAanmaakDatum( String datum )
{
this.aanmaakDatum = datum;
}
public String getAanmaakDatum()
{
return aanmaakDatum;
}
public String getVakgebied()
{
return vakgebied;
}
public void setVakgebied(String vakgebied)
{
this.vakgebied = vakgebied;
}
public String getInschrijfDatum()
{
return inschrijfDatum;
}
public void setInschrijfDatum(String inschrijfDatum)
{
this.inschrijfDatum = inschrijfDatum;
}
public String getMaxAantalDeelnemers()
{
return maxAantalDeelnemers;
}
public void setMaxAantalDeelnemers(String maxAantalDeelnemers)
{
this.maxAantalDeelnemers = maxAantalDeelnemers;
}
public String getPrijs()
{
return prijs;
}
public void setPrijs(String prijs)
{
this.prijs = prijs;
}
}
|
package cn.auto.platform.model;
/**
* Created by chenmeng on 2017/3/21.
*/
public class SuitDTO {
private Integer suitId;
private String suitName;
private String suitStatus;
private String suitType;
private String remark;
private String listeners;
private String parameters;
private Integer envId;
private String envName;
private String execType;
private String execExpr;
private String testPeriod;
private String version;
private String executor;
private Integer opId;
private String createTime;
public String getSuitType() {
return suitType;
}
public void setSuitType(String suitType) {
this.suitType = suitType;
}
public String getEnvName() {
return envName;
}
public void setEnvName(String envName) {
this.envName = envName;
}
public Integer getOpId() {
return opId;
}
public void setOpId(Integer opId) {
this.opId = opId;
}
public String getCreateTime() {
return createTime;
}
public void setCreateTime(String createTime) {
this.createTime = createTime;
}
public void setListeners(String listeners) {
this.listeners = listeners;
}
public void setParameters(String parameters) {
this.parameters = parameters;
}
public String getListeners() {
return listeners;
}
public String getParameters() {
return parameters;
}
public void setSuitId(Integer suitId) {
this.suitId = suitId;
}
public void setSuitName(String suitName) {
this.suitName = suitName;
}
public void setSuitStatus(String suitStatus) {
this.suitStatus = suitStatus;
}
public void setRemark(String remark) {
this.remark = remark;
}
public void setEnvId(Integer envId) {
this.envId = envId;
}
public void setExecType(String execType) {
this.execType = execType;
}
public void setExecExpr(String execExpr) {
this.execExpr = execExpr;
}
public void setTestPeriod(String testPeriod) {
this.testPeriod = testPeriod;
}
public void setVersion(String version) {
this.version = version;
}
public void setExecutor(String executor) {
this.executor = executor;
}
public Integer getSuitId() {
return suitId;
}
public String getSuitName() {
return suitName;
}
public String getSuitStatus() {
return suitStatus;
}
public String getRemark() {
return remark;
}
public Integer getEnvId() {
return envId;
}
public String getExecType() {
return execType;
}
public String getExecExpr() {
return execExpr;
}
public String getTestPeriod() {
return testPeriod;
}
public String getVersion() {
return version;
}
@Override
public String toString() {
return "SuitDTO{" +
"suitId=" + suitId +
", suitName='" + suitName + '\'' +
", suitStatus='" + suitStatus + '\'' +
", remark='" + remark + '\'' +
", listeners='" + listeners + '\'' +
", parameters='" + parameters + '\'' +
", envId=" + envId +
", execType='" + execType + '\'' +
", execExpr='" + execExpr + '\'' +
", testPeriod='" + testPeriod + '\'' +
", version='" + version + '\'' +
", executor='" + executor + '\'' +
'}';
}
public String getExecutor() {
return executor;
}
}
|
package com.bogdanovpd.spring.webapp.spring.webapp.client.service;
import com.bogdanovpd.spring.webapp.spring.webapp.client.model.Role;
import java.util.List;
public interface RoleRestService {
List<Role> getAllRoles();
Role getRoleByName(String name);
Role getRoleById(long id);
}
|
package snake.model;
import java.awt.Color;
import java.awt.Graphics;
public class SnakeBuild {
//snake square dimensions
private int x, y, width = 10, height = 10;
public SnakeBuild(int x, int y) {
this.x = x;
this.y = y;
}
//painting squares
public void paint(Graphics g) {
g.setColor(Color.black);
g.fillRect(x * width, y * height, width, height);
g.setColor(Color.green);
g.fillRect(x * width, y * height, width - 2, height - 2);
}
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
}
|
package org.jinku.sync.application.bootstrap;
import com.google.common.base.Preconditions;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
import javax.annotation.Nonnull;
@Component
public class ApplicationContextUtil implements ApplicationContextAware{
private static ApplicationContext context;
@Override
public void setApplicationContext(@Nonnull ApplicationContext applicationContext) throws BeansException {
Preconditions.checkNotNull(applicationContext);
context = applicationContext;
}
public static <T> T getBean(Class<T> requiredType) {
Preconditions.checkNotNull(context);
return context.getBean(requiredType);
}
} |
/*
* Copyright (c) 2016 ICM Uniwersytet Warszawski All rights reserved.
* See LICENCE.txt file for licensing information.
*/
package pl.edu.icm.unity.oauth.client.profile;
import java.net.URI;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import org.apache.http.entity.ContentType;
import org.apache.log4j.Logger;
import com.nimbusds.oauth2.sdk.AccessTokenResponse;
import com.nimbusds.oauth2.sdk.AuthorizationGrant;
import com.nimbusds.oauth2.sdk.ClientCredentialsGrant;
import com.nimbusds.oauth2.sdk.Scope;
import com.nimbusds.oauth2.sdk.TokenRequest;
import com.nimbusds.oauth2.sdk.TokenResponse;
import com.nimbusds.oauth2.sdk.auth.ClientAuthentication;
import com.nimbusds.oauth2.sdk.auth.ClientSecretBasic;
import com.nimbusds.oauth2.sdk.auth.Secret;
import com.nimbusds.oauth2.sdk.http.HTTPRequest;
import com.nimbusds.oauth2.sdk.http.HTTPRequest.Method;
import com.nimbusds.oauth2.sdk.http.HTTPResponse;
import com.nimbusds.oauth2.sdk.id.ClientID;
import com.nimbusds.oauth2.sdk.token.AccessToken;
import com.nimbusds.oauth2.sdk.token.BearerAccessToken;
import eu.unicore.util.httpclient.ServerHostnameCheckingMode;
import net.minidev.json.JSONArray;
import net.minidev.json.JSONObject;
import pl.edu.icm.unity.oauth.BaseRemoteASProperties;
import pl.edu.icm.unity.oauth.client.CustomHTTPSRequest;
import pl.edu.icm.unity.oauth.client.UserProfileFetcher;
import pl.edu.icm.unity.oauth.client.config.OrcidProviderProperties;
import pl.edu.icm.unity.server.authn.AuthenticationException;
import pl.edu.icm.unity.server.utils.Log;
/**
* Implementation of the {@link UserProfileFetcher} for ORCID. ORCID supports regular profile
* fetching only with paid API. The unpaid version requires to first retrieve client credentials grant
* and then, using the retrieved access token to retrieve the actual profile. In another words it is not
* possible to retrieve profile using the user's access token.
*
* @author K. Benedyczak
*/
public class OrcidProfileFetcher implements UserProfileFetcher
{
private static final Logger log = Log.getLogger(pl.edu.icm.unity.server.utils.Log.U_SERVER_OAUTH,
OrcidProfileFetcher.class);
@Override
public Map<String, String> fetchProfile(BearerAccessToken accessToken, String userInfoEndpoint,
BaseRemoteASProperties providerConfig, Map<String, String> attributesSoFar) throws Exception
{
ServerHostnameCheckingMode checkingMode = providerConfig.getEnumValue(
BaseRemoteASProperties.CLIENT_HOSTNAME_CHECKING,
ServerHostnameCheckingMode.class);
AccessToken clientAccessToken = getClientAccessToken(providerConfig, checkingMode);
JSONObject userBio = fetchUserBio(providerConfig, attributesSoFar, checkingMode, clientAccessToken);
return convertToFlatAttributes(userBio);
}
private Map<String, String> convertToFlatAttributes(JSONObject profile)
{
Map<String, String> ret = new HashMap<>();
convertToFlatAttributes("", profile, ret);
return ret;
}
private Map<String, String> convertToFlatAttributes(String prefix,
JSONObject profile, Map<String, String> ret)
{
for (Entry<String, Object> entry: profile.entrySet())
{
if (entry.getValue() != null)
{
Object value = entry.getValue();
if (value instanceof JSONObject)
{
convertToFlatAttributes(prefix + entry.getKey() + ".",
(JSONObject) value, ret);
} else if (value instanceof JSONArray)
{
convertToFlatAttributes(prefix + entry.getKey() + ".",
(JSONArray) value, ret);
} else
{
ret.put(prefix + entry.getKey(), value.toString());
}
}
}
return ret;
}
private Map<String, String> convertToFlatAttributes(String prefix,
JSONArray element, Map<String, String> ret)
{
for (int i=0; i<element.size(); i++)
{
Object value = element.get(i);
if (value != null)
{
if (value instanceof JSONObject)
{
convertToFlatAttributes(prefix + i + ".",
(JSONObject) value, ret);
} else if (value instanceof JSONArray)
{
convertToFlatAttributes(prefix + i + ".",
(JSONArray) value, ret);
} else
{
ret.put(prefix + i, value.toString());
}
}
}
return ret;
}
private AccessToken getClientAccessToken(BaseRemoteASProperties providerConfig,
ServerHostnameCheckingMode checkingMode) throws Exception
{
AuthorizationGrant clientGrant = new ClientCredentialsGrant();
ClientID clientID = new ClientID(providerConfig.getValue(OrcidProviderProperties.CLIENT_ID));
Secret clientSecret = new Secret(providerConfig.getValue(OrcidProviderProperties.CLIENT_SECRET));
ClientAuthentication clientAuth = new ClientSecretBasic(clientID, clientSecret);
Scope scope = new Scope("/read-public");
String accessTokenEndpoint = providerConfig.getValue(OrcidProviderProperties.ACCESS_TOKEN_ENDPOINT);
URI tokenEndpoint = new URI(accessTokenEndpoint);
TokenRequest request = new TokenRequest(tokenEndpoint, clientAuth, clientGrant, scope);
HTTPRequest httpRequest = new CustomHTTPSRequest(request.toHTTPRequest(),
providerConfig.getValidator(), checkingMode);
HTTPResponse httpResponse = httpRequest.send();
if (log.isTraceEnabled())
log.trace("Received client credentials grant:\n" + httpResponse.getContent());
TokenResponse response = TokenResponse.parse(httpResponse);
if (!response.indicatesSuccess())
{
throw new AuthenticationException("User's authentication was successful "
+ "but there was a problem authenticating server (with client credentials) "
+ "to obtain user's profile: " + response.toHTTPResponse().getContent());
}
AccessTokenResponse successResponse = (AccessTokenResponse) response;
return successResponse.getTokens().getAccessToken();
}
private JSONObject fetchUserBio(BaseRemoteASProperties providerConfig,
Map<String, String> attributesSoFar, ServerHostnameCheckingMode checkingMode,
AccessToken clientAccessToken) throws Exception
{
String userid = attributesSoFar.get("orcid");
if (userid == null)
throw new AuthenticationException("Authentication was successful "
+ "but the orcid id is missing in the received access token");
String userBioEndpoint = "https://pub.orcid.org/v1.2/" + userid;
HTTPRequest httpReqRaw = new HTTPRequest(Method.GET, new URL(userBioEndpoint));
CustomHTTPSRequest httpReq = new CustomHTTPSRequest(httpReqRaw, providerConfig.getValidator(), checkingMode);
httpReq.setAuthorization(clientAccessToken.toAuthorizationHeader());
httpReq.setAccept(ContentType.APPLICATION_JSON.getMimeType());
HTTPResponse resp = httpReq.send();
if (resp.getStatusCode() != 200)
{
throw new AuthenticationException("Authentication was successful "
+ "but there was a problem fetching user's profile information: " +
resp.getContent());
}
if (log.isTraceEnabled())
log.trace("Received user's profile:\n" + resp.getContent());
if (resp.getContentType() == null || !ContentType.APPLICATION_JSON.getMimeType().equals(
resp.getContentType().getBaseType().toString()))
throw new AuthenticationException("Authentication was successful "
+ "but there was a problem fetching user's profile information. "
+ "It has non-orcid-JSON content type: " + resp.getContentType());
return resp.getContentAsJSONObject();
}
}
|
package com.rabo.customerstatementprocessor.service.file;
import java.io.InputStream;
import java.util.Iterator;
/**
* This interface contains useful methods that return abstractions (such as an
* Iterator) for working with CSV files.
*
* @author rutvijr@gmail.com
*
*/
public interface CsvFileService<T>
{
/**
* It returns an Iterator (of the given target domain model class) for
* traversing the underlying inputstream that represents CSV data.
*
* Implementation Note:
* It takes the CSV schema from the target class's Jackson annotations.
*
* @param inputStream the inputstream that represents CSV data.
* @param targetClass the domain model class.
*/
Iterator<T> getIterator(InputStream inputStream, Class<T> targetClass);
}
|
package org.testproject.abcprovider.database;
import java.util.Date;
import java.util.Map;
import java.util.Map.Entry;
import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.testproject.abcprovider.App;
import org.testproject.abcprovider.data.UserDAO;
import org.testproject.abcprovider.database.entity.UserEntity;
import org.testproject.abcprovider.interfaces.DataListener;
/**
* класс для проведений операций с базами данных
*/
public class DatabaseController implements DataListener{
private static final Logger LOGGER = LoggerFactory.getLogger(DatabaseController.class);
private static DatabaseController instance = new DatabaseController();
private DatabaseController(){
LOGGER.info("Creating database...");
try{
init();
} catch (Exception e){
LOGGER.error("DB is already exists");
return;
}
LOGGER.info("Database succesfully created");
}
/**
* Инициализация БД: создание таблиц и юзеров
*/
private void init(){
Session session = HibernateUtil.getSessionFactory().openSession();
session.beginTransaction();
//создаем юзеров в БД с именами user0, user1, ... user*usernumber*
for (String userName : UserDAO.getUserNames()){
UserEntity user = new UserEntity(userName, 0L);
session.save(user);
}
LOGGER.info(App.userNumber + " users succesfully added to database");
session.getTransaction().commit();
HibernateUtil.shutdown();
}
public static DatabaseController getInstance(){
return instance;
}
public void dataLoaded(Map<String, Long> data, Date date) {
Session session = HibernateUtil.getSessionFactory().openSession();
session.beginTransaction();
for (Entry<String, Long> entry : data.entrySet()){
UserEntity userEntity = (UserEntity)session.createCriteria(UserEntity.class)
.add(Restrictions.eq("name",entry.getKey()))
.list().get(0);
long newBytesNumber = entry.getValue() + userEntity.getBytesNumber();
userEntity.setBytesNumber(newBytesNumber);
userEntity.setDate(date);
session.save(userEntity);
}
session.getTransaction().commit();
HibernateUtil.shutdown();
}
}
|
package org.bio5.irods.iplugin.referencecode;
import java.awt.Button;
import java.awt.Color;
import java.awt.Dimension;
import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollBar;
import javax.swing.JScrollPane;
import javax.swing.JTabbedPane;
import javax.swing.JTable;
import javax.swing.border.LineBorder;
import javax.swing.border.MatteBorder;
import javax.swing.table.DefaultTableModel;
import java.awt.ComponentOrientation;
import java.awt.Cursor;
import javax.swing.LayoutStyle.ComponentPlacement;
import javax.swing.JSplitPane;
import javax.swing.JTextField;
import javax.swing.JTree;
import java.awt.Component;
public class samplePanel extends JPanel {
/**
*
*/
private static final long serialVersionUID = 5527815157916844473L;
private JTable table;
/**
* Create the panel.
*/
public samplePanel() {
JTabbedPane tabbedPane = new JTabbedPane(JTabbedPane.TOP);
GroupLayout groupLayout = new GroupLayout(this);
groupLayout.setHorizontalGroup(groupLayout.createParallelGroup(
Alignment.LEADING).addGroup(
groupLayout
.createSequentialGroup()
.addGap(20)
.addComponent(tabbedPane, GroupLayout.PREFERRED_SIZE,
570, GroupLayout.PREFERRED_SIZE)
.addContainerGap(19, Short.MAX_VALUE)));
groupLayout.setVerticalGroup(groupLayout.createParallelGroup(
Alignment.LEADING).addGroup(
groupLayout
.createSequentialGroup()
.addGap(23)
.addComponent(tabbedPane, GroupLayout.PREFERRED_SIZE,
405, GroupLayout.PREFERRED_SIZE)
.addContainerGap(38, Short.MAX_VALUE)));
Object[][] data =
{
{"Homer", "Simpson", "delete Homer"},
{"Madge", "Simpson", "delete Madge"},
{"Bart", "Simpson", "delete Bart"},
{"Lisa", "Simpson", "delete Lisa"},
};
String[] columnNames = {"First Name", "Last Name", "avf"};
JPanel panel_1 = new JPanel();
tabbedPane.addTab("File Information", null, panel_1, null);
table = new JTable();
table.setRowHeight(20);
table.setIntercellSpacing(new Dimension(2, 2));
table.setBorder(new MatteBorder(1, 1, 1, 1, (Color) new Color(0, 0, 0)));
table.setToolTipText("File Information");
table.setModel(new DefaultTableModel(new Object[][] {
{ "abcd", "abcd" }, { null, null }, { null, null },
{ null, null }, { null, null }, { null, null }, { null, null },
{ null, null }, { null, null }, { null, null }, },
new String[] { "Field", "Information" }));
table.getColumnModel().getColumn(0).setPreferredWidth(150);
table.getColumnModel().getColumn(0).setMinWidth(100);
table.getColumnModel().getColumn(1).setPreferredWidth(300);
table.getColumnModel().getColumn(1).setMinWidth(200);
JLabel label_ProgressBar_BytesTrasferredOutofTotalFileSize = new JLabel(
" Progress:");
label_ProgressBar_BytesTrasferredOutofTotalFileSize
.setToolTipText(" Progress: bytesTransferred/Total File Size in Bytes");
label_ProgressBar_BytesTrasferredOutofTotalFileSize
.setBorder(new LineBorder(new Color(0, 0, 0)));
GroupLayout gl_panel_1 = new GroupLayout(panel_1);
gl_panel_1
.setHorizontalGroup(gl_panel_1
.createParallelGroup(Alignment.LEADING)
.addGroup(
gl_panel_1
.createSequentialGroup()
.addGroup(
gl_panel_1
.createParallelGroup(
Alignment.LEADING)
.addGroup(
gl_panel_1
.createSequentialGroup()
.addGap(43)
.addComponent(
table,
GroupLayout.DEFAULT_SIZE,
GroupLayout.DEFAULT_SIZE,
Short.MAX_VALUE))
.addGroup(
gl_panel_1
.createSequentialGroup()
.addGap(146)
.addComponent(
label_ProgressBar_BytesTrasferredOutofTotalFileSize,
GroupLayout.PREFERRED_SIZE,
179,
GroupLayout.PREFERRED_SIZE)))
.addGap(72)));
gl_panel_1
.setVerticalGroup(gl_panel_1
.createParallelGroup(Alignment.LEADING)
.addGroup(
gl_panel_1
.createSequentialGroup()
.addGap(76)
.addComponent(
label_ProgressBar_BytesTrasferredOutofTotalFileSize,
GroupLayout.PREFERRED_SIZE, 41,
GroupLayout.PREFERRED_SIZE)
.addGap(41)
.addComponent(table,
GroupLayout.DEFAULT_SIZE,
GroupLayout.DEFAULT_SIZE,
Short.MAX_VALUE).addGap(57)));
panel_1.setLayout(gl_panel_1);
JPanel panel = new JPanel();
tabbedPane.addTab("New tab", null, panel, null);
JSplitPane splitPane = new JSplitPane();
GroupLayout gl_panel = new GroupLayout(panel);
gl_panel.setHorizontalGroup(
gl_panel.createParallelGroup(Alignment.LEADING)
.addGroup(gl_panel.createSequentialGroup()
.addContainerGap()
.addComponent(splitPane, GroupLayout.DEFAULT_SIZE, 545, Short.MAX_VALUE)
.addContainerGap())
);
gl_panel.setVerticalGroup(
gl_panel.createParallelGroup(Alignment.TRAILING)
.addGroup(Alignment.LEADING, gl_panel.createSequentialGroup()
.addContainerGap()
.addComponent(splitPane, GroupLayout.DEFAULT_SIZE, 355, Short.MAX_VALUE)
.addContainerGap())
);
JTree tree = new JTree();
tree.setComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT);
tree.setAlignmentX(Component.RIGHT_ALIGNMENT);
tree.setAutoscrolls(true);
splitPane.setLeftComponent(tree);
JPanel panel_2 = new JPanel();
splitPane.setRightComponent(panel_2);
panel.setLayout(gl_panel);
setLayout(groupLayout);
}
}
|
package realtime.util.thread.impl;
import java.util.ArrayList;
import java.util.List;
import org.apache.log4j.Logger;
import elasticsearch.service.ElasticService;
import elasticsearch.service.impl.ElasticServiceImpl;
import elasticsearch.util.ElasticUtil;
import realtime.bean.JuHeStock;
import realtime.service.RealTimeStockService;
import realtime.service.impl.RealTimeStockServiceImpl;
import realtime.util.ThreadUtil;
import realtime.util.thread.RealDataService;
import util.ConstantUtil;
import util.RefUtil;
public class JuHeRealDataServiceImpl implements RealDataService, Runnable {
private static final Logger LOG = Logger
.getLogger(JuHeRealDataServiceImpl.class);
private static int batchCount = Integer
.parseInt(ConstantUtil.BATCH_QUERY_COUNT);
public JuHeRealDataServiceImpl() {
if (null == RefUtil.juHeFieldMapping) {
RefUtil.initJuHeMapping();
}
}
@Override
public void run() {
LOG.info("thread come into JuHeRealDataThread");
LOG.info("before setupRealTimeData function");
setupRealTimeData();
}
/**
* 实时数据入库
*
* @throws Exception
*/
public void setupRealTimeData() {
try {
List<String> entityJSONList = new ArrayList<>();
RealTimeStockService realTimeStockService = RealTimeStockServiceImpl
.getInstance();
// 遍历查询
for (int z = 0; z < batchCount; z++) {
// 队列中取出代码
String code = ThreadUtil.arrayBlockingQueue.take();
// 根据code查询出实体,并将实体转换成字符串
JuHeStock jhStock = realTimeStockService.queryJuHeAPIOnce(code);
if (null != jhStock) {
entityJSONList.add(ElasticUtil.model2Json(jhStock));
}
// 查询后重新放回队列
ThreadUtil.arrayBlockingQueue.put(code);
}
// 将实时数据插入
ElasticService elasticService = ElasticServiceImpl.getInstance();
elasticService.batchInsertEntity(entityJSONList,
ConstantUtil.INDICES_TIM, ConstantUtil.TYPES_TOTAL);
} catch (Exception e) {
e.printStackTrace();
}
}
}
|
/* Copyright 2015 Esri
*
* 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.esri.android.samples.mgrsgrid;
import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import com.esri.android.map.GraphicsLayer;
import com.esri.android.map.MapView;
import com.esri.android.map.ags.ArcGISTiledMapServiceLayer;
import com.esri.android.map.event.OnSingleTapListener;
import com.esri.core.geometry.CoordinateConversion;
import com.esri.core.geometry.CoordinateConversion.MGRSConversionMode;
import com.esri.core.geometry.Point;
import com.esri.core.map.Graphic;
import com.esri.core.symbol.SimpleMarkerSymbol;
import com.esri.core.symbol.TextSymbol;
public class LocateMGRSActivity extends Activity {
MapView mMapView;
GraphicsLayer gl = null;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Retrieve the map and initial extent from XML layout
mMapView = (MapView) findViewById(R.id.map);
// create a Tile Layer from String resource URL
ArcGISTiledMapServiceLayer baseMap = new ArcGISTiledMapServiceLayer(
this.getResources().getString(R.string.basemap_url));
// add layer to map view
mMapView.addLayer(baseMap);
// create graphics layer to show results
gl = new GraphicsLayer();
// add graphic layer to map view
mMapView.addLayer(gl);
// enable map to wrap around date line
mMapView.enableWrapAround(true);
// attribute Esri logo on map
mMapView.setEsriLogoVisible(true);
// on single tap convert the map coordinates to grid reference
mMapView.setOnSingleTapListener(new OnSingleTapListener() {
private static final long serialVersionUID = 1L;
public void onSingleTap(float screenX, float screenY) {
// remove any previous graphics
gl.removeAll();
// get map point
Point mapPoint = mMapView.toMapPoint(screenX, screenY);
// convert the coordinates to military grid strings
String mgrsPoint = CoordinateConversion.pointToMgrs(mapPoint,
mMapView.getSpatialReference(),
MGRSConversionMode.NEW_STYLE, 6, true, true);
// String[] mgrsPoint = mMapView.getSpatialReference()
// .toMilitaryGrid(MGRSConversionMode.NEW_STYLE, 6,
// true, true, new Point[] { mapPoint });
// create a symbol for point
SimpleMarkerSymbol sms = new SimpleMarkerSymbol(Color.YELLOW,
15, SimpleMarkerSymbol.STYLE.X);
// create a text symbol for point coords
TextSymbol txtSym = new TextSymbol(20, mgrsPoint, Color.RED);
txtSym.setOffsetX(10);
txtSym.setOffsetX(10);
// add point and symbol to Graphic
Graphic gMarker = new Graphic(mapPoint, sms);
// add text symbol to graphic
Graphic gText = new Graphic(mapPoint, txtSym);
// add graphics to graphics alyer
gl.addGraphics(new Graphic[] { gMarker, gText });
}
});
}
@Override
protected void onDestroy() {
super.onDestroy();
}
@Override
protected void onPause() {
super.onPause();
mMapView.pause();
}
@Override
protected void onResume() {
super.onResume();
mMapView.unpause();
}
} |
package javaCode;
import java.util.*;
/* Queues Implementation in Java */
class LinearQueues{
private int front = -1;
private int rear = -1;
//ENQUEUE operation on queue - O(1)
public void enQueue(int key, int[] queueArray){
if(front == -1){
front++;
}
if(rear == queueArray.length-1){
System.out.println("Queue Overflow Occurred");
}else{
queueArray[++rear] = key;
System.out.println("Key Element is EnQueued");
}
}
//DEQUEUE operation on queue - O(1)
public void deQueue(int[] queueArray){
if(front >= 0 && rear >= 0){
int key = queueArray[front];
System.out.println("Key Element "+ key +" DeQueued");
for(int k=0; k<rear; k++){
queueArray[k] = queueArray[k+1];
}
rear--;
}else{
System.out.println("Queue Underflow Occurred");
}
}
//To Check Whether queue is Empty
public void isEmpty(int[] queueArray){
if(rear == queueArray.length-1){
System.out.println("Queue Is Not Empty");
}else{
System.out.println("Queue Is Empty");
}
}
//Print Queue Elements
public void printQueue(int[] queueArray){
System.out.println("Queue Elements in order are: ");
for(int i=0; i<=rear; i++){
System.out.print(queueArray[i]+",");
}
}
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
System.out.println("Enter Queue Size");
int queueSize = scan.nextInt();
int queueArray[] = new int[queueSize];
LinearQueues lQueueDS = new LinearQueues();
while(true){
System.out.println("\nSelect Queue Operation: 0.Exit, 1.EnQueue, 2.DeQueue, 3.IsEmpty, 4.PrintQueue");
int queueOperation = scan.nextInt();
switch(queueOperation){
case 1: System.out.println("Enter Key Element to be EnQueued");
lQueueDS.enQueue(scan.nextInt(),queueArray);
break;
case 2: lQueueDS.deQueue(queueArray);
break;
case 3: lQueueDS.isEmpty(queueArray);
break;
case 4: lQueueDS.printQueue(queueArray);
break;
default: System.out.println("Queue Says Bye"); break;
}
if(queueOperation == 0){
break;
}
}
}
} |
package com.aof.webapp.action.prm;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import net.sf.hibernate.HibernateException;
import net.sf.hibernate.Transaction;
import org.apache.log4j.Logger;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.util.MessageResources;
import org.apache.struts.validator.DynaValidatorForm;
import com.aof.component.domain.party.UserLogin;
import com.aof.core.persistence.Persistencer;
import com.aof.core.persistence.hibernate.Hibernate2Session;
import com.aof.core.persistence.jdbc.SQLExecutor;
import com.aof.core.persistence.jdbc.SQLResults;
import com.aof.core.persistence.util.EntityUtil;
import com.aof.util.Constants;
import com.aof.util.UtilDateTime;
import com.aof.webapp.action.BaseAction;
public class BidChooseDialogueAction extends BaseAction {
public ActionForward perform(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) {
// Extract attributes we will need
Logger log = Logger.getLogger(PRMProjectListAction.class.getName());
Locale locale = getLocale(request);
MessageResources messages = getResources();
String action = request.getParameter("FormAction");
DynaValidatorForm actionForm = (DynaValidatorForm) form;
HttpSession session = request.getSession();
List projectSelectArr = new ArrayList();
List result = new ArrayList();
String UserId = request.getParameter("UserId");
String DataPeriod = request.getParameter("DataPeriod");
String nowTimestampString = UtilDateTime.nowTimestamp().toString();
String DateStart = "";
if (UserId == null)
UserId = "";
if (DataPeriod == null) {
DateStart = nowTimestampString;
} else {
DateStart = DataPeriod + " 00:00:00.000";
}
try {
net.sf.hibernate.Session hs = Hibernate2Session.currentSession();
Transaction tx = null;
String lStrOpt = request.getParameter("rad");
String srchproj = request.getParameter("srchproj");
if (lStrOpt == null)
lStrOpt = "2";
if (srchproj == null)
srchproj = "";
String QryStr = "";
if (!srchproj.equals("")) {
if (lStrOpt.equals("2")) {
// QryStr = QryStr + " and (p.projId like '%" + srchproj
// + "%' or p.projName like '%" + srchproj + "%')";
QryStr = QryStr + " and (master.bid_no like '%" + srchproj
+ "%' or master.bid_description like '%" + srchproj + "%'"
+ " or cust.description like '%" + srchproj + "%')";
} else {
// QryStr = QryStr + " and (p.projId = '" + srchproj
// + "' or p.projName = '" + srchproj + "')";
QryStr = QryStr + " and (master.bid_no = '" + srchproj
+ "' or master.bid_description ='" + srchproj
+ "' or cust.description = '" + srchproj + "')";
}
}
UserLogin userLogin = (UserLogin) request.getSession().getAttribute(Constants.USERLOGIN_KEY);
request.setAttribute("result", initSelect(QryStr, userLogin.getUserLoginId()));
} catch (Exception e) {
e.printStackTrace();
log.error(e.getMessage());
return (mapping.findForward("success"));
} finally {
try {
Hibernate2Session.closeSession();
} catch (HibernateException e1) {
log.error(e1.getMessage());
e1.printStackTrace();
} catch (SQLException e1) {
log.error(e1.getMessage());
e1.printStackTrace();
}
}
return (mapping.findForward("success"));
}
private SQLResults initSelect(String AddCondition, String userId) {
try {
SQLExecutor sqlExec = new SQLExecutor(Persistencer.getSQLExecutorConnection(EntityUtil
.getConnectionByName("jdbc/aofdb")));
String SqlStr;
SqlStr = " select master.bid_id as id,master.bid_no as bid,master.bid_description as description,cust.party_id as cust_id,cust.description as cust_desc,"
+ " dep.party_id as dep_id,dep.description as dep_desc from bid_mstr as master "
+ " inner join party as cust on master.bid_prospect_company_id = cust.party_id "
+ " inner join party as dep on master.bid_dep_id = dep.party_id "
+ " where master.bid_id not in(select m.bid_id from proj_plan_bom_mstr as m where m.bid_id is not null )"
+ " and master.bid_no is not null ";
if (!AddCondition.trim().equals(""))
SqlStr = SqlStr + AddCondition;
UserLogin ul = (UserLogin)Hibernate2Session.currentSession().load(UserLogin.class, userId);
if(ul.getParty().getPartyId().equals("014")){
SqlStr+=" and master.bid_dep_id in ('014','005','006','007') ";
}else{
SqlStr+=" and master.bid_dep_id in ('"+ul.getParty().getPartyId()+"') ";
}
SqlStr = SqlStr + " order by cust.description asc";
System.out.println(SqlStr);
SQLResults sr = sqlExec.runQueryCloseCon(SqlStr);
return sr;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package org.apache.hadoop.util;
import java.nio.ByteBuffer;
import java.nio.charset.CharacterCodingException;
/**
*
* @author ashwinkayyoor
*/
public class ByteUtil {
private final static int INT_64 = 64, INT_8 = 8;
private final static int MASK = 0x000000FF;
public static void writeInt(byte[] b, int i, int value) {
b[i++] = (byte) (value >> 24);
b[i++] = (byte) (value >> 16);
b[i++] = (byte) (value >> 8);
b[i++] = (byte) (value);
}
public static int readInt(final byte[] a, final int i) {
//return ByteBuffer.wrap(Arrays.copyOfRange(a, i, j)).getInt();
return a[i] << 24 | (a[i + 1] & 0x000000FF) << 16 | (a[i + 2] & 0x000000FF) << 8 | (a[i + 3] & 0x000000FF);
}
public static float readFloat(final byte[] b, final int offset) {
if (b.length != 4) {
return 0.0F;
}
final int i = readInt(b, offset);
return Float.intBitsToFloat(i);
}
public static double readDouble(final byte[] b, final int offset) {
long accum = 0;
int i = offset;
for (int shiftBy = 0; shiftBy < INT_64; shiftBy += INT_8) {
accum |= ((long) (b[i] & 0xff)) << shiftBy;
i++;
}
return Double.longBitsToDouble(accum);
}
public static double toDouble(final byte[] b, final int offset) {
byte[] bytes = new byte[8];
int ind = 0;
for (int i = offset; i < offset + 8; ++i) {
bytes[ind++] = b[i];
}
return ByteBuffer.wrap(bytes).getDouble();
}
private static String decodeUTF16BE(final byte[] bytes, int startByte, final int byteCount) {
final StringBuilder builder = new StringBuilder(byteCount);
//char[] buffer = new char[byteCount];
//builder.delete(0, builder.length());
//int sByte = startByte;
for (int i = 0; i < byteCount; i++) {
final byte low = bytes[startByte++];
//byte high = bytes[startByte++];
final int ch = (low & MASK);
builder.append((char) ch);
//buffer[i] = (char) ch;
}
return builder.toString();
//return new String(buffer);
}
public static String readString(final byte[] a, final int i, final int j) throws CharacterCodingException {
//return new String(Arrays.copyOfRange(a, i, j + 1));
//byte[] bytes = Arrays.copyOfRange(a, i, j+1);
//return Text.decode(bytes);
return decodeUTF16BE(a, i, (j - i) + 1);
}
}
|
package br.pucrs.ep.es.model;
import br.pucrs.ep.es.model.Cliente;
public class Conta {
private Cliente cliente;
public Conta(Cliente cliente) {
setCliente(cliente);
}
private void setCliente(Cliente cliente) {
this.cliente = cliente;
}
public String getNomeCliente(){
return this.cliente.getNome();
}
}
|
import Pack1.EmployeePack;
import Pack1.ManagerPack;
public class MainClass{
public static void main(String args[]){
ManagerPack m = new ManagerPack();
m.disp();
EmployeePack obj= new EmployeePack();
obj.disp();
}
}
|
package Problem_9294;
import java.util.Scanner;
public class Main {
static int n,m,s;
static StringBuilder sb;
static int[] arr;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int C = sc.nextInt();
for(int c = 1; c<=C;c++) {
n = sc.nextInt();
m = sc.nextInt();
s = sc.nextInt();
arr = new int[n];
sb = new StringBuilder("Case ");
sb.append(c + ":").append("\n");
answer(0,0);
System.out.print(sb.toString());
}
}
public static void answer(int num, int sum) {
if(num == n) {
if(sum == s) {
sb.append("(");
for(int i = 0; i<arr.length; i++) {
sb.append(arr[i]);
if(i != arr.length-1) sb.append(",");
}
sb.append(")\n");
}
} else if(num == 0){
for(int i = 1; i<=m; i++) {
arr[num] = i;
answer(num+1, sum+i);
arr[num] = 0;
}
} else {
for(int i = arr[num-1]; i<=m; i++) {
arr[num] = i;
answer(num+1, sum+i);
arr[num] = 0;
}
}
}
}
|
package com.trump.auction.order.api.impl;
import com.alibaba.dubbo.config.annotation.Service;
import com.cf.common.utils.ServiceResult;
import com.trump.auction.order.api.AppraisesSenstiveWordStubService;
import com.trump.auction.order.service.AppraisesSenstiveWordService;
import org.springframework.beans.factory.annotation.Autowired;
/**
* @Author=hanliangliang
* @Date=2018/03/08
*/
@Service(version = "1.0.0")
public class AppraisesSenstiveWordStubServiceImpl implements AppraisesSenstiveWordStubService {
@Autowired
private AppraisesSenstiveWordService appraisesSenstiveWordService;
@Override
public ServiceResult checkAppraises(String appraises) {
return appraisesSenstiveWordService.checkAppraises(appraises);
}
}
|
package queue;
import java.util.EmptyStackException;
public class DynArrayQueue<T>{
/**
* 基于动态循环数组实现队列
* 1、当第一次元素入栈时,队头指向第一个元素,即由-1变为0
* 2、队列中front指向队头元素,rear指向队尾元素
* 3、当front==rear时,队列中只有一个元素
*/
private int front = -1; // 队头
private int rear = -1; // 队尾
private int capacity = 10; // 容量
private Object[] array = new Object[capacity];
public boolean isEmpty(){ // 判断队列是否为空
return front == -1;
}
public void enQueue(T data){ // 入队操作
if((rear+1)%capacity == front){ // 如果队列已满
Object[] newarr = new Object[capacity+capacity/2]; // 新建1.5倍大小的数组
System.arraycopy(array, 0, newarr, 0, array.length);
if(rear < front){
for(int i = 0; i < front; ++i){
newarr[i+capacity] = array[i];
newarr[i] = null;
}
rear = rear+capacity; // 新队尾的位置
}
array = newarr;
capacity = capacity + capacity/2;
}
rear = (rear+1) % capacity;
array[rear] = data;
if(front == -1) // 第一次入队操作后,使队首指向第一个元素
front = 0;
}
@SuppressWarnings("unchecked")
public T deQueue(){
if(isEmpty())
throw new EmptyStackException();
T data = (T) array[front];
if(front == rear) // 如果队列中只有一个元素
front = rear = -1;
else
front = (front+1)%capacity;
return data;
}
@SuppressWarnings("unchecked")
public T getFront(){ // 获取队头元素
if(isEmpty())
throw new EmptyStackException();
return (T)array[front];
}
public int size(){ // 队列中元素个数
if(front == -1)
return 0;
int size = (rear-front+1+capacity)%capacity;
return size == 0 ? capacity : size;
}
}
|
package cn.mldn.util.dbc;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class DatabaseConnection {
private static final String DBDRIVER = "org.gjt.mm.mysql.Driver";
private static final String DBURL = "jdbc:mysql://localhost:3306/mldn";
private static final String USER = "root";
private static final String PASSWORD = "mysqladmin";
private static ThreadLocal<Connection> threadLocal = new ThreadLocal<Connection>();
public static Connection getConnection() {
Connection conn = threadLocal.get();
if (conn == null) {
conn = buildConnection() ;
threadLocal.set(conn);
}
return conn ;
}
public static void close() {
Connection conn = threadLocal.get();
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
threadLocal.remove();
}
}
private static Connection buildConnection() {
try {
Class.forName(DBDRIVER);
return DriverManager.getConnection(DBURL, USER, PASSWORD);
} catch (Exception e) {
e.printStackTrace();
return null ;
}
}
}
|
package com.hotsoup;
import android.annotation.SuppressLint;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import java.util.Formatter;
public class BMICalculator extends Fragment {
LoadProfile lp = LoadProfile.getInstance();
UserProfile user = lp.getUser();
double bmi;
TextView textWeight;
TextView textHeight;
TextView textBmi;
TextView textInfo;
@SuppressLint("SetTextI18n")
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
}
@SuppressLint("SetTextI18n")
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@SuppressLint("SetTextI18n")
@Override
public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_b_m_i_calculator, container, false);
textWeight = view.findViewById(R.id.text_weight_bmi);
textHeight = view.findViewById(R.id.text_height_bmi);
textBmi = view.findViewById(R.id.text_bmi_bmi);
textInfo = view.findViewById(R.id.text_info_bmi);
if(!user.getWeight().isEmpty() && user.getHeight() !=0){
textWeight.setText(getString(R.string.your_last_weight) +" "+
(new Formatter()).format("%.0f", user.getWeight().get(user.getWeight().size()-1)));
textHeight.setText(getString(R.string.height_is) +" "+ user.getHeight());
textBmi.setText(getString(R.string.calculated_bmi) +" "+ (new Formatter()).format("%.1f",
bmi = calculateBMI(user.getWeight().get(user.getWeight().size()-1), user.getHeight())));
if(bmi<18.5){textInfo.setText(getString(R.string.underWeight));
textInfo.setTextColor(getResources().getColor(R.color.blue));}
else if(18.5<= bmi && bmi< 25){textInfo.setText(getString(R.string.normal_weight));
textInfo.setTextColor(getResources().getColor(R.color.green));}
else if(25<= bmi && bmi< 30){textInfo.setText(getString(R.string.overweight));
textInfo.setTextColor(getResources().getColor(R.color.dark_orange));}
else if(30<= bmi && bmi<= 35){textInfo.setText(getString(R.string.obese));
textInfo.setTextColor(getResources().getColor(R.color.very_orange));}
else {textInfo.setText(getString(R.string.extremly_obese));
textInfo.setTextColor(getResources().getColor(R.color.red));}}
else{textWeight.setText(R.string.give_weight_height);
textInfo.setText("");
textBmi.setText("");
textHeight.setText("");}
return view;
}
//Calculates BMI :DDDD
private double calculateBMI(double weight, double height){
return weight/(height/100*height/100);
}
} |
/**
* ApplicationArea
*/
package com.bs.bod;
import java.io.Serializable;
import java.util.Date;
import java.util.UUID;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import org.apache.commons.lang3.builder.ToStringBuilder;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
/**
* application-specific information common to all BODs
*
* * The ApplicationArea carries information that an application may need to know in order to communicate in an integration
* of two or more business applications.
* The ApplicationArea is used at the applications layer of communication. While the integration frameworks web services
* and middleware provide the communication layer that OAGIS operates on top of.
*
* The ApplicationArea serves four main purposes:
*
* 1. To identify the sender of the message.
* 2. To identify when the document was created.
* 3. To provide authentication of the sender through the use of a digital signature, if applicable.
* 4. To uniquely identify a BOD instance. The BODId field is the Globally Unique Identifier for the BOD instance.
*
* The ApplicationArea is comprised of the following elements:
* - Sender
* - Creation – (date and time)
* - Signature
* - BODID
* - UserArea TODO
*
* @author dbs on Dec 25, 2015 11:13:35 AM
* @version 1.0
* @since 0.3.5
*
*/
@JsonAutoDetect(fieldVisibility = Visibility.NON_PRIVATE, getterVisibility = Visibility.NON_PRIVATE, setterVisibility = Visibility.NON_PRIVATE)
@JsonInclude(Include.NON_ABSENT)
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class ApplicationArea implements Serializable{
private static final long serialVersionUID = 1L;
@JsonProperty("s")
Sender sender;
/**
* CreationDateTime is the date time stamp that the given instance of the Business Object Document was created.
* This date must not be modified during the life of the Business Object Document.
*
* OAGIS Date time type supports ISO Date Time format.
*/
@JsonProperty("dt")
@XmlAttribute(name = "creation-date-time", required = true)
final Date creationDateTime;
/**
* If the BOD is to be signed the signature element is included, otherwise it is not.
*
* Signature will support any digital signature that maybe used by an implementation of OAGIS. The qualifying Agency identifies the agency that provided the
* format for the signature.
*
* This element supports any digital signature specification that is available today and in the future. This is accomplished by not actually defining the
* content but by allowing the implementation to specify the digital signature to be used via an external XML Schema namespace declaration. The Signature
* element is defined to have any content from any other namespace.
*
* This allows the user to carry a digital signature in the xml instance of a BOD. The choice of which digital signature to use is left up to the user and
* their integration needs.
*
* For more information on the W3C’s XML Signature specification refer to: http://www.w3.org/TR/xmldsig-core/.<br>
* Alternatively, this field can be used to automatically compute a digest of the message being sent cf {@link com.bs.bod.Bod#__sharedPrivateKey}
*/
@JsonProperty("sig")
@XmlElement
String signature;
/**
* The BODID provides a place to carry a Globally Unique Identifier (GUID) that will make each Business Object Document uniquely identifiable. This is a
* critical success factor to enable software developers to use the Globally Unique Identifier (GUID) to build the following services or capabilities:
*
* 1. Legally binding transactions,
*
* 2. Transaction logging,
*
* 3. Exception handling,
*
* 4. Re-sending,
*
* 5. Reporting,
*
* 6. Confirmations,
*
* 7. Security.
*/
@JsonProperty("bid")
@XmlAttribute(name="bod-id", required = true)
final String bodId;
ApplicationArea() {
this(new Date(), UUID.randomUUID().toString());
}
public ApplicationArea(Sender sender, Date creationDateTime, String signature, String bodId) {
this(creationDateTime, bodId);
this.sender = sender;
this.signature = signature;
}
public ApplicationArea(Date creationDateTime, String bodId) {
assert creationDateTime != null : "BOD creation Date cannot be null";
assert bodId != null : "BOD Id cannot be null";
this.creationDateTime = creationDateTime;
this.bodId = bodId;
}
public ApplicationArea(Date creationDateTime, UUID bodId) {
assert creationDateTime != null : "BOD creation Date cannot be null";
assert bodId != null : "BOD ID cannot be null";
this.creationDateTime = creationDateTime;
this.bodId = bodId.toString();
}
@JsonIgnore
public boolean isSetSender() {
return sender != null;
}
/**
* @return the sender, never null
*/
public Sender getSender() {
if(null == sender)
sender = new Sender();
return sender;
}
/**
* @param sender the sender to set
*/
public ApplicationArea setSender(Sender sender) {
assert sender != null : "BOD sender cannot be null";
this.sender = sender;
return this;
}
/**
* @return the signature
*/
public String getSignature() {
return signature;
}
/**
* @param signature the signature to set
*/
public ApplicationArea setSignature(String signature) {
this.signature = signature;
return this;
}
/**
* @return the creationDateTime
*/
public Date getCreationDateTime() {
return creationDateTime;
}
/**
* @return the bodId
*/
public String getBodId() {
return bodId;
}
/* (non-Javadoc)
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((bodId == null) ? 0 : bodId.hashCode());
result = prime * result + ((creationDateTime == null) ? 0 : creationDateTime.hashCode());
result = prime * result + ((sender == null) ? 0 : sender.hashCode());
result = prime * result + ((signature == null) ? 0 : signature.hashCode());
return result;
}
/* (non-Javadoc)
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (!(obj instanceof ApplicationArea)) {
return false;
}
ApplicationArea other = (ApplicationArea) obj;
if (bodId == null) {
if (other.bodId != null) {
return false;
}
} else if (!bodId.equals(other.bodId)) {
return false;
}
if (creationDateTime == null) {
if (other.creationDateTime != null) {
return false;
}
} else if (!creationDateTime.equals(other.creationDateTime)) {
return false;
}
if (sender == null) {
if (other.sender != null) {
return false;
}
} else if (!sender.equals(other.sender)) {
return false;
}
if (signature == null) {
if (other.signature != null) {
return false;
}
} else if (!signature.equals(other.signature)) {
return false;
}
return true;
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return ToStringBuilder.reflectionToString(this);
}
}
|
package jp.co.monkey.button;
import jp.co.monkey.activity.MainActivity;
import jp.co.monkey.jsbapp.R;
import jp.co.monkey.window.WindowLayoutRed;
import android.content.Context;
import android.graphics.Color;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
public class RedButton extends LinearLayout {
private final int WC = LinearLayout.LayoutParams.WRAP_CONTENT;
private Button redButton;
public RedButton(Context context) {
super(context);
setLayout();
setListener();
}
public void setLayout() {
redButton = new Button(getContext());
redButton.setBackgroundResource(R.drawable.redbtn);
redButton.setOnClickListener((OnClickListener) getContext());
LayoutParams paramsex = new LayoutParams(WC, WC);
paramsex.gravity = Gravity.CENTER_HORIZONTAL;
this.addView(redButton, paramsex);
}
private void setListener() {
redButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
WindowLayoutRed windowsRed = new WindowLayoutRed(getContext());
MainActivity.popupWindow.setContentView(windowsRed);
if (MainActivity.popupWindow.isShowing()) {
MainActivity.popupWindow.dismiss();
} else {
int xoff = BlueButton.blueButton.getWidth();
int yoff = BlueButton.blueButton.getHeight();
WindowLayoutRed.mainRedLinerLayout.setBackgroundColor(Color.argb(70, 255, 0, 0));
MainActivity.popupWindow.showAsDropDown(BlueButton.blueButton, xoff / 10,
-yoff / 50);
}
}
});
}
}
|
package com.pwc.brains.trie;
import java.io.Serializable;
import java.util.HashMap;
public class Node implements Serializable {
private final char letter;
private boolean bound = false;
private long serialVersionUID = 3334143;
private HashMap<Character, Node> children = new HashMap<Character, Node>();
public Node(char c) {
this.letter = c;
}
public char letter() {
return letter;
}
public HashMap<Character, Node> children() {
return children;
}
public Node getChild(char c) {
return children.get(c);
}
public void putChild(char c, Node node) {
children.put(c, node);
}
public int sizeOfChildren() {
return children.size();
}
@Override
public boolean equals(Object o) {
if (o == null) {
throw new NullPointerException();
}
Node node;
if (o instanceof Node) {
node = (Node) o;
}
else {
throw new ClassCastException();
}
return node.letter() == node.letter();
}
public boolean isWord() {
return bound;
}
public void setWord(boolean word) {
bound = word;
}
public boolean contains(char c) {
return children.containsKey(c);
}
}
|
import java.io.*;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
public class HelloWorldExample extends HttpServlet {
/**
* ERR_MALFORMED_STOCK = "Stock name is malformed"
ERR_EMPTY_STOCK ="Stock is empty"
ERR_PARSING_ERROR ="Stock data can't be parsed"
ERR_EMPTY_NEWS_FEED ="Stock news feed is empty"
ERR_GENERAL_SYSTEM_ERROR ="Unknown error has occurred" s
**/
// from http://yohandfblog.blogspot.com/2010/01/string-replaceall-method-for-java-13.html
public static String replaceAll(String source, String toReplace, String replacement)
{
int idx = source.lastIndexOf( toReplace );
if ( idx != -1 )
{
StringBuffer ret = new StringBuffer( source );
ret.replace( idx, idx+toReplace.length(), replacement );
while((idx=source.lastIndexOf(toReplace, idx-1)) != -1 )
{
ret.replace( idx, idx+toReplace.length(), replacement );
}
source = ret.toString();
}
return source;
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException{
try{
String urlstream = "";
response.setContentType("application/json");
PrintWriter out = response.getWriter();
String company = request.getParameter("symbol");
if(company == null || company == ""){
out.println(errorResponse("ERR_EMPTY_STOCK"));
return ;
}
URL urldemo = null;
InputStream urlStream =null;
try {
urldemo = new URL("http://default-environment-qmv3qmez2p.elasticbeanstalk.com/?company="+company);
URLConnection urlConnection = urldemo.openConnection();
urlConnection.setAllowUserInteraction(false);
urlStream = urldemo.openStream();
}
catch (MalformedURLException e) {
out.println(errorResponse("ERR_MALFORMED_STOCK"));
return ;
}catch(IOException ioe){
out.println(errorResponse("ERR_MALFORMED_STOCK"));
return;
}
DocumentBuilderFactory DBF = DocumentBuilderFactory.newInstance();
DocumentBuilder DB = null;
Document doc = null;
try
{
DB = DBF.newDocumentBuilder();
doc = DB.parse(urlStream);
}
catch (SAXException e)//add needed exceptions
{
out.println(errorResponse("ERR_PARSING_ERROR"));
return;
}
String ChangeType = "N/A";
String Change = "N/A";
String ChangeInPercent = "N/A";
String LastTradePriceOnly = "N/A";
String PreviousClose = "N/A";
String DaysLow = "N/A";
String DaysHigh = "N/A";
String Open = "N/A";
String YearLow = "N/A";
String YearHigh = "N/A";
String Bid = "N/A";
String Volume = "N/A";
String Ask= "N/A";
String AverageDailyVolume = "N/A";
String OneYearTargetPrice = "N/A";
String MarketCapitalization = "N/A";
String Title = "N/A";
String Link = "N/A";
NodeList names = doc.getElementsByTagName("Name");
Node nameNode = names.item(0); // only one exists
Element name_element = (Element) nameNode;
String name = name_element.getFirstChild().getNodeValue();
//out.println(name);
NodeList symbols = doc.getElementsByTagName("symbol");
Node symbolNode = symbols.item(0); // only one exists
Element symbol_element = (Element) symbolNode;
String symbol = symbol_element.getFirstChild().getNodeValue(); // alternative for getFirstChild().getNodeValue();
NodeList nList = doc.getElementsByTagName("Quote");
Node nNode = nList.item(0);
Element eElement = (Element) nNode;
ChangeType = eElement.getElementsByTagName("ChangeType").item(0).getFirstChild()==null? "": eElement.getElementsByTagName("ChangeType").item(0).getFirstChild().getNodeValue();
Change = eElement.getElementsByTagName("Change").item(0).getFirstChild()==null? "": eElement.getElementsByTagName("Change").item(0).getFirstChild().getNodeValue();
ChangeInPercent = eElement.getElementsByTagName("ChangeInPercent").item(0).getFirstChild()==null? "": eElement.getElementsByTagName("ChangeInPercent").item(0).getFirstChild().getNodeValue();
LastTradePriceOnly = eElement.getElementsByTagName("LastTradePriceOnly").item(0).getFirstChild()==null? "": eElement.getElementsByTagName("LastTradePriceOnly").item(0).getFirstChild().getNodeValue();
PreviousClose= eElement.getElementsByTagName("PreviousClose").item(0).getFirstChild()==null? "": eElement.getElementsByTagName("PreviousClose").item(0).getFirstChild().getNodeValue();
DaysLow = eElement.getElementsByTagName("DaysLow").item(0).getFirstChild()==null? "": eElement.getElementsByTagName("DaysLow").item(0).getFirstChild().getNodeValue();
DaysHigh = eElement.getElementsByTagName("DaysHigh").item(0).getFirstChild()==null? "": eElement.getElementsByTagName("DaysHigh").item(0).getFirstChild().getNodeValue();
Open = eElement.getElementsByTagName("Open").item(0).getFirstChild()==null? "": eElement.getElementsByTagName("Open").item(0).getFirstChild().getNodeValue();
YearLow = eElement.getElementsByTagName("YearLow").item(0).getFirstChild()==null? "": eElement.getElementsByTagName("YearLow").item(0).getFirstChild().getNodeValue();
YearHigh = eElement.getElementsByTagName("YearHigh").item(0).getFirstChild()==null? "": eElement.getElementsByTagName("YearHigh").item(0).getFirstChild().getNodeValue();
Bid = eElement.getElementsByTagName("Bid").item(0).getFirstChild() ==null? "": eElement.getElementsByTagName("Bid").item(0).getFirstChild().getNodeValue();
Volume = eElement.getElementsByTagName("Volume").item(0).getFirstChild()==null? "": eElement.getElementsByTagName("Volume").item(0).getFirstChild().getNodeValue();
Ask = eElement.getElementsByTagName("Ask").item(0).getFirstChild()==null? "": eElement.getElementsByTagName("Ask").item(0).getFirstChild().getNodeValue();
AverageDailyVolume = eElement.getElementsByTagName("AverageDailyVolume").item(0).getFirstChild()==null? "": eElement.getElementsByTagName("AverageDailyVolume").item(0).getFirstChild().getNodeValue();
OneYearTargetPrice = eElement.getElementsByTagName("OneYearTargetPrice").item(0).getFirstChild()==null? "": eElement.getElementsByTagName("OneYearTargetPrice").item(0).getFirstChild().getNodeValue();
MarketCapitalization = eElement.getElementsByTagName("MarketCapitalization").item(0).getFirstChild()==null? "": eElement.getElementsByTagName("MarketCapitalization").item(0).getFirstChild().getNodeValue();
//out.println(ChangeType+Change+ChangeInPercent+LastTradePriceOnly+PreviousClose+DaysLow+DaysHigh+Open+YearLow+YearHigh+Bid+Volume+Ask+AverageDailyVolume+OneYearTargetPrice+MarketCapitalization);
NodeList ImageList = doc.getElementsByTagName("StockChartImageURL");
Node imageNodes = ImageList.item(0);
Element imageListeElements = (Element) imageNodes;
String imageName = imageListeElements.getFirstChild().getNodeValue();
NodeList NewList = doc.getElementsByTagName("News");
Node NewListNodes = NewList.item(0);
Element NewListeElements = (Element) NewListNodes;
String outPutArray = "";
outPutArray = outPutArray+ "\"News\":{" ;
outPutArray = outPutArray+ "\"Item\":[";
NodeList ItemLists = NewListeElements.getElementsByTagName("Item");
if(ItemLists.getLength() ==0 || (ItemLists.getLength() ==1 && ((Element)ItemLists.item(0)).getElementsByTagName("Link").item(0).getFirstChild() ==null)){
outPutArray += errorResponse("ERR_EMPTY_NEWS_FEED") ;
}else{
for(int temp = 0; temp < ItemLists.getLength(); temp++) {
Node ItemListsNodes = ItemLists.item(temp);
//out.println("\n\n Current Element :" + ItemListsNodes.getNodeName());
Element ItemListseElement = (Element) ItemListsNodes;
Title = ItemListseElement.getElementsByTagName("Title").item(0).getFirstChild().getNodeValue();
Link = ItemListseElement.getElementsByTagName("Link").item(0).getFirstChild().getNodeValue();
outPutArray = outPutArray+ "{";
outPutArray = outPutArray+ "\"Link\": \""+Link+"\"," ;
//Title= replaceAll(Title, "\"", "\\\"");
Title= replaceAll(Title, "\\", "\\\\");
Title= replaceAll(Title, "\"", "\\\"");
outPutArray = outPutArray+ "\"Title\": \"" + Title+ "\"" ;
if(temp+1 == ItemLists.getLength()){
outPutArray = outPutArray+ "}";
}
else{
outPutArray = outPutArray+ "},";
}
}
}
String outPut = "{";
outPut = outPut+"\"result\":{";
outPut = outPut+ "\"Name\":\""+name+"\"," ;
outPut = outPut+ "\"symbol\":\""+symbol+"\"," ;
outPut = outPut+"\"Quote\":{";
outPut = outPut+"\"ChangeType\":\""+ChangeType+"\"," ;
outPut = outPut+"\"Change\":\""+Change+"\"," ;
outPut = outPut+"\"ChangeInPercent\":\""+ChangeInPercent+"\"," ;
outPut = outPut+"\"LastTradePriceOnly\":\""+LastTradePriceOnly+"\"," ;
outPut = outPut+"\"PreviousClose\":\""+PreviousClose+"\"," ;
outPut = outPut+"\"DaysLow\":\""+DaysLow+"\"," ;
outPut = outPut+"\"DaysHigh\":\""+DaysHigh+"\"," ;
outPut = outPut+"\"Open\":\""+Open+"\"," ;
outPut = outPut+"\"YearLow\":\""+YearLow+"\"," ;
outPut = outPut+"\"YearHigh\":\""+YearHigh+"\"," ;
outPut = outPut+"\"Bid\":\""+Bid+"\"," ;
outPut = outPut+"\"Volume\":\""+Volume+"\"," ;
outPut = outPut+"\"Ask\":\""+Ask+"\"," ;
outPut = outPut+"\"OneYearTargetPrice\":\""+OneYearTargetPrice+"\"," ;
outPut = outPut+"\"AverageDailyVolume\":\""+AverageDailyVolume+"\"," ;
outPut = outPut+"\"MarketCapitalization\":\""+MarketCapitalization+"\"";
outPut = outPut+"},";
outPut = outPut + outPutArray ;
outPut = outPut+ "]";
outPut = outPut+ "},";
outPut = outPut+"\"StockChartImageURL\":\""+imageName.trim()+"\"" ;
outPut = outPut+ "}";
outPut = outPut+ "}";
out.println(outPut);
}catch(Throwable t){
response.setContentType("application/json");
PrintWriter out = response.getWriter();
t.printStackTrace();
out.println(errorResponse("ERR_GENERAL_SYSTEM_ERROR"));
return ;
}
}
private String errorResponse(String stockError){
String outPut = "{";
outPut = outPut+"\"Error\":\""+stockError.toString()+"\"}";
return outPut;
}
}
|
package com.apirest.webflux;
import java.util.UUID;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
import com.apirest.webflux.document.Playlist;
import com.apirest.webflux.repository.PlaylistReposotory;
import reactor.core.publisher.Flux;
//@Component
//public class DummyData implements CommandLineRunner{
//
// private final PlaylistReposotory playlistReposotory;
//
// DummyData(PlaylistReposotory playlistReposotory){
// this.playlistReposotory = playlistReposotory;
// }
//
// public void run(String... args) throws Exception {
// playlistReposotory.deleteAll()
// .thenMany(
// Flux.just("Teste 1", "Teste 2", "Teste 3", "Teste 4", "Teste 5")
// .map(nome -> new Playlist(UUID.randomUUID().toString(), nome))
// .flatMap(playlistReposotory::save))
// .subscribe(System.out::println);
// }
//}
|
package com.pan.al.test;
import javax.swing.plaf.synth.SynthOptionPaneUI;
import java.math.BigInteger;
import java.sql.Array;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Scanner;
import java.util.Stack;
public class Test5 {
/** 题目描述 反转数组
给定一个长度为n的整数数组a,元素均不相同,问数组是否存在这样一个片段,只将该片段翻转就可以使整个数组升序排列。
其中数组片段[l,r]表示序列a[l], a[l+1], ..., a[r]。原始数组为
a[1], a[2], ..., a[l-2], a[l-1], a[l], a[l+1], ..., a[r-1], a[r], a[r+1], a[r+2], ..., a[n-1], a[n],
将片段[l,r]反序后的数组是
a[1], a[2], ..., a[l-2], a[l-1], a[r], a[r-1], ..., a[l+1], a[l], a[r+1], a[r+2], ..., a[n-1], a[n]
*/
public static void shengxu(String[] args){
Scanner scanner = new Scanner(System.in);
while(scanner.hasNextInt())
{
int len = scanner.nextInt();
int[] array = new int[len];
int[] copy = new int[len];
for(int i=0;i<len;i++)
{
array[i] = scanner.nextInt();
copy[i] = array[i];
}
Arrays.sort(copy);
int left = 0,right = len-1;
while(left<len && copy[left]==array[left]) left++;
while(right>=0 && copy[right]==array[right]) right--;
int i;
for(i=0;i<=right-left;i++)
{
if(copy[left+i]!=array[right-i])
break;
}
if(i>right-left)
System.out.println("yes");
else
System.out.println("no");
}
}
/**
* 题目描述 字符判断
* 判断字符串b的所有字符是否都在字符串a中出现过,a、b都是可能包含汉字的字符串。b中重复出现的汉字,那么a中也要至少重复相同的次数。
* 汉字使用gbk编码(简单的说,用两个字节表示一个汉字,高字节最高位为1的代表汉字,低字节最高位可以不为1)。
*
* int is_include(char *a, char *b);
*
* 返回0表示没有都出现过,返回1表示都出现过。
* @param args
*/
public static void acontainb (String[] args)
{
Scanner sc=new Scanner(System.in);
HashMap<Character,Integer> aa=new HashMap<>();
HashMap<Character,Integer> bb=new HashMap<>();
String a=sc.nextLine();
String b=sc.nextLine();
sc.close();
for(int i=0;i<a.length();i++)
{
if(aa.containsKey(a.charAt(i)))
{
aa.put(a.charAt(i),aa.get(a.charAt(i))+1);
}else{
aa.put(a.charAt(i),1);
}
}
for(int i=0;i<b.length();i++)
{
if(bb.containsKey(b.charAt(i)))
{
bb.put(b.charAt(i),bb.get(b.charAt(i))+1);
}else{
bb.put(b.charAt(i),1);
}
}
for(char s : bb.keySet())
if( !aa.containsKey(s)||aa.get(s) < bb.get(s))
{
System.out.println(0);
return;
}
System.out.println(1);
}
/**
* 有股神吗?
*
* 有,小赛就是!
*
* 经过严密的计算,小赛买了一支股票,他知道从他买股票的那天开始,股票会有以下变化:第一天不变,以后涨一天,跌一天,涨两天,跌一天,涨三天,跌一天...依此类推。
*
* 为方便计算,假设每次涨和跌皆为1,股票初始单价也为1,请计算买股票的第n天每股股票值多少钱?
* @param n
* @return
*/
public static int gusheng(int n)
{
int i = 0;// i统计遇到了多少次下跌
int j = 2;// 每次下跌之后上涨的天数,包含已经下跌的那天
int k = n;
while (k > j) {
i += 2;
k -= j;
++j;
}
return n - i;
}
}
|
package com.brainacademy.vehicle;
public class Vehicle
implements Moveable {
public Vehicle() {
System.out.println("Vehicle");
}
@Override
public void start() {
}
@Override
public void stop() {
}
@Override
public void move() {
}
}
|
package com.example.kyle.myapplication.Database;
import android.content.Context;
import android.os.AsyncTask;
import android.widget.Toast;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.concurrent.ExecutionException;
public class DatabaseManager extends AsyncTask<Void, Void, DBOperation>
{
private String URL = "http://71.79.36.3/ICSFormsManagement/";
private Context context;
private DBOperation operation;
private String phpFile;
public static void CreateDatabase(Context context, DBOperation operation)
{
PerformOperation(context, null, "CreateDB.php");
PerformOperation(context, operation);
}
public static DBOperation PerformOperation(DBOperation operation)
{
return PerformOperation(null, operation, "DBOperation.php");
}
public static DBOperation PerformOperation(Context context, DBOperation operation)
{
return PerformOperation(context, operation, "DBOperation.php");
}
private static DBOperation PerformOperation(Context context, DBOperation operation, String phpFile)
{
try
{
DatabaseManager dbManager = new DatabaseManager(context, operation, phpFile);
operation = dbManager.execute().get();
}
catch (InterruptedException e)
{
e.printStackTrace();
}
catch (ExecutionException e)
{
e.printStackTrace();
}
return operation;
}
DatabaseManager(Context context, DBOperation operation, String phpFile)
{
this.context = context;
this.operation = operation;
this.phpFile = phpFile;
}
protected void onPreExecute()
{
}
@Override
protected DBOperation doInBackground(Void... params)
{
try
{
String theURL = URL + phpFile;
URL url = new URL(theURL);
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
if (operation != null && !operation.Operation.isEmpty())
{
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
String op = URLEncoder.encode("operation", "UTF-8") + "=" + URLEncoder.encode(operation.Operation, "UTF-8") +
"&" + URLEncoder.encode("mode", "UTF-8") + "=" + URLEncoder.encode(operation.SQLMode.name(), "UTF-8");
wr.write(op);
wr.flush();
}
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = "";
String result = "";
boolean firstLine = true;
while ((line = reader.readLine()) != null)
{
if (firstLine)
{
result = line;
firstLine = false;
}
sb.append(line);
break;
}
if (operation != null)
{
operation.ResultMessage = sb.toString();
if (result.equals("FAIL"))
{
operation.ResultMessage = operation.FailMessage;
}
else
{
switch (operation.SQLMode)
{
case INSERT:
operation.ResultID = Long.parseLong(operation.ResultMessage);
operation.AffectedRows = 1;
break;
case UPDATE:
case DELETE:
operation.AffectedRows = Integer.parseInt(operation.ResultMessage);
break;
case SELECT:
operation.JSONResult = operation.ResultMessage;
break;
}
operation.ResultMessage = operation.SuccessMessage;
}
}
}
catch (Exception ex)
{
ex.printStackTrace();
}
return operation;
}
@Override
protected void onPostExecute(DBOperation operation)
{
if (context != null && operation != null && !operation.ResultMessage.isEmpty())
{
Toast.makeText(context, operation.ResultMessage, Toast.LENGTH_LONG).show();
}
}
} |
package utn.sau.hp.com.beans;
import java.io.Serializable;
import javax.enterprise.context.SessionScoped;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.inject.Inject;
import javax.inject.Named;
import utn.sau.hp.com.dao.AlumnoDao;
import utn.sau.hp.com.modelo.Alumnos;
/**
*
* @author christian
*/
@Named(value = "alumnoBean")
@SessionScoped
public class AlumnoBean implements Serializable {
@Inject
private LoginBean login;
private Alumnos alumno;
private AlumnoDao dao;
public AlumnoBean() {
this.alumno = new Alumnos();
this.dao = new AlumnoDao();
}
public Alumnos getAlumno() {
return alumno;
}
public void setAlumno(Alumnos alumno) {
this.alumno = alumno;
}
public void doActualizarAlumno(){
FacesMessage messages;
if(login.getUserLoggedIn().getApellido().equals("ANONIMO")){
messages = new FacesMessage(FacesMessage.SEVERITY_INFO, "Advertencia:" ,"Usuario no registrado.");
System.out.println("Usuario no registrado.");
}else{
messages = new FacesMessage(FacesMessage.SEVERITY_INFO, "Notificación:" ,"Datos actualizados exitosamente.");
alumno = login.getUserLoggedIn();
dao.actualizarAlumno(alumno);
}
FacesContext.getCurrentInstance().addMessage(null, messages);
}
}
|
package maven;
public class Chocolate extends Sweets{
String type;
Chocolate(int n, int ct, int wt, String type){
super(n,ct,wt);
this.type = type;
}
public String toString() {
return "Cost: "+this.ct+" Weight: "+this.wt+" Total Number: "+this.n;
}
}
|
package moh.gov.il.specialble.listeners;
public interface IEventListener {
void onEvent(String event, Object data);
}
|
package ru.goodroads.api;
import java.util.ArrayList;
import ru.goodroads.data.Auth;
import ru.goodroads.data.Hole;
import ru.goodroads.data.HoleSet;
import ru.goodroads.data.Register;
import ru.goodroads.net.jsonrpc.JSONRPCClient;
import ru.goodroads.net.jsonrpc.JSONRPCClientException;
import ru.goodroads.utils.SHA256;
public class GoodRoadsClient {
private static final String GOODROADS_URL = "http://goodroads.ru/another/api.php";
// private static final String GOODROADS_URL = "http://localhost/another/api.php";
// XXX: one instance?
private final JSONRPCClient rpcClient = new JSONRPCClient(GOODROADS_URL, new GoodRoadsErrorHandler());
private String mSessionKey = null;
public GoodRoadsClient() {
// TODO: initialize auth token, currently through cookie.
// Steph think about add it in json as 'session'
}
// XXX: use annotation for json-rpc methods?
/* User */
public boolean register(String login, String password, String email) throws JSONRPCClientException {
String digest = SHA256.compute(password);
Register register = new Register(login, digest, email);
Object result = rpcClient.call("register", register);
System.out.println(result);
return true;
}
public boolean auth(String login, String password) throws JSONRPCClientException {
String digest = SHA256.compute(password);
Auth auth = new Auth(login, digest);
String session = (String) rpcClient.call("auth", auth);
if (session.compareTo("") == 0) {
throw new GoodRoadsClientException("Session not found");
}
setSessionKey(session);
System.out.println("Session key: " + session);
return true;
}
public boolean rememberPassword() throws JSONRPCClientException {
throw new GoodRoadsClientException("Not implemented");
}
public boolean vkauth() throws JSONRPCClientException {
throw new GoodRoadsClientException("Not implemented");
}
public boolean bindUser() throws JSONRPCClientException {
throw new GoodRoadsClientException("Not implemented");
}
/* Info */
public boolean lookup() throws JSONRPCClientException {
throw new GoodRoadsClientException("Not implemented");
}
public boolean alert() throws JSONRPCClientException {
throw new GoodRoadsClientException("Not implemented");
}
public boolean getUserRating() throws JSONRPCClientException {
throw new GoodRoadsClientException("Not implemented");
}
public boolean getScreen() throws JSONRPCClientException {
throw new GoodRoadsClientException("Not implemented");
}
/* Path-hole */
public boolean addHoleSet(HoleSet holeSet) throws JSONRPCClientException {
Object result = rpcClient.call("addHoleSet", holeSet);
System.out.println(result);
return true;
}
public boolean addHole(Hole hole) throws JSONRPCClientException {
Object result = rpcClient.call("addHole", hole);
System.out.println(result);
return true;
}
public boolean getHoles() throws JSONRPCClientException {
throw new GoodRoadsClientException("Not implemented");
}
@SuppressWarnings("serial")
public static void main(String[] args) {
GoodRoadsClient grc = new GoodRoadsClient();
try {
//grc.register("hello2", "omgomgomg", "hello2@mail.ru");
grc.setSessionKey("Q8dz5UmGC4u7Bg05M61FrJhdMGKDE4tV2MKvhx3jqmgsJgmVbdbJn9mzFx4Jqmfi");
grc.auth("hello2", "omgomgomg");
//grc.addHole(new Hole());
grc.addHoleSet(new HoleSet(new ArrayList<Hole>() {
{
add(new Hole());
add(new Hole());
}
}));
} catch (GoodRoadsClientException e) {
// Some response error (not valid login/pwd or anything)
e.printStackTrace();
} catch (JSONRPCClientException e) {
// Not valid response (not jsonrpc)?
e.printStackTrace();
}
}
public void setSessionKey(String mSessionKey) {
this.mSessionKey = mSessionKey;
}
public String getSessionKey() {
return mSessionKey;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.