text
stringlengths 10
2.72M
|
|---|
package com.reactive.reactiveProgrammingGradle02.fluxandmonoTest;
import org.junit.jupiter.api.Test;
import reactor.core.publisher.Flux;
import reactor.test.StepVerifier;
public class FluxMonoTest01 {
@Test
public void fluxTesting(){
Flux<String> flux = Flux.just("Sprint","Spring02","loveSpring")
//to attach error to the flux, Try
.concatWith(Flux.error(new RuntimeException()))
.concatWith(Flux.just("after Error"));
// to log the error
// .log();
// catch error here
flux.subscribe(System.out::println,(e)->System.err.println("Exception error :: "+e));
}
@Test
public void FluxTesting01(){
Flux<String> stringFlux = Flux.just("Sprint","Spring02","loveSpring").log();
//to verify the steps i.e validating content in string flux
//verifycomplete will start the step varification
StepVerifier.create(stringFlux)
.expectNext("Sprint")
.expectNext("Spring02")
.expectNext("loveSpring").verifyComplete();
//When there is possible error at that time we can us verfiy()
Flux<String> stringFlux02 = Flux.just("Sprint","Spring02","loveSpring")
.concatWith(Flux.error(new RuntimeException()));
StepVerifier.create(stringFlux02)
.expectNext("Sprint")
.expectNext("Spring02")
.expectNext("loveSpring")
.expectError(RuntimeException.class)
.verify();
}
}
|
package com.zc.base.common.bo;
import java.util.List;
public class ExcelCell {
private String cellValue;
private int firstRow;
private int lastRow;
private int firstColumn;
private int lastColumn;
private int direction;
private String formatAsString;
private List<String> cellInclude;
public String getFormatAsString() {
return this.formatAsString;
}
public void setFormatAsString(String formatAsString) {
this.formatAsString = formatAsString;
}
public List<String> getCellInclude() {
return this.cellInclude;
}
public void setCellInclude(List<String> cellInclude) {
this.cellInclude = cellInclude;
}
public String getCellValue() {
return this.cellValue;
}
public void setCellValue(String cellValue) {
this.cellValue = cellValue;
}
public int getFirstRow() {
return this.firstRow;
}
public void setFirstRow(int firstRow) {
this.firstRow = firstRow;
}
public int getLastRow() {
return this.lastRow;
}
public void setLastRow(int lastRow) {
this.lastRow = lastRow;
}
public int getFirstColumn() {
return this.firstColumn;
}
public void setFirstColumn(int firstColumn) {
this.firstColumn = firstColumn;
}
public int getLastColumn() {
return this.lastColumn;
}
public void setLastColumn(int lastColumn) {
this.lastColumn = lastColumn;
}
public int getDirection() {
return this.direction;
}
public void setDirection(int direction) {
this.direction = direction;
}
}
|
package me.saptarshidebnath.jwebsite.node;
import me.saptarshidebnath.jwebsite.db.JwDbEntityManager;
import me.saptarshidebnath.jwebsite.db.entity.website.JwConfig;
import me.saptarshidebnath.jwebsite.utils.Cnst;
import me.saptarshidebnath.jwebsite.utils.WebInstanceConstants;
import me.saptarshidebnath.jwebsite.utils.jlog.JLog;
import org.apache.commons.lang3.StringUtils;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.Scanner;
import java.util.stream.Collectors;
import static me.saptarshidebnath.jwebsite.utils.Cnst.WIC_KEY_NODE_INST_DIR;
public class NpmPackageInstaller {
private static NpmPackageInstaller INSTANCE = null;
private final File installationDir;
private NpmPackageInstaller() throws IOException, InterruptedException {
this.installationDir = new File(WebInstanceConstants.INST.getValueFor(WIC_KEY_NODE_INST_DIR));
if (!this.installationDir.exists()) {
if (this.installationDir.mkdirs() == false) {
final String message =
"Unable to create node app package directory : "
+ this.installationDir.getCanonicalPath();
JLog.severe(message);
throw new IOException(message);
} else {
JLog.info(
"Node app package directory created : " + this.installationDir.getCanonicalPath());
}
}
//
//Install package provided
//
this.installPackageJson();
//
// Install package marked in the data base
//
this.installAllPackagesMarkedInDataBase();
}
public static NpmPackageInstaller getInstance() throws IOException, InterruptedException {
if (NpmPackageInstaller.INSTANCE == null) {
synchronized (NpmPackageInstaller.class) {
if (NpmPackageInstaller.INSTANCE == null) {
NpmPackageInstaller.INSTANCE = new NpmPackageInstaller();
}
}
}
return NpmPackageInstaller.INSTANCE;
}
private Process executeNpmCommand(final String installationCommand) throws IOException {
final Process process =
Runtime.getRuntime()
.exec(
installationCommand,
null,
new File(WebInstanceConstants.INST.getValueFor(WIC_KEY_NODE_INST_DIR)));
//
//Log the output
//
new Thread(() -> this.readInputStream("OUT-", process.getInputStream())).start();
new Thread(() -> this.readInputStream("ERR-", process.getErrorStream())).start();
return process;
}
public int installAllPackagesMarkedInDataBase() throws IOException, InterruptedException {
JLog.info("Installing user packages from database");
return this.installPackage(
JwDbEntityManager.getInstance()
.streamData(JwConfig.class)
.filter(e -> e.getConfigName().equalsIgnoreCase(Cnst.DB_CONFIG_KEY_NPM_PACKAGE_NAME))
.map(e -> e.getConfigValue())
.collect(Collectors.toList()));
}
private int installPackageJson() throws IOException, InterruptedException {
JLog.info("Installing user packages from package.json");
return this.installPackage(new String[] {""});
}
private int installPackage(final List<String> packageName)
throws IOException, InterruptedException {
return this.installPackage(packageName.toArray(new String[packageName.size()]));
}
private int installPackage(final String... packageName) throws IOException, InterruptedException {
JLog.info("Beginning npm package installation");
final String installString = ("npm install " + StringUtils.join(packageName, " ")).trim();
JLog.info("Running command : " + installString);
final int returnCode = executeNpmCommand(installString).waitFor();
if (returnCode == 0) {
executeNpmCommand("npm run --list").waitFor();
}
return returnCode;
}
private void readInputStream(final String message, final InputStream inputStream) {
final Scanner sc = new Scanner(inputStream);
while (sc.hasNextLine()) {
JLog.info(message + sc.nextLine());
}
}
}
|
/**
* #segment-tree (1,2,3,4,5,6,7,8,9) h = 1 1 | 2 = 3 3 | 4 = 7 5 | 6 = 7 7 | 8 = 15 9 = 9 ->>> h = 2
* 3 ^ 7 7 ^ 15 9 ---> h = 3 7 | 15. 9 ---> h = 4 9 ^ 15 = 6
*/
import java.util.Scanner;
class XeniaAndBitOperations {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt(); // also is height of segment tree.
int m = sc.nextInt();
int sz = (int) Math.pow(2, n);
int[] arr = new int[sz];
for (int i = 0; i < sz; i++) {
arr[i] = sc.nextInt();
}
// max size of segment tree
int sizeTree = 2 * sz - 1;
int[] segmentTree = new int[sizeTree];
// build segment Tree
buildTree(arr, segmentTree, 0, sz - 1, 0, n);
// calculate
int p, b;
for (int i = 0; i < m; i++) {
p = sc.nextInt();
b = sc.nextInt();
// update segment Tree
updateQuery(arr, segmentTree, 0, sz - 1, 0, n, p - 1, b);
System.out.println(segmentTree[0]);
}
}
// build segment Tree
private static void buildTree(
int[] arr, int[] segmentTree, int left, int right, int idx, int heightOfTree) {
if (left == right) {
segmentTree[idx] = arr[left];
return;
}
int mid = left + (right - left) / 2;
buildTree(arr, segmentTree, left, mid, 2 * idx + 1, heightOfTree - 1);
buildTree(arr, segmentTree, mid + 1, right, 2 * idx + 2, heightOfTree - 1);
if (heightOfTree % 2 == 0) {
segmentTree[idx] = segmentTree[2 * idx + 1] ^ segmentTree[2 * idx + 2];
} else {
segmentTree[idx] = segmentTree[2 * idx + 1] | segmentTree[2 * idx + 2];
}
}
// update segmentTree
private static void updateQuery(
int[] arr,
int[] segmentTree,
int left,
int right,
int idx,
int heightOfTree,
int pos,
int val) {
if (pos > right || pos < left) {
return;
}
if (left == right) {
arr[pos] = val;
segmentTree[idx] = val;
return;
}
int mid = left + (right - left) / 2;
if (pos <= mid) {
updateQuery(arr, segmentTree, left, mid, 2 * idx + 1, heightOfTree - 1, pos, val);
} else { // pos > mid
updateQuery(arr, segmentTree, mid + 1, right, 2 * idx + 2, heightOfTree - 1, pos, val);
}
if (heightOfTree % 2 == 0) {
segmentTree[idx] = segmentTree[2 * idx + 1] ^ segmentTree[2 * idx + 2];
} else {
segmentTree[idx] = segmentTree[2 * idx + 1] | segmentTree[2 * idx + 2];
}
}
}
|
package com.getkhaki.api.bff.persistence.models;
import lombok.Getter;
import lombok.Setter;
import lombok.experimental.Accessors;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import javax.persistence.UniqueConstraint;
@Entity
@Getter
@Setter
@Accessors(chain = true)
@Table(uniqueConstraints = {
@UniqueConstraint(columnNames = {"calendar_event_id", "email_id"}),
@UniqueConstraint(columnNames = {"calendar_event_id", "organizer"})
})
public class CalendarEventParticipantDao extends EntityBaseDao {
@ManyToOne(optional = false)
CalendarEventDao calendarEvent;
@ManyToOne(optional = false)
EmailDao email;
@Column(nullable = true)
Boolean organizer = null;
public CalendarEventParticipantDao setOrganizer(Boolean organizer) {
this.organizer = organizer;
if (organizer.equals(false)) {
this.organizer = null;
}
return this;
}
}
|
package exam.iz0_803;
public class Exam_124 {
}
/*
Given:
public class gotop.vicenttuan.tiger7.exam.Test {
String edition;
gotop.vicenttuan.tiger7.exam.Test() {
edition = "SE";
}
public static void main(String[] args) {
gotop.vicenttuan.tiger7.exam.Test obj = new gotop.vicenttuan.tiger7.exam.Test();
String edition = args[2];
System.out.println(obj.edition);
}
}
And the command line invocation:
Java gotop.vicenttuan.tiger7.exam.Test EE ME FX
What is the result?
A. SE
B. EE
C. ME
D. FX
Answer: A
*/
|
package com.finca.ccw.cucumber;
import com.finca.ccw.CcwApplicationApp;
import io.cucumber.java.Before;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.web.WebAppConfiguration;
@SpringBootTest
@WebAppConfiguration
@ContextConfiguration(classes = CcwApplicationApp.class)
public class CucumberContextConfiguration {
@Before
public void setup_cucumber_spring_context() {
// Dummy method so cucumber will recognize this class as glue
// and use its context configuration.
}
}
|
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class MyFrame extends JFrame implements ActionListener {
private JButton b1 = new JButton("Guest Login");
private JButton b2 = new JButton("Admin Login");
private JTextField t1 = new JTextField("");
private JTextField t2 = new JPasswordField("");
private JLabel l1 = new JLabel("Movie Booking Application");
private Panel p2 = new Panel();
private int index = 0;
LinkedList list=new LinkedList();
public MyFrame(LinkedList list2) {
this.list=list2;
Container content = getContentPane();
Font f=new Font("TimesRoman", Font.BOLD,20);
getContentPane().setLayout(null);
l1.setBounds(7, 5, 227, 27);
l1.setFont(f);
content.add(l1);
b2.setBounds(7, 191, 227, 31);
getContentPane().add(b2);
b1.setBounds(7, 35, 227, 31);
getContentPane().add(b1);
t2.setBounds(106, 147, 128, 31);
getContentPane().add(t2);
t1.setBounds(106, 98, 128, 31);
getContentPane().add(t1);
JLabel lblNewLabel = new JLabel("Username");
lblNewLabel.setBounds(12, 105, 82, 16);
getContentPane().add(lblNewLabel);
JLabel lblNewLabel_1 = new JLabel("Password");
lblNewLabel_1.setBounds(12, 154, 56, 16);
getContentPane().add(lblNewLabel_1);
b1.addActionListener(this);
b2.addActionListener(this);
setSize(260,300);
setVisible(true);
}
public static void main(String[] args) {
// TODO Auto-generated method stub
}
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
Object target = e.getSource();
if(target==b1) {
GuestPage gp= new GuestPage(list);
gp.setVisible(true);
this.dispose();
}
if(target==b2) {
String v1 = t1.getText();
String v2 = t2.getText();
if(v1.equals("admin") && v2.equals("admin")) {
AdminPage page = new AdminPage(list);
page.setVisible(true);
JLabel la = new JLabel("Welcome : " + v1);
page.getContentPane().add(la);
this.dispose();
}
else {
JOptionPane.showMessageDialog(this, "Invalid Credential","Error", JOptionPane.ERROR_MESSAGE);
}
}
}
}
|
package org.jscep.transport;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import net.jcip.annotations.ThreadSafe;
import org.apache.commons.io.IOUtils;
import org.jscep.transport.request.Operation;
import org.jscep.transport.request.Request;
import org.jscep.transport.response.ScepResponseHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* AbstractTransport representing the <code>HTTP GET</code> method
*/
@ThreadSafe
final class UrlConnectionGetTransport extends AbstractTransport {
private static final Logger LOGGER = LoggerFactory
.getLogger(UrlConnectionGetTransport.class);
/**
* Creates a new <tt>HttpGetTransport</tt> for the given <tt>URL</tt>.
*
* @param url
* the <tt>URL</tt> to send <tt>GET</tt> requests to.
*/
public UrlConnectionGetTransport(final URL url) {
super(url);
}
/**
* {@inheritDoc}
*/
@Override
public <T> T sendRequest(final Request msg,
final ScepResponseHandler<T> handler) throws TransportException {
URL url = getUrl(msg.getOperation(), msg.getMessage());
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Sending {} to {}", msg, url);
}
HttpURLConnection conn;
try {
conn = (HttpURLConnection) url.openConnection();
} catch (IOException e) {
throw new TransportException(e);
}
try {
int responseCode = conn.getResponseCode();
String responseMessage = conn.getResponseMessage();
LOGGER.debug("Received '{} {}' when sending {} to {}",
varargs(responseCode, responseMessage, msg, url));
if (responseCode != HttpURLConnection.HTTP_OK) {
throw new TransportException(responseCode + " "
+ responseMessage);
}
} catch (IOException e) {
throw new TransportException("Error connecting to server", e);
}
byte[] response;
try {
response = IOUtils.toByteArray(conn.getInputStream());
} catch (IOException e) {
throw new TransportException("Error reading response stream", e);
}
return handler.getResponse(response, conn.getContentType());
}
private URL getUrl(final Operation op, final String message)
throws TransportException {
try {
return new URL(getUrl(op).toExternalForm() + "&message="
+ URLEncoder.encode(message, "UTF-8"));
} catch (MalformedURLException e) {
throw new TransportException(e);
} catch (UnsupportedEncodingException e) {
throw new TransportException(e);
}
}
}
|
/*
* 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 Map;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
*
* @author YNZ
*/
public class MapGenerics {
public static void main(String[] args) {
Map<String, List<IceCream>> map = new HashMap<>();
List<IceCream> list = new ArrayList<>();
list.add(IceCream.CHOCOLATE);
list.add(IceCream.STRAWBERRY);
list.add(IceCream.WALNUT);
map.put("one", list);
map.put("two", new ArrayList<IceCream>());
}
}
|
package com.example.hante.newprojectsum.pay.bean;
import java.io.Serializable;
/**
* 购买方式封装
*/
public class BuyStyle implements Serializable{
private int id_code;
private int rate;
public int getId_code () {
return id_code;
}
public void setId_code (int id_code) {
this.id_code = id_code;
}
public int getRate () {
return rate;
}
public void setRate (int rate) {
this.rate = rate;
}
}
|
import com.palani.examples.factoryPattern.Building;
import com.palani.examples.factoryPattern.BuildingFactory;
public class PalaniMain {
public static void main(String args[]) {
String location = "Home";
BuildingFactory buildFactory = new BuildingFactory();
// factory instantiates an object
Building building = buildFactory.getMyLocation(location);
}
}
|
package com.pdd.pop.sdk.http.api.request;
import com.pdd.pop.ext.fasterxml.jackson.annotation.JsonProperty;
import com.pdd.pop.sdk.http.api.response.PddStockWareSkuUpdateResponse;
import com.pdd.pop.sdk.http.HttpMethod;
import com.pdd.pop.sdk.http.PopBaseHttpRequest;
import com.pdd.pop.sdk.common.util.JsonUtil;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
public class PddStockWareSkuUpdateRequest extends PopBaseHttpRequest<PddStockWareSkuUpdateResponse>{
/**
* 货品id
*/
@JsonProperty("ware_id")
private Long wareId;
/**
* 组合货品中子货品的关联关系
*/
@JsonProperty("ware_skus")
private List<WareSkusItem> wareSkus;
@Override
public String getVersion() {
return "V1";
}
@Override
public String getDataType() {
return "JSON";
}
@Override
public String getType() {
return "pdd.stock.ware.sku.update";
}
@Override
public HttpMethod getHttpMethod() {
return HttpMethod.POST;
}
@Override
public Class<PddStockWareSkuUpdateResponse> getResponseClass() {
return PddStockWareSkuUpdateResponse.class;
}
@Override
public Map<String, String> getParamsMap() {
Map<String, String> paramsMap = new TreeMap<String, String>();
paramsMap.put("version", getVersion());
paramsMap.put("data_type", getDataType());
paramsMap.put("type", getType());
paramsMap.put("timestamp", getTimestamp().toString());
if(wareId != null) {
paramsMap.put("ware_id", wareId.toString());
}
if(wareSkus != null) {
paramsMap.put("ware_skus", wareSkus.toString());
}
return paramsMap;
}
public void setWareId(Long wareId) {
this.wareId = wareId;
}
public void setWareSkus(List<WareSkusItem> wareSkus) {
this.wareSkus = wareSkus;
}
public static class WareSkusItem {
/**
* sku id
*/
@JsonProperty("sku_id")
private Long skuId;
/**
* 商品id
*/
@JsonProperty("goods_id")
private Long goodsId;
public void setSkuId(Long skuId) {
this.skuId = skuId;
}
public void setGoodsId(Long goodsId) {
this.goodsId = goodsId;
}
@Override
public String toString() {
return JsonUtil.transferToJson(this);
}
}
}
|
package com.mediafire.sdk.api.responses;
public class UserGetSessionTokenResponse extends ApiResponse {
private String session_token;
private long secret_key;
private String pkey;
private String ekey;
private String time;
private String permanent_token;
public String getSessionToken() {
return session_token;
}
public long getSecretKey() {
return secret_key;
}
public String getPkey() {
return pkey;
}
public String getEkey() {
return ekey;
}
public String getTime() {
return time;
}
public String getPermanentToken() {
return permanent_token;
}
}
|
package io.zentity.resolution;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import org.elasticsearch.ElasticsearchStatusException;
import org.elasticsearch.action.search.SearchAction;
import org.elasticsearch.action.search.SearchRequestBuilder;
import org.elasticsearch.client.ElasticsearchClient;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.rest.RestStatus;
import org.junit.Test;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import static io.zentity.devtools.JsonTestUtil.assertUnorderedEquals;
import static org.mockito.Mockito.mock;
public class LoggedQueryTest {
static final ObjectMapper MAPPER = new ObjectMapper()
.configure(SerializationFeature.ORDER_MAP_ENTRIES_BY_KEYS, true);
@Test
public void testSerialize() throws JsonProcessingException {
LoggedSearch loggedSearch = new LoggedSearch();
SearchRequestBuilder searchRequest = new SearchRequestBuilder(
mock(ElasticsearchClient.class),
SearchAction.INSTANCE
);
QueryBuilder query = QueryBuilders.boolQuery().mustNot(QueryBuilders.matchAllQuery());
searchRequest.setQuery(query);
searchRequest.setFetchSource(true);
loggedSearch.searchRequest = searchRequest;
loggedSearch.responseError = new ElasticsearchStatusException("This was not found", RestStatus.NOT_FOUND);
LoggedFilter attributesFilter = new LoggedFilter();
Map<String, Collection<String>> attributesFilterResolverAttributes = new HashMap<>();
attributesFilterResolverAttributes.put("name", Arrays.asList("Alice Jones", "Alice"));
attributesFilter.resolverAttributes = attributesFilterResolverAttributes;
Map<Integer, FilterTree> attributesFilterGroupedTree = new HashMap<>();
FilterTree attributesFilterTree1 = new FilterTree();
attributesFilterTree1.put("name_dob", new FilterTree());
attributesFilterGroupedTree.put(0, attributesFilterTree1);
attributesFilter.groupedTree = attributesFilterGroupedTree;
LoggedFilter termsFilter = new LoggedFilter();
Map<String, Collection<String>> termsFilterResolverAttributes = new HashMap<>();
termsFilterResolverAttributes.put("city", Arrays.asList("Alice Jones", "Alice"));
termsFilter.resolverAttributes = termsFilterResolverAttributes;
Map<Integer, FilterTree> termsFilterGroupedTree = new HashMap<>();
FilterTree termsFilterTree1 = new FilterTree();
termsFilterTree1.put("city", new FilterTree());
termsFilterGroupedTree.put(0, termsFilterTree1);
termsFilter.groupedTree = termsFilterGroupedTree;
Map<String, LoggedFilter> filters = new HashMap<>();
filters.put("attributes", attributesFilter);
filters.put("terms", attributesFilter);
LoggedQuery loggedQuery = new LoggedQuery();
loggedQuery.index = ".zentity-test-index";
loggedQuery.hop = 3;
loggedQuery.queryNumber = 4;
loggedQuery.search = loggedSearch;
loggedQuery.filters = filters;
JsonNode actual = MAPPER.readTree(MAPPER.writeValueAsString(loggedQuery));
JsonNode expected = MAPPER.readTree("{\"search\":{\"request\":{\"query\":{\"bool\":{\"must_not\":[{\"match_all\":{\"boost\":1.0}}],\"adjust_pure_negative\":true,\"boost\":1.0}},\"_source\":{\"includes\":[],\"excludes\":[]}},\"response\":{\"error\":{\"root_cause\":[{\"type\":\"status_exception\",\"reason\":\"This was not found\"}],\"type\":\"status_exception\",\"reason\":\"This was not found\",\"status\":404}}},\"filters\":{\"attributes\":{\"resolvers\":{\"name\":{\"attributes\":[\"Alice Jones\",\"Alice\"]}},\"tree\":{\"0\":{\"name_dob\":{}}}},\"terms\":{\"resolvers\":{\"name\":{\"attributes\":[\"Alice Jones\",\"Alice\"]}},\"tree\":{\"0\":{\"name_dob\":{}}}}},\"_index\":\".zentity-test-index\",\"_hop\":3,\"_query\":4}");
assertUnorderedEquals(expected, actual);
}
}
|
package ua.epam.provider.servlet.tariff;
import ua.epam.provider.dao.ServiceDao;
import ua.epam.provider.dao.TariffDao;
import ua.epam.provider.entity.Service;
import ua.epam.provider.entity.Tariff;
import ua.epam.provider.service.TariffService;
import ua.epam.provider.service.TariffServiceService;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
@WebServlet(urlPatterns = "/admin/add-tariff.do")
public class AddTariffAdminServlet extends HttpServlet {
private static final String FILE_DIR = "files";
private static final long serialVersionUID = 1L;
private TariffService tariffService = new TariffService();
private ServiceDao serviceDao = new ServiceDao();
private TariffServiceService tariffServiceService = new TariffServiceService();
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
request.setAttribute("listServices", serviceDao.showListServicesTitles());
request.getRequestDispatcher("/WEB-INF/views/admin/add-tariff.jsp").forward(
request, response);
}
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
String title = request.getParameter("title");
Double priceByDay = Double.valueOf(request.getParameter("priceByDay"));
String[] titles = request.getParameterValues("services");
List<Service> serviceList = new ArrayList<>();
for (String serviceTitle : titles) {
Service service = new ServiceDao().getService(serviceTitle);
serviceList.add(service);
}
Tariff tariff = new Tariff(priceByDay, title);
if (!new TariffDao().isExistTariff(title)) {
tariffService.addNewTariff(tariff);
Tariff newTariff = new TariffDao().getTariff(title);
tariffServiceService.createTariffServices(newTariff, serviceList);
response.sendRedirect("/admin/tariff-admin.do");
} else {
request.setAttribute("errorMessage", "Service " + tariff.getTitle() + " is already exists");
request.getRequestDispatcher("/WEB-INF/views/admin/add-tariff.jsp").forward(
request, response);
}
}
}
|
/*
* Copyright (c) 2014 ICM Uniwersytet Warszawski All rights reserved.
* See LICENCE.txt file for licensing information.
*/
package pl.edu.icm.unity.saml.metadata.cfg;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.log4j.Logger;
import org.apache.xmlbeans.XmlCursor;
import org.apache.xmlbeans.XmlException;
import org.apache.xmlbeans.XmlObject;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import pl.edu.icm.unity.exceptions.EngineException;
import pl.edu.icm.unity.exceptions.WrongArgumentException;
import pl.edu.icm.unity.saml.SamlProperties;
import pl.edu.icm.unity.saml.SamlProperties.Binding;
import pl.edu.icm.unity.server.api.PKIManagement;
import pl.edu.icm.unity.server.utils.Log;
import pl.edu.icm.unity.server.utils.UnityMessageSource;
import xmlbeans.org.oasis.saml2.assertion.AttributeType;
import xmlbeans.org.oasis.saml2.metadata.EndpointType;
import xmlbeans.org.oasis.saml2.metadata.EntitiesDescriptorDocument;
import xmlbeans.org.oasis.saml2.metadata.EntitiesDescriptorType;
import xmlbeans.org.oasis.saml2.metadata.EntityDescriptorType;
import xmlbeans.org.oasis.saml2.metadata.ExtensionsType;
import xmlbeans.org.oasis.saml2.metadata.KeyDescriptorType;
import xmlbeans.org.oasis.saml2.metadata.KeyTypes;
import xmlbeans.org.oasis.saml2.metadata.LocalizedNameType;
import xmlbeans.org.oasis.saml2.metadata.OrganizationType;
import xmlbeans.org.oasis.saml2.metadata.SSODescriptorType;
import xmlbeans.org.oasis.saml2.metadata.extattribute.EntityAttributesDocument;
import xmlbeans.org.oasis.saml2.metadata.extattribute.EntityAttributesType;
import xmlbeans.org.oasis.saml2.metadata.extui.LogoType;
import xmlbeans.org.oasis.saml2.metadata.extui.UIInfoDocument;
import xmlbeans.org.oasis.saml2.metadata.extui.UIInfoType;
import xmlbeans.org.w3.x2000.x09.xmldsig.X509DataType;
import eu.emi.security.authn.x509.impl.CertificateUtils;
import eu.emi.security.authn.x509.impl.CertificateUtils.Encoding;
import eu.emi.security.authn.x509.impl.X500NameUtils;
import eu.unicore.samly2.SAMLConstants;
/**
* Base for converters of SAML metadata into a series of property statements.
*
* @author K. Benedyczak
*/
public abstract class AbstractMetaToConfigConverter
{
private static final Logger log = Log.getLogger(Log.U_SERVER_SAML, AbstractMetaToConfigConverter.class);
protected PKIManagement pkiManagement;
protected UnityMessageSource msg;
public AbstractMetaToConfigConverter(PKIManagement pkiManagement, UnityMessageSource msg)
{
this.pkiManagement = pkiManagement;
this.msg = msg;
}
/**
* Inserts metadata to the configuration in properties. All entries which are present in
* realConfig are preserved.
* @param meta
* @param properties
* @param realConfig
*/
protected void convertToProperties(EntitiesDescriptorDocument metaDoc, Properties properties,
SamlProperties realConfig, String configKey)
{
EntitiesDescriptorType meta = metaDoc.getEntitiesDescriptor();
convertToProperties(meta, properties, realConfig, configKey);
}
protected void convertToProperties(EntitiesDescriptorType meta, Properties properties,
SamlProperties realConfig, String configKey)
{
EntitiesDescriptorType[] nested = meta.getEntitiesDescriptorArray();
if (nested != null)
{
for (EntitiesDescriptorType nestedD: nested)
convertToProperties(nestedD, properties, realConfig, configKey);
}
EntityDescriptorType[] entities = meta.getEntityDescriptorArray();
if (entities != null)
{
for (EntityDescriptorType entity: entities)
{
convertToProperties(entity, properties, realConfig, configKey);
}
}
}
protected abstract void convertToProperties(EntityDescriptorType meta, Properties properties,
SamlProperties realConfig, String configKey);
protected boolean supportsSaml2(SSODescriptorType idpDef)
{
List<?> supportedProtocols = idpDef.getProtocolSupportEnumeration();
for (Object supported: supportedProtocols)
if (SAMLConstants.PROTOCOL_NS.equals(supported))
return true;
return false;
}
/**
*
* @param entityAttributes
* @return true only if the entity attribtues parameter is not null and contains an REFEDS attribute
* hide-from-discovery.
*/
protected boolean isDisabled(EntityAttributesType entityAttributes)
{
if (entityAttributes == null)
return false;
AttributeType[] attributeArray = entityAttributes.getAttributeArray();
for (AttributeType a: attributeArray)
{
if ("http://macedir.org/entity-category".equals(a.getName()))
{
for (XmlObject value : a.getAttributeValueArray())
{
XmlCursor c = value.newCursor();
String valueStr = c.getTextValue();
c.dispose();
if (valueStr.equals("http://refeds.org/category/hide-from-discovery"))
return true;
}
}
}
return false;
}
protected List<X509Certificate> getSigningCerts(KeyDescriptorType[] keys, String entityId)
{
List<X509Certificate> ret = new ArrayList<X509Certificate>();
for (KeyDescriptorType key: keys)
{
if (!key.isSetUse() || KeyTypes.SIGNING.equals(key.getUse()))
{
X509DataType[] x509Keys = key.getKeyInfo().getX509DataArray();
if (x509Keys == null || x509Keys.length == 0)
{
log.info("Key in SAML metadata is ignored as it doesn't contain "
+ "X.509 certificate. Entity " + entityId);
continue;
}
for (X509DataType x509Key: x509Keys)
{
byte[][] certsAsBytes = x509Key.getX509CertificateArray();
X509Certificate cert;
try
{
cert = CertificateUtils.loadCertificate(
new ByteArrayInputStream(certsAsBytes[0]), Encoding.DER);
} catch (IOException e)
{
log.warn("Can not load/parse a certificate from metadata of " + entityId
+ ", ignoring it", e);
continue;
}
ret.add(cert);
}
}
}
return ret;
}
protected void updatePKICerts(List<X509Certificate> certs, String entityId, String prefix)
throws EngineException
{
synchronized (pkiManagement)
{
for (X509Certificate cert : certs)
{
String pkiKey = getCertificateKey(cert, entityId, prefix);
try
{
X509Certificate existingCert = pkiManagement
.getCertificate(pkiKey);
if (!existingCert.equals(cert))
{
pkiManagement.updateCertificate(pkiKey, cert);
}
} catch (WrongArgumentException e)
{
pkiManagement.addCertificate(pkiKey, cert);
}
}
}
}
protected String getCertificateKey(X509Certificate cert, String entityId, String prefix)
{
String dn = X500NameUtils.getComparableForm(cert.getSubjectX500Principal()
.getName());
String key = prefix + DigestUtils.md5Hex(entityId) + "#" + DigestUtils.md5Hex(dn);
return key;
}
protected Map<String, String> getLocalizedNames(UIInfoType uiInfo, SSODescriptorType idpDesc,
EntityDescriptorType mainDescriptor)
{
Map<String, String> ret = new HashMap<String, String>();
OrganizationType mainOrg = mainDescriptor.getOrganization();
if (mainOrg != null)
{
addLocalizedNames(mainOrg.getOrganizationNameArray(), ret);
addLocalizedNames(mainOrg.getOrganizationDisplayNameArray(), ret);
}
OrganizationType org = idpDesc.getOrganization();
if (org != null)
{
addLocalizedNames(org.getOrganizationNameArray(), ret);
addLocalizedNames(org.getOrganizationDisplayNameArray(), ret);
}
if (uiInfo != null)
{
addLocalizedNames(uiInfo.getDisplayNameArray(), ret);
}
return ret;
}
protected Map<String, LogoType> getLocalizedLogos(UIInfoType uiInfo)
{
Map<String, LogoType> ret = new HashMap<String, LogoType>();
if (uiInfo != null)
{
LogoType[] logos = uiInfo.getLogoArray();
if (logos == null)
return ret;
for (LogoType logo: logos)
{
String key = logo.getLang() == null ? "" : "." + logo.getLang();
LogoType e = ret.get(key);
if (e == null)
{
ret.put(key, logo);
} else
{
if (e.getHeight().longValue() < logo.getHeight().longValue())
ret.put(key, logo);
}
}
}
return ret;
}
/**
* Converts SAML names to a language key->value map. All language keys are prefixed with dot.
* The empty key is used to provide a default value, for the default system locale. If such default
* was not found in the SAML names, then the 'en' locale is tried. Not fully correct, but this is
* de facto standard default locale for international federations.
*
* @param names
* @param ret
*/
protected void addLocalizedNames(LocalizedNameType[] names, Map<String, String> ret)
{
if (names == null)
return;
String enName = null;
for (LocalizedNameType name: names)
{
String lang = name.getLang();
if (lang != null)
{
ret.put("." + lang, name.getStringValue());
if (lang.equals(msg.getDefaultLocaleCode()))
ret.put("", name.getStringValue());
if (lang.equals("en"))
enName = name.getStringValue();
} else
{
ret.put("", name.getStringValue());
}
}
if (enName != null && !ret.containsKey(""))
ret.put("", enName);
}
protected UIInfoType parseMDUIInfo(ExtensionsType extensions, String entityId)
{
if (extensions == null)
return null;
NodeList nl = extensions.getDomNode().getChildNodes();
for (int i=0; i<nl.getLength(); i++)
{
Node elementN = nl.item(i);
if (elementN.getNodeType() != Node.ELEMENT_NODE)
continue;
Element element = (Element) elementN;
if ("UIInfo".equals(element.getLocalName()) &&
"urn:oasis:names:tc:SAML:metadata:ui".equals(element.getNamespaceURI()))
{
try
{
return UIInfoDocument.Factory.parse(element).getUIInfo();
} catch (XmlException e)
{
log.warn("Can not parse UIInfo metadata extension for " + entityId, e);
}
}
}
return null;
}
protected EntityAttributesType parseMDAttributes(ExtensionsType extensions, String entityId)
{
if (extensions == null)
return null;
NodeList nl = extensions.getDomNode().getChildNodes();
for (int i=0; i<nl.getLength(); i++)
{
Node elementN = nl.item(i);
if (elementN.getNodeType() != Node.ELEMENT_NODE)
continue;
Element element = (Element) elementN;
if ("EntityAttributes".equals(element.getLocalName()) &&
"urn:oasis:names:tc:SAML:metadata:attribute".equals(element.getNamespaceURI()))
{
try
{
return EntityAttributesDocument.Factory.parse(element).getEntityAttributes();
} catch (XmlException e)
{
log.warn("Can not parse entity attributes metadata extension for " + entityId, e);
}
}
}
return null;
}
protected String convertBinding(String samlBinding)
{
if (SAMLConstants.BINDING_HTTP_POST.equals(samlBinding))
return Binding.HTTP_POST.toString();
if (SAMLConstants.BINDING_HTTP_REDIRECT.equals(samlBinding))
return Binding.HTTP_REDIRECT.toString();
if (SAMLConstants.BINDING_SOAP.equals(samlBinding))
return Binding.SOAP.toString();
throw new IllegalStateException("Unsupported binding: " + samlBinding);
}
protected void setSLOProperty(Properties properties, String configKey, boolean noPerEntryConfig,
EndpointType sloEndpoint, String SLOProperty, String SLORetProperty)
{
if (noPerEntryConfig || !properties.containsKey(configKey + SLOProperty))
{
if (sloEndpoint != null)
{
properties.setProperty(configKey + SLOProperty,
sloEndpoint.getLocation());
if (SLORetProperty != null && sloEndpoint.getResponseLocation() != null)
properties.setProperty(configKey + SLORetProperty,
sloEndpoint.getResponseLocation());
}
}
}
}
|
// package com.qualcomm.ftcrobotcontroller.opmodes; //ignore the red yo
package org.firstinspires.ftc.teamcode; //revert to top if needed
import com.qualcomm.robotcore.eventloop.opmode.Autonomous;
import com.qualcomm.robotcore.eventloop.opmode.OpMode;
import com.qualcomm.robotcore.hardware.DcMotor;
import com.qualcomm.robotcore.eventloop.opmode.Disabled;
import com.qualcomm.robotcore.hardware.DcMotorSimple;
import com.qualcomm.robotcore.hardware.Servo;
import com.qualcomm.robotcore.util.ElapsedTime;
import com.qualcomm.robotcore.eventloop.opmode.LinearOpMode;
@Autonomous(name = "OmegaBotAuto", group = "VelocityVortex")
//@Disable
public class OmegaBotAuto extends LinearOpMode {
private DcMotor leftDrive;
private DcMotor rightDrive;
private DcMotor pickUp;
private DcMotor roll;
private DcMotor fling;
public int loadPos;
public boolean isShooting = false;
private ElapsedTime runtime = new ElapsedTime();
@Override
public void runOpMode() {
leftDrive = hardwareMap.dcMotor.get("left_drive");
rightDrive = hardwareMap.dcMotor.get("right_drive");
rightDrive.setDirection(DcMotor.Direction.REVERSE);
pickUp = hardwareMap.dcMotor.get("pickUp");
roll = hardwareMap.dcMotor.get("roll");
fling = hardwareMap.dcMotor.get("catapult");
fling.setDirection(DcMotor.Direction.FORWARD);
fling.setZeroPowerBehavior(DcMotor.ZeroPowerBehavior.BRAKE);
loadPos = fling.getCurrentPosition();
telemetry.addData("Load Position", loadPos);
waitForStart();
runtime.reset();
while (opModeIsActive() && (runtime.seconds() < 1.5)) {
leftDrive.setPower(1);
rightDrive.setPower(1);
roll.setPower(-1);
pickUp.setPower(1);
}
leftDrive.setPower(0);
rightDrive.setPower(0);
runtime.reset();
if (opModeIsActive() && (runtime.seconds() < 2) && (!isShooting)) {
fling.setMode(DcMotor.RunMode.RUN_TO_POSITION);
fling.setTargetPosition(loadPos + 1440);
fling.setPower(0.05);
isShooting = true;
}
if (isShooting) {
fling.setPower(0);
}
runtime.reset();
while (opModeIsActive() && (runtime.seconds() < 1)) { //5-8 seconds
leftDrive.setPower(1);
rightDrive.setPower(1);
}
leftDrive.setPower(0);
rightDrive.setPower(0);
}
}
|
/**
*/
package iso20022.impl;
import java.lang.reflect.InvocationTargetException;
import java.util.Collection;
import java.util.Map;
import org.eclipse.emf.common.notify.Notification;
import org.eclipse.emf.common.notify.NotificationChain;
import org.eclipse.emf.common.util.DiagnosticChain;
import org.eclipse.emf.common.util.EList;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.InternalEObject;
import org.eclipse.emf.ecore.impl.ENotificationImpl;
import org.eclipse.emf.ecore.util.EObjectContainmentWithInverseEList;
import org.eclipse.emf.ecore.util.EcoreUtil;
import org.eclipse.emf.ecore.util.InternalEList;
import iso20022.DataDictionary;
import iso20022.Iso20022Package;
import iso20022.Repository;
import iso20022.TopLevelDictionaryEntry;
/**
* <!-- begin-user-doc -->
* An implementation of the model object '<em><b>Data Dictionary</b></em>'.
* <!-- end-user-doc -->
* <p>
* The following features are implemented:
* </p>
* <ul>
* <li>{@link iso20022.impl.DataDictionaryImpl#getTopLevelDictionaryEntry <em>Top Level Dictionary Entry</em>}</li>
* <li>{@link iso20022.impl.DataDictionaryImpl#getRepository <em>Repository</em>}</li>
* </ul>
*
* @generated
*/
public class DataDictionaryImpl extends ModelEntityImpl implements DataDictionary {
/**
* The cached value of the '{@link #getTopLevelDictionaryEntry() <em>Top Level Dictionary Entry</em>}' containment reference list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getTopLevelDictionaryEntry()
* @generated
* @ordered
*/
protected EList<TopLevelDictionaryEntry> topLevelDictionaryEntry;
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected DataDictionaryImpl() {
super();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
protected EClass eStaticClass() {
return Iso20022Package.eINSTANCE.getDataDictionary();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EList<TopLevelDictionaryEntry> getTopLevelDictionaryEntry() {
if (topLevelDictionaryEntry == null) {
topLevelDictionaryEntry = new EObjectContainmentWithInverseEList<TopLevelDictionaryEntry>(TopLevelDictionaryEntry.class, this, Iso20022Package.DATA_DICTIONARY__TOP_LEVEL_DICTIONARY_ENTRY, Iso20022Package.TOP_LEVEL_DICTIONARY_ENTRY__DATA_DICTIONARY);
}
return topLevelDictionaryEntry;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public Repository getRepository() {
if (eContainerFeatureID() != Iso20022Package.DATA_DICTIONARY__REPOSITORY) return null;
return (Repository)eInternalContainer();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public NotificationChain basicSetRepository(Repository newRepository, NotificationChain msgs) {
msgs = eBasicSetContainer((InternalEObject)newRepository, Iso20022Package.DATA_DICTIONARY__REPOSITORY, msgs);
return msgs;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setRepository(Repository newRepository) {
if (newRepository != eInternalContainer() || (eContainerFeatureID() != Iso20022Package.DATA_DICTIONARY__REPOSITORY && newRepository != null)) {
if (EcoreUtil.isAncestor(this, newRepository))
throw new IllegalArgumentException("Recursive containment not allowed for " + toString());
NotificationChain msgs = null;
if (eInternalContainer() != null)
msgs = eBasicRemoveFromContainer(msgs);
if (newRepository != null)
msgs = ((InternalEObject)newRepository).eInverseAdd(this, Iso20022Package.REPOSITORY__DATA_DICTIONARY, Repository.class, msgs);
msgs = basicSetRepository(newRepository, msgs);
if (msgs != null) msgs.dispatch();
}
else if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, Iso20022Package.DATA_DICTIONARY__REPOSITORY, newRepository, newRepository));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated NOT
*/
public boolean EntriesHaveUniqueName(Map context, DiagnosticChain diagnostics) {
// TODO: implement this method >>> DONE
// Ensure that you remove @generated or mark it @generated NOT
return true;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@SuppressWarnings("unchecked")
@Override
public NotificationChain eInverseAdd(InternalEObject otherEnd, int featureID, NotificationChain msgs) {
switch (featureID) {
case Iso20022Package.DATA_DICTIONARY__TOP_LEVEL_DICTIONARY_ENTRY:
return ((InternalEList<InternalEObject>)(InternalEList<?>)getTopLevelDictionaryEntry()).basicAdd(otherEnd, msgs);
case Iso20022Package.DATA_DICTIONARY__REPOSITORY:
if (eInternalContainer() != null)
msgs = eBasicRemoveFromContainer(msgs);
return basicSetRepository((Repository)otherEnd, msgs);
}
return super.eInverseAdd(otherEnd, featureID, msgs);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public NotificationChain eInverseRemove(InternalEObject otherEnd, int featureID, NotificationChain msgs) {
switch (featureID) {
case Iso20022Package.DATA_DICTIONARY__TOP_LEVEL_DICTIONARY_ENTRY:
return ((InternalEList<?>)getTopLevelDictionaryEntry()).basicRemove(otherEnd, msgs);
case Iso20022Package.DATA_DICTIONARY__REPOSITORY:
return basicSetRepository(null, msgs);
}
return super.eInverseRemove(otherEnd, featureID, msgs);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public NotificationChain eBasicRemoveFromContainerFeature(NotificationChain msgs) {
switch (eContainerFeatureID()) {
case Iso20022Package.DATA_DICTIONARY__REPOSITORY:
return eInternalContainer().eInverseRemove(this, Iso20022Package.REPOSITORY__DATA_DICTIONARY, Repository.class, msgs);
}
return super.eBasicRemoveFromContainerFeature(msgs);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public Object eGet(int featureID, boolean resolve, boolean coreType) {
switch (featureID) {
case Iso20022Package.DATA_DICTIONARY__TOP_LEVEL_DICTIONARY_ENTRY:
return getTopLevelDictionaryEntry();
case Iso20022Package.DATA_DICTIONARY__REPOSITORY:
return getRepository();
}
return super.eGet(featureID, resolve, coreType);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@SuppressWarnings("unchecked")
@Override
public void eSet(int featureID, Object newValue) {
switch (featureID) {
case Iso20022Package.DATA_DICTIONARY__TOP_LEVEL_DICTIONARY_ENTRY:
getTopLevelDictionaryEntry().clear();
getTopLevelDictionaryEntry().addAll((Collection<? extends TopLevelDictionaryEntry>)newValue);
return;
case Iso20022Package.DATA_DICTIONARY__REPOSITORY:
setRepository((Repository)newValue);
return;
}
super.eSet(featureID, newValue);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void eUnset(int featureID) {
switch (featureID) {
case Iso20022Package.DATA_DICTIONARY__TOP_LEVEL_DICTIONARY_ENTRY:
getTopLevelDictionaryEntry().clear();
return;
case Iso20022Package.DATA_DICTIONARY__REPOSITORY:
setRepository((Repository)null);
return;
}
super.eUnset(featureID);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public boolean eIsSet(int featureID) {
switch (featureID) {
case Iso20022Package.DATA_DICTIONARY__TOP_LEVEL_DICTIONARY_ENTRY:
return topLevelDictionaryEntry != null && !topLevelDictionaryEntry.isEmpty();
case Iso20022Package.DATA_DICTIONARY__REPOSITORY:
return getRepository() != null;
}
return super.eIsSet(featureID);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public Object eInvoke(int operationID, EList<?> arguments) throws InvocationTargetException {
switch (operationID) {
case Iso20022Package.DATA_DICTIONARY___ENTRIES_HAVE_UNIQUE_NAME__MAP_DIAGNOSTICCHAIN:
return EntriesHaveUniqueName((Map)arguments.get(0), (DiagnosticChain)arguments.get(1));
}
return super.eInvoke(operationID, arguments);
}
} //DataDictionaryImpl
|
package com.adapteach.codeassesser.verify;
import com.adapteach.codeassesser.compile.*;
import com.adapteach.codeassesser.run.CodeRunParams;
import com.adapteach.codeassesser.run.CodeRunner;
import java.util.List;
import java.util.stream.Collectors;
public class SubmissionVerifier {
private CodeCompiler compiler = new CodeCompiler();
private CodeRunner runner = new CodeRunner();
private TestClassCodeBuilder testCodeBuilder = new TestClassCodeBuilder();
public SubmissionResult verify(Submission submission) {
CompilationCheck compilation = compiler.checkCanCompile(submission.getAllCompilationUnits());
if (compilation.passed()) {
return compileWithTestsAndRun(submission);
} else {
return compilation.asSubmissionResult();
}
}
private SubmissionResult compileWithTestsAndRun(Submission submission) {
CompilationResult compilation;
try {
compilation = compileWithTests(submission);
} catch (CodeStyleException e) {
SubmissionResult result = new SubmissionResult();
result.setPass(false);
result.getCompilationErrors().add(e.getMessage());
return result;
}
if (compilation.passed()) {
return run(compilation);
} else {
return compilation.asSubmissionResult();
}
}
private CompilationResult compileWithTests(Submission submission) {
List<CompilationUnit> unsafeCompilationUnits = submission.getAllCompilationUnits();
List<CompilationUnit> safeCompilationUnits = protectAgainstInfiniteLoops(unsafeCompilationUnits);
CompilationUnit testClass = testCodeBuilder.build(submission.getAssessment());
safeCompilationUnits.add(testClass);
return compiler.compile(safeCompilationUnits);
}
private SubmissionResult run(CompilationResult compilationResult) {
CodeRunParams runParams = new CodeRunParams();
runParams.setCompilationResult(compilationResult);
runParams.setMethodName(TestClassCodeBuilder.EXECUTE);
return runner.run(runParams).asSubmissionResult();
}
private List<CompilationUnit> protectAgainstInfiniteLoops(List<CompilationUnit> unsafeCompilationUnits) {
return unsafeCompilationUnits.stream().map(CompilationUnit::safeCopy).collect(Collectors.toList());
}
}
|
package ejercicio07;
import java.util.Scanner;
public class Ejercicio07 {
public static void main(String[] args) {
Scanner entrada = new Scanner(System.in);
System.out.print("Introduce el primer número: ");
int primero = entrada.nextInt();
System.out.print("Introduce el segundo número: ");
int segundo = entrada.nextInt();
System.out.print("Introduce el tercer número: ");
int tercero = entrada.nextInt();
System.out.print("Introduce el cuarto número: ");
int cuarto = entrada.nextInt();
System.out.print("Orden de menor a mayor: ");
// primera comprobacion, obtenemos el menor y seguimos con los 3 restantes
if (primero <= segundo && primero <= tercero && primero <= cuarto) {
System.out.print(primero + ", ");
comprobacion2(segundo, tercero, cuarto);
}
else if (segundo <= primero && segundo <= tercero && segundo <= cuarto) {
System.out.print(segundo + ", ");
comprobacion2(primero, tercero, cuarto);
}
else if (tercero <= primero && tercero <= segundo && tercero <= cuarto) {
System.out.print(tercero + ", ");
comprobacion2(primero, segundo, cuarto);
}
else if (cuarto <= primero && cuarto <= segundo && cuarto <= tercero) {
System.out.print(cuarto + ", ");
comprobacion2(primero, segundo, tercero);
}
}
// segunda comprobacion, comparamos los 3 que quedaron de la primera y seguimos con los 2 restantes
static void comprobacion2(int x2, int x3, int x4) {
if (x2 <= x3 && x2 <= x4) {
System.out.print(x2 + ", ");
comprobacion3(x3, x4);
}
else if (x3 <= x2 && x3 <= x4) {
System.out.print(x3 + ", ");
comprobacion3(x2, x4);
}
else if (x3 <= x4) {
System.out.print(x4 + ", ");
comprobacion3(x2, x3);
}
else if (x4 <= x3) {
System.out.print(x4 + ", ");
comprobacion3(x2, x3);
}
}
// tercera comprobacion, comparamos los 2 que quedaron de la segunda
static void comprobacion3(int x3, int x4) {
if (x3 <= x4) {
System.out.print(x3 + ", ");
System.out.println(x4);
}
else if (x4 <= x3) {
System.out.print(x4 + ", ");
System.out.println(x3);
}
}
}
|
package com.solid.codes.cache;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class Test {
private static final Logger logger = LoggerFactory.getLogger(Test.class);
public static void main(String[] args) {
CacheTable cacheTable = new CacheTable(50);
cacheTable.put("Kareem", new Person("Kareem", 33));
while (true) {
try {
Thread.sleep(200);
if (cacheTable.get("Kareem") != null) {
logger.debug("available {}", cacheTable.get("Kareem"));
} else {
logger.debug("NO FOUND");
}
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public static class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "Name: " + name + " Age: " + age;
}
}
}
|
package main;
public class Grid {
private char[][] grid;
private int size;
private final char DEAD_CELL = '.';
private final char LIVE_CELL = 'x';
public Grid(int size) {
this.size = size;
grid = new char[size][size];
for(int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
if((int)Math.round(Math.random()) == 1){
grid[i][j] = LIVE_CELL;
}else {
grid[i][j] = DEAD_CELL;
}
}
}
}
public String toString() {
String string = "";
for(int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
string += grid[i][j] + " ";
}
string += "\n";
}
return string;
}
public void newGeneration() {
char[][] tempGrid = new char[size][size];
//For every cell in grid
for(int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
//Count living cells surrounding current cell
int num_live_cells = 0;
for(int k = -1; k < 2; k++) {
for(int l = -1; l < 2; l++) {
boolean currentCell = (k==0 && l==0);
boolean negativeBounds = (i+k < 0 || j+l < 0);
boolean overBounds = (i+k >= size || j+l >= size);
if(!currentCell && !negativeBounds && !overBounds) {
int cell = grid[i+k][j+l];
if(cell == LIVE_CELL) {
num_live_cells++;
}
}
}
}
//Apply rules and put cell in tempGrid
char cell = grid[i][j];
if(cell == DEAD_CELL && num_live_cells == 3) {
tempGrid[i][j] = LIVE_CELL;
}else if(cell == LIVE_CELL && (num_live_cells < 2 || num_live_cells > 3)) {
tempGrid[i][j] = DEAD_CELL;
}else{
tempGrid[i][j] = cell;
}
}
}
//Set grid to new updated grid
grid = tempGrid;
}
}
|
package edu.upenn.cis455.Indexer.EMRIndexer;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.json.simple.JSONObject;
import com.amazonaws.AmazonClientException;
import com.amazonaws.AmazonServiceException;
import com.amazonaws.auth.profile.ProfileCredentialsProvider;
import com.amazonaws.regions.Regions;
import com.amazonaws.services.dynamodbv2.AmazonDynamoDB;
import com.amazonaws.services.dynamodbv2.AmazonDynamoDBClientBuilder;
import com.amazonaws.services.dynamodbv2.model.AttributeValue;
import com.amazonaws.services.dynamodbv2.model.PutItemRequest;
import com.amazonaws.services.dynamodbv2.model.PutItemResult;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3ClientBuilder;
import com.amazonaws.services.s3.model.ListObjectsV2Request;
import com.amazonaws.services.s3.model.ListObjectsV2Result;
import com.amazonaws.services.s3.model.S3Object;
import com.amazonaws.services.s3.model.S3ObjectInputStream;
import com.amazonaws.services.s3.model.S3ObjectSummary;
public class UploadToDynamo {
public static void main(String[] args) {
final String USAGE = "\n" +
"To run this example, supply the name of a bucket to list!\n" +
"\n" +
"Ex: ListObjects <bucket-name>\n";
if (args.length < 1) {
System.out.println(USAGE);
System.exit(1);
}
String bucket_name = args[0];
System.out.format("Objects in S3 bucket %s:\n", bucket_name);
final AmazonS3 s3 = AmazonS3ClientBuilder.standard().withRegion(Regions.US_EAST_1).build();
ProfileCredentialsProvider credentialsProvider = new ProfileCredentialsProvider();
try {
credentialsProvider.getCredentials();
} catch (Exception e) {
throw new AmazonClientException(
"Cannot load the credentials from the credential profiles file. " +
"Please make sure that your credentials file is at the correct " +
"location (~/.aws/credentials), and is in valid format.",
e);
}
AmazonDynamoDB client = AmazonDynamoDBClientBuilder.standard()
.withCredentials(credentialsProvider)
.withRegion("us-east-1")
.build();
ListObjectsV2Request req = new ListObjectsV2Request().withBucketName(bucket_name).withPrefix("output/");
ListObjectsV2Result listing = s3.listObjectsV2(req);
for (S3ObjectSummary os: listing.getObjectSummaries()) {
System.out.println("* " + os.getKey());
if(!os.getKey().startsWith("output/part")) {
continue;
}
try {
S3Object o = s3.getObject(bucket_name, os.getKey());
S3ObjectInputStream s3is = o.getObjectContent();
InputStreamReader streamReader = new InputStreamReader(s3is);
BufferedReader reader = new BufferedReader(streamReader);
String line;
while((line=reader.readLine())!=null) {
String[] splits = line.split("\\s+");
Map<String,AttributeValue> attributeValues = new HashMap<>();
attributeValues.put("word", new AttributeValue().withS(splits[0]));
Map<String,Float> map = new HashMap<String, Float>();
for(int i = 1; i< splits.length; i+=2) {
//attributeValues.put(splits[i], new AttributeValue().withN(splits[i+1]));
map.put(splits[i],Float.parseFloat(splits[i+1]));
}
JSONObject text = new JSONObject(map);
attributeValues.put("info", new AttributeValue().withS(text.toString()));
PutItemRequest putItemRequest = new PutItemRequest()
.withTableName("InvertedIndex")
.withItem(attributeValues);
PutItemResult putItemResult = client.putItem(putItemRequest);
}
s3is.close();
} catch (AmazonServiceException e) {
System.err.println(e.getErrorMessage());
System.exit(1);
} catch (IOException e) {
System.err.println(e.getMessage());
System.exit(1);
}
System.out.println("Done!");
}
client.shutdown();
s3.shutdown();
System.out.println("List Done!");
}
}
|
package by.academy.classwork.lesson4;
public class Task23 {
// 23.Вычислить : 1+2+4+8+...+ 2 в 10 степени. ???условие
}
|
package tarea.interfaz.matricula;
import java.util.Scanner;
public class MatriculaESPE implements MatriculaInterfaz{
Scanner entrada = new Scanner(System.in);
@Override
public void identificacion(int cedula, String contraseņa) {
// TODO Auto-generated method stub
System.out.println("Bienvenido a nuestro sistema de matricula ESPE");
System.out.println("Ingrese su cedula: ");
cedula = entrada.nextInt();
System.out.println("Ingrese su contraseņa: ");
contraseņa = entrada.nextLine();
}
@Override
public void semestreDelEstudiante(byte semestreEstudiante) {
// TODO Auto-generated method stub
System.out.println("Ingrese en que semestre entrara: ");
semestreEstudiante = entrada.nextByte();
}
@Override
public void cuposDisponibles(int cupos) {
// TODO Auto-generated method stub
System.out.println("Actualmente solo existen un total de "+cupos+"para su semestre");
}
@Override
public void fechaAMatricular(String fechaMatricula) {
// TODO Auto-generated method stub
System.out.println("La fecha para su matricula es "+fechaMatricula);
}
@Override
public void materiasATomar(byte semestreEstudiante, String materia1, String materia2,
String materia3, String materia4, String materia5) {
// TODO Auto-generated method stub
System.out.println("Usted cumple con los requisitos para");
System.out.println("matricularse en este semestre "+semestreEstudiante);
System.out.println("Eliga en que materias quiere registrarse para este semestre");
System.out.println("Desea matricularse en "+materia1+"?");
System.out.println("Desea matricularse en "+materia2+"?");
System.out.println("Desea matricularse en "+materia3+"?");
System.out.println("Desea matricularse en "+materia4+"?");
System.out.println("Desea matricularse en "+materia5+"?");
System.out.println("Usted ha sido exitosamente matriculado");
}
}
|
package pooPractica.Vehiculos;
/**
*
* @author RadW
*/
public class Camion extends Vehiculo {
private int capacidadCarga;
}
|
package com.example.longxiang0001;
import android.os.Bundle;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import com.example.longxiang0001.util.DisplayUtil;
import com.example.longxiang0001.util.Utils;
public class MainActivity extends AppCompatActivity {
private TextView text_screen;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//获取id
text_screen = findViewById(R.id.test_screen);
int dip_10 = Utils.dip2px(this,10L);
text_screen.setPadding(dip_10, dip_10, dip_10, dip_10);
text_screen.setBackgroundColor(0xff00ffff);
text_screen.setTextColor(0xff333333);
showScreenInfo();
}
private void showScreenInfo(){
int width = DisplayUtil.getScreenWidth( this);
int height = DisplayUtil.getScreenWidth( this);
int sensity = DisplayUtil.getScreenWidth( this);
String info = String.format("当前屏幕的宽度是%dpx,高度是%dpx,像数密度是%f",width,height,sensity);
text_screen.setText(info);
}
}
|
package org.xtext.template.ui.highlighting;
import org.eclipse.swt.graphics.RGB;
import org.eclipse.xtext.ui.editor.syntaxcoloring.IHighlightingConfigurationAcceptor;
import org.eclipse.xtext.ui.editor.utils.TextStyle;
import org.eclipse.xtext.xbase.lib.ObjectExtensions;
import org.eclipse.xtext.xbase.lib.Procedures.Procedure1;
import org.eclipse.xtext.xbase.lib.Procedures.Procedure3;
import org.eclipse.xtext.xbase.ui.highlighting.XbaseHighlightingConfiguration;
@SuppressWarnings("all")
public class TemplateHighlightingConfiguration extends XbaseHighlightingConfiguration {
public final static String TEXT = "template.text";
public final static String ESCAPE = "teamplate.escape";
public void configure(final IHighlightingConfigurationAcceptor acceptor) {
TextStyle _staticText = this.staticText();
acceptor.acceptDefaultHighlighting(TemplateHighlightingConfiguration.TEXT, "Text", _staticText);
TextStyle _staticEscape = this.staticEscape();
acceptor.acceptDefaultHighlighting(TemplateHighlightingConfiguration.ESCAPE, "Statement/Expression Escape Symbols", _staticEscape);
final Procedure3<String,String,TextStyle> _function = new Procedure3<String,String,TextStyle>() {
public void apply(final String id, final String name, final TextStyle style) {
RGB _rGB = new RGB(230, 230, 230);
style.setBackgroundColor(_rGB);
acceptor.acceptDefaultHighlighting(id, name, style);
}
};
super.configure(new IHighlightingConfigurationAcceptor() {
public void acceptDefaultHighlighting(String id,String name,TextStyle style) {
_function.apply(id,name,style);
}
});
}
public TextStyle staticText() {
TextStyle _defaultTextStyle = this.defaultTextStyle();
TextStyle _copy = _defaultTextStyle.copy();
final Procedure1<TextStyle> _function = new Procedure1<TextStyle>() {
public void apply(final TextStyle it) {
RGB _rGB = new RGB(0, 0, 0);
it.setColor(_rGB);
}
};
TextStyle _doubleArrow = ObjectExtensions.<TextStyle>operator_doubleArrow(_copy, _function);
return _doubleArrow;
}
public TextStyle staticEscape() {
TextStyle _defaultTextStyle = this.defaultTextStyle();
TextStyle _copy = _defaultTextStyle.copy();
final Procedure1<TextStyle> _function = new Procedure1<TextStyle>() {
public void apply(final TextStyle it) {
RGB _rGB = new RGB(180, 180, 180);
it.setColor(_rGB);
RGB _rGB_1 = new RGB(230, 230, 230);
it.setBackgroundColor(_rGB_1);
}
};
TextStyle _doubleArrow = ObjectExtensions.<TextStyle>operator_doubleArrow(_copy, _function);
return _doubleArrow;
}
}
|
package com.cl.earosb.iipzs;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.annotation.TargetApi;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import com.cl.earosb.iipzs.models.Message;
import com.cl.earosb.iipzs.models.User;
import com.github.kevinsawicki.http.HttpRequest;
import com.google.gson.Gson;
import java.util.HashMap;
import java.util.Map;
/**
* A login screen that offers login via email/password.
*/
public class LoginActivity extends AppCompatActivity {
/**
* Keep track of the login task to ensure we can cancel it if requested.
*/
private UserLoginTask mAuthTask = null;
// UI references.
private EditText mUsernameView;
private EditText mPasswordView;
private View mProgressView;
private View mLoginFormView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
// Set up the login form.
mUsernameView = (EditText) findViewById(R.id.username);
mPasswordView = (EditText) findViewById(R.id.password);
mPasswordView.setOnEditorActionListener(new TextView.OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView textView, int id, KeyEvent keyEvent) {
if (id == R.id.login || id == EditorInfo.IME_NULL) {
attemptLogin();
return true;
}
return false;
}
});
Button mSignInButton = (Button) findViewById(R.id.email_sign_in_button);
mSignInButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
attemptLogin();
}
});
mLoginFormView = findViewById(R.id.login_form);
mProgressView = findViewById(R.id.login_progress);
// Redirige a MainActivity si el usuario esta logueado
boolean logueado = getSharedPreferences("PREFERENCE", MODE_PRIVATE).getBoolean("logueado", false);
if (logueado) {
startActivity(new Intent(this, MainActivity.class));
}
}
/**
* Attempts to sign in or register the account specified by the login form.
* If there are form errors (invalid email, missing fields, etc.), the
* errors are presented and no actual login attempt is made.
*/
private void attemptLogin() {
if (mAuthTask != null) {
return;
}
// Reset errors.
mUsernameView.setError(null);
mPasswordView.setError(null);
// Store values at the time of the login attempt.
String email = mUsernameView.getText().toString();
String password = mPasswordView.getText().toString();
boolean cancel = false;
View focusView = null;
// Check for a valid password, if the user entered one.
if (!TextUtils.isEmpty(password) && !isPasswordValid(password)) {
mPasswordView.setError(getString(R.string.error_invalid_password));
focusView = mPasswordView;
cancel = true;
}
if (cancel) {
// There was an error; don't attempt login and focus the first
// form field with an error.
focusView.requestFocus();
} else {
// Show a progress spinner, and kick off a background task to
// perform the user login attempt.
showProgress(true);
mAuthTask = new UserLoginTask(email, password);
mAuthTask.execute((Void) null);
}
}
private boolean isPasswordValid(String password) {
return password.length() > 4;
}
/**
* Shows the progress UI and hides the login form.
*/
@TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
private void showProgress(final boolean show) {
// On Honeycomb MR2 we have the ViewPropertyAnimator APIs, which allow
// for very easy animations. If available, use these APIs to fade-in
// the progress spinner.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
int shortAnimTime = getResources().getInteger(android.R.integer.config_shortAnimTime);
mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
mLoginFormView.animate().setDuration(shortAnimTime).alpha(
show ? 0 : 1).setListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
}
});
mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
mProgressView.animate().setDuration(shortAnimTime).alpha(
show ? 1 : 0).setListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
}
});
} else {
// The ViewPropertyAnimator APIs are not available, so simply show
// and hide the relevant UI components.
mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
}
}
public class UserLoginTask extends AsyncTask<Void, Void, Message> {
private final String mEmail;
private final String mPassword;
UserLoginTask(String email, String password) {
mEmail = email;
mPassword = password;
}
@Override
protected Message doInBackground(Void... params) {
try {
Map<String, String> data = new HashMap<String, String>();
data.put("username", mEmail);
data.put("password", mPassword);
String response = HttpRequest.post("https://icilicafalpzs.cl/api/v1/login").form(data).body();
return new Gson().fromJson(response, Message.class);
} catch (Exception e) {
return new Message(true, "Error de conexión", null);
}
}
@Override
protected void onPostExecute(Message msg) {
mAuthTask = null;
showProgress(false);
if (!msg.isError()) {
User user = msg.getUser();
getSharedPreferences("PREFERENCE", MODE_PRIVATE).edit().putBoolean("logueado", true).apply();
getSharedPreferences("PREFERENCE", MODE_PRIVATE).edit().putString("username", user.getUsername()).apply();
getSharedPreferences("PREFERENCE", MODE_PRIVATE).edit().putString("email", user.getEmail()).apply();
getSharedPreferences("PREFERENCE", MODE_PRIVATE).edit().putString("token_api", user.getToken_api()).apply();
startActivity(new Intent(getApplicationContext(), MainActivity.class));
} else {
mPasswordView.setError(msg.getMsg());
mPasswordView.requestFocus();
}
}
@Override
protected void onCancelled() {
mAuthTask = null;
showProgress(false);
}
}
}
|
package org.mycompany;
import org.apache.camel.Exchange;
import java.io.StringReader;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.xml.sax.InputSource;
public class MyBeanProcessor {
public MyBeanProcessor() {
// should do nothing
}
public void processExchange(Exchange exchange) {
// Get your XML from exchange (maybe, your need to convert them to DOM Document
// before processing)
String xmlStr = exchange.getIn().getBody(String.class);
System.out.println(xmlStr);
Document doc = convertStringToXMLDocument(xmlStr);
}
private static Document convertStringToXMLDocument(String xmlString) {
// Parser that produces DOM object trees from XML content
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
// API to obtain DOM Document instance
DocumentBuilder builder = null;
try {
// Create DocumentBuilder with default configuration
builder = factory.newDocumentBuilder();
// Parse the content to Document object
Document doc = builder.parse(new InputSource(new StringReader(xmlString)));
System.out.println(doc);
return doc;
} catch (Exception e) {
System.out.print(e);
e.printStackTrace();
}
return null;
}
}
|
package com.zjf.myself.codebase.util;
import android.widget.Toast;
import com.zjf.myself.codebase.application.AppController;
import com.zjf.myself.codebase.helper.FileHelper;
import java.io.IOException;
/**
* Created by Administrator on 2017/3/16.
*/
public class ZjfReadFile {
public static String readFile(String fileName){
String detail = "";
FileHelper fHelper2 = new FileHelper(AppController.getInstance().getTopAct());
try {
detail = fHelper2.read(fileName);
} catch (IOException e) {
e.printStackTrace();
}
return detail;
}
}
|
package Supermercado;
public class Funcionario extends Pessoa {
private static int totalID;
private final int idFunc;
private int cargo;
Funcionario (String nome, String login, String senha, int cargo) {
super(nome,login,senha);
Funcionario.totalID++;
this.idFunc = totalID;
this.cargo = cargo;
}
public int getIDFunc() {
return this.idFunc;
}
public int getCargo(){
return this.cargo;
}
}
|
package uebeungFolie18;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
public class UebungFolie18 {
public static void main(String[] args) throws IOException {
/*
* Um etwas einzulesen brauchen wir erstmal einen InputStream
* (eingehendenDatenstrom) Da wir von der Konsole einlesen möchten benutzen wir
* System.in
*/
InputStream konsolenInput = System.in;
// Diesen Strom können wir mit einem InputStreamReader lesen.
InputStreamReader konsolenLeser = new InputStreamReader(konsolenInput);
// Da der InputStreamReader nur Byte lesen kann wir aber mehr als nur paar Bytes
// wollen können wir diesen erweitern. Zur Vefügung stehen: BufferedReader und
// Scanner
BufferedReader finalreader = new BufferedReader(konsolenLeser);
/*
* Nun können wir ganz angenehm aus der Konsole mit einem readLine lesen. Warum
* readLine() und nicht read() ? read ließt nicht die komplette zeile! sonder
* nur einen Bruchteil Wenn ihr es testen wollt könnt ihr einfach diesen Code
* auskommentieren.
*/
// System.out.println("Gebe jetzt deine zahl zum prüfen ein");
// int readZahl = finalreader.read();
// System.out.println("Die zahl die mit read eingelesen wurde ist:"+readZahl);
// System.out.println("gebe deine zahl erneut ein");
// finalreader.readLine();
// String readLineZahl = finalreader.readLine();
// System.out.println("Die zahl mit dem Readline:"+readLineZahl);
// Hier ist der code für die Aufgabe
String uebungString = finalreader.readLine();
// da readLine einen String einliest muessen wir diesen in eine Integer zahl
// umwandeln
int uebungZahl = Integer.parseInt(uebungString);
// Wir pruefen ob die Zahl groeßer als 0 ist
if (uebungZahl > 0) {
// da die Zahl groeßer als 0 ist kommen wir hier rein und multiplizieren sie mit
// -1 um sie zu negieren
uebungZahl = uebungZahl * (-1);
System.out.println(uebungZahl);
} else if (uebungZahl == 0) {
// wenn die zahl gleich 0 ist sagen wir das dem User
System.out.println("Hey deine Zahl ist 0. Bitte gebe doch eine positive Zahl ein die groeßer als 0 ist.");
} else {
// und hier kommen wir reinn falls sie kleiner als 0 ist
System.out.println("Deine Zahl ist bereits negativ! Gebe doch eine positive Zahl ein.");
}
}
}
|
package com.maliang.core.service;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import org.bson.types.ObjectId;
public class DBData {
public final static Map<String,Object> ObjectMetadataMap = new HashMap<String,Object>();
public final static Map<String,Object> DBDataMap = new HashMap<String,Object>();
static {
initMetadata();
initBrands();
initProductType();
initProduct();
initUserGrade();
initUser();
initUserAddress();
//System.out.println(DBDataMap.get("Product"));
}
public static void main(String[] args) {
Random r = new Random();
for(int i = 0; i < 10;i++){
System.out.println(r.nextInt(10));
}
}
/**
*
* Product:[{name:滋阴乳液125ml,product_type:面霜/乳液,brand:雪花秀,price:368.00,picture:pic,description:aa},"
+ "{name:弹力面霜75ml,product_type:面霜/乳液,brand:雪花秀,price:520.00,picture:pic,description:aa},"
+ "{name:天气丹华泫平衡化妆水150ml,product_type:保湿水,brand:Whoo,price:478.00,picture:pic,description:aa}]
* **/
private static void initProduct(){
String ps = "Product:[{name:滋阴乳液125ml,product_type:面霜/乳液,brand:雪花秀,price:368.00,picture:pic,description:aa},"
+ "{name:弹力面霜75ml,product_type:面霜/乳液,brand:雪花秀,price:520.00,picture:pic,description:aa},"
+ "{name:天气丹华泫平衡化妆水150ml,product_type:保湿水,brand:Whoo,price:478.00,picture:pic,description:aa}]";
DBDataMap.putAll(MapHelper.curlyToMap(ps));
rightFieldValue("Product");
}
public static List<Map<String,Object>> list(String coll){
return (List<Map<String,Object>>)DBData.DBDataMap.get(coll);
}
public static Map<String,Object> getRandom(String collSymbol){
List<Map<String,Object>> products = (List<Map<String,Object>>)DBDataMap.get(collSymbol);
if(products == null || products.size() == 0){
return null;
}
return products.get(new Random().nextInt(products.size()));
}
private static void innerObject(Map<String,Object> obj,String fieldName,String collName){
innerObject(obj,fieldName,collName,"name");
}
private static void innerObject(Map<String,Object> obj,String fieldName,String collName,String columnName){
Object value = obj.get(fieldName);
value = get(collName,columnName,value);
obj.put(fieldName, value);
}
public static Map<String,Object> get(String collection,String key,Object value){
List<Map<String,Object>> list = (List<Map<String,Object>>)DBDataMap.get(collection);
for(Map<String,Object> obj:list){
if(value.equals(obj.get(key))){
return obj;
}
}
return null;
}
private static void initBrands(){
String[] bnames = new String[]{"海蓝之谜","sisley","雪花秀","黛珂","Whoo","pola","科莱丽"};
List<Map<String,Object>> brands = new ArrayList<Map<String,Object>>();
DBDataMap.put("Brand", brands);
for(int i = 0; i < bnames.length; i++){
ObjectId id = new ObjectId();
Map<String,Object> brand = new HashMap<String,Object>();
brand.put("id", id);
brand.put("name", bnames[i]);
brands.add(brand);
}
}
private static void initProductType(){
String[] tnames = new String[]{"洁面","卸妆","爽肤水","保湿水","精华","面霜/乳液","眼霜","面膜","去角质产品"};
List<Map<String,Object>> types = new ArrayList<Map<String,Object>>();
DBDataMap.put("ProductType", types);
for(int i = 0; i < tnames.length; i++){
ObjectId id = new ObjectId();
Map<String,Object> type = new HashMap<String,Object>();
type.put("id", id);
type.put("name", tnames[i]);
types.add(type);
}
}
private static void initUserGrade(){
String us = "UserGrade:[{name:普通会员,discount:90.00},"
+ "{name:黄金会员,discount:85.00},"
+ "{name:白金会员,discount:80.00},"
+ "{name:钻石会员,discount:75.00}]";
DBDataMap.putAll(MapHelper.curlyToMap(us));
rightFieldValue("UserGrade");
}
private static void rightFieldValue(String coll){
List<Map<String,Object>> dataList = (List<Map<String,Object>>)DBDataMap.get(coll);
List<Map<String,Object>> fields = (List<Map<String,Object>>)MapHelper.readValue(ObjectMetadataMap, coll+".fields");
for(Map<String,Object> data:dataList){
data.put("id", new ObjectId());
for(Map<String,Object> field : fields){
Object type = field.get("type");
String fieldName = (String)field.get("name");
Object value = data.get(fieldName);
if("double".equals(type)){
try {
data.put(fieldName, new Double(value.toString()));
}catch(Exception e){}
}else if("int".equals(type)){
try {
data.put(fieldName, new Integer(value.toString()));
}catch(Exception e){}
}else if("object".equals(type)){
String related = (String)field.get("related");
innerObject(data,fieldName,related);
}
}
}
}
public static Map<String,Object> getMetadata(String coll){
return (Map<String,Object>)ObjectMetadataMap.get(coll);
}
private static void initUser(){
String us = "User:[{user_name:wangmx,password:111111,real_name:王美霞,mobile:13456789776,email:wmx@tm.com,user_grade:黄金会员},"
+ "{user_name:wangfan,password:111111,real_name:王凡,mobile:13298790987,email:wf@tm.com,user_grade:普通会员},"
+ "{user_name:wangzq,password:111111,real_name:王梓青,mobile:13876598708,email:wzq@tm.com,user_grade:钻石会员},"
+ "{user_name:wangyn,password:111111,real_name:王易楠,mobile:13609873451,email:wyn@tm.com,user_grade:白金会员},"
+ "{user_name:wangml,password:111111,real_name:王美良,mobile:13876789034,email:wml@tm.com,user_grade:普通会员},"
+ "{user_name:zhanghui,password:111111,real_name:张惠,mobile:13543456765,email:zh@tm.com,user_grade:黄金会员},"
+ "{user_name:zhaoms,password:111111,real_name:赵默笙,mobile:13456789776,email:zms@tm.com,user_grade:白金会员}]";
DBDataMap.putAll(MapHelper.curlyToMap(us));
rightFieldValue("User");
}
private static void initUserAddress(){
String us = "UserAddress:[{address:南京市鼓楼区龙江小区蓝天园26号402室内,consignee:王美霞,mobile:13456789776,default:1,user:wangmx},"
+ "{address:东阳市商城5号楼12号毛线摊,consignee:王振华,mobile:18957951177,default:0,user:wangmx},"
+ "{address:上海市浦东区张杨路1348号305室,consignee:王凡,mobile:13761136601,default:0,user:wangmx}]";
Map<String,Object> data = MapHelper.curlyToMap(us);
DBDataMap.putAll(data);
List<Map<String,Object>> addresses = (List<Map<String,Object>>)data.get("UserAddress");
for(Map<String,Object> address:addresses){
address.put("id", new ObjectId());
innerObject(address,"user","User","user_name");
}
}
/**
* Product {
* _id:objectId,
* name:'Product',
* fields:[{name:name,type:string,label:名称,unique:{scope:brand}},
* {name:product_type,type:object,related:ProductType,label:分类,edit:{type:select}},
* {name:brand,type:object,related:Brand,label:品牌},
* {name:price,type:double,label:价格},
* {name:production_date,type:date,label:生产日期},
* {name:expiry_date,type:date,label:有效期},
* {name:picture,type:string,label:图片,edit:{type:file}},
* {name:description,type:string,label:描述,edit:{type:html}}
* ]
* }
*
*
* User {
* _id:objectId,
* name:User,
* fields:[{name:user_name,type:string,label:用户名},
* {name:password,type:string,label:密码},
* {name:real_name,type:string,label:真实姓名},
* {name:birthday,type:date,label:真实姓名},
* {name:mobile,type:string,label:手机号码},
* {name:email,type:string,label:email},
* {name:user_grade,type:object,related:UserGrade,label:会员等级}]
* }
*
* UserGrade {
* _id:objectId,
* name:'UserGrade',
* fields:[{name:'name',type:'string',label:'等级 名称'},
* {name:'discount',type:'double',label:'商品折扣'}]
* }
*
* UserAddress {
* _id:objectId,
* name:UserAddress,
* fields:[{name:address,type:string,label:详细地址},
* {name:consignee,type:string,label:收货人},
* {name:mobile,type:string,label:手机号码},
* {name:default,type:int,label:是否默认},
* {name:user,type:object,related:User,label:所属会员}]
* }
*
*
* Order {sn,totalPrice,user,status,pay_status,totalNum,
* address:{address,consignee,mobile}
* items:{product,num,price,status}}
*
*
* Order {
* _id:objectId,
* name:Order,
* fields:[{name:sn,type:string,label:订单编号},
* {name:total_price,type:double,label:总价},
* {name:user,type:object,related:User,label:会员},
* {name:status,type:int,label:状态},
* {name:pay_statys,type:int,label:支付状态},
* {name:total_num,type:int,label:总数量},
* {name:address,type:object,related:inner,label:收货地址},
* {name:items,type:list,related:inner,label:订单明细}],
* address:{
* fields:[{name:address,type:string,label:详细地址},
* {name:consignee,type:string,label:收货人},
* {name:mobile,type:string,label:手机号码}]},
* items:{
* fields:[{name:product,type:object,related:Product,label:商品},
* {name:num,type:int,label:订购数量},
* {name:price,type:double,label:订购价格},
* {name:status,type:int,label:状态}]}
* }
* **/
private static void initMetadata(){
String product = "{_id:objectId,name:Product,"
+ "fields:[{name:name,type:string,label:名称,unique:{scope:brand}},"
+ "{name:product_type,type:object,related:ProductType,label:分类,edit:{type:select}},"
+ "{name:brand,type:object,related:Brand,label:品牌,edit:{type:select}},"
+ "{name:price,type:double,label:价格},"
+ "{name:production_date,type:date,label:生产日期},"
+ "{name:expiry_date,type:date,label:有效期},"
+ "{name:picture,type:string,label:图片,edit:{type:file}},"
+ "{name:description,type:string,label:描述,edit:{type:html}}]}";
ObjectMetadataMap.put("Product", MapHelper.curlyToMap(product));
String brand = "{_id:objectId,name:Brand,fields:[{name:name,type:string,label:名称}]}";
ObjectMetadataMap.put("Brand", MapHelper.curlyToMap(brand));
String productType =" {_id:objectId,name:ProductType,fields:[{name:name,type:string,label:名称}]}";
ObjectMetadataMap.put("ProductType", MapHelper.curlyToMap(productType));
String user = "{_id:objectId,name:User,"
+ "fields:[{name:user_name,type:string,label:用户名},"
+ "{name:password,type:string,label:密码},"
+ "{name:real_name,type:string,label:真实姓名},"
+ "{name:birthday,type:date,label:生日},"
+ "{name:mobile,type:string,label:手机号码},"
+ "{name:email,type:string,label:email},"
+ "{name:user_grade,type:object,related:UserGrade,label:会员等级}]}";
ObjectMetadataMap.put("User", MapHelper.curlyToMap(user));
String userGrade = "{_id:objectId,name:UserGrade,"
+ "fields:[{name:name,type:string,label:等级名称},"
+ "{name:discount,type:double,label:商品折扣}]}";
ObjectMetadataMap.put("UserGrade", MapHelper.curlyToMap(userGrade));
String order = "{_id:objectId,name:Order,"
+ "fields:[{name:sn,type:string,label:订单编号},"
+ "{name:total_price,type:double,label:总价},"
+ "{name:user,type:object,related:User,label:会员},"
+ "{name:status,type:int,label:状态},"
+ "{name:pay_statys,type:int,label:支付状态},"
+ "{name:total_num,type:int,label:总数量},"
+ "{name:address,type:object,related:inner,label:收货地址},"
+ "{name:items,type:list,related:inner,label:订单明细}],"
+ "address:{"
+ "fields:[{name:address,type:string,label:详细地址},"
+ "{name:consignee,type:string,label:收货人},"
+ "{name:mobile,type:string,label:手机号码}]},"
+ "items:{"
+ "fields:[{name:product,type:object,related:Product,label:商品},"
+ "{name:num,type:int,label:订购数量},"
+ "{name:price,type:double,label:订购价格},"
+ "{name:status,type:int,label:状态}]}}";
ObjectMetadataMap.put("Order", MapHelper.curlyToMap(order));
}
}
|
package poeMultitool;
import com.gargoylesoftware.htmlunit.*;
import com.gargoylesoftware.htmlunit.html.*;
import java.awt.Frame;
import java.io.IOException;
import java.util.List;
import java.util.logging.Level;
/**
* @author Haris Koktsidis
*/
public class PoeAutoMessageRefresh
{
/**
* Simulates a chrome browser and logs on to the Path Of Exile site, reads
* and returns the number of new mails currently waiting in the mailbox.
* There are 2 sites we need to check. When the user does have new mails the link href
* changes to "/private-messages/inbox" otherwise it's the default "/private-messages".
* @param guiFrame A frame to display a pop up error in case something goes wrong.
* @param accountName a String containing the account name of the player.
* @param password a String containing the password of the player.
* @return -1 if an error has occurred or any other number >=0 indicating the number of new messages.
*/
public int checkMessages(Frame guiFrame, String accountName, String password)
{
java.util.logging.Logger.getLogger("com.gargoylesoftware").setLevel(Level.OFF); // Turning off warnings by htmlUnit
WebClient webClient = new WebClient(BrowserVersion.CHROME); // Simulating a Chrome browser
try
{
// Grabbing the login site and the correct form...
HtmlPage poeLogin = webClient.getPage("https://www.pathofexile.com/login");
List<HtmlForm> logins = poeLogin.getForms();
HtmlForm first = logins.get(0);
// Grabbing the Account name/Password inputs and the submit button...
final HtmlSubmitInput login = first.getInputByValue("Login");
final HtmlTextInput usernameTextField = first.getInputByName("login_email");
final HtmlPasswordInput passwordTextField = first.getInputByName("login_password");
// Setting the textfields according to the given Accountname/password...
usernameTextField.setValueAttribute(accountName);
passwordTextField.setValueAttribute(password);
// Submitting the form...
HtmlPage loggedIn = login.click();
// Switching to logged in site...
loggedIn = webClient.getPage("http://www.pathofexile.com/my-account");
try
{ // Verifying succesful login by looking up for the messages link...
HtmlAnchor anchorLink = loggedIn.getAnchorByHref("/private-messages/inbox");
String substring[] = (anchorLink.getTextContent().split(" "));
webClient.closeAllWindows();
return Integer.parseInt(substring[0]);
}
catch(ElementNotFoundException exception)
{ // Or the specified link was not found, trying to verify with default link.
try
{
HtmlAnchor anchorLink = loggedIn.getAnchorByHref("/private-messages");
webClient.closeAllWindows();
return 0;
}
catch (ElementNotFoundException ex)
{ // Both links failed, we are not logged in, popup error message and return
HelpfulFunctions.displayPopupError(ex.getMessage(), 151);
webClient.closeAllWindows();
return -1;
}
}
}
catch (IOException | FailingHttpStatusCodeException failToOpenSite)
{ // Error logging..
HelpfulFunctions.displayPopupError(failToOpenSite.getMessage(), 152);
webClient.closeAllWindows();
return -1;
}
}
}
|
package com.programapprentice.app;
/**
* User: program-apprentice
* Date: 8/9/15
* Time: 9:30 PM
*/
public class SetMatrixZeroes_73 {
/** Brute force:
* have a vector store which row or column need to be as zero
*/
public void setZeroes_bruteforce(int[][] matrix) {
if(matrix == null) {
return;
}
int height = matrix.length;
if(height == 0) {
return;
}
int width = matrix[0].length;
if(width == 0) {
return;
}
boolean[] rowVector = new boolean[height];
boolean[] colVector = new boolean[width];
for(int i = 0; i < height; i ++) {
for(int j = 0; j < width; j++) {
if(matrix[i][j] == 0) {
rowVector[i] = true;
colVector[j] = true;
}
}
}
for(int i = 0; i < height; i ++) {
for (int j = 0; j < width; j++) {
if(rowVector[i]|| colVector[j]) {
matrix[i][j] = 0;
}
}
}
}
public void setZeroes(int[][] matrix) {
if(matrix == null) {
return;
}
int height = matrix.length;
if(height == 0) {
return;
}
int width = matrix[0].length;
if(width == 0) {
return;
}
boolean isFirstRowZero = false;
boolean isFirstColZero = false;
for(int i = 0; i < width; i++) {
if(matrix[0][i] == 0) {
isFirstRowZero = true;
break;
}
}
for(int i = 0; i < height; i++) {
if(matrix[i][0] == 0) {
isFirstColZero = true;
break;
}
}
for(int i = 1; i < height; i++) {
for(int j = 1; j < width; j++) {
if(matrix[i][j] == 0) {
matrix[0][j] = 0;
matrix[i][0] = 0;
}
}
}
for(int i = 1; i < height; i++) {
for(int j = 1; j < width; j++) {
if(matrix[0][j] == 0 || matrix[i][0] == 0) {
matrix[i][j] = 0;
}
}
}
if(isFirstColZero) {
for(int i = 0; i < height; i++) {
matrix[i][0] = 0;
}
}
if(isFirstRowZero) {
for(int i = 0; i < width; i++) {
matrix[0][i] = 0;
}
}
}
}
|
package com.stepdefinition;
import java.io.IOException;
import org.openqa.selenium.WebDriver;
import com.pages.Contact_page;
import cucumber.api.java.en.Given;
import cucumber.api.java.en.Then;
import cucumber.api.java.en.When;
public class Contact_stepdefinition {
WebDriver driver;
public Contact_page con=new Contact_page(driver); //Contact_page object creation
@Given("^the user launch the demoblaze site$")
public void the_user_launch_the_demoblaze_site() {
con.Browserandapp_launch("chrome", "https://www.demoblaze.com/"); //Accessing the browser and application launch method
}
@When("^the user clicks on contact link$")
public void the_user_clicks_on_contact_link() {
con.Contact_link(); //Accesssing the Clicking contact link method
}
@When("^the user enter the email name and message$")
public void the_user_enter_the_email_name_and_message() {
con.Details_Enter("svssnarasimharao@gmail.com", "narasimharao", "Good website"); // Passing parameters to send details method
}
@Then("^the user get a pop window message$")
public void the_user_get_a_pop_window_message() throws InterruptedException, IOException {
con.Get_message(); //Acccessing the message getting method
}
}
|
package com.lsjr.zizisteward.activity.classly.adapter;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import com.lsjr.zizisteward.R;
import com.lsjr.zizisteward.bean.Commodity;
import com.lsjr.zizisteward.http.AppUrl;
import java.util.ArrayList;
import java.util.List;
/**
* Created by admin on 2017/5/12.
*/
public class GridViewAdapter extends RecyclerView.Adapter<GridViewAdapter.ViewHolder> {
private View headView;
private View foodView;
private LayoutInflater inflater;
private Context mContent;
private List<Commodity.FamousShopBean> mFamousShop=new ArrayList<>();
public GridViewAdapter(Context content) {
this.mContent = content;
inflater=LayoutInflater.from(content);
}
public void setmFamousShop(List<Commodity.FamousShopBean> famousShop) {
this.mFamousShop = famousShop;
notifyDataSetChanged();
}
public void addmFamousShop(List<Commodity.FamousShopBean> famousShop) {
this.mFamousShop.addAll(famousShop);
notifyDataSetChanged();
}
public View getHeadView() {
return headView;
}
public void setHeadView(View headView) {
this.headView = headView;
}
public View getFoodView() {
return foodView;
}
public void setFoodView(View foodView) {
this.foodView = foodView;
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view=inflater.inflate(R.layout.item_gridview_classify,parent,false);
ViewHolder viewHolder=new ViewHolder(view);
viewHolder.imageView= (ImageView) view.findViewById(R.id.iv_classic);
viewHolder.textName= (TextView) view.findViewById(R.id.tv_brand);
viewHolder.textPrice= (TextView) view.findViewById(R.id.tv_price);
return viewHolder;
}
@Override
public void onBindViewHolder(ViewHolder holder, int position) {
holder.textName.setText(mFamousShop.get(position).getSname());
holder.textPrice.setText(mFamousShop.get(position).getSprice()+"");
Glide.with(mContent).load(AppUrl.Http + mFamousShop.get(position).getSpic())
.into(holder.imageView);
// LoaderFactory.getInstance().displayImage(holder.imageView,BaseUrl.IMAGEHOST + mBanners.get(0).getImage_filename());
}
@Override
public int getItemCount() {
return mFamousShop.size();
}
static class ViewHolder extends RecyclerView.ViewHolder {
ViewHolder(View itemView) {
super(itemView);
}
ImageView imageView;
TextView textName;
TextView textPrice;
}
}
|
package com.example.startup;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.net.ConnectivityManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import com.example.startup.Backend.BroadcastReciever;
import com.example.startup.Constants.NavigationDrawerConstants;
import org.json.JSONObject;
import java.nio.channels.NetworkChannel;
import java.util.HashMap;
import java.util.Objects;
import static android.provider.ContactsContract.CommonDataKinds.Website.URL;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.util.Log;
import android.view.Menu;
import android.widget.TextView;
public class Login extends AppCompatActivity {
Button logininto;
TextView forgot;
private static final String URL = "https://edfinix.herokuapp.com/api/login/checkCredentials";
ProgressBar prog;
SharedPreferences sp;
private BroadcastReceiver mNetworkReceiver;
static TextView tv_check_connection;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
tv_check_connection= findViewById(R.id.tv_check_connection);
mNetworkReceiver = new BroadcastReciever();
registerNetworkBroadcastForNougat();
prog= findViewById(R.id.progress_login);
final EditText id = findViewById(R.id.User);
final EditText pass = findViewById(R.id.Password);
Login.this.setTitle(NavigationDrawerConstants.TAG_Login);
forgot = findViewById(R.id.forgot_pass);
logininto = findViewById(R.id.buttonLogin);
//final String username = "14441";
//final String password = "12345";
sp=getSharedPreferences("login",MODE_PRIVATE);
if(sp.contains("username") && sp.contains("password")){
if(sp.contains("student"))
{
startActivity(new Intent(Login.this,StudentMainActivity.class));
finish(); //finish current activity
}
else if(sp.contains("teacher"))
{
startActivity(new Intent(Login.this,TeacherMainActivity.class));
finish(); //finish current activity
}
else
{
Toast.makeText(this, "invalid", Toast.LENGTH_SHORT).show();
}
}
logininto.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
final String username = String.valueOf(id.getText());
final String password = String.valueOf(pass.getText());
if (username.trim().length() > 0 && password.trim().length() > 0) {
loginuser(username, password);
}
else {
Toast.makeText(Login.this, "Enter The Details To login", Toast.LENGTH_SHORT).show();
}
}
});
}
public void loginuser(final String username, final String password) {
RequestQueue requestQueue = Volley.newRequestQueue(this);
HashMap<String, String> params = new HashMap<>();
params.put("username", username);
params.put("password", password);
JsonObjectRequest request_json = new JsonObjectRequest(URL, new JSONObject(params),
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
Log.d("response","inside response");
try {
//Process os success response
// Log.d("response",response.login);
JSONObject login = (JSONObject) response.get("login");
int isUser = login.getInt("message");
//Toast.makeText(Login.this, "here"+isUser, Toast.LENGTH_SHORT).show();
if(isUser == 1 ){
Log.d("response", "valid");
if(login.getString("user").equals("student"))
{
SharedPreferences.Editor e=sp.edit();
e.putString("username",username);
e.putString("password",password);
e.putString("student","student");
e.apply();
// Log.d("response", "student");
//Toast.makeText(Login.this, "student", Toast.LENGTH_SHORT).show();
Intent a = new Intent(Login.this,StudentMainActivity.class);
startActivity(a);
finish();
// student logic
}
else if(login.getString("user").equals("teacher"))
{
SharedPreferences.Editor e=sp.edit();
e.putString("username",username);
e.putString("password",password);
e.putString("teacher","teacher");
e.apply();
//Log.d("response", "teacher");
//Toast.makeText(Login.this, "teacher", Toast.LENGTH_SHORT).show();
Intent a = new Intent(Login.this,TeacherMainActivity.class);
startActivity(a);
finish();
}
else
{
//Log.d("response", "admin");
Toast.makeText(Login.this, "Wrong ID or Password", Toast.LENGTH_SHORT).show();
}
}
else if(isUser == 0)
{
Log.d("response","invalid");
}
else
{
Log.d("response", "server error");
}
} catch (Exception e) {
Log.d("response",e.toString());
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.d("response", Objects.requireNonNull(error.getMessage()));
}
});
// add the request object to the queue to be executed
requestQueue.add(request_json);
}
public static void dialog(boolean value){
if(value){
tv_check_connection.setText("We are back !!!");
tv_check_connection.setBackgroundColor(Color.YELLOW);
tv_check_connection.setTextColor(Color.WHITE);
Handler handler = new Handler();
Runnable delayrunnable = new Runnable() {
@Override
public void run() {
tv_check_connection.setVisibility(View.GONE);
}
};
handler.postDelayed(delayrunnable, 3000);
}else {
tv_check_connection.setVisibility(View.VISIBLE);
tv_check_connection.setText("Could not Connect to internet");
tv_check_connection.setBackgroundColor(Color.RED);
tv_check_connection.setTextColor(Color.WHITE);
}
}
private void registerNetworkBroadcastForNougat() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
registerReceiver(mNetworkReceiver, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
registerReceiver(mNetworkReceiver, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
}
}
protected void unregisterNetworkChanges() {
try {
unregisterReceiver(mNetworkReceiver);
} catch (IllegalArgumentException e) {
e.printStackTrace();
}
}
@Override
public void onDestroy() {
super.onDestroy();
unregisterNetworkChanges();
}
}
|
package com.prep.quiz83;
//Given a sorted list of intervals, how do you tell if at least two overlap?
public class Drill15 {
public static void main(String[] args){
int[][] input ={
{0,4},
{1,8},
{2,15},
{3,14},
{4,5},
{5,9},
{6,9},
{7,8},
{8,9},
{9,13},
{10,14},
{11,11},
{12,13},
{13,15},
{14,16},
{15,20}
};
System.out.println(isOverlapped(input));
}
public static boolean isOverlapped(int[][] input){
//if it becomes 2 then its true
int overlapCounter=0;
for(int i=0;i<input.length-1;i++){
//(a,b) compare (c,d)
int a=input[i][0];
int b=input[i][1];
int c=input[i+1][0];
int d=input[i+1][1];
// a c b d
if(c>a && c<b)
overlapCounter++;
if(overlapCounter>=2)
return true;
}
return false;
}
}
|
package cn.test.demo01;
/*
* Integer其他方法
* 包括三个方法,和2个静态成员变量
*/
public class IntegerDemo2 {
public static void main(String[] args) {
function();
function1();
}
/*
* 三个静态方法
* 做进制的转换
* 十进制转成二进制 toBinaryString(int)
* 十进制转成八进制 toOctalString(int)
* 十进制转成十六进制 to HexString(int)
* 三个方法,返回值都是String形式出现
*/
public static void function1() {
System.out.println(Integer.toBinaryString(999));
System.out.println(Integer.toOctalString(999));
System.out.println(Integer.toHexString(999));
}
/*
* MAX_VALUE
* MIN_VALUE
*/
public static void function() {
System.out.println(Integer.MAX_VALUE);
System.out.println(Integer.MIN_VALUE);
}
}
|
/*
* @(#) SmailInfoDAO.java
* Copyright (c) 2007 eSumTech Co., Ltd. All Rights Reserved.
*/
package com.esum.wp.ims.smailinfo.dao.impl;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.sql.DataSource;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.esum.appframework.dao.impl.SqlMapDAO;
import com.esum.appframework.exception.ApplicationException;
import com.esum.wp.ims.smailinfo.dao.ISmailInfoDAO;
/**
*
* @author
* @version $Revision: $ $Date: $
*/
public class SmailInfoDAO extends SqlMapDAO implements ISmailInfoDAO {
private static Logger log = LoggerFactory.getLogger(SmailInfoDAO.class);
/**
* Default constructor. Can be used in place of getInstance()
*/
public SmailInfoDAO () {}
public String updatePasswordID = "";
public String selectPageListID = "";
public String smailInfoDetailID = "";
public String selectInPartnerListID = "";
public String insertInPartnerInfoID = "";
public String updateInPartnerInfoID = "";
public String deleteInPartnerInfoID = "";
public String selectOutPartnerListID = "";
public String insertOutPartnerInfoID = "";
public String updateOutPartnerInfoID = "";
public String deleteOutPartnerInfoID = "";
public String getSelectPageListID() {
return selectPageListID;
}
public void setSelectPageListID(String selectPageListID) {
this.selectPageListID = selectPageListID;
}
public List selectPageList(Object object) throws ApplicationException {
try {
log.info("return -> " + getSqlMapClientTemplate().queryForList(selectPageListID, object));
return getSqlMapClientTemplate().queryForList(selectPageListID, object);
} catch (Exception e) {
throw new ApplicationException(e);
}
}
public List smailInfoDetail(Object object) throws ApplicationException {
try {
return getSqlMapClientTemplate().queryForList(smailInfoDetailID, object);
} catch (Exception e) {
throw new ApplicationException(e);
}
}
public int updatePassword(Object object) throws ApplicationException {
try {
return getSqlMapClientTemplate().update(updatePasswordID, object);
} catch (Exception e) {
throw new ApplicationException(e);
}
}
public List selectInPartnerList(Object object) throws ApplicationException {
try {
return getSqlMapClientTemplate().queryForList(selectInPartnerListID, object);
} catch (Exception e) {
throw new ApplicationException(e);
}
}
public Object insertInPartnerInfo(Object object) throws ApplicationException {
try {
return getSqlMapClientTemplate().insert(insertInPartnerInfoID, object);
} catch (Exception e) {
throw new ApplicationException(e);
}
}
public int updateInPartnerInfo(Object object) throws ApplicationException {
try {
return getSqlMapClientTemplate().update(updateInPartnerInfoID, object);
} catch (Exception e) {
throw new ApplicationException(e);
}
}
public int deleteInPartnerInfo(Object object) throws ApplicationException {
try {
return getSqlMapClientTemplate().delete(deleteInPartnerInfoID, object);
} catch (Exception e) {
throw new ApplicationException(e);
}
}
public List selectOutPartnerList(Object object) throws ApplicationException {
try {
return getSqlMapClientTemplate().queryForList(selectOutPartnerListID, object);
} catch (Exception e) {
throw new ApplicationException(e);
}
}
public Object insertOutPartnerInfo(Object object) throws ApplicationException {
try {
return getSqlMapClientTemplate().insert(insertOutPartnerInfoID, object);
} catch (Exception e) {
throw new ApplicationException(e);
}
}
public int updateOutPartnerInfo(Object object) throws ApplicationException {
try {
return getSqlMapClientTemplate().update(updateOutPartnerInfoID, object);
} catch (Exception e) {
throw new ApplicationException(e);
}
}
public int deleteOutPartnerInfo(Object object) throws ApplicationException {
try {
return getSqlMapClientTemplate().delete(deleteOutPartnerInfoID, object);
} catch (Exception e) {
throw new ApplicationException(e);
}
}
public Map saveSmailInfoExcel(Object object) throws ApplicationException {
try {
String sqlStr = "select * from SMAIL_INFO ";
Map result = saveInfoExcel(sqlStr, "SMAIL_INFO");
return result;
} catch (Exception e) {
throw new ApplicationException(e);
}
}
public Map saveSmailInPartnerInfoExcel(Object object) throws ApplicationException {
try {
String sqlStr = "select * from SMAIL_IN_PARTNER_INFO";
Map result = saveInfoExcel(sqlStr, "SMAIL_IN_PARTNER_INFO");
return result;
} catch (Exception e) {
throw new ApplicationException(e);
}
}
public Map saveSmailOutPartnerInfoExcel(Object object) throws ApplicationException {
try {
String sqlStr = "select * from SMAIL_OUT_PARTNER_INFO";
Map result = saveInfoExcel(sqlStr, "SMAIL_OUT_PARTNER_INFO");
return result;
} catch (Exception e) {
throw new ApplicationException(e);
}
}
public String getUpdatePasswordID() {
return updatePasswordID;
}
public void setUpdatePasswordID(String updatePasswordID) {
this.updatePasswordID = updatePasswordID;
}
public String getSmailInfoDetailID() {
return smailInfoDetailID;
}
public void setSmailInfoDetailID(String smailInfoDetailID) {
this.smailInfoDetailID = smailInfoDetailID;
}
public String getDeleteInPartnerInfoID() {
return deleteInPartnerInfoID;
}
public void setDeleteInPartnerInfoID(String deleteInPartnerInfoID) {
this.deleteInPartnerInfoID = deleteInPartnerInfoID;
}
public String getSelectInPartnerListID() {
return selectInPartnerListID;
}
public void setSelectInPartnerListID(String selectInPartnerListID) {
this.selectInPartnerListID = selectInPartnerListID;
}
public String getInsertInPartnerInfoID() {
return insertInPartnerInfoID;
}
public void setInsertInPartnerInfoID(String insertInPartnerInfoID) {
this.insertInPartnerInfoID = insertInPartnerInfoID;
}
public String getUpdateInPartnerInfoID() {
return updateInPartnerInfoID;
}
public void setUpdateInPartnerInfoID(String updateInPartnerInfoID) {
this.updateInPartnerInfoID = updateInPartnerInfoID;
}
public String getDeleteOutPartnerInfoID() {
return deleteOutPartnerInfoID;
}
public void setDeleteOutPartnerInfoID(String deleteOutPartnerInfoID) {
this.deleteOutPartnerInfoID = deleteOutPartnerInfoID;
}
public String getSelectOutPartnerListID() {
return selectOutPartnerListID;
}
public void setSelectOutPartnerListID(String selectOutPartnerListID) {
this.selectOutPartnerListID = selectOutPartnerListID;
}
public String getInsertOutPartnerInfoID() {
return insertOutPartnerInfoID;
}
public void setInsertOutPartnerInfoID(String insertOutPartnerInfoID) {
this.insertOutPartnerInfoID = insertOutPartnerInfoID;
}
public String getUpdateOutPartnerInfoID() {
return updateOutPartnerInfoID;
}
public void setUpdateOutPartnerInfoID(String updateOutPartnerInfoID) {
this.updateOutPartnerInfoID = updateOutPartnerInfoID;
}
private Map saveInfoExcel(String sqlStr, String tableName) throws ApplicationException {
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try {
Map result = new HashMap();
List queryResult = new ArrayList();
String sql = sqlStr;
DataSource ds = getSqlMapClientTemplate().getDataSource();
conn = ds.getConnection();
stmt = conn.createStatement();
rs = stmt.executeQuery(sql);
ResultSetMetaData rsmd = rs.getMetaData();
String[] title = new String[rsmd.getColumnCount()];
int[] colSize = new int[rsmd.getColumnCount()];
for(int i=0; i<rsmd.getColumnCount(); i++) {
title[i] = rsmd.getColumnName(i+1);
colSize[i] = rsmd.getColumnDisplaySize(i+1);
}
for(int i=0; i<rsmd.getColumnCount(); i++) {
title[i] = rsmd.getColumnName(i+1);
}
int count = 0;
while(rs.next()) {
List row = new ArrayList();
for(int i=0; i<rsmd.getColumnCount(); i++) {
Object col = rs.getObject(i+1);
row.add(i, col);
}
queryResult.add(count, row);
count++;
}
result.put("table", StringUtils.isEmpty(rsmd.getTableName(1)) ? tableName : rsmd.getTableName(1));
result.put("header", title);
result.put("size", colSize);
result.put("data", queryResult);
return result;
} catch (Exception e) {
throw new ApplicationException(e);
} finally {
if(rs != null) try { rs.close(); } catch(SQLException e) { }
if(stmt != null) try { stmt.close(); } catch(SQLException e) { }
if(conn != null) try { conn.close(); } catch(SQLException e) { }
}
}
}
|
package com.dian.diabetes.activity.sugar.adapter;
import java.util.List;
import android.content.Context;
import android.view.View;
import android.widget.TextView;
import com.dian.diabetes.R;
import com.dian.diabetes.activity.MBaseAdapter;
import com.dian.diabetes.activity.sugar.model.TimeModel;
import com.dian.diabetes.tool.Config;
public class PlanTimeAdapter extends MBaseAdapter {
public PlanTimeAdapter(Context context, List<?> data) {
super(context, data, R.layout.item_plan_time);
}
@Override
protected void newView(View convertView) {
ViewHolder holder = new ViewHolder();
holder.itemDelta = (TextView) convertView.findViewById(R.id.time_delta);
holder.time = (TextView) convertView.findViewById(R.id.time);
convertView.setTag(holder);
}
@Override
protected void holderView(View convertView, Object itemObject) {
ViewHolder holder = (ViewHolder) convertView.getTag();
TimeModel set = (TimeModel) itemObject;
holder.itemDelta.setText(set.getName());
final String key = "clock" + set.getType() + set.getSubType();
holder.time.setText(Config.getProperty(key) + "");
}
class ViewHolder {
TextView itemDelta;
TextView time;
}
}
|
// **********************************************************
// 1. 제 목: SCO Object Operation Data
// 2. 프로그램명: SCOData.java
// 3. 개 요: SCO관리에 관련된 Data Object
// 4. 환 경: JDK 1.3
// 5. 버 젼: 1.0
// 6. 작 성: 박미복 2004. 11.11
// 7. 수 정: 박미복 2004. 11.11
// **********************************************************
package com.ziaan.beta;
import java.util.Hashtable;
public class BetaSCOData {
private String oid = "";
private String otype = "";
private String filetype = "";
private int npage =0;
private String sdesc = "";
private String master = "";
private String starting = "";
private String server = "";
private String subj = "";
private String parameterstring = "";
private String datafromlms = "";
private String identifier = "";
private String prerequisites = "";
private int masteryscore =0;
private String maxtimeallowed = "";
private String timelimitaction = "";
private int sequence =0;
private int thelevel =0;
private String luserid = "";
private String ldate = "";
private int oidnumber =0;
private String highoid = "";
private String metalocation = "";
private String scolocate = "";
private int scoall =0;
private String scotitle = "";
private int metadata_idx =0 ;
private int ordering =0 ; // tz_scosubjobj 순서
private String module = "" ; // tz_scosubjobj 모듈
private String lesson = "" ; // tz_scosubjobj 레슨(차시)
private String jindostatus = "" ; // 진도결과
private String core_lesson_location = "" ; // 북마크 페이지
/*addon */
private String mastername = ""; // master 이름
private int cntUsed =0; // 사용된 과목수
public Hashtable subjList = new Hashtable();
public BetaSCOData() { };
public void makeSub(String subj,String subjnm) {
cntUsed = subjList.size();
subjList.put(String.valueOf(cntUsed), subjnm);
// subjList.put(subj, subjnm);
}
/**
* @return
*/
public String getDatafromlms() {
return datafromlms;
}
/**
* @return
*/
public String getFiletype() {
return filetype;
}
/**
* @return
*/
public String getIdentifier() {
return identifier;
}
/**
* @return
*/
public String getLdate() {
return ldate;
}
/**
* @return
*/
public String getLuserid() {
return luserid;
}
/**
* @return
*/
public String getMaster() {
return master;
}
/**
* @return
*/
public int getMasteryscore() {
return masteryscore;
}
/**
* @return
*/
public String getMaxtimeallowed() {
return maxtimeallowed;
}
/**
* @return
*/
public int getNpage() {
return npage;
}
/**
* @return
*/
public String getOid() {
return oid;
}
/**
* @return
*/
public String getOtype() {
return otype;
}
/**
* @return
*/
public String getParameterstring() {
return parameterstring;
}
/**
* @return
*/
public String getPrerequisites() {
return prerequisites;
}
/**
* @return
*/
public String getSdesc() {
return sdesc;
}
/**
* @return
*/
public int getSequence() {
return sequence;
}
/**
* @return
*/
public String getServer() {
return server;
}
/**
* @return
*/
public String getSubj() {
return subj;
}
/**
* @return
*/
public int getThelevel() {
return thelevel;
}
/**
* @return
*/
public String getTimelimitaction() {
return timelimitaction;
}
/**
* @param string
*/
public void setDatafromlms(String string) {
datafromlms = string;
}
/**
* @param string
*/
public void setFiletype(String string) {
filetype = string;
}
/**
* @param string
*/
public void setIdentifier(String string) {
identifier = string;
}
/**
* @param string
*/
public void setLdate(String string) {
ldate = string;
}
/**
* @param string
*/
public void setLuserid(String string) {
luserid = string;
}
/**
* @param string
*/
public void setMaster(String string) {
master = string;
}
/**
* @param i
*/
public void setMasteryscore(int i) {
masteryscore = i;
}
/**
* @param string
*/
public void setMaxtimeallowed(String string) {
maxtimeallowed = string;
}
/**
* @param i
*/
public void setNpage(int i) {
npage = i;
}
/**
* @param string
*/
public void setOid(String string) {
oid = string;
}
/**
* @param string
*/
public void setOtype(String string) {
otype = string;
}
/**
* @param string
*/
public void setParameterstring(String string) {
parameterstring = string;
}
/**
* @param string
*/
public void setPrerequisites(String string) {
prerequisites = string;
}
/**
* @param string
*/
public void setSdesc(String string) {
sdesc = string;
}
/**
* @param i
*/
public void setSequence(int i) {
sequence = i;
}
/**
* @param string
*/
public void setServer(String string) {
server = string;
}
/**
* @param string
*/
public void setSubj(String string) {
subj = string;
}
/**
* @param i
*/
public void setThelevel(int i) {
thelevel = i;
}
/**
* @param string
*/
public void setTimelimitaction(String string) {
timelimitaction = string;
}
/**
* @return
*/
public String getStarting() {
return starting;
}
/**
* @param string
*/
public void setStarting(String string) {
starting = string;
}
/**
* @return
*/
public int getCntUsed() {
return cntUsed;
}
/**
* @return
*/
public Hashtable getSubjList() {
return subjList;
}
/**
* @param i
*/
public void setCntUsed(int i) {
cntUsed = i;
}
/**
* @param hashtable
*/
public void setSubjList(Hashtable hashtable) {
subjList = hashtable;
}
/**
* @return
*/
public String getMastername() {
return mastername;
}
/**
* @param string
*/
public void setMastername(String string) {
mastername = string;
}
/**
* @return
*/
public int getOidnumber() {
return oidnumber;
}
/**
* @param i
*/
public void setOidnumber(int i) {
oidnumber = i;
}
/**
* @return
*/
public String getHighoid() {
return highoid;
}
/**
* @param string
*/
public void setHighoid(String string) {
highoid = string;
}
/**
* @return
*/
public String getMetalocation() {
return metalocation;
}
/**
* @param string
*/
public void setMetalocation(String string) {
metalocation = string;
}
/**
* @return
*/
public String getScolocate() {
return scolocate;
}
/**
* @param string
*/
public void setScolocate(String string) {
scolocate = string;
}
/**
* @return
*/
public int getScoAll() {
return scoall;
}
/**
* @param string
*/
public void setScoAll(int i) {
scoall = i;
}
/**
* @return
*/
public String getScoTitle() {
return scotitle;
}
/**
* @param string
*/
public void setScoTitle(String string) {
scotitle = string;
}
/**
* @return
*/
public int getMetadata() {
return metadata_idx;
}
/**
* @param string
*/
public void setMetadata(int i) {
metadata_idx = i;
}
/**
* @return
*/
public int getOrdering() {
return ordering;
}
/**
* @param string
*/
public void setOrdering(int i) {
ordering = i;
}
/**
* @return
*/
public String getModule() {
return module;
}
/**
* @param string
*/
public void setModule(String s) {
module = s;
}
/**
* @return
*/
public String getLesson() {
return lesson;
}
/**
* @param string
*/
public void setLesson(String s) {
lesson = s;
}
/**
* @return
*/
public String getJindoStatus() {
return jindostatus;
}
/**
* @param string
*/
public void setJindoStatus(String s) {
jindostatus = s;
}
/**
* @return
*/
public String getCoreLessonLocation() {
return core_lesson_location;
}
/**
* @param string
*/
public void setCoreLessonLocation(String s) {
core_lesson_location = s;
}
}
|
/* The isBadVersion API is defined in the parent class VersionControl.
boolean isBadVersion(int version); */
//good job!
//there are things need to pay attention:
//1. use mid = low + (high - low) / 2; instead of mid = (low + high) / 2;
//can avoid overflow when the number of "high" are very big
//2. non-recursive solution is ususally faster. And since a little different from binary sort
// , try some simple example to make sure the new range, etc. (mid + 1, high) is correct
public class Solution extends VersionControl {
public int firstBadVersion(int n) {
int start = 1, end = n;
while (start < end) {
int mid = start + (end-start) / 2;
if (!isBadVersion(mid)) start = mid + 1;
else end = mid;
}
return start;
}
}
// public class Solution extends VersionControl {
// public int firstBadVersion(int n) {
// return recurCheck(1, n);
// }
// public int recurCheck(int low, int high)
// {
// if (low >= high)
// return low;
// int mid = low + (high - low) / 2;
// if (isBadVersion(mid))
// {
// return recurCheck(low, mid);
// }
// else
// return recurCheck(mid + 1, high);
// }
// }
|
package model;
import java.util.List;
import javax.persistence.*;
@Entity
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
public class Institution {
@Id
private Long id;
private String name;
@OneToOne
private BusinessAddress address;
@OneToMany
private List<Class> institutionClasses;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public BusinessAddress getAddress() {
return address;
}
public void setAddress(BusinessAddress address) {
this.address = address;
}
public List<Class> getInstitutionClasses() {
return institutionClasses;
}
public void setInstitutionClasses(List<Class> institutionClasses) {
this.institutionClasses = institutionClasses;
}
}
|
package GerenteDeExercicios;
import java.util.ArrayList;
import java.util.List;
public class Professor extends Pessoa {
List<Professor> professores;
public Professor(String nome, String matricula) {
super(nome, matricula);
this.professores = new ArrayList<>();
}
public void cadastraProfessor(String nome, String matricula)throws ProfessorJaExisteException{
boolean existe = false;
for(Professor a: professores){
if(a.getMatricula().equals(matricula)){
existe = true;
break;
}
}
if(existe == true){
throw new ProfessorJaExisteException("Já existe aluno com essa matrícula:"+matricula);
}else{
Professor pro = new Professor(nome,matricula);
professores.add(pro);
}
}
public String toString() {
return "Professor [nome = " + super.getNome() + ", matricula = " + super.getMatricula() + "]";
}
}
|
package com.mingrisoft;
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.UIManager;
import javax.swing.border.EmptyBorder;
public class PopupMenuTest extends JFrame {
/**
*
*/
private static final long serialVersionUID = -5570749657628665431L;
private JPanel contentPane;
/**
* Launch the application.
*/
public static void main(String[] args) {
try {
UIManager.setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");
} catch (Throwable e) {
e.printStackTrace();
}
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
PopupMenuTest frame = new PopupMenuTest();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public PopupMenuTest() {
setTitle("\u5F39\u51FA\u5F0F\u83DC\u5355\u7684\u5E94\u7528");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 300, 200);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
JPopupMenu popupMenu = new JPopupMenu();
contentPane.setComponentPopupMenu(popupMenu);
JMenuItem cut = new JMenuItem("\u526A\u5207");
cut.setIcon(new ImageIcon(PopupMenuTest.class.getResource("cut.png")));
cut.setFont(new Font("微软雅黑", Font.PLAIN, 16));
cut.addActionListener(listener);
popupMenu.add(cut);
JMenuItem find = new JMenuItem("\u67E5\u8BE2");
find.setIcon(new ImageIcon(PopupMenuTest.class.getResource("find.png")));
find.setFont(new Font("微软雅黑", Font.PLAIN, 16));
find.addActionListener(listener);
popupMenu.add(find);
JMenuItem open = new JMenuItem("\u6253\u5F00");
open.setIcon(new ImageIcon(PopupMenuTest.class.getResource("open.png")));
open.setFont(new Font("微软雅黑", Font.PLAIN, 16));
open.addActionListener(listener);
popupMenu.add(open);
JMenuItem save = new JMenuItem("\u4FDD\u5B58");
save.setIcon(new ImageIcon(PopupMenuTest.class.getResource("save.png")));
save.setFont(new Font("微软雅黑", Font.PLAIN, 16));
save.addActionListener(listener);
popupMenu.add(save);
contentPane.setLayout(new BorderLayout(0, 0));
setContentPane(contentPane);
label = new JLabel("\u5355\u51FB\u9F20\u6807\u53F3\u952E\u5F39\u51FA\u83DC\u5355");
label.setFont(new Font("微软雅黑", Font.PLAIN, 20));
contentPane.add(label, BorderLayout.CENTER);
}
private ActionListener listener = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
label.setText(e.getActionCommand());// 设置标签的文本为用户选择的操作
}
};
private JLabel label;
}
|
package github;
import settings.Settings;
import org.eclipse.egit.github.core.Gist;
import org.eclipse.egit.github.core.GistFile;
import org.eclipse.egit.github.core.service.GistService;
import java.io.IOException;
import java.util.Collections;
public class GistProcess {
private String content;
private String filename;
private Gist gist;
public GistProcess()
{
}
public boolean addGist() {
GistFile file = new GistFile();
file.setContent(content);
gist = new Gist();
gist.setDescription(" ");
gist.setFiles(Collections.singletonMap(filename, file));
GistService service = new GistService();
service.getClient().setCredentials(Settings.username, Settings.password);
try {
gist = service.createGist(gist); //returns the created gist
} catch (IOException e) {
System.out.println(e);
return false;
}
System.out.println();
System.out.println(gist.getComments());
return true;
}
public String getURl()
{
return gist.getHtmlUrl();
}
public void setContent(String content) {
this.content = content;
}
public void setFilename(String filename) {
this.filename = filename;
}
}
|
package com.example.Springsecurity.config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;
import javax.sql.DataSource;
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
UserDetailsService userDetailsService;
public SpringSecurityConfig() {
System.out.println("SpringSecurityConfig.SpringSecurityConfig()");
}
@Override
public void configure(AuthenticationManagerBuilder auth) throws Exception {
System.out.println("AuthenticationManagerBuilder() assign role");
auth.userDetailsService(userDetailsService)
.passwordEncoder(getPasswordEncoder());
/*auth.inMemoryAuthentication()
.withUser("user").password("{noop}password").roles("USER")
.and()
.withUser("shankar").password("{noop}12345678").roles("USER", "ADMIN");*/
}
PasswordEncoder getPasswordEncoder() {
return new PasswordEncoder() {
@Override
public String encode(CharSequence charSequence) {
return charSequence.toString();
}
@Override
public boolean matches(CharSequence charSequence, String s) {
return true;
}
};
}
@Override
protected void configure(HttpSecurity http) throws Exception {
System.out.println("HttpSecurity access Url privilege()");
// http.httpBasic()
// .and()
// .authorizeRequests()
// .antMatchers(HttpMethod.GET, "/books/**").hasRole("USER")
// .antMatchers(HttpMethod.POST, "/book").hasRole("ADMIN")
// .antMatchers(HttpMethod.PUT, "/book").hasRole("ADMIN")
// .antMatchers(HttpMethod.DELETE, "/book/**").hasRole("ADMIN")
// .antMatchers(HttpMethod.DELETE, "/delete/account/**").hasRole("ADMIN")
// .and()
// .csrf().disable()
// .formLogin().disable();
http.csrf().disable();
http.authorizeRequests()
.antMatchers("/book/**").authenticated()
.antMatchers("/books").authenticated()
.antMatchers("/delete/account/**").authenticated()
.anyRequest().permitAll()
.and()
.formLogin().permitAll();
}
}
|
package com.git.cloud.resmgt.openstack.model.vo;
import com.git.cloud.common.model.base.BaseBO;
public class RmNwVfwRouteVo extends BaseBO implements java.io.Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
private String id;
private String vfwId;
private String routeId;
private String routeName;
private String projectId;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getVfwId() {
return vfwId;
}
public void setVfwId(String vfwId) {
this.vfwId = vfwId;
}
public String getRouteId() {
return routeId;
}
public void setRouteId(String routeId) {
this.routeId = routeId;
}
@Override
public String getBizId() {
// TODO Auto-generated method stub
return null;
}
public String getRouteName() {
return routeName;
}
public void setRouteName(String routeName) {
this.routeName = routeName;
}
public String getProjectId() {
return projectId;
}
public void setProjectId(String projectId) {
this.projectId = projectId;
}
}
|
package leetCode;
/**
* Created by gengyu.bi on 2015/1/8.
*/
public class RecoverBinarySearchTree {
TreeNode node1 = null;
TreeNode node2 = null;
TreeNode preNode = null;
public void recoverTree(TreeNode root) {
inorder(root);
int val=node1.val;
node1.val=node2.val;
node2.val=val;
}
private void inorder(TreeNode node) {
if (node == null)
return;
if (node.left != null)
inorder(node.left);
if (preNode != null && preNode.val > node.val) {
if (node1 == null)
node1 = preNode;
node2 = node;
}
preNode = node;
if (node.right != null)
inorder(node.right);
}
}
|
/*
* Copyright 2002-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.core.env;
import java.util.Iterator;
import java.util.List;
import java.util.Spliterator;
import java.util.Spliterators;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.stream.Stream;
import org.springframework.lang.Nullable;
/**
* The default implementation of the {@link PropertySources} interface.
* Allows manipulation of contained property sources and provides a constructor
* for copying an existing {@code PropertySources} instance.
*
* <p>Where <em>precedence</em> is mentioned in methods such as {@link #addFirst}
* and {@link #addLast}, this is with regard to the order in which property sources
* will be searched when resolving a given property with a {@link PropertyResolver}.
*
* @author Chris Beams
* @author Juergen Hoeller
* @since 3.1
* @see PropertySourcesPropertyResolver
*/
public class MutablePropertySources implements PropertySources {
private final List<PropertySource<?>> propertySourceList = new CopyOnWriteArrayList<>();
/**
* Create a new {@link MutablePropertySources} object.
*/
public MutablePropertySources() {
}
/**
* Create a new {@code MutablePropertySources} from the given propertySources
* object, preserving the original order of contained {@code PropertySource} objects.
*/
public MutablePropertySources(PropertySources propertySources) {
this();
for (PropertySource<?> propertySource : propertySources) {
addLast(propertySource);
}
}
@Override
public Iterator<PropertySource<?>> iterator() {
return this.propertySourceList.iterator();
}
@Override
public Spliterator<PropertySource<?>> spliterator() {
return Spliterators.spliterator(this.propertySourceList, 0);
}
@Override
public Stream<PropertySource<?>> stream() {
return this.propertySourceList.stream();
}
@Override
public boolean contains(String name) {
for (PropertySource<?> propertySource : this.propertySourceList) {
if (propertySource.getName().equals(name)) {
return true;
}
}
return false;
}
@Override
@Nullable
public PropertySource<?> get(String name) {
for (PropertySource<?> propertySource : this.propertySourceList) {
if (propertySource.getName().equals(name)) {
return propertySource;
}
}
return null;
}
/**
* Add the given property source object with the highest precedence.
*/
public void addFirst(PropertySource<?> propertySource) {
synchronized (this.propertySourceList) {
removeIfPresent(propertySource);
this.propertySourceList.add(0, propertySource);
}
}
/**
* Add the given property source object with the lowest precedence.
*/
public void addLast(PropertySource<?> propertySource) {
synchronized (this.propertySourceList) {
removeIfPresent(propertySource);
this.propertySourceList.add(propertySource);
}
}
/**
* Add the given property source object with precedence immediately higher
* than the named relative property source.
*/
public void addBefore(String relativePropertySourceName, PropertySource<?> propertySource) {
assertLegalRelativeAddition(relativePropertySourceName, propertySource);
synchronized (this.propertySourceList) {
removeIfPresent(propertySource);
int index = assertPresentAndGetIndex(relativePropertySourceName);
addAtIndex(index, propertySource);
}
}
/**
* Add the given property source object with precedence immediately lower
* than the named relative property source.
*/
public void addAfter(String relativePropertySourceName, PropertySource<?> propertySource) {
assertLegalRelativeAddition(relativePropertySourceName, propertySource);
synchronized (this.propertySourceList) {
removeIfPresent(propertySource);
int index = assertPresentAndGetIndex(relativePropertySourceName);
addAtIndex(index + 1, propertySource);
}
}
/**
* Return the precedence of the given property source, {@code -1} if not found.
*/
public int precedenceOf(PropertySource<?> propertySource) {
return this.propertySourceList.indexOf(propertySource);
}
/**
* Remove and return the property source with the given name, {@code null} if not found.
* @param name the name of the property source to find and remove
*/
@Nullable
public PropertySource<?> remove(String name) {
synchronized (this.propertySourceList) {
int index = this.propertySourceList.indexOf(PropertySource.named(name));
return (index != -1 ? this.propertySourceList.remove(index) : null);
}
}
/**
* Replace the property source with the given name with the given property source object.
* @param name the name of the property source to find and replace
* @param propertySource the replacement property source
* @throws IllegalArgumentException if no property source with the given name is present
* @see #contains
*/
public void replace(String name, PropertySource<?> propertySource) {
synchronized (this.propertySourceList) {
int index = assertPresentAndGetIndex(name);
this.propertySourceList.set(index, propertySource);
}
}
/**
* Return the number of {@link PropertySource} objects contained.
*/
public int size() {
return this.propertySourceList.size();
}
@Override
public String toString() {
return this.propertySourceList.toString();
}
/**
* Ensure that the given property source is not being added relative to itself.
*/
protected void assertLegalRelativeAddition(String relativePropertySourceName, PropertySource<?> propertySource) {
String newPropertySourceName = propertySource.getName();
if (relativePropertySourceName.equals(newPropertySourceName)) {
throw new IllegalArgumentException(
"PropertySource named '" + newPropertySourceName + "' cannot be added relative to itself");
}
}
/**
* Remove the given property source if it is present.
*/
protected void removeIfPresent(PropertySource<?> propertySource) {
this.propertySourceList.remove(propertySource);
}
/**
* Add the given property source at a particular index in the list.
*/
private void addAtIndex(int index, PropertySource<?> propertySource) {
removeIfPresent(propertySource);
this.propertySourceList.add(index, propertySource);
}
/**
* Assert that the named property source is present and return its index.
* @param name {@linkplain PropertySource#getName() name of the property source} to find
* @throws IllegalArgumentException if the named property source is not present
*/
private int assertPresentAndGetIndex(String name) {
int index = this.propertySourceList.indexOf(PropertySource.named(name));
if (index == -1) {
throw new IllegalArgumentException("PropertySource named '" + name + "' does not exist");
}
return index;
}
}
|
/*
* Created on Dec 13, 2006
*
*
* Window - Preferences - Java - Code Style - Code Templates
*/
package com.citibank.ods.entity.pl;
import com.citibank.ods.entity.pl.valueobject.BaseTplPotentialWealthEntityVO;
import com.citibank.ods.common.entity.BaseODSEntity;
/**
* @author User
*
*
* Window - Preferences - Java - Code Style - Code Templates
*/
public class BaseTplPotentialWealthEntity extends BaseODSEntity {
protected BaseTplPotentialWealthEntityVO m_data;
public BaseTplPotentialWealthEntityVO getData()
{
return m_data;
}
}
|
/*
* 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 main.java.spatialrelex.ling;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import main.java.spatialrelex.markup.SpatialElement;
/**
*
* @author Jenny D'Souza
*/
public class VerbNet {
public static Map<String, List<String>> wordVerbNetClass = new HashMap<>();
public static Map<String, List<String>> wordVerbNetSubClass = new HashMap<>();
public static void initializeVerbNet(File file) throws IOException {
List<String> words = new ArrayList<>();
String classV = "";
String subClassV = "";
BufferedReader in = new BufferedReader(new FileReader(file));
while (in.ready()) {
String s = in.readLine().trim();
if (s.matches("CLASS:.*")) {
if (!words.isEmpty()) {
if (!subClassV.equals(""))
setVerbNetSubClasses(words, subClassV);
setVerbNetClasses(words, classV);
}
words = new ArrayList<>();
subClassV = "";
classV = s.split(":")[1].trim();
}
else if (s.matches("SUBCLASS:.*")) {
if (!words.isEmpty() && !subClassV.equals("")) {
setVerbNetSubClasses(words, subClassV);
setVerbNetClasses(words, classV);
}
words = new ArrayList<>();
subClassV = s.split(":")[1].trim();
}
else if (s.matches("MEMBER:.*"))
words.add(s.split(":")[1]);
}
if (!words.isEmpty()) {
if (!subClassV.equals(""))
setVerbNetSubClasses(words, subClassV);
setVerbNetClasses(words, classV);
}
}
public static void setVerbNetSubClasses(List<String> words, String subClassV) {
for (String word : words) {
List<String> subClass = wordVerbNetSubClass.get(word);
if (subClass == null)
wordVerbNetSubClass.put(word, subClass = new ArrayList<>());
subClass.add(subClassV);
}
}
public static void setVerbNetClasses(List<String> words, String classV) {
for (String word : words) {
List<String> classes = wordVerbNetClass.get(word);
if (classes == null)
wordVerbNetClass.put(word, classes = new ArrayList<>());
classes.add(classV);
}
}
public static List<String> getClasses(List<String> classes, String word) {
if (!wordVerbNetClass.containsKey(word))
return classes;
Set<String> classesSet = new HashSet<>(classes);
classesSet.addAll(wordVerbNetClass.get(word));
return new ArrayList<>(classesSet);
}
public static List<String> getSubClasses(List<String> classes, String word) {
if (!wordVerbNetSubClass.containsKey(word))
return classes;
Set<String> subClassesSet = new HashSet<>(classes);
subClassesSet.addAll(wordVerbNetSubClass.get(word));
return new ArrayList<>(subClassesSet);
}
public static List<String> getVerbNetClasses(List<String> verbNetClasses, String word) {
verbNetClasses = getClasses(verbNetClasses, word.toLowerCase());
verbNetClasses = getSubClasses(verbNetClasses, word.toLowerCase());
return verbNetClasses;
}
}
|
package com.cinema.sys.model;
public class UserSessionItems implements java.io.Serializable {
private static final long serialVersionUID = -2664497757926794819L;
// 登录信息
private User user;
// 所有权限字符串
private String authCodes;
// 是否为超级管理员
private Boolean isAdmin = false;
private String authLevel;
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public String getAuthCodes() {
return authCodes;
}
public void setAuthCodes(String authCodes) {
this.authCodes = authCodes;
}
public Boolean getIsAdmin() {
return isAdmin;
}
public void setIsAdmin(Boolean isAdmin) {
this.isAdmin = isAdmin;
}
public String getAuthLevel() {
return authLevel;
}
public void setAuthLevel(String authLevel) {
this.authLevel = authLevel;
}
}
|
package br.com.pwc.nfe.connector;
import br.com.pwc.nfe.connector.enums.SoapVersionEnum;
import br.com.pwc.nfe.connector.vo.NFeEntradaConnectorExportacaoVO;
/**
* Serviço de Exportação do NFeEntrada
*
* @author Marcelo Coutinho
*
*/
public class NFeEntradaExportacao {
public String exportar(NFeEntradaConnectorExportacaoVO dados) {
// SoapBuilderRequestVO vo = new SoapBuilderRequestVO();
// vo.setWsdl(dados.getWsdl());
// vo.setPort(EXPORTACAO_PORT);
// vo.setOperation(EXPORTACAO_OPERATION);
// vo.setSoapVersion(EXPORTACAO_SOAP_VERSION);
// vo.setAtributos(Arrays.asList(buildMessage(dados)));
// SoapBuilderResponseVO mensagem = soapBuilder.construirMensagem(vo);
// HttpCommunicatorRequestVO httpVO = parseSoapBuilderResponseToHttpCommunicatorRequest(mensagem);
// httpCommunicator.comunica(httpVO);
return null;
}
private String buildMessage(NFeEntradaConnectorExportacaoVO vo) {
StringBuilder sb = new StringBuilder();
// sb.append(b);
// sb.append(b);
// sb.append(b);
return sb.toString();
}
private static final String EXPORTACAO_PORT = "WSExportacaoNFPort";
private static final String EXPORTACAO_OPERATION = "exportacaoNF";
private static final String EXPORTACAO_MENSAGEM_INICIO = "<![CDATA[<exportacaoNFTerceiros xmlns=\"http://www.pwc.com.br/nfe\">";
private static final String EXPORTACAO_MENSAGEM_FIM = "</exportacaoNFTerceiros>]]>";
private static final SoapVersionEnum EXPORTACAO_SOAP_VERSION = SoapVersionEnum.SOAP11;
private static final String MENSAGEM_DATA_INICIAL = "<dataInicial>§</dataInicial>";
private static final String MENSAGEM_DATA_FINAL = "<dataFinal>§</dataFinal>";
private static final String MENSAGEM_QTD_INICIAL = "<qtdInicial>§</qtdInicial>";
private static final String MENSAGEM_QTD_FINAL = "<qtdFinal>§</qtdFinal>";
private static final String MENSAGEM_CNPJ = "<cnpjDestinatario>§</cnpjDestinatario>";
private static final String MENSAGEM_IE = "<ieDestinatario>§</ieDestinatario>";
}
|
package com.proxiad.games.extranet.service;
import com.proxiad.games.extranet.dto.RiddleDto;
import com.proxiad.games.extranet.dto.UnlockDto;
import com.proxiad.games.extranet.enums.RiddleType;
import com.proxiad.games.extranet.exception.PasswordDontMatchException;
import com.proxiad.games.extranet.exception.RiddleAlreadySolvedException;
import com.proxiad.games.extranet.model.Riddle;
import com.proxiad.games.extranet.model.Room;
import com.proxiad.games.extranet.repository.RiddleRepository;
import com.proxiad.games.extranet.repository.RoomRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.persistence.EntityNotFoundException;
@Service
public class RiddleService {
@Autowired
private RoomRepository roomRepository;
@Autowired
private RiddleRepository riddleRepository;
public Riddle newRiddle(Integer roomId) {
Room room = roomRepository.findById(roomId)
.orElseThrow(() -> new EntityNotFoundException("No room with id " + roomId));
return riddleRepository.save(Riddle.builder()
.name("Nouveau")
.riddleId("idToSet")
.room(room)
.resolved(false)
.type(RiddleType.GAME)
.build());
}
public Riddle resolveOpenDoorRiddle(RiddleDto riddleDto) {
Room room = roomRepository.findById(riddleDto.getRoomId())
.orElseThrow(() -> new EntityNotFoundException("No room with id " + riddleDto.getRoomId()));
Riddle openDoorRiddle = room.getRiddles().stream()
.filter(riddle -> riddle.getType().equals(RiddleType.OPEN_DOOR))
.findFirst()
.orElseThrow(() -> new EntityNotFoundException("No open room riddle for room with id " + riddleDto.getRoomId()));
if (openDoorRiddle.getRiddlePassword().equals(riddleDto.getRiddlePassword())) {
openDoorRiddle.setResolved(true);
riddleRepository.save(openDoorRiddle);
}
return openDoorRiddle;
}
public Riddle resolveRiddle(UnlockDto unlockDto, Room room) throws PasswordDontMatchException, RiddleAlreadySolvedException {
Riddle riddle = room.getRiddles().stream()
.filter(r -> r.getRiddleId().equals(unlockDto.getRiddleId()))
.findFirst()
.orElse(null);
if (riddle == null) {
throw new EntityNotFoundException();
}
if (riddle.getResolved()) {
throw new RiddleAlreadySolvedException();
}
if (!riddle.getRiddlePassword().equals(unlockDto.getPassword())) {
throw new PasswordDontMatchException();
}
riddle.setResolved(true);
riddleRepository.save(riddle);
return riddle;
}
}
|
package sebisrlp.server;
import java.net.*;
import java.io.*;
import java.util.Arrays;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import sebisrlp.business.Command;
import sebisrlp.business.SRLPException;
import sebisrlp.business.WordPair;
import sebisrlp.business.Words;
import sebisrlp.persistence.DBWords;
import static sebisrlp.persistence.Datasource.DS;
/**
* Single client server for the SRLP protocol.
*
* @author hom
*/
public class SRLPSingleServer {
static Words dict = new DBWords( DS );
public static void main( String[] args ) throws IOException {
int portNumber = Integer.parseInt( System.getProperty( "sebisrlp.port",
"8333" ) );
System.out.println( "portNumber = " + portNumber );
try ( final ServerSocket serverSocket = new ServerSocket( portNumber );
final Socket clientSocket = serverSocket.accept(); ) {
handle( clientSocket, dict );
} catch ( IOException e ) {
System.out.println( "Exception caught when trying to listen on"
+ "port " + portNumber + " or listening "
+ "for a connection" );
System.out.println( e.getMessage() );
}
}
private static void handle( final Socket clientSocket, Words dict ) throws
IOException {
try (
PrintWriter out
= new PrintWriter( clientSocket.getOutputStream(), true );
BufferedReader in = new BufferedReader(
new InputStreamReader( clientSocket.getInputStream() ) ); ) {
String inputLine;
inputLine = in.readLine();
while ( inputLine != null ) {
String[] lp = inputLine.split( "\\s+" );
String[] words = Arrays.copyOfRange( lp, 1, lp.length );
try {
List<WordPair> result = null;
Command cmd = null;
try {
cmd = Command.valueOf( Command.class, lp[ 0 ]
.toUpperCase() );
} catch ( IllegalArgumentException iae ) {
throw new SRLPException( 400, "command not found" );
}
System.out.println( cmd.name() + "+" + Arrays.toString(
words ) );
result = cmd.process( dict, words );
if ( null == result ) {
throw new SRLPException( 500, "internal server error" );
}
out.print( "200 Ok\r\n\r\n" );
result.forEach( s -> {
out.print( s + "\r\n" );
System.out.println( s );
} );
out.print( "\r\n" );
out.flush();
result = null;
} catch ( SRLPException ex ) {
Logger.getLogger( SRLPSingleServer.class.getName() ).log(
Level.INFO, ex.getMessage(), ex );
out.print( ex.getStatuscode() + " " + ex.getMessage()
+ "\r\n\r\n" );
out.flush();
}
inputLine = in.readLine();
}
}
}
}
|
package frame;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.beans.Statement;
import java.sql.*;
import frame.check;
import db.DB;
import javax.swing.*;
import com.sun.corba.se.pept.transport.Connection;
import com.sun.glass.events.WindowEvent;
import com.sun.javafx.font.Disposer;
import com.sun.org.apache.xml.internal.security.Init;
public class frame {
static JFrame frame = new JFrame();
static JPanel panel = new JPanel();
public static void main(String args[]) {
framee(true);
// frame.addWindowListener(new CloseHandler());
//frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
// public static class CloseHandler extends WindowAdapter{
// public void windowClosing(WindowEvent e){
// System.out.println("asd");
// System.exit(0);
// }
// }
public static void framee (boolean flag){
JButton button = new JButton();
final JTextField username = new JTextField();
JTextArea usernameArea = new JTextArea();
final JTextField password = new JTextField();
JTextArea passwordArea = new JTextArea();
button.setText("登录");
usernameArea.setText("用户名");
usernameArea.setEditable(false);
usernameArea.setBackground(null);
passwordArea.setText("密码");
passwordArea.setEditable(false);
passwordArea.setBackground(null);
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
check.click(username.getText(),password.getText());
}
});
if (flag){
panel.add(username);
panel.add(password);
panel.add(button);
panel.add(usernameArea);
panel.add(passwordArea);
panel.setLayout(null);
usernameArea.setBounds(60,30,50,20);
//
passwordArea.setBounds(60,130,30,20);
username.setBounds(60,60,100,20);
password.setBounds(60,160,100,20);
button.setBounds(200,160,100,20);
}
else {
JLabel label = new JLabel();
label.setText("登录成功");
panel.removeAll();
panel.add(label);
panel.setLayout(null);
panel.repaint();
label.setBounds(150,100,100,50);
label.setBackground(null);
}
frame.getContentPane().add(panel);
frame.setSize(400,300);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
frame.addWindowListener(new WindowAdapter(){
public void windowClosing(java.awt.event.WindowEvent e){
file.deletefile();
System.exit(0);
}
});
}
public static void init(){
}
public static void login(){
framee(false);
}
}
|
import java.util.ArrayList;
/**
* @author 19044593
*
*/
public class Order {
private String username;
private String status;
private boolean takeaway;
private ArrayList<MenuItem> items;
/**
* @param username
* @param status
* @param menuItem
*/
public Order(String username, String status, boolean takeaway, ArrayList<MenuItem> items) {
this.username = username;
this.status = status;
this.takeaway = takeaway;
this.items = items;
}
/**
* @return the username
*/
public String getUsername() {
return username;
}
/**
* @param username the username to set
*/
public void setUsername(String username) {
this.username = username;
}
/**
* @return the status
*/
public String getStatus() {
return status;
}
/**
* @param status the status to set
*/
public void setStatus(String status) {
this.status = status;
}
/**
* @return the takeaway
*/
public boolean isTakeaway() {
return takeaway;
}
/**
* @param takeaway the takeaway to set
*/
public void setTakeaway(boolean takeaway) {
this.takeaway = takeaway;
}
/**
* @return the items
*/
public ArrayList<MenuItem> getItems() {
return items;
}
/**
* @param items the items to set
*/
public void setItems(ArrayList<MenuItem> items) {
this.items = items;
}
public String toString() {
String Order = super.toString();
return String.format("%-63s", Order);
}
}
|
package com.esum.as2util;
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateUtil
{
public static String format(String pattern)
{
SimpleDateFormat sdf = new SimpleDateFormat(pattern);
return sdf.format(new Date());
}
public static String formatDateTime(String date)
{
if(date.length() < 14) return date;
StringBuffer sb = new StringBuffer();
sb.append(date.substring(0, 4) + "/");
sb.append(date.substring(4, 6) + "/");
sb.append(date.substring(6, 8));
sb.append(" ");
sb.append(date.substring(8, 10) + ":");
sb.append(date.substring(10, 12) + ":");
sb.append(date.substring(12, 14));
return sb.toString();
}
public static String formatDateTime17(String date)
{
if(date.length() < 17) return date;
StringBuffer sb = new StringBuffer();
sb.append(date.substring(0, 4) + "/");
sb.append(date.substring(4, 6) + "/");
sb.append(date.substring(6, 8));
sb.append(" ");
sb.append(date.substring(8, 10) + ":");
sb.append(date.substring(10, 12) + ":");
sb.append(date.substring(12, 14));
return sb.toString();
}
}
|
package Implements;
import java.util.List;
import Entity.ChiTietSanPham;
import Entity.Size;
public interface ChiTietSPImp {
List<String> DsMau(int idSanPham);
int kiemTraSLSanPham(int idSanPham,String hinhAnh,int idSize);
String kiemTraSanPham(int idSanPham,int idMauSac);
ChiTietSanPham showCTSP(int idChiTietSanPham);
int layMaCTSP(int idSanPham,String hinhAnh,int idMauSac);
String XoaSLSanPham(int idChiTietSanPham, int SoLuong);
String ThemCTSP(ChiTietSanPham chiTietSanPham);
List<ChiTietSanPham> layCTSPTheoIdSP(int idSanPham);
int getMaCTSP(int idSanPham, int idMauSac, int idSize);
String updateSoLuong(int idChiTietSanPham, int SoLuong);
}
|
package com.hwj.daoImpl;
import org.springframework.stereotype.Repository;
import com.hwj.dao.IBaseDao;
import com.hwj.dao.IZsdDao;
import com.hwj.entity.Zsd;
@Repository(value = "IZsdDao")
public class ZsdDaoImpl extends BaseDaoImpl<Zsd> implements IZsdDao {
}
|
class Solution {
public String longestPalindrome(String s) {
if(s == null || s.length() == 0){
return "";
}
if(s.length() == 1){
return s;
}
int left = 0;
int right = 0;
for(int i = 0; i < s.length(); i++){
// start from same index - get palin with odd length
int oddPalinLen = expand(s, i, i);
// start from adjacent index - get palin with even length
int evenPalinLen = expand(s, i, i+1);
// use the longer length as current length
int len = Math.max(oddPalinLen, evenPalinLen);
// if found longer palindrome, update two bounds
if(len > right - left){
left = i - (len - 1) / 2;
right = i + len / 2;
}
}
return s.substring(left, right + 1);
}
private int expand(String s, int leftBound, int rightBound){
int left = leftBound;
int right = rightBound;
while(left >= 0 && right < s.length()
&& s.charAt(left) == s.charAt(right)){
left--;
right++;
}
return right - left - 1;
}
}
|
package com.radius.sodalityUser.controller;
import javax.json.JsonObject;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.radius.sodalityUser.common.Commonfunction;
import com.radius.sodalityUser.model.Unit;
import com.radius.sodalityUser.response.UnitResponseList;
import com.radius.sodalityUser.service.UnitService;
@RestController
@CrossOrigin
@RequestMapping("/Unit")
public class UnitController {
@Autowired
Commonfunction Commonfunctionl;
@Autowired
UnitService unitservice;
@PostMapping(value ="/Add")
public ResponseEntity<Unit> AddUnit(@Valid @RequestBody String requestBodyString){
JsonObject returnJsonObject = Commonfunctionl.ReturnJsonObject(requestBodyString);
return new ResponseEntity<>(unitservice.unitSave(returnJsonObject), HttpStatus.OK);
}
@PostMapping(value ="/Get")
public ResponseEntity<UnitResponseList> getUnitTower(@Valid @RequestBody String requestBodyString){
JsonObject returnJsonObject = Commonfunctionl.ReturnJsonObject(requestBodyString);
return new ResponseEntity<>(unitservice.getUnitTower(returnJsonObject), HttpStatus.OK);
}
@GetMapping(value ="/Get/{uuid}")
public ResponseEntity<Unit> getUnit(@PathVariable("uuid") String uuid){
return new ResponseEntity<>(unitservice.getUnit(uuid), HttpStatus.OK);
}
@PutMapping(value ="/Update")
public ResponseEntity<Unit> UpdateTower(@Valid @RequestBody String requestBodyString){
JsonObject returnJsonObject = Commonfunctionl.ReturnJsonObject(requestBodyString);
return new ResponseEntity<>(unitservice.unitUpdate(returnJsonObject), HttpStatus.OK);
}
@GetMapping(value ="/Resident/Get/{uuid}")
public ResponseEntity<UnitResponseList> getResidentFlat(@PathVariable("uuid") String uuid){
return new ResponseEntity<>(unitservice.getResidentUnitList(uuid), HttpStatus.OK);
}
}
|
package com.gxtc.huchuan.ui.circle.circleInfo;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import com.gxtc.commlibrary.base.BaseTitleActivity;
import com.gxtc.commlibrary.utils.EventBusUtil;
import com.gxtc.commlibrary.utils.GotoUtil;
import com.gxtc.commlibrary.utils.ToastUtil;
import com.gxtc.commlibrary.utils.WindowUtil;
import com.gxtc.huchuan.Constant;
import com.gxtc.huchuan.R;
import com.gxtc.huchuan.bean.CircleBean;
import com.gxtc.huchuan.bean.CircleMemberBean;
import com.gxtc.huchuan.bean.event.EventCircleIntro;
import com.gxtc.huchuan.data.UserManager;
import com.gxtc.huchuan.ui.mine.loginandregister.LoginAndRegisteActivity;
import com.gxtc.huchuan.utils.AndroidBug5497Workaround;
import java.io.File;
import java.util.HashMap;
import java.util.List;
import butterknife.BindView;
/**
* 输入简介
*/
public class InputIntroActivity extends BaseTitleActivity implements View.OnClickListener,
CircleInfoContract.View {
private static final String TAG = InputIntroActivity.class.getSimpleName();
@BindView(R.id.edit_content) EditText editContent;
private CircleBean bean;
private int mGroupID;
private String mGroupName;
private CircleInfoContract.Presenter mPresenter;
private HashMap<String, Object> map;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_input_intro);
AndroidBug5497Workaround.assistActivity(this);
}
@Override
public void initView() {
getBaseHeadView().showTitle(getString(R.string.title_circle_intro));
getBaseHeadView().showBackButton(this);
getBaseHeadView().showHeadRightButton("保存", this);
}
@Override
public void initData() {
super.initData();
new CircleInfoPresenter(this);
map = new HashMap<>();
bean = (CircleBean) getIntent().getSerializableExtra(Constant.INTENT_DATA);
if (bean != null) {
mGroupID = bean.getId();
mGroupName = bean.getName();
Log.d(TAG, "initData: " + mGroupID + ",groupName:" + mGroupName);
}
}
@Override
public void onClick(View v) {
WindowUtil.closeInputMethod(this);
switch (v.getId()) {
case R.id.headBackButton:
finish();
break;
case R.id.headRightButton:
save();
break;
}
}
private void save() {
String content = editContent.getText().toString();
if (TextUtils.isEmpty(content)) {
ToastUtil.showShort(this, "内容不能为空");
return;
} else {
map.put("token", UserManager.getInstance().getToken());
map.put("id", mGroupID);
map.put("groupName", mGroupName);
map.put("content", editContent.getText().toString());
mPresenter.editCircleInfo(map);
}
/*Intent intent = new Intent();
intent.putExtra(Constant.INTENT_DATA,content);
setResult(101,intent);
finish();*/
}
@Override
public void tokenOverdue() {
GotoUtil.goToActivity(this, LoginAndRegisteActivity.class);
}
@Override
public void showMemberList(List<CircleMemberBean> datas) {}
@Override
public void showRefreshFinish(List<CircleMemberBean> datas) {}
@Override
public void showLoadMore(List<CircleMemberBean> datas) {}
@Override
public void showNoMore() {}
@Override
public void showCompressSuccess(File file) {}
@Override
public void showCompressFailure() {}
@Override
public void showUploadingSuccess(String url) {}
@Override
public void showCircleInfo(CircleBean bean) {}
@Override
public void showEditCircle(Object o) {
ToastUtil.showShort(this, getString(R.string.modify_success));
EventBusUtil.post(new EventCircleIntro(editContent.getText().toString()));
this.finish();
}
//---------------- 在圈子成员管理用到的
@Override
public void removeMember(CircleMemberBean circleMemberBean) {
}
@Override
public void transCircle(CircleMemberBean circleMemberBean) {
}
@Override
public void showChangeMemberTpye(CircleMemberBean circleMemberBean) {
}
//---------------- 在圈子成员管理用到的
@Override
public void setPresenter(CircleInfoContract.Presenter presenter) {
this.mPresenter = presenter;
}
@Override
public void showLoad() {
getBaseLoadingView().showLoading();
}
@Override
public void showLoadFinish() {
getBaseLoadingView().hideLoading();
}
@Override
public void showEmpty() {}
@Override
public void showReLoad() {}
@Override
public void showError(String info) {
ToastUtil.showShort(this, info);
}
@Override
public void showNetError() {
ToastUtil.showShort(this, getString(R.string.empty_net_error));
}
@Override
protected void onDestroy() {
super.onDestroy();
if(mPresenter != null) mPresenter.destroy();
}
}
|
package blazeplus;
import cpw.mods.fml.common.Side;
import cpw.mods.fml.common.asm.SideOnly;
import net.minecraft.src.CreativeTabs;
public class BlazeCreativeTabs extends CreativeTabs {
public BlazeCreativeTabs(String type) {
super(type);
}
@Override
@SideOnly(Side.CLIENT)
public int getTabIconItemIndex()
{
return BlazePlus.BlazeBlock.blockID;
}
@Override
@SideOnly(Side.CLIENT)
public String getTranslatedTabLabel()
{
return DefaultProps.MOD;
}
}
|
package com.agoda.hotels.repo;
import java.io.Serializable;
import org.springframework.data.domain.Sort;
import org.springframework.data.repository.NoRepositoryBean;
import org.springframework.data.repository.Repository;
@NoRepositoryBean
public interface ReadOnlyRepository<T, ID extends Serializable> extends Repository<T, ID> {
T findOne(ID id);
Iterable<T> findAll(Sort sort);
}
|
package com.oa.dictionary.controller;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import com.oa.dictionary.form.FieldType;
import com.oa.dictionary.service.FieldTypeService;
import com.oa.page.PageUtils;
import com.oa.page.form.Page;
@Controller
@RequestMapping("/fieldType/fieldTypeManager")
public class FieldTypeController {
@Autowired
private FieldTypeService fieldTypeService;
@RequestMapping(value = "/addFieldType")
public String addFieldType(@ModelAttribute("fieldType") FieldType fieldType) {
fieldTypeService.addFieldType(fieldType);
return "redirect:/fieldType/fieldTypeManager/listFieldType";
}
@RequestMapping(value = "/listFieldType")
public String selectAllFieldTypes(Map<String, Object> map, HttpServletRequest request) {
String pageNo = request.getParameter("pageNo");
pageNo = pageNo == null ? "1" : pageNo;
String pageSize = request.getParameter("pageSize");
pageSize = pageSize == null ? "10" : pageSize;
map.put("fieldType", new FieldType());
Page<FieldType> page = PageUtils.createPage(Integer.parseInt(pageSize), fieldTypeService.findAllFieldTypes().size(),
Integer.parseInt(pageNo));
List<FieldType> fieldTypeList = fieldTypeService.findAllFieldTypeByPage(page);
map.put("fieldTypeList", fieldTypeList);
map.put("page", page);
return "/fieldType/fieldTypeManager/listFieldType";
}
@RequestMapping(value = "/editFieldTypeByName/{fieldTypeName}")
public ModelAndView selectFieldTypeByName(@PathVariable("fieldTypeName") String fieldTypeName) {
FieldType fieldType = fieldTypeService.findFieldTypeByFieldTypeTitle(fieldTypeName);
Map<String, Object> map = new HashMap<String, Object>();
map.put("fieldType", fieldType);
return new ModelAndView("/fieldType/fieldTypeManager/editFieldType", map);
}
@RequestMapping(value="/editFieldTypeById/{id}")
public ModelAndView selectFieldTypeById(@PathVariable("id")int fieldTypeId) {
FieldType fieldType = fieldTypeService.findFieldTypeById(fieldTypeId);
Map<String, Object> map = new HashMap<String, Object>();
map.put("fieldType", fieldType);
return new ModelAndView("/fieldType/fieldTypeManager/editFieldType", map);
}
@RequestMapping(value="/updateFieldType", method=RequestMethod.POST)
public String updateFieldType(@ModelAttribute("fieldType")FieldType fieldType) {
fieldTypeService.updateFieldType(fieldType);
return "redirect:/fieldType/fieldTypeManager/listFieldType";
}
@RequestMapping(value="/deleteFieldType/{id}")
public String deleteFieldType(@PathVariable("id") Integer fieldTypeId) {
fieldTypeService.deleteFieldType(fieldTypeId);
return "redirect:/fieldType/fieldTypeManager/listFieldType";
}
}
|
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class subFrame extends JFrame implements ActionListener{
Font f1 = new Font("Aharoni", Font.BOLD,15);
Font f4= new Font("Aharoni",Font.BOLD,20);
private JMenuBar mbar;
private JMenu pat,us,doc,me,hel;
private JLabel l1;
private JMenuItem reg,amp,ext,chp,pe,ab,cl;
public subFrame() {
Container c = getContentPane();
c.add(mbar= new JMenuBar());
mbar.setBackground(Color.GRAY);
setJMenuBar(mbar);
c.add(me= new JMenu("MASTERY ENTRY"));
mbar.add(me);
c.add(us= new JMenu("USERS"));
mbar.add(us);
us.addActionListener(this);
c.add(chp= new JMenuItem("Change Password"));
us.add(chp);
chp.addActionListener(this);
c.add(doc= new JMenu("DOCTOR"));
mbar.add(doc);
doc.addActionListener(this);
c.add(pe= new JMenuItem("Profile Entry"));
doc.add(pe);
pe.addActionListener(this);
c.add(pat= new JMenu("PATIENT"));
mbar.add(pat);
c.add(reg= new JMenuItem("Registration"));
pat.add(reg);
reg.addActionListener(this);
pat.addActionListener(this);
c.add(amp= new JMenuItem("Admin Patient"));
pat.add(amp);
amp.addActionListener(this);
c.add(ext= new JMenuItem("Exit"));
pat.add(ext);
ext.addActionListener(this);
c.add(hel= new JMenu("HELP"));
mbar.add(hel);
c.add(ab= new JMenuItem("About"));
hel.add(ab);
ab.addActionListener(this);
c.add(cl= new JMenuItem("Close"));
hel.add(cl);
cl.addActionListener(this);
pat.setForeground(Color.WHITE);
us.setForeground(Color.WHITE);
doc.setForeground(Color.WHITE);
me.setForeground(Color.WHITE);
hel.setForeground(Color.WHITE);
c.add(l1= new JLabel(""));
Image io = new ImageIcon(this.getClass().getResource("/mainwall.png")).getImage();
l1.setIcon(new ImageIcon(io));
l1.setBounds(0,0,1366,768);
me.setFont(f4);
pat.setFont(f4);
us.setFont(f4);
doc.setFont(f4);
hel.setFont(f4);
reg.setFont(f1);
amp.setFont(f1);
ext.setFont(f1);
pe.setFont(f1);
chp.setFont(f1);
ab.setFont(f1);
cl.setFont(f1);
}
public void actionPerformed(ActionEvent o) {
JFrame af=null,bf = null,cf=null;
if (o.getSource()==pe){
af = new subDoc();
af.setTitle("Doctor");
af.setVisible(true);
af.setSize(600,450);
af.setLocationRelativeTo(null);
af.setResizable(false);
bf.setVisible(false);
cf.setVisible(false);
}
if (o.getSource()==amp){
bf = new subAd();
bf.setTitle("Admit Patient");
bf.setVisible(true);
bf.setSize(1150,550);
bf.setLocationRelativeTo(null);
bf.setResizable(false);
af.setVisible(false);
cf.setVisible(false);
}
if (o.getSource()== reg){
cf= new subReg ();
cf.setTitle("Patient Registration Form");
cf.setVisible(true);
cf.setSize(750,550);
cf.setLocationRelativeTo(null);
cf.setResizable(false);
bf.setVisible(false);
af.setVisible(false);
}
if (o.getSource()==ext){
System.exit(0);
}
if (o.getSource ()==cl){
System.exit(0);
}
}
}
|
package com.land.back.util;
import java.text.DecimalFormat;
public class UtilBodyEmail {
public static DecimalFormat formatDecimal = new DecimalFormat("$ ###,###,###,###,###,###,###,###,###,###.00");
public static String plantillaNotaCredito(String doa,String Modelo,String Serie,String Factura) {
String header="<!DOCTYPE html><html>" +
"<meta charset=\"UTF-8\">" +
"<meta name=\"viewport\" content=\"width=device-width, user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1\">" +
" <title>" +
" AOC" +
" </title>" +
"<body>" +
"<header>" +
"<h1><b>AOC Web</b></h1>" +
"</header>";
String contenido="<main>" +
"<div class=\"contenedor\">" +
"<h3>Favor de Generar Nota de Crédito a AEM Computación por el siguiente producto: </h3>" +
"<b>DOA: " +doa+
"<br/>MODELO: "+ Modelo +
"<br/>SERIE: "+Serie +
"<br/> FACTURA: </b>"+Factura +
"</div>" +
"</main>";
String footer="</body>" +
"<footer>" +
"<h5 ><strong>© Copyright 2017 </strong> " +
"<a style='color: white' href='http://latin.aoc.com/'> AOC </a> Derechos Reservados. " +
"<b > AOC Web </b></h5><br/>" +
"</footer>" +
"<div class=\"contenedor_footer\">" +
"<br/>La información contenida en este mensaje es confidencial y privada, está protegida por secreto profesional y está destinada únicamente para el uso de" +
"la(s) persona(s) arriba indicada(s). Está estrictamente prohibida cualquier difusión, distribución, impresión, edición no autorizada, o copia de este mensaje." +
" Si ha recibido esta comunicación o copia de este mensaje por error, favor de desecharlo permanentemente o destruirlo inmediatamente y comunicarlo al remitente" +
" o llamar al (52) (55) 51332500. El uso o diseminación no autorizados de esta información confidencial serán perseguidos conforme a derecho. Este mensaje no c" +
"rea obligaciones para el remitente ni pretende ser usado como medio para celebrar convenios o contratos de cualquier tipo. Gracias " +
"<br/><br/>The information contained in this message is protected by professional privilege, is confidential and private, and is intended only for the use of the" +
" individual(s) named above. Any unauthorized dissemination, distribution, edition, print or copy of this communicatión is strictly prohibited. If by error, you " +
"have received this communication, or its copy, please delete it or destroy it immediately and contact the sender, or call (52) (55) 51332500. The unauthorized us" +
"e or dissemination of this confidential information will be sanctioned according to the applicable law. This data message does not" +
" create obligations for the sender and is not an instrument to agree on contracts of any kind. Thank You." +
"</div>";
String estilos="<style type=\"text/css\"> " +
"body{ " +
" font-family: 'times new roman', sans-serif; " +
"} " +
"header{ " +
" width: 100%; " +
" height: 10%; " +
" display: block; " +
" background: #00537B; " +
" color: white; " +
" text-align: center; " +
" position: absolute; " +
" top: 0; " +
" left: 0; " +
" z-index: 100; " +
"} " +
"main{ " +
" display: block; " +
" margin-top: 5%; " +
" width: 100%; " +
" height: 40%; " +
" background:#DEDEDE; " +
" color: #00537B; " +
"} " +
"footer{ " +
" position: fixed; " +
" display: block; " +
" width: 100%; " +
" margin-top: 5%; " +
" background: #00537B; " +
" text-align: center; " +
" justify-content: center; " +
" clear: both; " +
"} " +
".contenedor{ " +
" width: 98%; " +
" margin: auto; " +
" display: table;" +
"} " +
".contenedor_footer{" +
" position: absolute;" +
" width: 98%;" +
" margin-top: 11%;" +
" display: table;" +
" background: white;" +
" text-align:justify;" +
" font: small-caps 70%/150% serif;" +
"}" +
"</style>" +
"</html>";
return header+contenido+footer+estilos ;
}
public static String pantillaRestablecimiento(String url) {
String cabecera = "<h1 style='color: #00537B;text-align: center'><b>AOC Web</b></h1>"
+ "<h3 style='color: #00537B;text-align: center'>Restablecimiento de contraseña</h3>";
String contenido = "<div style='text-align:center'>" + "<table border='0' >"
+ "<caption><strong style='color: white;'>Resumen de Operación</strong></caption>" + "<tr>"
+ "<td style='background-color:#00537B;'><strong><h4 style='color: white;'>" + url
+ "</h4></strong></td>" + "</tr>" + "</table>" + "</div>";
String footer = "<br/><footer><h5 style='text-align:center'><strong>© Copyright 2017 </strong> "
+ "<a style='color: #00537B' href='http://latin.aoc.com/'> AOC </a> Derechos Reservados. "
+ " <b style='color: #00537B'> AOC Web </b></h5><br/>"
+ "<div style='text-align:justify;font: small-caps 70%/150% serif;'>"
+ "<br/>La información contenida en este mensaje es confidencial y privada, está protegida por secreto profesional y está destinada únicamente para el uso de"
+ "la(s) persona(s) arriba indicada(s). Está estrictamente prohibida cualquier difusión, distribución, impresión, edición no autorizada, o copia de este mensaje."
+ " Si ha recibido esta comunicación o copia de este mensaje por error, favor de desecharlo permanentemente o destruirlo inmediatamente y comunicarlo al remitente"
+ " o llamar al (52) (55) 51332500. El uso o diseminación no autorizados de esta información confidencial serán perseguidos conforme a derecho. Este mensaje no c"
+ "rea obligaciones para el remitente ni pretende ser usado como medio para celebrar convenios o contratos de cualquier tipo. Gracias"
+ "<br/><br/>The information contained in this message is protected by professional privilege, is confidential and private, and is intended only for the use of the"
+ " individual(s) named above. Any unauthorized dissemination, distribution, edition, print or copy of this communication is strictly prohibited. If by error, you "
+ "have received this communication, or its copy, please delete it or destroy it immediately and contact the sender, or call (52) (55) 51332500. The unauthorized us"
+ "e or dissemination of this confidential information will be sanctioned according to the applicable law. This data message does not"
+ " create obligations for the sender and is not an instrument to agree on contracts of any kind. Thank You."
+ "</div></footer>";
String cuerpoCorreo = cabecera + "<br/>" + contenido + "<br/>" + footer;
return cuerpoCorreo;
}
public static String mailAppWhere() {
return "";
// SMTPMessage m = new SMTPMessage(session);
// MimeMultipart content = new MimeMultipart("related");
// SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
// String date = sdf.format(new Date());
//
// // ContentID is used by both parts
// String cid = ContentIdGenerator.getContentId();
//
// // HTML part
// MimeBodyPart textPart = new MimeBodyPart();
//
//
// if(nombreCliente.length() > 0 && nombreBeneficiario.length() > 0){
// textPart.setText("<html><head>"
// + "<title></title>"
// + "</head>\n"
// + "<body>"
// + "<div><img src=\"cid:"
// + cid
// + "\" /></div><br>"
// + "<span style='color: #000000; font-weight: bold;
// font-family:arial;'>Área de Cumplimiento: Se comunica que
// existen acciones pendientes de revisar en el proceso de
// autorización</span>"
// + "<p> </p>"
// + "<p><span style='color: #4a0061; font-family:arial;'>Fecha de
// Búsqueda: " + date +".</span>"
// + "</p>"
// + "<p> </p>"
// + "<p><span style='color: #4a0061; font-family:arial;'>Cliente
// encontrado en listas: " + nombreCliente +".</span>"
// + "</p>"
// + "<p><span style='color: #4a0061; font-family:arial;'>ID Cliente: "
// + sMensaje + ".</span>"
// + "</p>"
// + "<p><span style='color: #4a0061; font-family:arial;'>Status:
// 1.</span>"
// + "</p>"
// + "<p> </p>"
// + "<hr>"
// + "<p> </p>"
// + "<p><span style='color: #4a0061; font-family:arial;'>Beneficiario
// encontrado en listas: " + nombreBeneficiario + ".</span>"
// + "</p>"
// + "<p><span style='color: #4a0061; font-family:arial;'>ID
// Beneficiario: " + sMensaje2 + ".</span>"
// + "</p>"
// + "<p><span style='color: #4a0061; font-family:arial;'>Status:
// 1.</span>"
// + "</p>"
// + "</p>"
// + "<p><span style='color: #4a0061; font-family:arial;'></span></p>"
// + "</body></html>",
// "US-ASCII", "html");
//
//
// }else{
// if(nombreCliente.length() > 0){
// textPart.setText("<html><head>"
// + "<title></title>"
// + "</head>\n"
// + "<body>"
// + "<div><img src=\"cid:"
// + cid
// + "\" /></div><br>"
// + "<span style='color: #000000; font-weight: bold;
// font-family:arial;'>Área de Cumplimiento: Se comunica que
// existen acciones pendientes de revisar en el proceso de
// autorización</span>"
// + "<p> </p>"
// + "<p><span style='color: #4a0061; font-family:arial;'>Fecha de
// Búsqueda: " + date +".</span>"
// + "</p>"
// + "<p> </p>"
// + "<p><span style='color: #4a0061; font-family:arial;'>Cliente
// encontrado en listas: " + nombreCliente +".</span>"
// + "</p>"
// + "<p><span style='color: #4a0061; font-family:arial;'>ID Cliente: "
// + sMensaje + ".</span>"
// + "</p>"
// + "<p><span style='color: #4a0061; font-family:arial;'>Status:
// 1.</span>"
// + "</p>"
//
// + "<p><span style='color: #4a0061; font-family:arial;'></span></p>"
// + "</body></html>",
// "US-ASCII", "html");
//
// }else{
// if(nombreBeneficiario.length() > 0){
// textPart.setText("<html><head>"
// + "<title></title>"
// + "</head>\n"
// + "<body>"
// + "<div><img src=\"cid:"
// + cid
// + "\" /></div><br>"
// + "<span style='color: #000000; font-weight: bold;
// font-family:arial;'>Área de Cumplimiento: Se comunica que
// existen acciones pendientes de revisar en el proceso de
// autorización</span>"
// + "<p> </p>"
// + "<p><span style='color: #4a0061; font-family:arial;'>Fecha de
// Búsqueda: " + date +".</span>"
// + "</p>"
// + "<p> </p>"
// + "<p><span style='color: #4a0061; font-family:arial;'>Beneficiario
// encontrado en listas: " + nombreBeneficiario + ".</span>"
// + "</p>"
// + "<p><span style='color: #4a0061; font-family:arial;'>ID
// Beneficiario: " + sMensaje2 + ".</span>"
// + "</p>"
// + "<p><span style='color: #4a0061; font-family:arial;'>Status:
// 1.</span>"
// + "</p>"
//
// + "<p><span style='color: #4a0061; font-family:arial;'></span></p>"
// + "</body></html>",
// "US-ASCII", "html");
//
//
// }
// }
//
// }
//
//
//
//
//
//
// content.addBodyPart(textPart);
//
// // Image part
// MimeBodyPart imagePart = new MimeBodyPart();
// imagePart.attachFile(Propiedades.get("MAIL_IMG"));
// imagePart.setContentID("<" + cid + ">");
// imagePart.setDisposition(MimeBodyPart.INLINE);
// content.addBodyPart(imagePart);
//
// m.setContent(content);
// m.setSubject(sAsunto);
// return m;
}
public static void main(String[] args) {
System.out.println("");
}
}
|
package org.reactome.web.nursa.analysis.client.model;
import org.reactome.web.analysis.client.model.ExpressionSummary;
/**
* An {@link ExpressionSummary} with data set descriptors for the
* expression legend labels and a min/max range of [0, .05].
*
* @author Fred Loney <loneyf@ohsu.edu>
*/
public class ComparisonPseudoExpressionSummary extends PseudoExpressionSummary
implements ComparisonExpressionSummary {
public static final double COMPARISON_EXPRESSION_MIN = 0.0;
public static final double COMPARISON_EXPRESSION_MAX = 0.05;
public ComparisonPseudoExpressionSummary() {
// Base Reactome hard-codes min to 0 and max to 0.05 in various
// places, so we must go along with that here.
super(COMPARISON_EXPRESSION_MIN, COMPARISON_EXPRESSION_MAX);
}
}
|
package com.codeclan.coursebooker.coursebooker;
import com.codeclan.coursebooker.coursebooker.models.Booking;
import com.codeclan.coursebooker.coursebooker.models.Course;
import com.codeclan.coursebooker.coursebooker.models.Customer;
import com.codeclan.coursebooker.coursebooker.repositories.BookingRepository.BookingRepository;
import com.codeclan.coursebooker.coursebooker.repositories.CourseRepository.CourseRepository;
import com.codeclan.coursebooker.coursebooker.repositories.CustomerRepository.CustomerRepository;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.TestExecutionListeners;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.List;
import static org.junit.Assert.assertEquals;
@RunWith(SpringRunner.class)
@SpringBootTest
public class CoursebookerApplicationTests {
@Autowired
CourseRepository courseRepository;
@Autowired
BookingRepository bookingRepository;
@Autowired
CustomerRepository customerRepository;
@Test
public void contextLoads() {
}
@Test
public void canCreateCourseBookingAndCustomer() {
// Course course = new Course("Java", "Edinburgh", 5);
// courseRepository.save(course);
//
// Customer customer = new Customer("Jamie", "Edinburgh", 23);
// customerRepository.save(customer);
//
// Booking booking = new Booking("01-07-19", course, customer);
// bookingRepository.save(booking);
}
@Test
public void canGetCourseByRating() {
List<Course> found = courseRepository.getCoursesByRating(5);
assertEquals("Java", found.get(0).getName());
}
@Test
public void canGetCustomersByCourseId(){
List<Customer> found = customerRepository.getCustomersByCourseId(1L);
assertEquals("Jamie", found.get(0).getName());
}
@Test
public void canGetCoursesByCustomerId(){
List<Course> found = courseRepository.getCoursesByCustomerId(1L);
assertEquals("Java", found.get(0).getName());
}
@Test
public void canGetBookingsByDate(){
List<Booking> found = bookingRepository.getBookingsByDate("01-07-19");
assertEquals("01-07-19", found.get(0).getDate());
assertEquals(1, found.size());
}
}
|
package gui.db;
import java.io.Serializable;
import db.Model;
/** The <b>TableFormat<\b> class formats tabular data for use in reports. */
public final class TableFormat implements Serializable
{
private static final String columnSeparator = " ";
private Model model;
private int max = 0;
private boolean allowEmpty; // true to show columns with no values
/**
* Creates an instance of TableFormat.
*
* @param model The table model.
* @param maxFieldWidth The maximum size of any column.
* If 0 is specified It will use the longest data value
* for that column. If -1 is specified, it will allow empty columns.
*/
public TableFormat (Model model, int maxFieldWidth)
{
this.model = model;
if (maxFieldWidth > 0)
this.max = maxFieldWidth;
else if (maxFieldWidth < 0)
allowEmpty = true;
}
/**
* Creates an instance of TableFormat.
* @param model The table model.
*/
public TableFormat (Model model)
{
this.model = model;
}
/**
* Gets the maximum width for each column. If the caller did not
* specify a maximum, then this width will be large enough to hold
* every value in that column, as well as the column header. If the
* caller did specify a valid (> 0) maximum, then the width will not
* exceed that (and the values may get truncated).
*
* @return : An array of lengths.
*/
public int[] getMaxLength()
{
int rowCount = model.getRowCount();
int colCount = model.getColumnCount();
int colWidth[] = new int[colCount];
for (int col = 0; col < colCount; col++) // initialize
colWidth[col] = 0;
// check the width of each value, and increase colWidth if necessary
for (int col = 0; col < colCount; col++)
{
for (int row = 0; row < rowCount; row++)
{
String val = (String) model.getValueAt (row, col);
if (val != null)
colWidth[col] = Math.max (colWidth [col], val.trim().length());
if ((max > 0) && (colWidth[col] >= max))
break; // we must truncate, so don't bother to check all values
}
if (allowEmpty || (colWidth[col] > 0)) // if there were any values
{
// ensure the colWidth is wide enough to hold the column name
String header = model.getColumnName (col);
colWidth[col] = Math.max (colWidth[col], header.length());
// if there is a caller-set maximum, enforce it
if (max > 0)
colWidth[col] = Math.min (max, colWidth[col]);
}
}
return (colWidth);
}
/**
* Writes formatted table model to a StringBuilder.
* @return The formatted StringBuilder.
*/
public StringBuilder getFormattedBuffer()
{
StringBuilder buff = new StringBuilder();
int maxData[] = getMaxLength();
StringBuilder header = printHeaders (maxData);
buff.append (header.toString());
StringBuilder separator = writeSeparators (maxData);
buff.append (separator);
if (model.getRowCount() > 0)
{
StringBuilder body = printBody (maxData);
buff.append (body);
}
return (buff);
}
/**
* Formats the Column Headers.
* @param lens : An array of lengths.
* @return A StringBuilder containing the formated headers.
*/
private StringBuilder printHeaders (int[] lens)
{
StringBuilder buff = new StringBuilder ("");
int colCount = model.getColumnCount();
for (int col = 0; col < colCount; col++)
if (lens[col] > 0)
{
String sepr = (col == colCount - 1) ? "" : columnSeparator;
String name = model.getColumnName (col);
name = name.trim();
if (name.length() < lens[col])
{
int offset = lens[col] - name.length();
buff.append (name + append (offset, " ") + sepr);
}
else if (name.length() > lens[col])
buff.append (name.substring (0, lens[col]) + sepr);
else
buff.append (name + sepr);
}
buff.append ("\n");
return (buff);
}
/**
* Creates a String consisting of <numOf> <str> strings.
* @param numOf : The number of <str> strings to concatenate.
* @return A new String with the specified number of <str> strings.
*/
private String append (int numOf, String str)
{
StringBuilder result = new StringBuilder();
for (int i = 0; i < numOf; i++)
result.append (str);
return (result.toString());
}
// pad or truncate as needed
private String fitValue (String value, int maxWidth, int col)
{
String fit;
int len = value.length();
if (len == maxWidth) // the simple case, just copy it
fit = value;
else if (len > maxWidth) // truncate
fit = value.substring (0, (maxWidth - 1)) + "+";
/* TBD
else if (model.isNumeric (col)) // pad on the left (right-justify)
fit = append (maxWidth - len, " ") + value;
*/
else // pad on the right (left-justify)
fit = value + append (maxWidth - len, " ");
return (fit);
}
/**
* Formats the body of the table model or the data
* @param lens : An of array of lengths
* @return A StringBuilder containing the formatted model.
*/
private StringBuilder printBody (int[] lens)
{
StringBuilder buff = new StringBuilder ("");
int rowCount = model.getRowCount();
int colCount = model.getColumnCount();
for (int row = 0; row < rowCount; row++)
{
for (int col = 0; col < colCount; col++)
{
if (lens[col] > 0)
{
String value = (String) model.getValueAt (row, col);
String sepr = (col == colCount - 1) ? "" : columnSeparator;
if (value != null)
buff.append (fitValue (value.trim(), lens[col], col) + sepr);
else
buff.append (append (lens[col], " ") + sepr);
}
}
buff.append ("\n");
}
return (buff);
}
/**
* Formats the separators.
* @param lens : The Column Lengths.
* @return A StringBuilder containing the separators.
*/
private StringBuilder writeSeparators (int[] lens)
{
StringBuilder buff = new StringBuilder ("");
int colCount = model.getColumnCount();
for (int col = 0; col < colCount; col++)
if (lens[col] > 0)
{
String sepr = (col == colCount - 1) ? "" : columnSeparator;
buff.append (append (lens[col], "-") + sepr);
}
buff.append ("\n");
return (buff);
}
}
|
package com.zzp.lc.vo;
import java.io.Serializable;
import java.util.Date;
/**
* @Description Base Log
* @Author Garyzeng
* @since 2020.12.20
**/
public class BaseLog implements Serializable {
private static final long serialVersionUID = 1L;
/**
* 应用名称
*/
private String appName;
/**
* 主机ip
*/
private String host;
/**
* 端口号
*/
private String port;
/**
* 创建时间
*/
private Date createTime;
public String getAppName() {
return appName;
}
public void setAppName(String appName) {
this.appName = appName;
}
public String getHost() {
return host;
}
public void setHost(String host) {
this.host = host;
}
public String getPort() {
return port;
}
public void setPort(String port) {
this.port = port;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
}
|
/*
* Copyright (c) 2020. The Kathra Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Contributors:
* IRT SystemX (https://www.kathra.org/)
*
*/
package org.kathra.resourcemanager.pipeline.dao;
import com.arangodb.springframework.core.ArangoOperations;
import org.kathra.core.model.Pipeline;
import org.kathra.resourcemanager.resource.dao.AbstractResourceDao;
import org.kathra.resourcemanager.resource.utils.LeanResourceDbUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.kathra.resourcemanager.resource.utils.EdgeUtils;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
import javax.annotation.PostConstruct;
import fr.xebia.extras.selma.Selma;
import java.util.stream.Stream;
import org.kathra.resourcemanager.sourcerepository.dao.SourceRepositoryDb;
import org.kathra.resourcemanager.sourcerepository.dao.SourceRepositoryPipelineEdge;
import org.kathra.resourcemanager.sourcerepository.dao.SourceRepositoryPipelineEdgeRepository;
/**
* Abtrasct dao service to manage Pipeline using PipelineDb with ArangoRepository
*
* Auto-generated by resource-db-generator@1.3.0 at 2020-02-06T20:56:21.622Z
* @author jboubechtoula
*/
public abstract class AbstractPipelineDao extends AbstractResourceDao<Pipeline, PipelineDb, String> {
@Autowired
SourceRepositoryPipelineEdgeRepository sourceRepositoryPipelineEdgeRepository;
public AbstractPipelineDao(@Autowired PipelineRepository repository, @Autowired ArangoOperations operations){
super(repository, operations);
}
@PostConstruct
public void initCollectionIfNotExist(){
if(repository.count() == 0) {
try {
operations.insert(new PipelineDb("init"));
repository.deleteById("init");
} catch (Exception e) {
e.printStackTrace();
}
}
//init edge repositories
this.sourceRepositoryPipelineEdgeRepository.count();
}
@Override
public void create(Pipeline object, String author) throws Exception {
super.create(object, author);
updateReferences(object);
}
@Override
public void update(Pipeline object, String author) throws Exception {
super.update(object, author);
updateReferences(object);
}
@Override
public void delete(Pipeline object, String author) throws Exception {
super.delete(object, author);
updateReferences(object);
}
private void updateReferences(Pipeline object) throws Exception {
PipelineDb resourceDb = this.convertResourceToResourceDb(object);
EdgeUtils.of(SourceRepositoryPipelineEdge.class).updateReference(resourceDb, "sourceRepository", sourceRepositoryPipelineEdgeRepository);
}
PipelineMapper mapper = Selma.mapper(PipelineMapper.class);
public PipelineDb convertResourceToResourceDb(Pipeline object) {
return mapper.asPipelineDb(object);
}
public Pipeline convertResourceDbToResource(PipelineDb object) {
LeanResourceDbUtils leanResourceDbUtils = new LeanResourceDbUtils();
return mapper.asPipeline((PipelineDb) leanResourceDbUtils.leanResourceDb(object));
}
public Stream<Pipeline> convertResourceDbToResource(Stream<PipelineDb> objectsStream){
LeanResourceDbUtils leanUtils = new LeanResourceDbUtils();
return objectsStream.map(i -> (PipelineDb) leanUtils.leanResourceDb(i))
.collect(Collectors.toList())
.parallelStream()
.map(i -> mapper.asPipeline(i));
}
}
|
package net.jnmap.scanner.nmap;
import net.jnmap.data.ScanJob;
import net.jnmap.scanner.Job;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import static junit.framework.Assert.assertEquals;
import static net.jnmap.TestConstants.*;
import static org.powermock.api.mockito.PowerMockito.*;
/**
* Created by lucas.
*/
@RunWith(PowerMockRunner.class)
@PrepareForTest(NMapScanner.class)
public class NMapScannerTest {
@Test
public void testScan() throws IOException {
mockStatic(Runtime.class);
Runtime mockedRuntime = mock(Runtime.class);
Process mockedProcess = mock(Process.class);
// Mock streams with real strings
InputStream mockedInputStream = new ByteArrayInputStream(SAMPLE_XML_OUTPUT1.getBytes());
InputStream mockedErrorStream = new ByteArrayInputStream(SAMPLE_XML_ERROR.getBytes());
// Setups before executing scans
ScanJob testJob = new ScanJob(TEST_TARGET);
when(Runtime.getRuntime()).thenReturn(mockedRuntime);
when(mockedProcess.getInputStream()).thenReturn(mockedInputStream);
when(mockedProcess.getErrorStream()).thenReturn(mockedErrorStream);
// Execute scans and expect the output/errors
NMapScanner scanner = new NMapScanner(TEST_CONFIG.getCommandLinePrefix());
when(mockedRuntime.exec(scanner.getFullCommandLine(TEST_TARGET))).thenReturn(mockedProcess);
Job returnedJob = scanner.scan(testJob);
assertEquals(SAMPLE_XML_OUTPUT1.trim(), returnedJob.getOutputs().trim());
assertEquals(SAMPLE_XML_ERROR.trim(), returnedJob.getErrors().trim());
}
}
|
package com.example.parstagram;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.bumptech.glide.Glide;
import com.parse.ParseFile;
import java.util.List;
public class ProfilePostAdapter extends RecyclerView.Adapter<ProfilePostAdapter.ViewHolder> {
public static final String KEY_PROFILE_IMAGE = "profileImage";
public ProfilePostAdapter(Context context, List<Post> posts) {
this.context = context;
this.posts = posts;
}
private Context context;
private List<Post> posts;
@NonNull
@Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.item_post_profile, parent,false);
return new ViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
Post post = posts.get(position);
holder.bind(post);
}
@Override
public int getItemCount() {
return posts.size();
}
//clears elements of recyclerview
public void clear() {
posts.clear();
notifyDataSetChanged();
}
// Add a list of items -- change to type used
public void addAll(List<Post> postsList){
posts.addAll(postsList);
notifyDataSetChanged();
}
class ViewHolder extends RecyclerView.ViewHolder{
private ImageView ivImageProfilePage;
public ViewHolder(@NonNull View itemView) {
super(itemView);
itemView.findViewById(R.id.ivprofpost);
}
public void bind(Post post) {
ParseFile image = post.getImage();
if (image != null){
Glide.with(context).load(post.getImage().getUrl()).into(ivImageProfilePage);
}
}
}
}
|
class Outer
{
int x = 100;
void test()
{
Inner obj = new Inner();
obj.display();
}
class Inner
{
void display()
{
System.out.println(x);
}
}
}
class Demo
{
public static void main(String[] args) {
Outer obj = new Outer();
obj.test();
}
}
|
package com.outsource.dinhvi.hethongdinhvi;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.MenuItem;
import android.widget.RadioGroup;
import com.outsource.dinhvi.hethongdinhvi.adapter.AdapterLanguage;
import com.outsource.dinhvi.hethongdinhvi.component.DialogChangePass;
import com.outsource.dinhvi.hethongdinhvi.component.DialogComment;
import com.outsource.dinhvi.hethongdinhvi.component.DialogSearchUser;
import com.outsource.dinhvi.hethongdinhvi.objectclass.Language;
import com.outsource.dinhvi.hethongdinhvi.util.CommonDefine;
import com.outsource.dinhvi.hethongdinhvi.util.FunctionHelper;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
public class ConfigActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
Context ctx;
RadioGroup rbParent;
RecyclerView recyclerLang;
List<Language> lstLang;
AdapterLanguage adapterLanguage;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_config);
ctx = ConfigActivity.this;
rbParent = findViewById(R.id.rbParent);
recyclerLang = findViewById(R.id.recyclerLang);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle(R.string.config_sys);
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
GetLanguage();
ShowLanguage();
rbParent.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
final ProgressDialog dialog = ProgressDialog.show(ctx, "", "Đang cài đặt...",
true);
dialog.show();
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
dialog.dismiss();
}
}, 3000);
}
});
}
@Override
public void onBackPressed() {
super.onBackPressed();
FunctionHelper.Back(ctx);
}
private void GetLanguage() {
lstLang = new ArrayList<>();
for (Locale locale : Locale.getAvailableLocales()) {
Language language = new Language();
language.setLangname(locale.getDisplayName() + " - " + locale.getLanguage());
language.setLang_code(locale.getLanguage());
lstLang.add(language);
Log.d("LOCALES", locale.getLanguage() + "_" + locale.getCountry() + " [" + locale.getDisplayName() + "]");
}
}
private void ShowLanguage() {
adapterLanguage = new AdapterLanguage(ctx, lstLang);
RecyclerView.LayoutManager lmUser = new GridLayoutManager(ctx, 1);
recyclerLang.setLayoutManager(lmUser);
recyclerLang.setAdapter(adapterLanguage);
}
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
int id = item.getItemId();
switch (id) {
case R.id.nav_notif:
FunctionHelper.GotoRemind(ctx, CommonDefine.CONFIG_PAGE);
break;
case R.id.nav_user:
FunctionHelper.GotoListUser(ctx, CommonDefine.CONFIG_PAGE);
break;
case R.id.nav_my:
FunctionHelper.GotoProfile(ctx, CommonDefine.CONFIG_PAGE);
break;
case R.id.nav_his:
FunctionHelper.GotoHis(ctx, CommonDefine.CONFIG_PAGE);
break;
case R.id.nav_search:
new DialogSearchUser(ctx).show();
break;
case R.id.nav_manage:
FunctionHelper.GotoReport(ctx, CommonDefine.CONFIG_PAGE);
break;
case R.id.nav_change:
new DialogChangePass(ctx).show();
break;
case R.id.nav_config:
break;
case R.id.nav_pos:
break;
case R.id.nav_share:
FunctionHelper.GotoShare(ctx);
break;
case R.id.nav_send:
new DialogComment(ctx).show();
break;
case R.id.nav_help:
FunctionHelper.GotoHelp(ctx, CommonDefine.CONFIG_PAGE);
break;
case R.id.nav_ver:
FunctionHelper.GotoVer(ctx, CommonDefine.CONFIG_PAGE);
break;
case R.id.nav_logout:
FunctionHelper.Logout(ctx);
break;
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
|
package ru.itmo.ctlab.sgmwcs.solver;
import ilog.concert.IloException;
import ilog.concert.IloNumVar;
import ilog.cplex.IloCplex;
import ru.itmo.ctlab.sgmwcs.graph.Edge;
import ru.itmo.ctlab.sgmwcs.graph.Graph;
import ru.itmo.ctlab.sgmwcs.graph.Node;
import ru.itmo.ctlab.sgmwcs.graph.Unit;
import java.util.*;
public class Separator extends IloCplex.UserCutCallback {
public static final double ADDITION_CAPACITY = 1e-6;
public static final double STEP = 0.1;
public static final double EPS = 1e-5;
private final IloCplex cplex;
private final IloNumVar sum;
private final AtomicDouble lb;
private Map<Node, CutGenerator> generators;
private int maxToAdd;
private int minToConsider;
private List<Node> nodes;
private List<CutGenerator> generatorList;
private Map<Node, IloNumVar> y;
private Map<Edge, IloNumVar> w;
private int waited;
private double period;
private Graph graph;
private double last;
private boolean inited;
private Map<Unit, Integer> indices;
private IloNumVar[] vars;
public Separator(Map<Node, IloNumVar> y, Map<Edge, IloNumVar> w, IloCplex cplex, Graph graph,
IloNumVar sum, AtomicDouble lb) {
this.y = y;
this.w = w;
generators = new HashMap<>();
generatorList = new ArrayList<>();
nodes = new ArrayList<>();
maxToAdd = Integer.MAX_VALUE;
minToConsider = Integer.MAX_VALUE;
this.cplex = cplex;
this.graph = graph;
this.sum = sum;
this.lb = lb;
last = -Double.MAX_VALUE;
}
public void setMaxToAdd(int n) {
maxToAdd = n;
}
public void setMinToConsider(int n) {
minToConsider = n;
}
private synchronized boolean isCutsAllowed() {
waited++;
if (waited > period) {
waited = 0;
period += STEP;
return true;
}
return false;
}
public Separator clone() {
Separator result = new Separator(y, w, cplex, graph, sum, lb);
for (CutGenerator generator : generatorList) {
result.addComponent(graph.subgraph(generator.getNodes()), generator.getRoot());
}
return result;
}
@Override
protected void main() throws IloException {
double currLb = lb.get();
if (currLb > last) {
last = currLb;
add(cplex.ge(sum, currLb), IloCplex.CutManagement.UseCutPurge);
}
if (!isCutsAllowed()) {
return;
}
initWeights();
Collections.shuffle(nodes);
List<Node> now = nodes.subList(0, Math.min(nodes.size(), minToConsider));
int added = 0;
for (Node node : now) {
CutGenerator generator = generators.get(node);
List<Edge> cut = generator.findCut(node);
if (cut != null) {
Set<Edge> minCut = new HashSet<>();
minCut.addAll(cut);
synchronized (cplex) {
IloNumVar[] evars = minCut.stream().map(x -> w.get(x)).toArray(IloNumVar[]::new);
add(cplex.le(cplex.diff(y.get(node), cplex.sum(evars)), 0), IloCplex.CutManagement.UseCutPurge);
}
added++;
}
if (added == maxToAdd) {
break;
}
}
}
private void initWeights() throws IloException {
if (!inited) {
init();
}
double[] values = getValues(vars);
for (CutGenerator generator : generatorList) {
Set<Edge> visited = new HashSet<>();
for (Edge edge : generator.getEdges()) {
if (visited.contains(edge)) {
continue;
}
double weight = 0;
for (Edge e : graph.getAllEdges(graph.getEdgeSource(edge), graph.getEdgeTarget(edge))) {
weight += values[indices.get(e)];
visited.add(e);
}
generator.setCapacity(edge, weight + ADDITION_CAPACITY);
}
for (Node node : generator.getNodes()) {
generator.setVertexCapacity(node, values[indices.get(node)] - EPS);
}
}
}
private void init() {
inited = true;
indices = new HashMap<>();
int i = 0;
vars = new IloNumVar[w.size() + y.size()];
for (Edge e : graph.edgeSet()) {
vars[i] = w.get(e);
indices.put(e, i++);
}
for (Node v : graph.vertexSet()) {
vars[i] = y.get(v);
indices.put(v, i++);
}
}
public void addComponent(Graph graph, Node root) {
CutGenerator generator = new CutGenerator(graph, root);
generatorList.add(generator);
for (Node node : generator.getNodes()) {
if (node != generator.getRoot()) {
generators.put(node, generator);
nodes.add(node);
}
}
inited = false;
}
}
|
/**
*
*/
/**
* @author user
*
*/
package kr.co.shop.batch.sample.vo.xml.generator;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementRef;
import javax.xml.bind.annotation.XmlElementRefs;
import javax.xml.bind.annotation.XmlElementWrapper;
import javax.xml.bind.annotation.XmlElements;
import javax.xml.bind.annotation.XmlRootElement;
import lombok.Data;
@XmlRootElement(name="configuration")
@XmlAccessorType(XmlAccessType.FIELD)
@Data
public class GeneratorConfiguration {
@XmlElementWrapper
@XmlElementRefs(
@XmlElementRef(name="property")
)
private List<Property> properties;
@XmlElements({
@XmlElement(name="controllerpkg", type=ControllerPkg.class),
@XmlElement(name="servicepkg", type=ServicePkg.class),
@XmlElement(name="daopkg", type=DaoPkg.class)
})
@XmlElementWrapper
private List<GlobalPkg> global;
}
|
package com.m2miage.boundary;
import com.m2miage.entity.Action;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.rest.core.annotation.RepositoryRestResource;
//@RepositoryRestResource(collectionResourceRel="demande", path="demande")
public interface ActionRessource extends JpaRepository<Action,String> {
}
|
package com.emg.projectsmanage.pojo;
import java.io.Serializable;
import java.util.Date;
public class MetadataModel implements Serializable {
private static final long serialVersionUID = -1462182132697434276L;
private Integer id;
private String module;
private String key;
private Long value;
private String desc;
private String memo;
private Date createtime;
private String createby;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getModule() {
return module;
}
public void setModule(String module) {
this.module = module == null ? null : module.trim();
}
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key == null ? null : key.trim();
}
public Long getValue() {
return value;
}
public void setValue(Long value) {
this.value = value;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc == null ? null : desc.trim();
}
public String getMemo() {
return memo;
}
public void setMemo(String memo) {
this.memo = memo == null ? null : memo.trim();
}
public Date getCreatetime() {
return createtime;
}
public void setCreatetime(Date createtime) {
this.createtime = createtime;
}
public String getCreateby() {
return createby;
}
public void setCreateby(String createby) {
this.createby = createby == null ? null : createby.trim();
}
}
|
package br.com.LoginSpringBootThymeleaf.dto.Grupo;
import java.util.List;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@NoArgsConstructor
@AllArgsConstructor
public class GrupoResquestDTO {
private Integer codigo;
private String nome;
private String descricao;
private List<Integer> permissoes;
}
|
package com.seleniumsimplified.junit.Junit;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.ComparisonFailure;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.interactions.Actions;
import static org.junit.Assert.*;
public class UserInteractionsExercise1 {
// crea el elemento llamado driver que es de tipo WebDriver
//public WebDriver driver;
// un elemento tipo de la clase Driver
public static Driver Driver;
@BeforeClass
public static void createDriverAndVisitTestPage() {
// a este elemento se le asigna el metodo constructor Driver, que esta dentro de la clase Driver y se le
//manda de parametro el string dentro del parentesis
Driver= new Driver("hola");
//con el elemento driver se hace uso del metodo getDriver que esta declarado en la clase Driver para aceder a
// los comandos
Driver.getDriver().get("http://compendiumdev.co.uk/selenium/gui_user_interactions.html");
//Driver.getDriver()get...("ww.google.com");
}
//DONDE DEBE DE IR ESTO?
//public WebElement submitButton = Driver.getDriver().findElement(By.cssSelector("input[value='submit']"));
//Move draggable1 on to droppable1
@Test
public void exerciseUno(){
WebElement dragMe1 = Driver.getDriver().findElement(By.cssSelector("div[id='draggable1']"));
WebElement dropHere1 = Driver.getDriver().findElement(By.cssSelector("div[id='droppable1']"));
WebElement dropHere1Txt = dropHere1.findElement(By.cssSelector("p"));
new Actions(Driver.getDriver()).dragAndDrop(dragMe1,dropHere1).release().perform();
//System.out.print(dropHere1Txt);
assertEquals("Dropped!",dropHere1Txt.getText());
}
//Drag and Drop draggable2 to droppable1
@Test
public void exerciseDos(){
WebElement dragMe2 = Driver.getDriver().findElement(By.cssSelector("div[id='draggable2']"));
WebElement dropHere1 = Driver.getDriver().findElement(By.cssSelector("div[id='droppable1']"));
WebElement dropHere1Txt = dropHere1.findElement(By.cssSelector("p"));
new Actions(Driver.getDriver()).dragAndDrop(dragMe2,dropHere1).release().perform();
//System.out.print(dropHere1Txt);
assertEquals("Get Off Me!",dropHere1Txt.getText());
}
//Press control+B and assert for text change on draggable1 to “Bwa! Ha! Ha!”
// sin el keysup del control marca error
@Test
public void exerciseTres(){
WebElement dragMe1 = Driver.getDriver().findElement(By.cssSelector("div[id='draggable1']"));
//WebElement dragMe1Txt = dragMe1.findElement(By.cssSelector("p"));
Actions actions = new Actions(Driver.getDriver());
new Actions(Driver.getDriver()).keyDown(Keys.CONTROL).sendKeys("b").keyUp(Keys.CONTROL).perform();
assertEquals("Bwa! Ha! Ha!",dragMe1.getText());
}
// Control+Space and red squares say “Let GO!!”
@Test
public void exerciseCuatro(){
WebElement droppable1 = Driver.getDriver().findElement(By.id("droppable1"));
Actions actions = new Actions(Driver.getDriver());
actions.click(droppable1).build().perform();
//sendkeys does a keydown followed by keyup, so you can't use it for this as keys need to be
//held down
actions.keyDown(Keys.CONTROL).sendKeys(Keys.SPACE).build().perform();
String dropText = droppable1.getText();
actions.keyUp(droppable1,Keys.CONTROL).build().perform();
try{
assertEquals("Let GO!!", dropText );
fail("send keys should not be held down long enough to get the text");
} catch (ComparisonFailure e){
assertTrue("How can we hold down the keys?", true);
assertEquals("Drop Here", dropText );
}
}
// draw something in the canvas
@Test
public void exerciseCinco(){
WebElement canvas = Driver.getDriver().findElement(By.id("canvas"));
WebElement eventList = Driver.getDriver().findElement(By.id("keyeventslist"));
int eventCount = eventList.findElements(By.tagName("li")).size();
new Actions(Driver.getDriver()).
//click does not do it, need to click and hold
clickAndHold(canvas).
moveByOffset(10,10).
release().
perform();
assertTrue("we should have had some draw events", eventCount < eventList.findElements(By.tagName("li")).size());
}
@AfterClass
public static void stopDriver() {
//driver.quit();
}
}
|
package Assign7;
public class OrderNotValidException extends Exception {
OrderNotValidException(){
System.out.println("Order id is not valid");
}
@Override
public String toString() {
return "OrderNotValidException [] Order id is not valid";
}
}
|
package io.jrevolt.sysmon.model;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import javax.ws.rs.core.UriBuilder;
import javax.ws.rs.core.UriBuilderException;
import java.net.URI;
/**
* @author <a href="mailto:patrikbeno@gmail.com">Patrik Beno</a>
*/
public class EndpointDef {
private String cluster;
private String server;
private String jndi;
private URI uri;
private URI test;
private EndpointType type;
private EndpointStatus status;
private String comment;
public EndpointDef() {
}
public EndpointDef(EndpointDef src, ServerDef server) {
this.cluster = server.getCluster();
this.server = server.getName();
this.jndi = src.jndi;
this.uri = src.uri;
this.test = src.test;
this.type = src.type;
this.status = src.status;
}
public EndpointDef(EndpointDef src, String cluster, String server, String hostname) {
this.cluster = cluster;
this.server = server;
this.jndi = src.jndi;
this.uri = src.uri;
if (hostname != null) {
this.uri = UriBuilder.fromUri(src.uri).host(hostname).build();
}
this.test = src.test;
this.type = src.type;
this.status = src.status;
}
public EndpointDef(String uri) {
this.uri = URI.create(uri);
}
///
public String getCluster() {
return cluster;
}
public void setCluster(String cluster) {
this.cluster = cluster;
}
public String getServer() {
return server;
}
public void setServer(String server) {
this.server = server;
}
public String getJndi() {
return jndi;
}
public void setJndi(String jndi) {
this.jndi = jndi;
}
public URI getUri() {
return uri;
}
public void setUri(URI uri) {
this.uri = uri;
}
public URI getTest() {
return test;
}
public void setTest(URI test) {
this.test = test;
}
public EndpointType getType() {
return type;
}
public void setType(EndpointType type) {
this.type = type;
}
public EndpointStatus getStatus() {
return status;
}
public void setStatus(EndpointStatus status) {
this.status = status;
}
public String getComment() {
return comment;
}
public void setComment(String comment) {
this.comment = comment;
}
///
@Override
public String toString() {
return new ToStringBuilder(this, ToStringStyle.SHORT_PREFIX_STYLE)
.append("uri", uri)
.toString();
}
}
|
package MainApp;
import javax.swing.*;
import AbstractTypes.GymUser;
import AbstractTypes.Trainer;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.*;
import AbstractTypes.Administrator;
import java.awt.*;
import java.awt.event.*;
import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;
import java.util.ArrayList;
import java.util.Iterator;
public class Login extends JFrame implements ActionListener{
//private JPanel panel;
private JPasswordField password;
private JTextField username;
private JLabel usernameLabel;
private JLabel passwordLabel;
private JButton loginButton;
private JButton createAccountButton;
private JRadioButton radioButton1;
private JRadioButton radioButton2;
private JRadioButton radioButton3;
public Login()
{
super("Login Page");
getContentPane().setBackground(new Color(65, 105, 225));
this.setSize(600,400);
username = new JTextField();
password = new JPasswordField();
usernameLabel = new JLabel("Username: ");
passwordLabel = new JLabel("Password: ");
loginButton = new JButton("Login");//action listener to be added
createAccountButton = new JButton("Create account");//action listener to be added
radioButton1 = new JRadioButton("admin");
radioButton1.setBackground(new Color(65, 105, 225));
radioButton2 = new JRadioButton("trainer");
radioButton2.setBackground(new Color(65, 105, 225));
radioButton3 = new JRadioButton("gym user");
radioButton3.setBackground(new Color(65, 105, 225));
usernameLabel.setBounds(175,100,150,25);
passwordLabel.setBounds(175,150,150,25);
username.setBounds(250,100,150,25);
password.setBounds(250,150,150,25);
loginButton.setBounds(250,250,75,25);
createAccountButton.setBounds(25,300,125,50);
createAccountButton.setFont(new Font("Dialog", Font.PLAIN, 12));
radioButton1.setBounds(175,200,100,30);
radioButton2.setBounds(275,200,100,30);
radioButton3.setBounds(375,200,100,30);
loginButton.addActionListener(this);
createAccountButton.addActionListener(this);
ButtonGroup bg = new ButtonGroup();
bg.add(radioButton1);
bg.add(radioButton2);
bg.add(radioButton3);
/*radioButton1.addActionListener(this);
radioButton2.addActionListener(this);
radioButton3.addActionListener(this);*/
getContentPane().add(username);
getContentPane().add(password);
getContentPane().add(passwordLabel);
getContentPane().add(loginButton);
getContentPane().add(usernameLabel);
getContentPane().add(radioButton1);
getContentPane().add(radioButton2);
getContentPane().add(radioButton3);
getContentPane().add(createAccountButton);
getContentPane().setLayout(null);
this.setVisible(true);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
}
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
String passwordField = password.getText();
String usernameField = username.getText();
//JButton clicked = (JButton)e.getSource();
JButton clicked = (JButton)e.getSource();
boolean isLogged=false;
JSONParser parser = new JSONParser();
try (Reader reader = new FileReader("src/main/java/Resources/users.json")) {
JSONArray jsonArray = (JSONArray)parser.parse(reader);
//System.out.println(jsonArray);
Iterator<JSONObject> it = jsonArray.iterator();
while (it.hasNext()) {
JSONObject obj = it.next();
String userName = obj.get("username").toString();
String password = obj.get("password").toString();
String role = obj.get("role").toString();
if(userName.equals(usernameField) && password.equals(passwordField) && radioButton1.isSelected() && role.equals("admin"))
{
Administrator admin = new Administrator("admin");
JOptionPane.showMessageDialog(this,"Logged in as admin");
new AdminPage(admin);
isLogged=true;
dispose();
}
else if(userName.equals(usernameField) && password.equals(passwordField) && radioButton2.isSelected() && role.equals("trainer"))
{
Trainer trainer = new Trainer(usernameField);
JOptionPane.showMessageDialog(this,"Logged in as trainer");
isLogged=true;
new TrainerPage();
dispose();
}
else if(userName.equals(usernameField) && password.equals(passwordField) && radioButton3.isSelected() && role.equals("gymUser"))
{
GymUser user=new GymUser(usernameField);
System.out.println("User");
isLogged=true;
JOptionPane.showMessageDialog(this,"Logged in as user");
new GymUserPage(user);
dispose();
}
//roleList.add(obj.get("role").toString());
}
} catch (IOException h) {
h.printStackTrace();
} catch (ParseException h) {
h.printStackTrace();
}
if(isLogged==false && clicked != createAccountButton)
{
JOptionPane.showMessageDialog(this,"Account not found! Check your credetentials or create an account!");
}
if(clicked == createAccountButton)
{
new RegisterPage();
}
/*if(usernameField.equals ("admin") && passwordField .equals("admin") && radioButton1.isSelected())
{
Administrator admin = new Administrator("admin");
System.out.println("admin");
JOptionPane.showMessageDialog(this,"Logged in as admin");
new AdminPage(admin);
dispose();
}
if(userNameList.contains(usernameField) && passwordList.contains(passwordField) && roleList.contains("trainer") && radioButton3.isSelected())
{
GymUser user=new GymUser(usernameField);
JOptionPane.showMessageDialog(this,"Logged in as user");
new GymUserPage(user);
dispose();
}
if( userNameList.contains(usernameField) && passwordList.contains(passwordField) && roleList.contains("gymUser") && radioButton2.isSelected())
{
JOptionPane.showMessageDialog(this,"Logged in as trainer");
}*/
}
}
|
package com.simpletour.utils.mybatisUtil;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import java.io.IOException;
import java.io.Reader;
public class DatabaseUtil {
Reader reader = Resource.getResourceAsReader
}
|
package sampleproject.gui;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.util.*;
import java.util.logging.*;
import javax.swing.*;
import javax.swing.border.*;
/**
* The graphical user interface the user sees when they start the server
* application. This class provides the structure necessary for displaying
* configurable objects, for starting the server, and for exiting the server
* in a safe manner.
*/
public class ServerWindow extends JFrame implements Observer {
// All strings are defined in static final declarations at the start of the
// class. This will make localisation easier later (if we want to add it).
// Note that localisation is not required for certification.
private static final String START_BUTTON_TEXT = "Start server";
private static final String EXIT_BUTTON_TEXT = "Exit";
private static final String EXIT_BUTTON_TOOL_TIP
= "Stops the server as soon as it is safe to do so";
private static final String INITIAL_STATUS
= "Enter configuration parameters and click \""
+ START_BUTTON_TEXT + "\"";
/**
* A version number for this class so that serialization can occur
* without worrying about the underlying class changing between
* serialization and deserialization.
*
* Not that we ever serialize this class of course, but JFrame implements
* Serializable, so therefore by default we do as well.
*/
private static final long serialVersionUID = 5165L;
// All user modifiable fields are defined here, along with all buttons.
// This makes it easy to disable the fields and buttons once the
// configuration is complete and the server starts.
private ConfigOptions configOptionsPanel =
new ConfigOptions(ApplicationMode.SERVER);
private JButton startServerButton = new JButton(START_BUTTON_TEXT);
private JButton exitButton = new JButton(EXIT_BUTTON_TEXT);
private JLabel status = new JLabel();
/**
* The Logger instance. All log messages from this class are routed through
* this member. The Logger namespace is <code>sampleproject.gui</code>.
*/
private Logger log = Logger.getLogger("sampleproject.gui");
/**
* Constructs the standard Server GUI Window and displays it on screen.
*/
public ServerWindow() {
super("Denny's DVDs Server Application");
this.setDefaultCloseOperation(this.EXIT_ON_CLOSE);
this.setResizable(false);
// Add the menu bar
JMenuBar menuBar = new JMenuBar();
JMenu fileMenu = new JMenu("File");
JMenuItem quitMenuItem = new JMenuItem("Quit");
quitMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
System.exit(0);
}
});
quitMenuItem.setMnemonic(KeyEvent.VK_Q);
fileMenu.add(quitMenuItem);
fileMenu.setMnemonic(KeyEvent.VK_F);
menuBar.add(fileMenu);
this.setJMenuBar(menuBar);
configOptionsPanel.getObservable().addObserver(this);
this.add(configOptionsPanel, BorderLayout.NORTH);
this.add(commandOptionsPanel(), BorderLayout.CENTER);
status.setBorder(BorderFactory.createBevelBorder(BevelBorder.LOWERED));
JPanel statusPanel = new JPanel(new BorderLayout());
statusPanel.add(status, BorderLayout.CENTER);
this.add(statusPanel, BorderLayout.SOUTH);
// load saved configuration
SavedConfiguration config = SavedConfiguration.getSavedConfiguration();
// there may not be a default database location, so we had better
// validate before using the returned value.
String databaseLocation =
config.getParameter(SavedConfiguration.DATABASE_LOCATION);
configOptionsPanel.setLocationFieldText(
(databaseLocation == null) ? "" : databaseLocation);
// there may not be a network connectivity type defined and, if not, we
// do not set a default - force the user to make a choice the at least
// for the first time they run this.
String networkType
= config.getParameter(SavedConfiguration.NETWORK_TYPE);
if (networkType != null) {
try {
ConnectionType connectionType
= ConnectionType.valueOf(networkType);
configOptionsPanel.setNetworkConnection(connectionType);
startServerButton.setEnabled(true);
} catch (IllegalArgumentException e) {
log.warning("Unknown connection type: " + networkType);
}
}
// there is always at least a default port number, so we don't have to
// validate this.
configOptionsPanel.setPortNumberText(
config.getParameter(SavedConfiguration.SERVER_PORT));
status.setText(INITIAL_STATUS);
this.pack();
// Center on screen
Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
int x = (int) ((d.getWidth() - this.getWidth()) / 2);
int y = (int) ((d.getHeight() - this.getHeight()) / 2);
this.setLocation(x, y);
this.setVisible(true);
}
/**
* This private panel provides the buttons the user may click upon in order
* to do a major action (start the server or exit).
*
* @return a panel containing the mode change buttons.
*/
private JPanel commandOptionsPanel() {
JPanel thePanel = new JPanel();
thePanel.setLayout(new FlowLayout(FlowLayout.CENTER));
// this is one way to add an action listener - have a class (even a
// private class) implement ActionListener, then create a new instance
// of it - this can make the code very clean if you have many operations
// to perform in your action listener.
startServerButton.addActionListener(new StartServer());
startServerButton.setEnabled(false);
thePanel.add(startServerButton);
// this is another option for adding an action listener - create an
// anonymous ActionListener. This has the advantage of having the code
// that is run right with the button - it is obvious what is going to
// happen if someone clicks the exitButton.
exitButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
System.exit(0);
}
});
exitButton.setToolTipText(EXIT_BUTTON_TOOL_TIP);
thePanel.add(exitButton);
return thePanel;
}
/**
* A private class that will get called if the "Start" button is called. It
* will disable any buttons that should no longer be clicked upon, extract
* the configuration information from the server application, saving it
* where necessary, and start the server.<p>
*
* Note 1: If this was an MVC, this reaction to an event would be in
* the controller.<p>
*
* Note 2: There are a lot of hard coded widgets disabled here - this could
* potentially cause problems if a widget is added somewhere else in the
* class, and the programmer forgets to disable it here. Options to work
* around this include: creating a collection that widgets could be added
* to (then at this point we just iterate through the collection, disabling
* widgets), or using reflection to programmatically find all widgets
* (possibly excluding specific widgets) and disable them all. However
* this is getting a bit beyond scope for this application.
*/
private class StartServer implements ActionListener {
/** {@inheritDoc} */
public void actionPerformed(ActionEvent ae) {
configOptionsPanel.setLocationFieldEnabled(false);
configOptionsPanel.setPortNumberEnabled(false);
configOptionsPanel.setBrowseButtonEnabled(false);
configOptionsPanel.setSocketOptionEnabled(false);
configOptionsPanel.setRmiOptionEnabled(false);
startServerButton.setEnabled(false);
String port = configOptionsPanel.getPortNumberText();
String databaseLocation = configOptionsPanel.getLocationFieldText();
Thread exitRoutine = new CleanExit(databaseLocation);
Runtime.getRuntime().addShutdownHook(exitRoutine);
switch (configOptionsPanel.getNetworkConnection()) {
case SOCKET:
new NetworkStarterSockets(databaseLocation, port, status);
break;
case RMI:
new NetworkStarterRmi(databaseLocation, port, status);
break;
default:
}
}
}
/**
* Called whenever the user changes something in our common connectivity
* panel. Using this allows us to build the common panel without it needing
* to know how it will be used in this frame - it only needs to update any
* interested observers who can then decide for themselves what to do with
* the information.
*
* @param o the <code>Observable</code> object that is calling this method.
* @param arg the information that we need to be updated with - in this case
* information on what network choice was made.
*/
public void update(Observable o, Object arg) {
// we are going to ignore the Observable object, since we are only
// observing one object. All we are interested in is the argument.
if (!(arg instanceof OptionUpdate)) {
return;
}
OptionUpdate optionUpdate = (OptionUpdate) arg;
switch (optionUpdate.getUpdateType()) {
case NETWORK_CHOICE_MADE:
startServerButton.setEnabled(true);
break;
default:
log.warning("Observed unknown update type "
+ optionUpdate.getUpdateType());
break;
}
}
}
|
package com.example.springdemo.utility;
import com.example.springdemo.utility.concurrency.ScheduleUtil;
import com.example.springdemo.utility.concurrency.SingleUtil;
import com.example.springdemo.utility.exception.LambdaExceptionUtil;
import com.google.gson.Gson;
import java.util.regex.Pattern;
/**
* @author skysoo
* @version 1.0.0
* @since 2020-05-06 오후 4:32
**/
public class UT {
public static final Gson gson = new Gson();
public static final LambdaExceptionUtil exceptionHandler = LambdaExceptionUtil.get();
public static final ScheduleUtil schedule = ScheduleUtil.get();
public static final SingleUtil single = SingleUtil.get();
public static final Pattern decimalPattern = Pattern.compile("^[-]?[0-9.]+");
public static final Pattern datePattern = Pattern.compile("(^[0-9]{8})");
public static final Pattern timePattern = Pattern.compile("(^[0-9]{6})");
public static final Pattern priorityPattern = Pattern.compile("^([0-9]{1})");
public static final Pattern gwIdPattern = Pattern.compile("^([a-zA-Z0-9]{12})");
public static final Pattern dataTypePattern = Pattern.compile("^([A-Z]{9})");
public static final Pattern dataKndPattern = Pattern.compile("([a-zA-Z])*(_([a-zA-Z]*))+");
public static final Pattern ipAddrPattern = Pattern.compile("([0-9]){1,3}[.]([0-9]){1,3}[.]([0-9]){1,3}[.]([0-9]{1,3})");
/* 더미로 올라오는 댐 이미지에 대한 정규표현식 */
public static final Pattern imageFilePattern = Pattern.compile("^[a-zA-Z0-9_-]*.(jpg|png|jpeg|bmp|dxf|pdf)$");
/* 댐 고유 번호 (7자리 숫자 고정) */
public static final Pattern damUniqueNumPattern = Pattern.compile("^[0-9]{7}$");
public static final Pattern extensionPattern = Pattern.compile("^(([a-zA-Z0-9]+)([_]*)([a-zA-Z0-9]+)(.png|.jpg|.dxf|.PNG|.JPG|.DXF))");
public UT() {
}
}
// TODO: 2020-07-28 이전 주기 미수집 시, 1시간당 1번, 주기 ALL, 요청 및 수신, 단지 파일이 있는지만 데이터 확인은, GW upld data,
|
package controller;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.alibaba.fastjson.JSON;
import util.FileUtil;
import util.MerkleUtil;
/**
* 接收客户端传来的datablock 并返回根节点 进行完整性验证
*
* @author roc_peng
*
*/
public class DataBlockServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public void println(Object object) {
System.out.println(object);
}
public void print(Object object) {
System.out.print(object);
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// 返回值
Map<String, String> map = new HashMap<>();
// 三个属性 文件名 区块名 hash值
String fileName = req.getParameter("fileName");
String dataBlockName = req.getParameter("dataBlockName");
String hash = req.getParameter("hash");
System.out.println("fileName:"+fileName);
System.out.println("dataBlockName:"+dataBlockName);
System.out.println("hash:"+hash);
// 首先判断服务端是否有该文件:
List<String> fileNames = new LinkedList<>();
fileNames = FileUtil.getFileNames(FileUtil.filesPath + "merkle/", fileNames);
System.out.println("path:" + FileUtil.filesPath + "merkle/");
System.out.println("files:" + JSON.toJSONString(fileNames));
if (!fileNames.contains(fileName)) {
map.put("errcode", "-1");
map.put("errmsg", "服务端不存在该文件");
String json = JSON.toJSONString(map);
resp.setContentType("text/plain");
resp.setCharacterEncoding("utf-8");
PrintWriter out = new PrintWriter(resp.getOutputStream());
out.print(json);
out.flush();
return;
}
// 根据区块计算根hash
String fileMerkleData = FileUtil.readFileToStr(FileUtil.filesPath + "merkle/" + fileName);
List<List<Map<String, String>>> allList = new LinkedList<>();
allList =JSON.parseObject(fileMerkleData,List.class);
List<Map<String, String>> leaf = allList.get(0);
System.out.println("之前:"+JSON.toJSONString(leaf));
for (Map<String, String> node : leaf) {
if (node.get("name").equals(dataBlockName))
node.put("hash", hash);
}
System.out.println("之后:"+JSON.toJSONString(leaf));
// 生成merkle tree
allList.clear();
MerkleUtil.getMerkleNode2(leaf, allList);
List<Map<String, String>> root = allList.get(allList.size()-1);
Map<String, String> node = root.get(0);
map.put("errcode", "0");
map.put("roothash", node.get("hash"));
String json = JSON.toJSONString(map);
resp.setContentType("text/plain");
resp.setCharacterEncoding("utf-8");
PrintWriter out = new PrintWriter(resp.getOutputStream());
out.print(json);
out.flush();
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doGet(req, resp);
}
}
|
package com.epam.creational;
import com.epam.beans.Customer;
import com.epam.beans.User;
/**
* Created by Aliaksei_Kankou on 2/11/2017.
*/
public class CustomerMaker implements UserMaker
{
public User createUser()
{
return new Customer();
}
}
|
package com.dylowen.tinglebot;
import java.util.List;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.DefaultParser;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.MissingOptionException;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
import com.dylowen.tinglebot.brain.TextBrain;
import com.dylowen.tinglebot.train.SerializedBrainTrainer;
import com.dylowen.tinglebot.train.SkypeDatabaseTrainer;
import com.dylowen.tinglebot.train.TextTrainer;
import com.dylowen.tinglebot.train.Trainer;
/**
* TODO add description
*
* @author dylan.owen
* @since Feb-2016
*/
public class Main {
final static Option BRAIN_EXPORT_PATH = Option.builder("e").longOpt("export").argName("export_location").hasArg().desc(
"where to export the brain").build();
final static Option HELP = new Option("help", "print this menu");
final static Options MAIN_OPTIONS = new Options();
static {
MAIN_OPTIONS.addOption(BRAIN_EXPORT_PATH);
MAIN_OPTIONS.addOption(HELP);
}
public static void main(String[] args) {
CommandLineParser parser = new DefaultParser();
try {
CommandLine line = parser.parse(MAIN_OPTIONS, args, true);
if (line.hasOption(HELP.getOpt())) {
HelpFormatter formatter = new HelpFormatter();
formatter.printHelp("tinglebot <trainer_file>", MAIN_OPTIONS, true);
return;
}
final String path;
final String exportPath = line.getOptionValue(BRAIN_EXPORT_PATH.getOpt());
//make sure we got a training file
if (line.getArgs().length > 0) {
path = line.getArgs()[0];
}
else {
System.err.println("Please enter a training file location");
return;
}
final int extensionIndex = path.lastIndexOf('.');
final String extension = (extensionIndex < 0) ? "" : path.substring(extensionIndex + 1);
final Trainer<TextBrain> trainer;
if ("json".equals(extension)) {
trainer = new SkypeDatabaseTrainer(path);
}
else if ("txt".equals(extension)) {
trainer = new TextTrainer(path);
}
else if ("brain".equals(extension)) {
trainer = new SerializedBrainTrainer<>(path);
}
else {
throw new UnsupportedOperationException("Unknown file type");
}
final TextBrain brain = trainer.train();
//check if we should export the brain
if (exportPath != null) {
brain.export(exportPath);
}
final Timer timer = new Timer();
for (int i = 0; i < 10; i++) {
final StringBuilder sb = new StringBuilder();
List<String> sentence = brain.getSentenceWords();
sb.append(brain.concatSentence(sentence));
while (sb.length() < 140) {
sb.append("\n");
sentence = brain.getSentenceWords();
sb.append(brain.concatSentence(sentence));
}
System.out.println(sb.toString() + "\n");
}
System.out.println("sentence generation time: " + timer.getS() + "s");
}
catch (MissingOptionException e) {
for (Object o : e.getMissingOptions()) {
printMissingArgError(MAIN_OPTIONS.getOption(o.toString()));
}
}
catch (ParseException exp) {
// oops, something went wrong
System.err.println("Parsing failed. Reason: " + exp.getMessage());
}
}
static void printMissingArgError(final Option option) {
System.err.println("Missing Argument: <" + option.getLongOpt() + "> " + option.getDescription());
}
}
|
package com.jtexplorer.controller;
import com.jtexplorer.service.UserService;
import com.jtexplorer.entity.User;
import com.jtexplorer.entity.enums.RequestEnum;
import com.jtexplorer.entity.dto.JsonResult;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
/**
*
* @author xu.wang
* @since 2020-03-01
*/
@RestController
@RequestMapping("/front/user")
public class UserController {
@Autowired
public UserService userService;
/**
* 分页查询条件
* @param user 对象中填充查询条件
* @param page 第几页
* @param limit 每页显示的数量
* @return jsonResult.root : 记录,jsonResult.success : 成功/失败,jsonResult.totalSize : 总数量
*/
@GetMapping("/getPageList")
public JsonResult getUserList(@ModelAttribute User user,
@RequestParam(required = false,defaultValue = "1")Integer page,
@RequestParam(required = false,defaultValue = "20")Integer limit) {
JsonResult jsonResult = new JsonResult();
QueryWrapper<User> userWrapper = new QueryWrapper<>();
// //条件DEMO
// //like
// if(StringUtils.isNotEmpty(article.getArtiTitle())){
// articleWrapper.lambda().like(Article::getArtiTitle,article.getArtiTitle());
// }
// //等于
// articleWrapper.eq("column","value");
Page userPage = new Page<>(page,limit);
//第三个参数为false的时候,不查询数据总数
// Page articlePage = new Page<>(page,limit,false);
IPage<User> userIPage = userService.page(userPage,userWrapper);
jsonResult.setSuccess(true);
jsonResult.setTotalSize(userIPage.getTotal());
jsonResult.setRoot(userIPage.getRecords());
return jsonResult;
}
/**
* 不分页查询条件
* @param user 对象中填充查询条件
* @return jsonResult.root : 记录,jsonResult.success : 成功/失败,jsonResult.totalSize : 总数量
*/
@GetMapping("/getList")
public JsonResult getList(@ModelAttribute User user) {
JsonResult jsonResult = new JsonResult();
QueryWrapper<User> userWrapper = new QueryWrapper<>();
// //条件DEMO
// //like
// if(StringUtils.isNotEmpty(article.getArtiTitle())){
// articleWrapper.lambda().like(Article::getArtiTitle,article.getArtiTitle());
// }
// //等于
// articleWrapper.eq("column","value");
List<User> userList = userService.list(userWrapper);
jsonResult.setSuccess(true);
jsonResult.setTotalSize(userService.count(userWrapper));
jsonResult.setRoot(userList);
return jsonResult;
}
/**
* 新增一条数据
* @param user
* @return jsonResult.success : 成功/失败
*/
@PostMapping("/add")
public JsonResult add(User user) {
JsonResult jsonResult= new JsonResult();
if(userService.save(user)){
jsonResult.setSuccess(true);
}else {
jsonResult.buildFalseNew(RequestEnum.REQUEST_ERROR_DATABASE_UPDATE_ERROR);
}
return jsonResult;
}
/**
* 根据主键更新
* @param user
* @return jsonResult.success : 成功/失败
*/
@PostMapping("/updateById")
public JsonResult articleSave(User user) {
JsonResult jsonResult= new JsonResult();
if(userService.updateById(user)){
jsonResult.setSuccess(true);
}else {
jsonResult.buildFalseNew(RequestEnum.REQUEST_ERROR_DATABASE_UPDATE_ERROR);
}
return jsonResult;
}
/**
* 根据id删除对象
* @param id 实体ID
* @return jsonResult.success : 成功/失败
*/
@PostMapping("/delete")
public JsonResult delete(@RequestParam(required = false,defaultValue = "0") Long id){
JsonResult jsonResult = new JsonResult();
//判断主键
if(id == 0){
jsonResult.buildFalseNew(RequestEnum.REQUEST_ERROR_DATABASE_DELETE_NO_KEY);
}
if(userService.removeById(id)){
jsonResult.setSuccess(true);
}else{
jsonResult.buildFalseNew(RequestEnum.REQUEST_ERROR_DATABASE_DELETE_ERROR);
}
return jsonResult;
}
/**
* 根据Id批量删除数据
* @param idList 需要删除对象ID列表
* @return jsonResult.success : 成功/失败
*/
@PostMapping("/batchDeleteById")
public JsonResult deleteBatchIds(@RequestParam(required = false,defaultValue = "") String idList){
JsonResult jsonResult=new JsonResult();
//先验证id组成的JOSN
List<Long> ids=null;
try{
ids=(List<Long>)JSON.parse(idList);
}catch(Exception e){
jsonResult.setSuccess(false);
jsonResult.setFailReason("JSON格式错误!");
return jsonResult;
}
if(userService.removeByIds(ids)){
jsonResult.setSuccess(true);
}else{
jsonResult.buildFalseNew(RequestEnum.REQUEST_ERROR_DATABASE_DELETE_ERROR);
}
return jsonResult;
}
}
|
package com.kodilla.stream.world;
import org.junit.Assert;
import org.junit.Test;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import static org.junit.Assert.assertEquals;
public class WorldTestSuite {
@Test
public void testGetPeopleQuantity() {
//Given
City wroclaw = new City("Wroclaw", new BigDecimal("200000"));
City poznan = new City("Poznan", new BigDecimal("100000"));
City warszawa = new City("Warszawa", new BigDecimal("500000"));
City berlin = new City("Berlin", new BigDecimal("1000000"));
City munchen = new City("Munchen", new BigDecimal("2000000"));
Country poland = new Country();
poland.addCity(wroclaw);
poland.addCity(poznan);
poland.addCity(warszawa);
Country germany = new Country();
germany.addCity(berlin);
germany.addCity(munchen);
Continent europe = new Continent();
europe.addCountry(poland);
europe.addCountry(germany);
World world = new World();
world.addContinent(europe);
System.out.println(poland.getListOfCities());
System.out.println(europe.getListOfCountries());
System.out.println(world.getListOfContinents());
BigDecimal result = world.getPeopleQuantity();
assertEquals(new BigDecimal(3800000), result);
}
}
|
package com.programapprentice.app;
import java.util.ArrayList;
import java.util.List;
public class PalindromePartitioning_131 {
// Begin start with 0.
private boolean isPalindrome(String s, int begin, int end) {
if(s == null || begin == end) {
return true;
}
int low = begin;
int high = end;
while(low < high) {
if(s.charAt(high) != s.charAt(low)) {
return false;
}
low++;
high--;
}
return true;
}
// This is unfinished
// public List<List<String>> partitionUncomplete(String s) {
// List<List<String>> output = new ArrayList<List<String>>();
// boolean[][] isPalindrome = new boolean[][];
//
// for(int i = 0; i < s.length(); i++) {
//
// }
//
// return output;
// }
//////////////////////////////////////////////////////////////////////
// DFS accepted
public List<List<String>> partitionDfs(String s) {
List<List<String>> output = new ArrayList<List<String>>();
for(int i = 0; i < s.length(); i++) {
if(isPalindrome(s, 0, i)) { // wrong: if(isPalindrome(s, 0, i+1)) {
if(i == s.length()-1) {
List<String> tmp = new ArrayList<String>();
tmp.add(s);
output.add(tmp);
} else {
List<List<String>> tmp = partitionDfs(s.substring(i + 1));
for(List<String> item : tmp) {
item.add(0, s.substring(0, i+1));
}
output.addAll(tmp);
}
}
}
return output;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.