text
stringlengths 10
2.72M
|
|---|
/*
* BrowsersVersionFilter.java
* This file was last modified at 2018.12.03 20:05 by Victor N. Skurikhin.
* $Id$
* This is free and unencumbered software released into the public domain.
* For more information, please refer to <http://unlicense.org>
*/
package ru.otus.servlets;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import ru.otus.utils.BrowserInfo;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import static ru.otus.gwt.shared.Constants.*;
@WebFilter(filterName = BROWSERS_VERSION_FILTER, urlPatterns = "/*")
public class BrowsersVersionFilter extends HttpFilter
{
private static final Logger LOGGER = LogManager.getLogger(BrowsersVersionFilter.class.getName());
private boolean isBrowserSupportCheckAlreadyPassed(HttpServletRequest request)
{
Cookie[] cookies = request.getCookies();
return cookies != null && Arrays.stream(cookies).anyMatch(
cookie -> cookie.getName().equals(COOKIE_NAME_BROWSER_SUPPORT_CHECK_PASSED)
);
}
private boolean isDecorRequest(HttpServletRequest request)
{
String url = request.getRequestURL().toString();
return url.contains("/css/") || url.contains("/img/") || url.contains("/webfonts/");
}
@Override
protected void doFilter(HttpServletRequest req, HttpServletResponse res, FilterChain chain)
throws IOException, ServletException
{
if (isDecorRequest(req)) {
chain.doFilter(req, res);
}
else if (isBrowserSupportCheckAlreadyPassed(req) || BrowserInfo.isSupportedBrowser(req)) {
LOGGER.debug("BrowserInfo supported.");
res.addCookie(new Cookie(COOKIE_NAME_BROWSER_SUPPORT_CHECK_PASSED, "1"));
LOGGER.debug("Cookie added.");
chain.doFilter(req, res);
}
else {
LOGGER.debug("BrowserInfo not supported. Forward ...");
req.getRequestDispatcher("/" + REQUEST_BROWSERS_JSP).forward(req, res);
LOGGER.debug("Never logged.");
}
}
}
/* vim: syntax=java:fileencoding=utf-8:fileformat=unix:tw=78:ts=4:sw=4:sts=4:et
*/
//EOF
|
package net.liuzd.spring.boot.v2.web.filter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import net.liuzd.spring.boot.v2.web.util.XssUtil;
@Slf4j
public class XssFilter implements Filter {
private List<String> excludes = new ArrayList<String>();
@Override
public void init(FilterConfig filterConfig) throws ServletException {
String excludesStr = filterConfig.getInitParameter("excludes");
if (null != excludesStr && excludesStr.length() > 0) {
excludes.addAll(Arrays.asList(excludesStr.split(",")));
}
log.debug("(XssFilter) initialize");
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException,
ServletException {
log.debug("(XssFilter) doFilter");
//
HttpServletRequest req = (HttpServletRequest) request;
if (XssUtil.handleExcludeURL(excludes, req.getServletPath())) {
log.debug("排除请求url...");
chain.doFilter(request, response);
return;
}
//
XssHttpServletRequestWrapper xssRequest = new XssHttpServletRequestWrapper(req);
chain.doFilter(xssRequest, response);
}
@Override
public void destroy() {
log.debug("(XssFilter) destroy");
}
}
|
package com.takshine.wxcrm.message.sugar;
import java.util.ArrayList;
import java.util.List;
/**
* 查询报表接口 从crm响应回来的参数
*
*/
public class AnalyticsResp extends BaseCrm {
private List<AnalyticsExpenseResp> expense = new ArrayList<AnalyticsExpenseResp>();// 费用列表
private List<AnalyticsOpptyResp> opptyList = new ArrayList<AnalyticsOpptyResp>();// 业务机会列表
private List<AnalyticsReceivableResp> receList = new ArrayList<AnalyticsReceivableResp>();// 回款列表
private List<AnalyticsCustomeryResp> customerList = new ArrayList<AnalyticsCustomeryResp>();// 客户列表列表
private List<AnalyticsContactResp> contactList = new ArrayList<AnalyticsContactResp>(); //联系人列表
private List<AnalyticsQuotaResp> quotas = new ArrayList<AnalyticsQuotaResp>();// 目标列表
private List<AnalyticsComplaintResp> complaints = new ArrayList<AnalyticsComplaintResp>();//服务请求列表
private String count = null;
public List<AnalyticsQuotaResp> getQuotas() {
return quotas;
}
public void setQuotas(List<AnalyticsQuotaResp> quotas) {
this.quotas = quotas;
}
public List<AnalyticsCustomeryResp> getCustomerList() {
return customerList;
}
public List<AnalyticsContactResp> getContactList() {
return contactList;
}
public void setCustomerList(List<AnalyticsCustomeryResp> customerList) {
this.customerList = customerList;
}
public void setContactList(List<AnalyticsContactResp> contactList) {
this.contactList = contactList;
}
public List<AnalyticsExpenseResp> getExpense() {
return expense;
}
public void setExpense(List<AnalyticsExpenseResp> expense) {
this.expense = expense;
}
public String getCount() {
return count;
}
public void setCount(String count) {
this.count = count;
}
public List<AnalyticsOpptyResp> getOpptyList() {
return opptyList;
}
public List<AnalyticsReceivableResp> getReceList() {
return receList;
}
public void setReceList(List<AnalyticsReceivableResp> receList) {
this.receList = receList;
}
public void setOpptyList(List<AnalyticsOpptyResp> opptyList) {
this.opptyList = opptyList;
}
public List<AnalyticsComplaintResp> getComplaints() {
return complaints;
}
public void setComplaints(List<AnalyticsComplaintResp> complaints) {
this.complaints = complaints;
}
}
|
import java.text.SimpleDateFormat;
import java.util.Date;
public class TimePeriod implements Comparable<TimePeriod> {
private long from;
private long to;
private final SimpleDateFormat dayFormat = new SimpleDateFormat("yyyy.MM.dd");
private static final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy.MM.dd HH:mm");
private static final SimpleDateFormat timeFormat = new SimpleDateFormat("HH:mm");
/**
* Time period within one day
*
* @param from
* @param to
*/
public TimePeriod(long from, long to) {
this.from = from;
this.to = to;
// SimpleDateFormat dayFormat = new SimpleDateFormat("yyyy.MM.dd");
if (!dayFormat.format(new Date(from)).equals(dayFormat.format(new Date(to))))
throw new IllegalArgumentException("Dates 'from' and 'to' must be within ONE day!");
}
// public TimePeriod(Date from, Date to) {
// this.from = from.getTime();
// this.to = to.getTime();
// // SimpleDateFormat dayFormat = new SimpleDateFormat("yyyy.MM.dd");
// if (!dayFormat.format(from).equals(dayFormat.format(to)))
// throw new IllegalArgumentException("Dates 'from' and 'to' must be within ONE day!");
// }
// public void appendTime(Date visitTime) {
// // SimpleDateFormat dayFormat = new SimpleDateFormat("yyyy.MM.dd");
// if (!dayFormat.format(new Date(from)).equals(dayFormat.format(visitTime)))
// throw new IllegalArgumentException("Visit time must be within the same day as the current TimePeriod!");
// long visitTimeTs = visitTime.getTime();
// if (visitTimeTs < from) {
// from = visitTimeTs;
// }
// if (visitTimeTs > to) {
// to = visitTimeTs;
// }
// }
public void appendTime(long visitTime) {
if (!dayFormat.format(new Date(from)).equals(dayFormat.format(visitTime)))
throw new IllegalArgumentException("Visit time must be within the same day as the current TimePeriod!");
if (visitTime < from) {
from = visitTime;
}
if (visitTime > to) {
to = visitTime;
}
}
public String toString() {
// String from = dateFormat.format(this.from);
// String to = timeFormat.format(this.to);
String from = dateFormat.format(new Date(this.from));
String to = timeFormat.format(new Date(this.to));
return from + "-" + to;
}
@Override
public int compareTo(TimePeriod period) {
long delta = 86400000;
long current = from;
long compared = period.from;
if (Math.abs(current - compared) < delta) {
return 0;
} else return -1;
// return dayFormat.format(from).compareTo(dayFormat.format(period.from));
}
}
|
package instruments.strings.boweds;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class CelloTest {
Cello cello;
@Before
public void before() {
cello = new Cello("Rialto VC 730", "Stenton", "Laminated", 282.78, 434.00, "zan zan",4, "1/4");
}
@Test
public void celloCanHaveModel() {
assertEquals("Rialto VC 730", cello.getModel());
}
@Test
public void cellonCanHaveBrand() {
assertEquals("Stenton", cello.getBrand());
}
@Test
public void celloCanHaveType() {
assertEquals("Laminated", cello.getType());
}
@Test
public void celloCanHaveNumberOfStrings() {
assertEquals(4, cello.getNumberOfStrings());
}
@Test
public void celloCanHaveSize() {
assertEquals("1/4", cello.getSize());
}
@Test
public void celloCanHaveBuyingPrice() {
assertEquals(282.78, cello.getBuyingPrice(), 0.001);
}
@Test
public void celloCanHaveSellingPrice() {
assertEquals(434.00, cello.getSellingPrice(), 0.001);
}
@Test
public void celloCanPlay() {
assertEquals("zan zan", cello.play());
}
@Test
public void celloHaveAMarkup() {
assertEquals(53.48, cello.markup(), 0.01);
}
}
|
/*
* 2012-3 Red Hat Inc. and/or its affiliates and other contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.overlord.rtgov.analytics.situation.store;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.overlord.commons.services.ServiceRegistryUtil;
import org.overlord.rtgov.common.util.RTGovProperties;
/**
* This class represents a CDI factory for obtaining a situation store implementation.
*
*/
public final class SituationStoreFactory {
private static final Logger LOG=Logger.getLogger(SituationStoreFactory.class.getName());
private static final String SITUATION_STORE_CLASS="SituationStore.class";
private static SituationStore _instance;
/**
* Private constructor.
*/
private SituationStoreFactory() {
}
/**
* This method resets the factory.
*/
public static void clear() {
_instance = null;
}
/**
* This method returns an instance of the SituationStore interface.
*
* @return The situation store
*/
public static SituationStore getSituationStore() {
if (_instance == null) {
java.util.Set<SituationStore> services=ServiceRegistryUtil.getServices(SituationStore.class);
String clsName=(String)RTGovProperties.getProperties().get(SITUATION_STORE_CLASS);
for (SituationStore sits : services) {
if (LOG.isLoggable(Level.FINEST)) {
LOG.finest("Checking situation store impl="+sits);
}
if (sits.getClass().getName().equals(clsName)) {
// Only overwrite if instance not set
if (_instance == null) {
_instance = sits;
if (LOG.isLoggable(Level.FINEST)) {
LOG.finest("Found situation store impl="+sits);
}
}
break;
}
}
}
if (LOG.isLoggable(Level.FINER)) {
LOG.finer("Situation store instance="+_instance);
}
return (_instance);
}
}
|
package datastructure.sort;
/**
* @author by dsy
* @Classname QuickSelect
* @Description TODO
* @Date 2022/12/30 10:47
*/
public class QuickSelect {
public static void main(String[] args) {
int[] arr = {4, 7, 1, 3, 9, 0, 8, 5, 20};
System.out.println(quickSelect(arr, 2));
}
public static int quickSelect(int[] arr, int k) {
return quickSelectHelper(arr, k, 0, arr.length - 1);
}
public static int quickSelectHelper(int[] arr, int k, int start, int end) {
if (start == end) {
return arr[start];
}
int pivotIndex = selectPivotRandom(start, end);
int index = partition(arr, start, end, pivotIndex);
if (index == k) {
return arr[k];
} else {
if (k < index) {
return quickSelectHelper(arr, k, start, index - 1);
} else {
return quickSelectHelper(arr, k, index + 1, end);
}
}
}
private static int partition(int[] arr, int start, int end, int pivotIndex) {
int pivot = arr[pivotIndex];
swap(arr, start, pivotIndex);
int i = start + 1;
for (int j = start + 1; j <= end; j++) {
if (arr[j] <= pivot) {
swap(arr, i, j);
i++;
}
}
swap(arr, start, i - 1);
return i - 1;
}
private static void swap(int[] arr, int i, int j) {
int tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
}
public static int selectPivotRandom(int start, int end) {
return start + (int) Math.floor(Math.random() * (end - start + 1));
}
}
|
package com.xujiangjun.archetype.web.interceptor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* 自定义Http请求拦截器
*
* @author xujiangjun
* @since 2018.11.26
*/
@Slf4j
public class CustomInterceptor extends HandlerInterceptorAdapter {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
String requestURI = request.getRequestURI();
// ...
return super.preHandle(request, response, handler);
}
}
|
package com.example.maximeglod.fbta;
import com.github.mikephil.charting.data.Entry;
import java.util.Comparator;
import java.util.function.Function;
import java.util.function.ToDoubleFunction;
import java.util.function.ToIntFunction;
import java.util.function.ToLongFunction;
/**
* Comparator for comparing Entry-objects by their x-value.
*/
public class EntryXComparator implements Comparator<Entry> {
@Override
public int compare(Entry entry1, Entry entry2) {
float diff = entry1.getX() - entry2.getX();
if (diff == 0f) return 0;
else {
if (diff > 0f) return 1;
else return -1;
}
}
@Override
public Comparator<Entry> reversed() {
return null;
}
@Override
public Comparator<Entry> thenComparing(Comparator<? super Entry> other) {
return null;
}
@Override
public <U> Comparator<Entry> thenComparing(Function<? super Entry, ? extends U> keyExtractor, Comparator<? super U> keyComparator) {
return null;
}
@Override
public <U extends Comparable<? super U>> Comparator<Entry> thenComparing(Function<? super Entry, ? extends U> keyExtractor) {
return null;
}
@Override
public Comparator<Entry> thenComparingInt(ToIntFunction<? super Entry> keyExtractor) {
return null;
}
@Override
public Comparator<Entry> thenComparingLong(ToLongFunction<? super Entry> keyExtractor) {
return null;
}
@Override
public Comparator<Entry> thenComparingDouble(ToDoubleFunction<? super Entry> keyExtractor) {
return null;
}
}
|
package com.commercetools.pspadapter.payone.notification.common;
import com.commercetools.payments.TransactionStateResolver;
import com.commercetools.pspadapter.payone.domain.payone.model.common.Notification;
import com.commercetools.pspadapter.payone.domain.payone.model.common.NotificationAction;
import com.commercetools.pspadapter.payone.notification.NotificationProcessorBase;
import com.commercetools.pspadapter.tenant.TenantConfig;
import com.commercetools.pspadapter.tenant.TenantFactory;
import io.sphere.sdk.commands.UpdateAction;
import io.sphere.sdk.payments.Payment;
import io.sphere.sdk.payments.Transaction;
import io.sphere.sdk.payments.TransactionDraftBuilder;
import io.sphere.sdk.payments.TransactionState;
import io.sphere.sdk.payments.TransactionType;
import io.sphere.sdk.payments.commands.updateactions.AddTransaction;
import io.sphere.sdk.payments.commands.updateactions.ChangeTransactionState;
import io.sphere.sdk.utils.MoneyImpl;
import javax.money.MonetaryAmount;
import java.util.ArrayList;
import java.util.List;
/**
* A NotificationProcessor for notifications with {@code txaction} "paid".
*
* @author Jan Wolter
*/
public class PaidNotificationProcessor extends NotificationProcessorBase {
public PaidNotificationProcessor(TenantFactory tenantFactory, TenantConfig tenantConfig,
TransactionStateResolver transactionStateResolver) {
super(tenantFactory, tenantConfig, transactionStateResolver);
}
@Override
protected boolean canProcess(final Notification notification) {
return NotificationAction.PAID.equals(notification.getTxaction());
}
@Override
protected List<UpdateAction<Payment>> createPaymentUpdates(final Payment payment,
final Notification notification) {
final List<UpdateAction<Payment>> updateActions = new ArrayList<>();
updateActions.addAll(super.createPaymentUpdates(payment, notification));
final List<Transaction> transactions = payment.getTransactions();
final String sequenceNumber = toSequenceNumber(notification.getSequencenumber());
final TransactionState ctTransactionState = notification.getTransactionStatus().getCtTransactionState();
return findMatchingTransaction(transactions, TransactionType.CHARGE, sequenceNumber)
.map(transaction -> {
if (ctTransactionState.equals(TransactionState.SUCCESS)) {
if (isNotCompletedTransaction(transaction)) {
updateActions.add(ChangeTransactionState.of(ctTransactionState, transaction.getId()));
}
}
return updateActions;
})
.orElseGet(() -> {
final MonetaryAmount amount = MoneyImpl.of(notification.getPrice(), notification.getCurrency());
updateActions.add(AddTransaction.of(TransactionDraftBuilder.of(TransactionType.CHARGE, amount)
.timestamp(toZonedDateTime(notification))
.state(ctTransactionState)
.interactionId(sequenceNumber)
.build()));
return updateActions;
});
}
}
|
package com.augment.golden.bulbcontrol.Beans;
import android.app.Activity;
import android.content.Context;
import com.augment.golden.bulbcontrol.Adapters.BulbGroupListAdapter;
import com.augment.golden.bulbcontrol.Adapters.SmartBulbListAdapter;
public class TaskInfo {
private Context context;
private Activity activity;
private SmartBulbListAdapter adapter;
private BulbGroupListAdapter groupAdapter;
public TaskInfo(Context context, Activity activity, SmartBulbListAdapter adapter, BulbGroupListAdapter groupAdapter) {
this.context = context;
this.activity = activity;
this.adapter = adapter;
this.groupAdapter = groupAdapter;
}
public Context getContext() {
return context;
}
public Activity getActivity() {
return activity;
}
public void setActivity(Activity activity) {
this.context = activity;
}
public SmartBulbListAdapter getAdapter() {
return adapter;
}
public BulbGroupListAdapter getGroupAdapter() {
return groupAdapter;
}
public void setGroupAdapter(BulbGroupListAdapter groupAdapter) {
this.groupAdapter = groupAdapter;
}
public void setAdapter(SmartBulbListAdapter adapter) {
this.adapter = adapter;
}
}
|
package com.java.app.controller;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.codehaus.jackson.map.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestTemplate;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.java.app.beans.AdminLoginDO;
import com.java.app.beans.DomainsDO;
import com.java.app.beans.ServerConfigDO;
import com.java.app.utils.AppConstants;
import com.java.app.utils.RestURIConstants;
@Controller
@RequestMapping(value ="/domain_controller")
public class DomainController
{
/** The logger. */
private static final Logger logger = LoggerFactory.getLogger(DomainController.class);
/**
* Create a new record.
*
* @param request
* @return true, if successful
*/
@RequestMapping(value = "/createRecord", method = RequestMethod.POST)
public @ResponseBody Integer createRecord (HttpServletRequest request, HttpSession session)
{
DomainsDO domainObj = new DomainsDO();
DomainsDO domainObj_name = new DomainsDO();
boolean bStatus = false;
Integer return_key = 2;
ServerConfigDO configDO = new ServerConfigDO();
try
{
configDO = fetchingServerConfig();
if(new Date().after(configDO.getdMaintainStartDate()) && new Date().before(configDO.getdMaintainEndDate()))
{
String sDomain_txt = request.getParameter("domain_txt");
AdminLoginDO session_admin = (AdminLoginDO) session.getAttribute(AppConstants.ADMIN);
String sprim_id = request.getParameter("domain_id");
if(null != sprim_id && sprim_id != "")
{
Integer id = Integer.valueOf(request.getParameter("domain_id"));
domainObj.setId(id);
domainObj.setsUpdatedBy(session_admin.getsUserName());
} else
{
domainObj_name = fetchingDomainDetailsByName(sDomain_txt.trim());
if(domainObj_name.getId() != null)
{
domainObj = domainObj_name;
domainObj.setsUpdatedBy(session_admin.getsUserName());
} else
{
domainObj.setsCreatedBy(session_admin.getsUserName());
}
}
RestTemplate restTemplate = new RestTemplate();
// set the values
domainObj.setsDomainName(sDomain_txt.trim());
domainObj.setcIsDeleted('N');
bStatus = restTemplate.postForObject(RestURIConstants.RESTAPI_URL+RestURIConstants.CREATE_UPDATE_DOMAIN, domainObj, Boolean.class);
if(bStatus)
{
return_key = 1;
logger.info("Domain Inserted");
} else
{
return_key = 2;
}
} else
{
return_key = 3;
}
} catch (Exception excp)
{
logger.error(excp.getMessage(), excp);
}
return return_key;
}
/**
* Update a existing record.
*
* @param request
* @return true, if successful
*/
@RequestMapping(value = "/deleteRecord", method = RequestMethod.POST)
public @ResponseBody Integer deleteRecord(HttpServletRequest request, HttpSession session)
{
DomainsDO domainObj = new DomainsDO();
boolean bStatus = false;
Integer return_key = 2;
ServerConfigDO configDO = new ServerConfigDO();
try
{
configDO = fetchingServerConfig();
if(new Date().after(configDO.getdMaintainStartDate()) && new Date().before(configDO.getdMaintainEndDate()))
{
Integer id = Integer.valueOf(request.getParameter("domain_id"));
String sKey = request.getParameter("key");
AdminLoginDO session_admin = (AdminLoginDO) session.getAttribute(AppConstants.ADMIN);
RestTemplate restTemplate = new RestTemplate();
// set the values
domainObj.setId(id);
domainObj.setcIsDeleted('Y');
domainObj.setsUpdatedBy(session_admin.getsUserName());
domainObj.setsKey(sKey);
bStatus = restTemplate.postForObject(RestURIConstants.RESTAPI_URL+RestURIConstants.DELETE_DOMAIN, domainObj, Boolean.class);
if(bStatus)
{
return_key = 1;
logger.info("Domain Deleted");
} else
{
return_key = 2;
}
} else
{
return_key = 3;
}
} catch (Exception excp)
{
logger.error(excp.getMessage(), excp);
}
return return_key;
}
@SuppressWarnings("unchecked")
@RequestMapping(value = "/fetching_all_list", method = RequestMethod.POST)
public @ResponseBody List<DomainsDO> getAllCompetenMst(HttpServletRequest request)
{
List<DomainsDO> list_demo = new ArrayList<DomainsDO>();
List<DomainsDO> list_demo_1 = new ArrayList<DomainsDO>();
List<DomainsDO> convert_list = new ArrayList<DomainsDO>();
try
{
RestTemplate restTemplate = new RestTemplate();
list_demo_1 = restTemplate.postForObject(RestURIConstants.RESTAPI_URL+RestURIConstants.GET_ALL_DOMAIN_LIST, list_demo, List.class);
String element = new Gson().toJson(list_demo_1, new TypeToken<ArrayList<DomainsDO>>() {}.getType());
ObjectMapper mapper = new ObjectMapper();
convert_list = Arrays.asList(mapper.readValue(element, DomainsDO[].class));
}catch (Exception e) {
logger.info("error :", e.getMessage());
}
return convert_list;
}
/**
* Retire record
*
* @param request
* @param session
* @return {@link ProcessMstDO}
*/
@RequestMapping(value = "/retriveRecord", method = RequestMethod.POST)
public @ResponseBody DomainsDO retriveRecord(HttpServletRequest request, HttpSession session)
{
DomainsDO do1 = new DomainsDO();
DomainsDO do1_1 = new DomainsDO();
try
{
Integer id = Integer.valueOf(request.getParameter("id"));
do1.setId(id);
RestTemplate restTemplate = new RestTemplate();
do1_1 = restTemplate.postForObject(RestURIConstants.RESTAPI_URL+RestURIConstants.GET_SINGLE_DOMAIN, do1, DomainsDO.class);
} catch (Exception e) {
logger.info("error :", e.getMessage());
}
return do1_1;
}
/**
* Retire record by name
*
* @param request
* @param session
* @return {@link ProcessMstDO}
*/
@RequestMapping(value = "/check_duplicate", method = RequestMethod.POST)
public @ResponseBody boolean check_duplicate(HttpServletRequest request, HttpSession session)
{
DomainsDO do1 = new DomainsDO();
boolean bStatus = false;
try
{
String domain_name = request.getParameter("domain_txt");
do1.setsDomainName(domain_name);
RestTemplate restTemplate = new RestTemplate();
do1 = restTemplate.postForObject(RestURIConstants.RESTAPI_URL+RestURIConstants.GET_SINGLE_DOMAIN_BY_NAME, do1, DomainsDO.class);
if(do1.getId() != null)
{
bStatus = true;
}
} catch (Exception e) {
logger.info("error :", e.getMessage());
}
return bStatus;
}
private DomainsDO fetchingDomainDetailsByName(String domain_name)
{
DomainsDO do1 = new DomainsDO();
try
{
do1.setsDomainName(domain_name);
RestTemplate restTemplate = new RestTemplate();
do1 = restTemplate.postForObject(RestURIConstants.RESTAPI_URL+RestURIConstants.GET_SINGLE_DOMAIN_BY_NAME, do1, DomainsDO.class);
} catch (Exception e) {
logger.info("error :", e.getMessage());
}
return do1;
}
/**
* Fetching server config
*
* @return
*/
private ServerConfigDO fetchingServerConfig()
{
ServerConfigDO serverConfigDO = new ServerConfigDO();
try
{
serverConfigDO.setId(1);
RestTemplate restTemplate = new RestTemplate();
serverConfigDO = restTemplate.postForObject(RestURIConstants.RESTAPI_URL+RestURIConstants.GET_SINGLE_SERVER_CONFIG, serverConfigDO, ServerConfigDO.class);
}catch (Exception excp) {
logger.error(excp.getMessage(), excp);
}
return serverConfigDO;
}
}
|
package com.bodansky.videochat.domain;/*
* Created by Adam Bodansky on 2017.05.26..
*/
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
@Getter
@AllArgsConstructor
@NoArgsConstructor
public enum Role {
USER("User"),
ADMIN("Admin");
private String roleName;
}
|
package org.sohil.ancrud.dao;
import java.util.List;
import org.hibernate.Criteria;
import org.hibernate.Hibernate;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.sohil.ancrud.model.User;
import org.springframework.stereotype.Repository;
@Repository("userDao")
public class UserDaoImpl extends AbstractDao<Integer,User> implements UserDao{
static final Logger logger=LoggerFactory.getLogger(UserDaoImpl.class);
public User findById(int id) {
User user=getByKey(id);
if (user!=null){
Hibernate.initialize(user.getUserProfiles());
}
return user;
}
public User findBySSO(String sso) {
logger.info("SSO:{}",sso);
Criteria crit= createEntityCriteria();
crit.add(Restrictions.eq("ssoId", sso));
User user=(User) crit.uniqueResult();
//System.out.println(user.getEmail());
if (user!=null){
Hibernate.initialize(user.getUserProfiles());;
}
return user;
}
@SuppressWarnings("unchecked")
public List<User> findAllUsers() {
Criteria criteria = createEntityCriteria().addOrder(Order.asc("firstName"));
criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);//To avoid duplicates.
List<User> users = (List<User>) criteria.list();
return users;
}
public void save(User user) {
// TODO Auto-generated method stub
persist(user);
}
public void deleteBySSO(String sso) {
// TODO Auto-generated method stub
Criteria crit=createEntityCriteria();
crit.add(Restrictions.eq("ssoId", sso));
User user=(User) crit.uniqueResult();
delete(user);
}
}
|
package com.tt.miniapp.audio;
import android.content.Context;
import android.media.AudioManager;
public class AudioManagerHelper {
public AudioManager.OnAudioFocusChangeListener mAudioFocusChangeListener;
private AudioManager mAudioManager;
public AudioManagerHelper(Context paramContext, final AudioFocusChangeListener listener) {
if (paramContext == null)
return;
this.mAudioManager = (AudioManager)paramContext.getApplicationContext().getSystemService("audio");
this.mAudioFocusChangeListener = new AudioManager.OnAudioFocusChangeListener() {
public void onAudioFocusChange(int param1Int) {
if (param1Int != -3 && param1Int != -2 && param1Int != -1) {
if (param1Int != 1 && param1Int != 2 && param1Int != 3)
return;
AudioFocusChangeListener audioFocusChangeListener = listener;
if (audioFocusChangeListener != null) {
audioFocusChangeListener.gainAudioFocus();
return;
}
} else {
AudioFocusChangeListener audioFocusChangeListener = listener;
if (audioFocusChangeListener != null)
audioFocusChangeListener.lossAudioFocus();
}
}
};
}
public void abandonAudioFocus(Context paramContext) {
if (this.mAudioManager == null && paramContext != null)
this.mAudioManager = (AudioManager)paramContext.getApplicationContext().getSystemService("audio");
AudioManager audioManager = this.mAudioManager;
if (audioManager != null) {
AudioManager.OnAudioFocusChangeListener onAudioFocusChangeListener = this.mAudioFocusChangeListener;
if (onAudioFocusChangeListener != null)
audioManager.abandonAudioFocus(onAudioFocusChangeListener);
}
this.mAudioManager = null;
}
public void requestAudioFocus(Context paramContext) {
if (this.mAudioManager == null && paramContext != null)
this.mAudioManager = (AudioManager)paramContext.getApplicationContext().getSystemService("audio");
AudioManager audioManager = this.mAudioManager;
if (audioManager != null) {
AudioManager.OnAudioFocusChangeListener onAudioFocusChangeListener = this.mAudioFocusChangeListener;
if (onAudioFocusChangeListener != null)
audioManager.requestAudioFocus(onAudioFocusChangeListener, 3, 2);
}
}
}
/* Location: C:\Users\august\Desktop\tik\df_miniapp\classes.jar!\com\tt\miniapp\audio\AudioManagerHelper.class
* Java compiler version: 6 (50.0)
* JD-Core Version: 1.1.3
*/
|
package com.pas.mall.service;
import com.pas.mall.entity.ResultPage;
import com.pas.mall.pojo.TbContent;
import java.util.List;
public interface ContentService {
public List<TbContent> findAll();
public void update(TbContent tbContent);
public void add(TbContent tbContent);
public TbContent findOne(Long id);
public void delete(Long[] ids);
public ResultPage findPage(int pageNum, int pageSize);
public List<TbContent> findCategoryById(Long categoryId);
}
|
package com.pine.template.demo;
import com.pine.template.base.BaseConstants;
public interface DemoUrlConstants extends BaseConstants {
String H5_WanAndroidUrl = "https://www.wanandroid.com";
}
|
package org.houqi.controller.annotation;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.houqi.domain.User;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
/**
*
* @author HouQi
*
*/
@Controller
public class UserController {
@RequestMapping(value="/register",method=RequestMethod.GET)
public String register(Model model){
List<String> hobbies=new ArrayList<String>();
hobbies.add("java");
hobbies.add("python");
List<String> allHobbies=new ArrayList<String>();
allHobbies.add("java");
allHobbies.add("android");
allHobbies.add("linux");
allHobbies.add("c++");
Map<String,String> mapHobbies=new HashMap<String, String>();
mapHobbies.put("c++", "c语言");
mapHobbies.put("java", "爪洼");
mapHobbies.put("linux", "里纽克斯");
mapHobbies.put("python", "派森");
List<Boolean> radio=new ArrayList<Boolean>();
radio.add(true);
radio.add(false);
Map<Boolean,String> free=new HashMap<Boolean, String>();
free.put(true, "免费");
free.put(false, "收费");
Map<Boolean,String> wantGo=new HashMap<Boolean, String>();
wantGo.put(true, "北京");
wantGo.put(false, "介休");
User user=new User("侯琪","hou940705",24,true,hobbies);
//model中添加属性 commond ,值是 user
model.addAttribute("command",user);
model.addAttribute("user",user);
model.addAttribute("allHobbies",allHobbies);
model.addAttribute("mapHobbies",mapHobbies);
model.addAttribute("radio",radio);
model.addAttribute("free",free);
model.addAttribute("wantGo",wantGo);
return "register";
}
}
|
package threads;
public class Exemplo4 implements Runnable {
public void run() {
for (int i = 1; i < 4; i++) {
System.out.println("Thread " + Thread.currentThread().getName());
}
}
}
|
// Digraph.java
//
// Simple class to represent a directed graph.
public class Digraph
{
private boolean[][] edge;
public Digraph(int numNodes)
{
edge = new boolean[numNodes][numNodes];
// By default, all boolean array values are false,
// so there are no edges in the graph.
}
public int getNumVertices()
{
return edge.length;
}
public int getNumEdges()
{
int edgesCount = 0;
for (int row = 0; row < edge.length; row++)
{
for (int col = 0; col < edge[0].length; col++)
{
if (edge[row][col])
edgesCount++;
}
}
return edgesCount++;
}
public void addEdge(int i, int j)
{
if (0 <= i && i < edge.length
&& 0 <= j && j < edge.length)
edge[i][j] = true;
}
public void removeEdge(int i, int j)
{
if (0 <= i && i < edge.length
&& 0 <= j && j < edge.length)
edge[i][j] = false;
}
public boolean hasEdge(int i, int j)
{
boolean result;
if (0 <= i && i < edge.length
&& 0 <= j && j < edge.length)
result = edge[i][j];
else
result = false;
return result;
}
public int getInDegree(int vertex)
{
int count = 0;
for (int row = 0; row < edge.length; row++)
{
if (edge[row][vertex])
count++;
}
return count;
}
public int getOutDegree(int vertex)
{
int count = 0;
for (int col = 0; col <edge[0].length; col++)
{
if (edge[vertex][col])
count++;
}
return count;
}
public boolean isSource(int vertex)
{
boolean source = false;
if (getInDegree(vertex) == 0)
{
source = true;
}
return source;
}
public boolean isSink(int vertex)
{
boolean sink = false;
if (getOutDegree(vertex) == 0)
{
sink = true;
}
return sink;
}
public String toString()
{
String result = "";
for (int i = 0; i < edge.length; i++)
{
for (int j = 0; j < edge[i].length; j++)
if (edge[i][j])
result += "T ";
else
result += " ";
result += "\n";
}
return result;
}
}
|
package org.example.broker.core.controller;
import lombok.RequiredArgsConstructor;
import org.example.broker.api.domain.Client;
import org.example.broker.core.service.client.ClientService;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("client")
@RequiredArgsConstructor
public class ClientRestController {
private final ClientService clientService;
@PutMapping
@ResponseStatus(HttpStatus.ACCEPTED)
public void register(@RequestBody Client client) {
clientService.register(client);
}
}
|
/*
* Copyright 2009 HPDI, LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jvss.logical;
import java.io.IOException;
import java.nio.charset.Charset;
/**
* Factory for obtaining VssDatabase instances.
*/
public class VssDatabaseFactory
{
private final String path;
private String encoding = Charset.defaultCharset().name();
/**
* @param encoding
* the encoding to set
*/
public void setEncoding(String encoding)
{
this.encoding = encoding;
}
/**
* @return the path
*/
public String getPath()
{
return path;
}
/**
* @return the encoding
*/
public String getEncoding()
{
return encoding;
}
public VssDatabaseFactory(String path)
{
this.path = path;
}
public VssDatabase Open() throws IOException
{
return new VssDatabase(path, encoding);
}
}
|
package boundary;
import java.text.NumberFormat;
import javax.ejb.Stateless;
import javax.json.Json;
import javax.json.JsonBuilderFactory;
import javax.json.JsonObject;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
/**
*
* @author romanm
*/
@Stateless
@Path("picreversdiscountrest")
public class PicReversDiscountRest {
String result = "";
String version = "version=7";
/*
public static void main(String[] args) {
PicReversDiscountRest picReversDiscountRest = new PicReversDiscountRest();
//picReversDiscountRest.getPicReversDiscount(100.00, 67.50);
picReversDiscountRest.getPicReversDiscount(111.00, 11.00);
//String str = picReversDiscount.getPicReversDiscount(100.00, 67.50);
//System.out.println(str);
}
*/
//http://localhost:8080/pic-revers-discount/resources/picreversdiscountrest/111.00/11.00
@GET
@Path("{priceBefore}/{priceAfter}")
public String getPicReversDiscount(@PathParam("priceBefore") Double priceBefore, @PathParam("priceAfter") Double priceAfter) {
//public String getPicReversDiscount(double priceBefore, double priceAfter) {
//System.out.println("priceBefore= " + priceBefore);
//System.out.println("priceAfter= " + priceAfter);
String result1 = getPicReversDiscount1Places(priceBefore, priceAfter);
String result2 = getPicReversDiscount2Places(priceBefore, priceAfter);
String result3 = getPicReversDiscount3Places(priceBefore, priceAfter);
//System.out.println("result1= " + result1);
//System.out.println("result2= " + result2);
//System.out.println("result3= " + result3);
JsonBuilderFactory factory = Json.createBuilderFactory(null);
JsonObject result = factory.createObjectBuilder()
.add("result1", result1)
.add("result2", result2)
.add("result3", result3)
.build();
//return "aaaaa";
return result.toString();
}
public String getPicReversDiscount3Places(double priceBefore, double priceAfter){
double disc1Value = 0.0;
double disc1Price = 0.0;
double disc2Value = 0.0;
double disc2Price = 0.0;
double disc3Value = 0.0;
double disc3Price = 0.0;
double diff = 0.0;
double diffTmp = priceAfter;
/*
double disc1 = 0.04; //discount %
double disc1Value = priceBefore*disc1; //discount value
double disc1Price = priceBefore - disc1Value; //price after discount1
double disc2 = 0.14;
double disc2Value = disc1Price*disc2;
double disc2Price = disc1Price - disc2Value;
double disc3 = 0.19;
double disc3Value = disc2Price*disc3;
double disc3Price = disc2Price - disc3Value;
System.out.println(disc1Value);
System.out.println(disc2Value);
System.out.println(disc3Value);
System.out.println(disc1Price);
System.out.println(disc2Price);
System.out.println(disc3Price);
*/
// i1/i2/i3
for (int i1 = 1; i1 < 100; i1++) {
for (int i2 = 1; i2 < 100; i2++) {
for (int i3 = 0; i3 < 100; i3++) {
disc1Value = priceBefore*i1/100; //discount value
disc1Price = priceBefore - disc1Value; //price after discount1
disc2Value = disc1Price*i2/100;
disc2Price = disc1Price - disc2Value;
disc3Value = disc2Price*i3/100;
disc3Price = disc2Price - disc3Value;
//System.out.println(i1+"-"+i2+"-"+i3+"---"+disc2Price);
diff = priceAfter - disc3Price;
if (Math.abs(diff) < diffTmp) {
diffTmp = Math.abs(diff);
result = " " +i1 +" / "+ i2 +" / "+ i3 + " diff= "+getDoubleFormat(diff);
//System.out.println(result);
}
}
}
}//end i1
//System.out.println("result=" +result);
return result;
}
public String getPicReversDiscount2Places(double priceBefore, double priceAfter){
double disc1Value = 0.0;
double disc1Price = 0.0;
double disc2Value = 0.0;
double disc2Price = 0.0;
double diff = 0.0;
double diffTmp = priceAfter;
// i1/i2/i3
for (int i1 = 1; i1 < 100; i1++) {
for (int i2 = 1; i2 < 100; i2++) {
disc1Value = priceBefore*i1/100; //discount value
disc1Price = priceBefore - disc1Value; //price after discount1
disc2Value = disc1Price*i2/100;
disc2Price = disc1Price - disc2Value;
//System.out.println(i1+"-"+i2+"-"+i3+"---"+disc2Price);
diff = priceAfter - disc2Price;
if (Math.abs(diff) < diffTmp) {
diffTmp = Math.abs(diff);
//result = " " +i1 +" / "+ i2 +" / "+ 0 + "<br>diff="+getDoubleFormat(diff)+ "<br>"+version;
result = " " +i1 +" / "+ i2 +" / "+ 0 + " diff= "+getDoubleFormat(diff);
//System.out.println(result);
}
}
}//end i1
//System.out.println("result=" +result);
return result;
}
public String getPicReversDiscount1Places(double priceBefore, double priceAfter){
double disc1Value = 0.0;
double disc1Price = 0.0;
double diff = 0.0;
double diffTmp = priceAfter;
// i1/i2/i3
for (int i1 = 1; i1 < 100; i1++) {
disc1Value = priceBefore*i1/100; //discount value
disc1Price = priceBefore - disc1Value; //price after discount1
//System.out.println(i1+"-"+i2+"-"+i3+"---"+disc2Price);
diff = priceAfter - disc1Price;
if (Math.abs(diff) < diffTmp) {
diffTmp = Math.abs(diff);
//result = " " +i1 +" / "+ 0 +" / "+ 0 + "<br>diff="+diff+ "<br>"+version;
//result = " " +i1 +" / "+ 0 +" / "+ 0 + " diff= "+getDoubleFormat(diff) + " " + version;
result = " " +i1 +" / "+ 0 +" / "+ 0 + " diff= "+getDoubleFormat(diff);
//System.out.println(result);
}
}//end i1
//System.out.println("result=" +result);
return result;
}
public String getDoubleFormat(double d) {
NumberFormat nf = NumberFormat.getInstance();
nf.setMaximumFractionDigits(6);
return nf.format(d);
}
}
|
class TestB{
public static void main(String ar[])
{
int p=22;
int r=19;
int t=5;
//double tot=a+b+c;
double si=p*r*t/100.0;
//System.out.println("a="+a+" b="+b+" c="+c);
System.out.println("SI is "+si);
}
}
|
package com.hiwes.cores.thread.thread1.Thread0214;
/**
* 停止线程是在多线程开发时很重要的技术点,可以对线程的停止进行有效的处理。
* 停止线程在Java语言中并不像break语句那么干脆,需要一些技巧性的处理。
* 1.停止不了的线程====>interrupt()方法,仅仅是在当前线程中打一个停止的标记,并不是真的停止线程。
*/
public class MyThread01 extends Thread {
@Override
public void run() {
super.run();
for(int i = 0;i < 5000 ;i ++){
System.out.println("i= "+(i+1));
}
}
}
class Run01{
public static void main(String[] args) {
try{
MyThread01 thread = new MyThread01();
thread.start();
thread.sleep(2000);
thread.interrupt();
}catch (InterruptedException e){
e.printStackTrace();
}
}
}
|
package Domain;
import Domain.Effetti.Effetto;
import Exceptions.DomainException;
import org.junit.Before;
import org.junit.Test;
import java.util.ArrayList;
import static org.junit.Assert.*;
/**
* Created by Michele on 04/06/2017.
*/
public class CartaPersonaggioTest {
CartaPersonaggio cartaPersonaggio;
@Before
public void setUp() throws Exception {
cartaPersonaggio = new CartaPersonaggio("carta", 1, new ArrayList<Effetto>(), new ArrayList<Effetto>());
assertEquals("carta", cartaPersonaggio.Nome);
assertEquals(1, cartaPersonaggio.Periodo);
assertEquals(0, cartaPersonaggio.getCostoRisorse().getLegno());
assertEquals(0, cartaPersonaggio.getCostoRisorse().getPietra());
assertEquals(0, cartaPersonaggio.getCostoRisorse().getServi());
assertEquals(0, cartaPersonaggio.getCostoRisorse().getMonete());
}
@Test
public void validaPresaCarta_OK() throws Exception {
Giocatore giocatore = new Giocatore();
Torre torre = new Torre(TipoCarta.Personaggio);
SpazioAzioneTorre spazioAzioneTorre = new SpazioAzioneTorre(1, new Risorsa(), torre);
cartaPersonaggio.ValidaPresaCarta(giocatore, spazioAzioneTorre);
}
@Test (expected = DomainException.class)
public void validaPresaCarta_PlanciaPiena() throws Exception {
Giocatore giocatore = new Giocatore();
Torre torre = new Torre(TipoCarta.Personaggio);
SpazioAzioneTorre spazioAzioneTorre = new SpazioAzioneTorre(1, new Risorsa(), torre);
for (int i = 0; i<6; i++)
giocatore.CartePersonaggio.add(new CartaPersonaggio("nome", 1, new ArrayList<Effetto>(), new ArrayList<Effetto>()));
cartaPersonaggio.ValidaPresaCarta(giocatore, spazioAzioneTorre);
}
@Test
public void assegnaGiocatore() throws Exception {
Giocatore giocatore = new Giocatore();
cartaPersonaggio.AssegnaGiocatore(giocatore);
assertEquals(1, giocatore.CartePersonaggio.size());
}
@Test
public void getTipoCarta() throws Exception {
assertEquals(TipoCarta.Personaggio, cartaPersonaggio.getTipoCarta());
}
}
|
package com.beiyelin.monitor.controller;
import com.beiyelin.common.resbody.ResultBody;
import com.beiyelin.monitor.entity.LoginTracker;
import com.beiyelin.monitor.service.LoginTrackerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* Created by xinsh on 2018/1/2.
*/
@RestController
@RequestMapping("/monitor")
public class MonitorController {
@Autowired
private LoginTrackerService loginTrackerService;
@GetMapping("/save")
public ResultBody<LoginTracker> saveEntity(){
LoginTracker loginTracker = generateDemoEntity();
// LoginTracker savedEntity = loginTrackerService.create(null);
LoginTracker savedEntity = loginTrackerService.create(loginTracker);
return new ResultBody<LoginTracker>(savedEntity);
}
private LoginTracker generateDemoEntity(){
LoginTracker loginTracker = new LoginTracker();
loginTracker.setBrand("Lenovo");
loginTracker.setBrowser("Chrome");
loginTracker.setIpAddress("localhost");
loginTracker.setModel("win10");
loginTracker.setOperatingSystem("win10");
loginTracker.setScreenSize("1960*1280");
loginTracker.setUserId("test");
loginTracker.setRemarks("测试数据");
return loginTracker;
}
}
|
package string;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class Exercise06Test {
@Test
public void test_shortenString() {
assertEquals(new Exercise06().shortenString("abcccceeeeeefd"), "abc4e6fd");
assertEquals(new Exercise06().shortenString("aabbbbbbbbbbbbbcc"), "a2b13c2");
}
}
|
package com.zhouyi.business.core.service;
import com.zhouyi.business.core.model.*;
import com.zhouyi.business.core.vo.SysRoleVo;
import java.util.List;
public interface SysRoleService {
Response findSysRoleById(String id);
List<SysRole> findSysRoleListBySysRole(SysRoleVo sysRoleVo);
void saveSysRole(SysRole sysRole);
void updateSysRole(SysRole sysRole);
void deleteSysRole(String id);
int findTotal(SysRoleVo sysRoleVo);
MenuTreeNode selectMenuTreeByUserCode(String userCode);
MenuTreeNode selectMenuTreeByRoleId(String roleId);
List<MenuTreeNode> selectMenuTreeTableByRoleId(String roleId);
Response updateRoleMenu(RoleMenuRequest roleMenuRequest);
Response saveRoleMenu(RoleMenuRequest roleMenuRequest);
}
|
package com.sunjian.services.impl;
import com.sunjian.datas.Datas2;
import com.sunjian.pages.FirstPage;
import com.sunjian.pages.HmcjPage;
import com.sunjian.pages.IframePage;
import com.sunjian.services.Hmcj;
import com.sunjian.utils.MyLog;
import com.sunjian.utils.MyWait;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import java.util.UUID;
import java.util.logging.Logger;
public class HmcjImpl extends HmcjPage implements Hmcj {
private WebDriver driver;
public HmcjImpl(WebDriver driver) {
super(driver);
this.driver = driver;
}
Datas2 data = new Datas2(System.getProperty("user.dir") + "/src/test/tools/xxx.csv");
IframePage iframe = new IframePage(driver);
public void intoHmcjIframe() throws Exception {//进入虹膜采集界面的iframe
driver.switchTo().frame(driver.findElement(By.xpath(iframe.getHmcjIframe())));
MyLog.log("进入虹膜采集界面");
MyWait.threadWait(1);
}
public void intoKscjIframe() throws Exception {//进入开始采集界面的iframe
driver.switchTo().frame(driver.findElement(By.xpath(iframe.getKscjIframe())));
MyLog.log("进入开始采集界面");
MyWait.threadWait(1);
}
public void backHomeIframe() {//返回主iframe
driver.switchTo().defaultContent();
MyLog.log("返回到主界面");
}
public void backParentIframe() {
driver.switchTo().parentFrame();
MyLog.log("返回到上一级界面");
}
public boolean kscjIsDisplay() {//判斷开始采集是否顯示
if (kscj().isDisplayed() || kscj().isEnabled()) {
return true;
} else {
return false;
}
}
private void doSelectOneRyfl() throws Exception {//选择一个人员分类
// MyWait.showTypeWait2(driver, 5, ryfl_button_str());
MyWait.threadWait(2);
ryfl_button().click();//点击人员分类的下拉按钮
MyWait.threadWait(1);
MyLog.log("选择一个人员分类");
ryfl().click();
MyLog.log("人员分类选择成功");
}
private void doSelectOneZjlx() throws Exception {//选择一个证件类型
// MyWait.showTypeWait2(driver, 3, zjlx_button_str());
MyWait.threadWait(1);
zjlx_button().click();
zjlx().click();
MyLog.log("选择一个证件类型");
}
private void doInputZjh() {//输入证件号
//zjh().sendKeys(data.getTestData("zjh", "v1"));
zjh().clear();
zjh().sendKeys(UUID.randomUUID().toString());
MyLog.log("输入证件号");
}
private void doInputXm() {//输入姓名
xm().sendKeys(data.getTestData("xm", "v1"));
MyLog.log("输入姓名");
}
private void doSelectOneXb() throws Exception {//选择一个性别
//MyWait.showTypeWait2(driver, 3, xb_button_str());
MyWait.millisWait(100);
xb_button().click();
xb().click();
MyLog.log("选择一个性别");
}
private void doSelectCsrq() {//选择一个出生日期
csrq().click();
csrq().sendKeys(data.getTestData("csrq", "v1"));
MyLog.log("选择一个出生日期");
}
private void doSelectOneGj() throws Exception {//选择一个国籍
MyWait.millisWait(100);
gj_button().click();
gj().click();
MyLog.log("选择一个国籍");
}
private void doSelectOneMz() throws Exception {//选择一个民族
MyWait.millisWait(100);
mz_button().click();
mz().click();
MyLog.log("选择一个民族");
}
private void doInputHjdz() {//输入户籍地址
hjdz().sendKeys(data.getTestData("hjdz", "v1"));
MyLog.log("输入户籍地址");
}
private void doInputZjqfjg() {//输入证件签发机关
zjqfjg().sendKeys(data.getTestData("zjqfjg", "v1"));
MyLog.log("输入证件签发机关");
}
private void doInputYxqx() {//输入证件有效期
yxqx().sendKeys(data.getTestData("zjyxq", "v1"));
MyLog.log("输入证件有效期");
}
private void doInputXjzdz() {//输入现居住地址
xjzdz().sendKeys(data.getTestData("xjzdz", "v1"));
MyLog.log("输入现居住地址");
}
private void doInputSjhm() {//输入手机号码
sjhm().sendKeys(data.getTestData("sjhm", "v1"));
MyLog.log("输入手机号码");
}
private void doInputQtlxdh() {//输入其他联系电话
qtlxdh().sendKeys(data.getTestData("qtlxdh", "v1"));
MyLog.log("输入其他联系电话");
}
private void doInputBz() {//输入备注
bz().sendKeys(data.getTestData("bz", "v1"));
MyLog.log("输入备注信息");
}
private void doReadIdcard() {//读取身份证
if (dedz().isDisplayed() || dedz().isEnabled())
doUseJsClickEelment(dedz());
else
MyLog.log("读二代证按钮没有找到");
}
public boolean whetherOrNotReadIdcard() throws Exception {//判断是否读取身份证成功
boolean flag = false;
MyWait.threadWait(3);
try {
if (qd() != null && qd().isDisplayed()) {
doClickQd();
flag = false;
MyLog.log("读取身份证信息失败了");
} else { //如果确定按钮元素没有出现
flag = true;
MyLog.log("读取身份证信息成功了");
}
} catch (NullPointerException e) {
flag = true;
MyLog.log("读取身份证信息成功了");
}
return flag;
}
private void doWfcjWay() throws Exception {//选择无法采集
wfcj().click();
MyWait.millisWait(100);
wfcj_button().click();
MyWait.millisWait(100);
wfcj_select().click();
MyLog.log("选择一个无法采集");
}
private void doSubmit() throws Exception {//提交
MyWait.threadWait(3);
if (tj().isDisplayed()) {
doUseJsClickEelment(tj());
MyLog.log("点击提交按钮");
} else {
MyLog.log("提交按钮没有发现");
}
}
public void doClickQd() throws Exception {//采集成功后,点击确定
MyWait.threadWait(5);
//MyWait.showTypeWait2(driver, 5, qd_str());
if (qd().isDisplayed() && qd().isEnabled()) {
doUseJsClickEelment(qd());
MyLog.log("点击确定按钮");
} else {
MyLog.log("提交后没有返回结果,找不到确定按钮");
}
}
private void doInputRyxx() throws Exception {//输入人员信息
doSelectOneRyfl();
doInputXm();
doSelectOneZjlx();
doInputZjh();
doSelectOneXb();
doSelectCsrq();
doSelectOneGj();
doSelectOneMz();
doInputHjdz();
doInputZjqfjg();
doInputYxqx();
doInputXjzdz();
doInputSjhm();
doInputQtlxdh();
doInputBz();
}
private void doDedzAfterUpdateRyxx() throws Exception {//读取身份证后,修改身份信息
doReadIdcard();
if (whetherOrNotReadIdcard() == true) {
doSelectOneRyfl();
doInputXm();
doSelectOneZjlx();
doInputZjh();
doInputHjdz();
doInputZjqfjg();
doInputXjzdz();
doInputSjhm();
doInputQtlxdh();
doInputBz();
} else {//没有读取成功
doSelectOneRyfl();
doInputXm();
doSelectOneZjlx();
doInputZjh();
doSelectOneXb();
doSelectCsrq();
doSelectOneGj();
doSelectOneMz();
doInputHjdz();
doInputZjqfjg();
doInputYxqx();
doInputXjzdz();
doInputSjhm();
doInputQtlxdh();
doInputBz();
}
}
private void doClickDialogBoxKscjButton() {//点击对话框中的开始采集
String js = "arguments[0].click();";
((JavascriptExecutor) driver).executeScript(js, kscj2());
}
private void doStartGather() throws Exception {//开始采集虹膜
//点击开始采集
kscj().click();
MyWait.threadWait(2);
intoKscjIframe();
doClickDialogBoxKscjButton();
}
private void doStartGatherForZuoYan() throws Exception {//开始采集虹膜zuoyan
//点击开始采集zuoyan
kscj().click();
MyWait.threadWait(2);
intoKscjIframe();
MyWait.threadWait(1);
doUseJsClickEelment(yy());
doClickDialogBoxKscjButton();
}
private void doStartGatherForYouYan() throws Exception {//开始采集虹膜右眼
//点击开始采集右眼
kscj().click();
MyWait.threadWait(2);
intoKscjIframe();
MyWait.threadWait(1);
doUseJsClickEelment(zy());
doClickDialogBoxKscjButton();
}
@SuppressWarnings("unused")
private String getTsyText() throws Exception {//获取提示语文本
if (tsy().isDisplayed()) {
return tsy().getText();
} else {
MyWait.threadWait(3);
return tsy().getText();
}
}
/**
* 使用JS click
*
* @param element
*/
public void doUseJsClickEelment(WebElement element) {
String js = "arguments[0].click();";
((JavascriptExecutor) driver).executeScript(js, element);
}
/**
* 进入虹膜采集界面中
*
* @param first
* @throws Exception
*/
public void doIntoHmcjPage2(FirstPage first) throws Exception {
//点击 采集识别
first.hmcj().click();
MyWait.threadWait(1);
intoHmcjIframe();
}
public void doIntoHmcjPage(FirstPage first) throws Exception {
if (first.hmcj().isDisplayed() && first.hmcj().isEnabled()) {
//点击 采集识别
first.hmcj().click();
MyWait.threadWait(1);
intoHmcjIframe();
} else {
//点击 采集识别
first.cjsb().click();
first.hmcj().click();
MyWait.threadWait(1);
intoHmcjIframe();
}
}
/**
* 无法采集方式
*
* @throws Exception
*/
@Override
public void doWfcjWayGatherPerson() throws Exception {
//输入人员信息
doInputRyxx();
//选择无法采集方式
doWfcjWay();
//点击提交按钮
doSubmit();
//点击确定
doClickQd();
}
/**
* 虹膜采集方式
*
* @throws Exception
*/
@Override
public void doHmcjWayGatherPerson(int schema) throws Exception {
//输入人员信息
doDedzAfterUpdateRyxx();
//点击开始采集虹膜
if (schema == 2) {
doStartGather();//双眼
} else if (schema == 1) {
doStartGatherForZuoYan();//左眼
} else {
doStartGatherForYouYan();//右眼
}
//判断是否正确打开设备,进入采集状态
MyWait.threadWait(10);
//虹膜采集成功后,点击提交
backHomeIframe();
intoHmcjIframe();
doSubmit();
//点击确定
doClickQd();
}
}
|
package com.rc.portal.vo;
import java.util.Date;
public class TMemberArchivesMedicalRecord {
private Long id;
private Long memberId;
private String hospital;
private String doctor;
private String department;
private Date createDt;
private String medicalRecordUrl;
private String illnessDescribe;
private String doctorEntrust;
private String illnessMedication;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Long getMemberId() {
return memberId;
}
public void setMemberId(Long memberId) {
this.memberId = memberId;
}
public String getHospital() {
return hospital;
}
public void setHospital(String hospital) {
this.hospital = hospital;
}
public String getDoctor() {
return doctor;
}
public void setDoctor(String doctor) {
this.doctor = doctor;
}
public String getDepartment() {
return department;
}
public void setDepartment(String department) {
this.department = department;
}
public Date getCreateDt() {
return createDt;
}
public void setCreateDt(Date createDt) {
this.createDt = createDt;
}
public String getMedicalRecordUrl() {
return medicalRecordUrl;
}
public void setMedicalRecordUrl(String medicalRecordUrl) {
this.medicalRecordUrl = medicalRecordUrl;
}
public String getIllnessDescribe() {
return illnessDescribe;
}
public void setIllnessDescribe(String illnessDescribe) {
this.illnessDescribe = illnessDescribe;
}
public String getDoctorEntrust() {
return doctorEntrust;
}
public void setDoctorEntrust(String doctorEntrust) {
this.doctorEntrust = doctorEntrust;
}
public String getIllnessMedication() {
return illnessMedication;
}
public void setIllnessMedication(String illnessMedication) {
this.illnessMedication = illnessMedication;
}
}
|
package is.hi.hbv501g.team28.mid.Controllers;
import is.hi.hbv501g.team28.mid.Persistence.Entities.Task;
import is.hi.hbv501g.team28.mid.Services.TaskService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import java.io.Console;
//TODO: Deprecate this controller.
@Controller
public class HomeController {
private TaskService taskService;
@Autowired
public HomeController(TaskService taskService){
this.taskService = taskService;
}
@RequestMapping("/")
public String homePage(Model model){
model.addAttribute("tasks", taskService.findByUser(1));
return "home";
}
@RequestMapping(value = "/addtask", method = RequestMethod.GET)
public String addTaskForm(Task task){
return "newtask";
}
@RequestMapping(value = "/addtask", method = RequestMethod.POST)
public String addTask(Task task, BindingResult result, Model model){
if(result.hasErrors()){
return "newtask";
}
taskService.save(task);
return "redirect:/";
}
@RequestMapping(value = "/delete/{id}", method = RequestMethod.GET)
public String deleteTask(@PathVariable("id") long id, Model model){
Task taskToDelete = taskService.findByTaskID(id);
taskService.delete(taskToDelete);
return "redirect:/";
}
}
|
package com.kenji47.volley_work.instagram_model;
import java.util.List;
/**
* Created by kenji1947 on 28.07.2015.
*/
public class Root {
public Root() {
}
public List<InstagramPost> getData() {
return data;
}
public void setData(List<InstagramPost> data) {
this.data = data;
}
private List<InstagramPost> data;
}
|
package com.tencent.mm.model;
import com.tencent.mm.sdk.e.d;
import com.tencent.mm.sdk.e.f;
import com.tencent.mm.storage.u;
import java.util.List;
public interface af extends d<u>, f {
String gT(String str);
u ih(String str);
u ii(String str);
String ij(String str);
String ik(String str);
List<String> il(String str);
boolean im(String str);
boolean in(String str);
void m(String str, long j);
}
|
package com.xwq520.extend;
public class Child extends Parent {
// 子类不能继承父类的构造器(构造方法或者构造函数),但是父类的构造器带有参数的,则必须在子类的构造器中显式地通过super关键字调用父类的构造器并配以适当的参数列表。
// 如果父类有无参构造器,则在子类的构造器中用super调用父类构造器不是必须的
// 如果没有使用super关键字,系统会自动调用父类的无参构造器。
// super 表示使用它的类的父类。super 可用于:
// 调用父类的构造方法;
// 调用父类的方法(子类覆盖了父类的方法时);
// 访问父类的数据域(可以这样用但没有必要这样用)。
// 调用父类的构造方法语法:
// super();
// 或
// super(参数列表);
public Child(int a, int b, int c, int d) {
super(a, b, c, d);
}
public static void main(String[] args) {
Child c = new Child(2, 2, 2, 2);
// Child d = new Parent(); 类型不匹配:无法从父项转换为子项
c.self();
/*向上转型:父类引用指向子类对象*/
// 指向子类的父类引用由于向上转型了,它只能访问父类中拥有的方法和属性
// 若子类重写了父类中的某些方法,在调用该些方法的时候,必定是使用子类中定义的这些方法(动态连接、动态调用)。
// 父类类型的引用可以调用父类中定义的所有属性和方法,对于只存在与子类中的方法和属性它就望尘莫及了
Parent p = new Child(2, 2, 2, 2);
System.out.println(p.publicCan());
System.out.println(p.protectedCan());
System.out.println(p.defaultSomeCan());
/*向下转型:指向子类对象的父类引用赋给子类引用,要强制转换*/
Child c1 = (Child) p;
// 子类对象可以直接调用父类的方法
System.out.println(c.publicCan());
System.out.println(c.protectedCan());
System.out.println(c.defaultSomeCan());
}
public int self() {
int c = 4;
Child c1 = new Child(3, 3, 33, 3);
System.out.println("子类");
System.out.println(c1.a);
// System.out.println(c1.b); Parent.b字段不可见
System.out.println(c1.c);
System.out.println(c1.d);
System.out.println(c1.Ab);
System.out.println("这是父类的c:" + super.c);// super 指向父类对象的引用
System.out.println();
return 4;
}
// 重写父类的方法
public String publicCan() {
System.out.println("这里是子类重写父类的publicCan()方法");
return "我重写了";
}
}
|
package com.jlgproject.fragment;
import android.content.Intent;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import com.google.gson.Gson;
import com.jlgproject.R;
import com.jlgproject.activity.New_Debt_Matter_Preson;
import com.jlgproject.activity.UpdownPhotos;
import com.jlgproject.base.BaseFragment;
import com.jlgproject.model.AddDebtVo;
import com.jlgproject.model.AddRess.Add;
import com.jlgproject.model.DebtPerson;
import com.jlgproject.util.ProvinceCq;
import com.jlgproject.util.ToastUtil;
import org.greenrobot.eventbus.EventBus;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* 债事自然人
*/
public class DebtNaturalPersonFrament extends BaseFragment {
private Button button_next;
private EditText mEt_nuturel_icard_t,
mEt_debrpeople_name_t,
mEt_nuturel_province_t,
mEt_nuturel_phone_t,
mEt_nuturel_contact_address_t;
private String isOwer;//判断是添加自己的债事,还是别人的 1是登录用户,2是其他用户
private Spinner mProvinceSpinner_zsr;
private Spinner mCitySpinner_zsr;
private Spinner mAreaSpinner_zsr;
private Add ssq;//地址
// 列表选择的省市区
private String selectedPro = "";
private String selectedCity = "";
public String selectedArea = "";
// 省份
private String[] mProvinceDatas;
// 城市
private String[] mCitiesDatas;
// 地区
private String[] mAreaDatas;
private ArrayAdapter<String> mProvinceAdapter;
private ArrayAdapter<String> mCityAdapter;
private ArrayAdapter<String> mAreaAdapter;
// 存储省对应的所有市 name
private Map<String, String[]> mCitiesDataMap = new HashMap<String, String[]>();
// 存储市对应的所有区 name
private Map<String, String[]> mAreaDataMap = new HashMap<String, String[]>();
//省市區Id
private String shengId = null, shiId = null, quId = null;
@Override
public int getLoadViewId() {
return R.layout.frament_debt_nuturel_person;
}
@Override
public View initView(View view) {
isOwer = New_Debt_Matter_Preson.isOwer;
mEt_nuturel_icard_t = (EditText) view.findViewById(R.id.et_nuturel_icard_t);//身份证
mEt_debrpeople_name_t = (EditText) view.findViewById(R.id.et_debrpeople_name_t);//名称
mEt_nuturel_phone_t = (EditText) view.findViewById(R.id.et_nuturel_phone_t);//手机号
mEt_nuturel_contact_address_t = (EditText) view.findViewById(R.id.et_nuturel_contact_address_t);//地址
button_next = (Button) view.findViewById(R.id.btn_nuturel_next);
button_next.setOnClickListener(new View.OnClickListener() {//下一步
@Override
public void onClick(View v) {
next();
}
});
mProvinceSpinner_zsr = (Spinner) view.findViewById(R.id.spinner_pro);
mCitySpinner_zsr = (Spinner) view.findViewById(R.id.spinner_city);
mAreaSpinner_zsr = (Spinner) view.findViewById(R.id.spinner_area);
jsonCitisData();
initSpinner();
return view;
}
private void next() {
if (TextUtils.isEmpty(mEt_nuturel_icard_t.getText().toString())) {
ToastUtil.showShort(getActivity(), "请输入身份证号/护照");
return;
}
if (mEt_nuturel_icard_t.getText().toString().length() != 18) {
ToastUtil.showShort(getActivity(), "输入有误,请重试");
return;
}
if (TextUtils.isEmpty(mEt_debrpeople_name_t.getText().toString())) {
ToastUtil.showShort(getActivity(), "请输入真实姓名");
return;
}
if (mEt_debrpeople_name_t.getText().toString().length() < 2) {
ToastUtil.showShort(getActivity(), "姓名长度不能小于2个字符");
return;
}
if (TextUtils.isEmpty(mEt_nuturel_phone_t.getText().toString())) {
ToastUtil.showShort(getActivity(), "请输入手机号");
return;
}
if (mEt_nuturel_phone_t.getText().toString().length() != 11) {
ToastUtil.showShort(getActivity(), "请输入正确的手机号");
return;
}
if (TextUtils.isEmpty(mEt_nuturel_contact_address_t.getText().toString())) {
ToastUtil.showShort(getActivity(), "请输入联系地址");
return;
}
String sfzh = mEt_nuturel_icard_t.getText().toString();//身份证
String name = mEt_debrpeople_name_t.getText().toString();//姓名
String phone = mEt_nuturel_phone_t.getText().toString();//电话
String address = mEt_nuturel_contact_address_t.getText().toString();//地址
DebtPerson debtPerson = new DebtPerson();
debtPerson.setIdCode(sfzh);
debtPerson.setName(name);
debtPerson.setProvinceCode(shengId);
debtPerson.setCityCode(shiId);
debtPerson.setPrCode(quId);
debtPerson.setPhoneNumber(phone);
debtPerson.setContactAddress(address);
AddDebtVo add = new AddDebtVo();
add.setDebtPerson(debtPerson);
add.setType("1");
add.setIsOwer(isOwer);
EventBus.getDefault().postSticky(add);
startActivity(new Intent(getActivity(), UpdownPhotos.class).putExtra("addpic", 3));
}
private void jsonCitisData() {
Gson gson = new Gson();
ssq = gson.fromJson(ProvinceCq.InitData(), Add.class);
int shengSize = ssq.getData().size();//省个数
mProvinceDatas = new String[shengSize];
String mProvinceStr;
for (int i = 0; i < shengSize; i++) {
mProvinceStr = ssq.getData().get(i).getValue();
mProvinceDatas[i] = mProvinceStr;
int shiSize = ssq.getData().get(i).getChild().size();//市个数
mCitiesDatas = new String[shiSize];
String mCityStr;
for (int j = 0; j < shiSize; j++) {
mCityStr = ssq.getData().get(i).getChild().get(j).getValue();
mCitiesDatas[j] = mCityStr;
int quSize = ssq.getData().get(i).getChild().get(j).getChild().size();
mAreaDatas = new String[quSize];
for (int k = 0; k < quSize; k++) {
mAreaDatas[k] = ssq.getData().get(i).getChild().get(j).getChild().get(k).getValue();
}
// 存储市对应的所有第三级区域
mAreaDataMap.put(mCityStr, mAreaDatas);
}
// 存储省份对应的所有市
mCitiesDataMap.put(mProvinceStr, mCitiesDatas);
}
}
private void initSpinner() {
//设置未下拉时的布局
mProvinceAdapter = new ArrayAdapter<String>(getActivity(),R.layout.my_spinner_item, mProvinceDatas);
//设置下拉时的布局
mProvinceAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
mProvinceSpinner_zsr.setAdapter(mProvinceAdapter);
// 省份选择
mProvinceSpinner_zsr.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
selectedPro = "";
selectedPro = (String) parent.getSelectedItem();
// 根据省份更新城市区域信息
shengId = updateCity(selectedPro);
Log.e("--省--id--", selectedPro + "------" + shengId);
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
// 市选择
mCitySpinner_zsr.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
selectedCity = "";
selectedCity = (String) parent.getSelectedItem();
shiId = updateArea(selectedPro, selectedCity);
Log.e("--市--id--", selectedCity + "------" + shiId);
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
// 区选择
mAreaSpinner_zsr.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
selectedArea = "";
selectedArea = (String) parent.getSelectedItem();
quId = getQuId(selectedPro, selectedCity, selectedArea);
Log.e("--区--id--", selectedArea + "------" + quId);
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
/**
* 根据省份更新城市数据 返回省id
*/
private String updateCity(String pro) {
String shengId = null;
String[] cities = null;
List<Add.DataBean.ChildBean> shiNameList;
for (int i = 0; i < ssq.getData().size(); i++) {
if (pro.equals(ssq.getData().get(i).getValue())) {
shiNameList = ssq.getData().get(i).getChild();
shengId = ssq.getData().get(i).getId();
Log.e("-----", "---选择---省 Id---- " + shengId);
cities = new String[shiNameList.size()];
for (int j = 0; j < shiNameList.size(); j++) {
cities[j] = shiNameList.get(j).getValue();
}
}
}
// 存在区
mCityAdapter = new ArrayAdapter<String>(getActivity(),R.layout.my_spinner_item, cities);
mCityAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
mCitySpinner_zsr.setAdapter(mCityAdapter);
mCityAdapter.notifyDataSetChanged();
mCitySpinner_zsr.setSelection(0);
return shengId;
}
/**
* 根据市 选择对应的区 返回市Id
*/
private String updateArea(String pro, String city) {
String[] areas = null;
String shiId = "";
//市 集合
List<Add.DataBean.ChildBean> shiNameList = null;
//区 集合
List<com.jlgproject.model.AddRess.ChildBean> quNameList = null;
for (int i = 0; i < ssq.getData().size(); i++) {//循环省
//找到指定省
if (pro.equals(ssq.getData().get(i).getValue())) {
//拿到指定省下的市
shiNameList = ssq.getData().get(i).getChild();
//循环市
for (int j = 0; j < shiNameList.size(); j++) {
//找到指定市
if (city.equals(shiNameList.get(j).getValue())) {
shiId = shiNameList.get(j).getId();
quNameList = shiNameList.get(j).getChild();
if (quNameList != null && quNameList.size() != 0) {
areas = new String[quNameList.size()];
for (int k = 0; k < quNameList.size(); k++) {
areas[k] = quNameList.get(k).getValue();
}
} else {
areas = null;
}
}
}
}
}
// 存在区
if (areas != null) {
// 存在区
mAreaSpinner_zsr.setVisibility(View.VISIBLE);
mAreaAdapter = new ArrayAdapter<String>(getActivity(),R.layout.my_spinner_item, areas);
mAreaAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
mAreaSpinner_zsr.setAdapter(mAreaAdapter);
mAreaAdapter.notifyDataSetChanged();
mAreaSpinner_zsr.setSelection(0);
} else {
mAreaSpinner_zsr.setVisibility(View.GONE);
quId = "";
}
return shiId;
}
/**
* 获取区Id
*
* @param pro
* @param city
* @param area
* @return
*/
private String getQuId(String pro, String city, String area) {
String shiId = null;
String quId = "";
//市 集合
List<Add.DataBean.ChildBean> shiNameList = null;
//区 集合
List<com.jlgproject.model.AddRess.ChildBean> quNameList = null;
for (int i = 0; i < ssq.getData().size(); i++) {//循环省
//找到指定省
if (pro.equals(ssq.getData().get(i).getValue())) {
//拿到指定省下的市
shiNameList = ssq.getData().get(i).getChild();
//循环市
for (int j = 0; j < shiNameList.size(); j++) {
//找到指定市
if (city.equals(shiNameList.get(j).getValue())) {
shiId = shiNameList.get(j).getId();
quNameList = shiNameList.get(j).getChild();
for (int k = 0; k < quNameList.size(); k++) {
if (area.equals(quNameList.get(k).getValue())) {
quId = quNameList.get(k).getId();
Log.e("---", "---选择---区---- " + quNameList.get(k).getValue());
Log.e("---", "---选择---区--Id-- " + quNameList.get(k).getId());
}
}
}
}
}
}
return quId;
}
}
|
package com.jkb.yanolja.domain.motel;
import java.sql.Timestamp;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class Motel {
private int id;
private String motelName ;
private String motelPic;
private String[] motelInfoPic;
private String motelInfo;
private String address;
private String roomPrice; // admin, user
private String lodgmentPrice;
private String star;
private Timestamp createDate;
private Timestamp updateDate;
}
|
package com.dishcuss.foodie.hub.Fragments;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.dishcuss.foodie.hub.Adapters.ReviewsAdapter;
import com.dishcuss.foodie.hub.Models.Restaurant;
import com.dishcuss.foodie.hub.Models.ReviewModel;
import com.dishcuss.foodie.hub.R;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import io.realm.Realm;
import io.realm.RealmList;
import io.realm.RealmResults;
/**
* Created by Naeem Ibrahim on 7/23/2016.
*/
public class RestaurantReviewsFragment extends Fragment {
AppCompatActivity activity;
RecyclerView reviewRecyclerView;
private RecyclerView.LayoutManager reviewLayoutManager;
Restaurant restaurant=new Restaurant();
Realm realm;
int restaurantID;
RealmList<ReviewModel> reviewModels;
public RestaurantReviewsFragment() {
}
public RestaurantReviewsFragment(int restaurantID) {
this.restaurantID=restaurantID;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.simple_recycler_view_for_all, container, false);
activity = (AppCompatActivity) getActivity();
reviewRecyclerView = (RecyclerView) rootView.findViewById(R.id.simple_recycler_view_for_all);
restaurant=GetRestaurantData(restaurantID);
if(restaurant!=null){
GetReviewsData();
}
reviewLayoutManager = new LinearLayoutManager(activity);
reviewRecyclerView.setLayoutManager(reviewLayoutManager);
reviewRecyclerView.setHasFixedSize(true);
reviewRecyclerView.setNestedScrollingEnabled(false);
ReviewsAdapter adapter = new ReviewsAdapter(reviewModels,getActivity());
reviewRecyclerView.setAdapter(adapter);
return rootView;
}
Restaurant GetRestaurantData(int rID){
realm = Realm.getDefaultInstance();
RealmResults<Restaurant> restaurants = realm.where(Restaurant.class).equalTo("id", rID).findAll();
if(restaurants.size()>0){
realm.beginTransaction();
realm.commitTransaction();
return restaurants.get(restaurants.size()-1);
}
return null;
}
void GetReviewsData(){
reviewModels =restaurant.getReviewModels();
// Collections.sort(reviewModels, new Comparator<ReviewModel>() {
// @Override
// public int compare(ReviewModel lhs, ReviewModel rhs) {
// return GetDate(rhs.getUpdated_at()).compareTo(GetDate(lhs.getUpdated_at()));
// }
// });
}
Date GetDate(String date){
// String pattern = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'";
// String segments[] = date.split("\\+");
// String d = segments[0];
// String d2 = segments[1];
String pattern = "yyyy-MM-dd'T'HH:mm:ss.SSS";
SimpleDateFormat dateFormat = new SimpleDateFormat(pattern);
Date convertedDate = new Date();
try {
convertedDate = dateFormat.parse(date);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// System.out.println(convertedDate);
return convertedDate;
}
}
|
package com.tencent.mm.plugin.fts.ui.a;
import android.content.Context;
import android.content.res.Resources;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.tencent.mm.plugin.fts.a.d.a.a.b;
import com.tencent.mm.plugin.fts.ui.a.c.a;
import com.tencent.mm.plugin.fts.ui.m;
import com.tencent.mm.plugin.fts.ui.n$d;
import com.tencent.mm.plugin.fts.ui.n.e;
import com.tencent.mm.plugin.fts.ui.n.g;
public class c$b extends b {
final /* synthetic */ c jxK;
public c$b(c cVar) {
this.jxK = cVar;
super(cVar);
}
public final View a(Context context, ViewGroup viewGroup) {
View inflate = LayoutInflater.from(context).inflate(e.fts_collapse_more_item, viewGroup, false);
a aVar = this.jxK.jxH;
aVar.jxI = (TextView) inflate.findViewById(n$d.more_tv);
aVar.jxJ = (ImageView) inflate.findViewById(n$d.more_arrow);
inflate.setTag(aVar);
return inflate;
}
public final void a(Context context, com.tencent.mm.plugin.fts.a.d.a.a.a aVar, com.tencent.mm.plugin.fts.a.d.a.a aVar2, Object... objArr) {
a aVar3 = (a) aVar;
c cVar = (c) aVar2;
Resources resources = context.getResources();
if (this.jxK.jxF) {
m.a(resources.getString(g.search_more_contact, new Object[]{resources.getString(cVar.jxE)}), aVar3.jxI);
aVar3.jxJ.setRotation(0.0f);
return;
}
m.a(resources.getString(g.search_more_contact_collapse), aVar3.jxI);
aVar3.jxJ.setRotation(180.0f);
}
public final boolean a(Context context, com.tencent.mm.plugin.fts.a.d.a.a aVar) {
return false;
}
}
|
//package action05;
//
//public class MainCalc {
// public static void main(String[] args) {
// CalcProff4Example calc = new CalcProff4Example();
// String str = "10*15=";
// for(char p:str.toCharArray()){
// System.out.println("Input "+p);
// calc.inChar(p);
// System.out.println();
// }
//
//
// }
//}
|
package bgu.spl171.net.srv.bidi;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map.Entry;
public class ConnectionsImpl<T> implements Connections<T> {
private HashMap<Integer, ConnectionHandler<T>> connectionList = new HashMap<>();
private HashMap<Integer, String> nameList = new HashMap<>();
@Override
public boolean send(int connectionId, T msg) {
if(connectionList.containsKey(connectionId)) {
connectionList.get((Integer) connectionId).send(msg);
return true;
}
return false;
}
@Override
public void broadcast(T msg) {
for (Iterator<Entry<Integer,ConnectionHandler<T>>> iterator = connectionList.entrySet().iterator(); iterator.hasNext();) {
ConnectionHandler<T> connectionHandler = iterator.next().getValue();
connectionHandler.send(msg);
}
}
@Override
public void disconnect(int connectionId) {
nameList.remove(connectionId);
connectionList.remove(connectionId);
}
public void connect(ConnectionHandler<T> connectionHandler, int id) {
connectionList.put(id, connectionHandler);
}
public void login(int id, String name) {
nameList.put((Integer) id, name);
}
public boolean isLoggedIn(int id) {
return nameList.containsKey(id);
}
public boolean isUsernameExists (String username){
return nameList.containsValue(username);
}
}
|
package by.dt.boaopromtorg.web.controller;
import by.dt.boaopromtorg.entity.Product;
import by.dt.boaopromtorg.entity.dto.PriceDTO;
import by.dt.boaopromtorg.entity.dto.ProductSearchDTO;
import by.dt.boaopromtorg.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping(path = "/product")
public class ProductController {
@Autowired
private ProductService productService;
@RequestMapping(method = RequestMethod.POST)
public ResponseEntity addProducts(@RequestBody Product product) {
productService.addProduct(product);
return new ResponseEntity(HttpStatus.OK);
}
@RequestMapping(method = RequestMethod.GET)
public List<Product> searchProducts(@RequestParam String name, @RequestParam String category,
@RequestParam String subCategory, @RequestParam Double priceFrom,
@RequestParam Double priceTo) {
ProductSearchDTO productSearchDTO = new ProductSearchDTO(name, category, subCategory, priceFrom, priceTo);
return productService.searchProduct(productSearchDTO);
}
@RequestMapping(path = "/{barcode}", method = RequestMethod.GET)
public Product searchProductByBarcode(@PathVariable String barcode) {
return productService.searchProductByBarсode(barcode);
}
@RequestMapping(path = "/price", method = RequestMethod.PUT)
public ResponseEntity updatePrices(@RequestBody List<PriceDTO> productDTOs) {
productDTOs.forEach((productDTO) -> productService.updatePrice(productDTO));
return new ResponseEntity(HttpStatus.OK);
}
}
|
package org.gmart.devtools.java.serdes.codeGenExample.featuresTestExample.generatedFilesCustomizationStubs;
import java.util.Map;
import java.util.function.Function;
import org.gmart.devtools.java.serdes.codeGen.javaGen.model.DeserialContext;
import org.gmart.devtools.java.serdes.codeGenExample.utils.ReflUtil;
public class SchemaOrRef extends org.gmart.devtools.java.serdes.codeGenExample.featuresTestExample.generatedFiles.SchemaOrRef {
// at the end of the deserialization, this will contains the
// "fileRootObject" (here a "OpenApiSpec" object) that is used below to get the schema.
public SchemaOrRef(DeserialContext deserialContext) {
super(deserialContext);
}
public Schema getSchema() {
Schema schema = asSchema(); //this method has been generated in the parent "oneOf" class.
if (schema != null)
return schema;
String ref = asSchemaRef().get$ref(); //this one too,
// ref must be a path to a member of a JSON (or Yaml) data-structure,
// in this OpenAPI example it can be: "#components/schemas/<name of the schema>"
// (cf. "OpenApiSpec" type definition
// that have a "components" property that a schemas property that have a Dict<Schema> type ...)
int lastSlashIndex = ref.lastIndexOf("/");
Map<String, Schema> schemas = (Map) makeJsonPathResolver(this.getDeserialContext().getFileRootObject())
.apply(ref.substring(0, lastSlashIndex));
String schemaName = ref.substring(lastSlashIndex + 1);
return schemas.get(schemaName);
}
//this function is just for demonstration purpose ...
public static <T> Function<String, T> makeJsonPathResolver(Object context){
Function<String, T> convertRefToSchema = ref -> {
if(ref.startsWith("#/")) {
ref = ref.substring(2);
String[] path = ref.substring(0).split("[/\\\\]");
try {
return (T) ReflUtil.getDeepFieldValue(context, path);
} catch (NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException e) {
e.printStackTrace();
assert false : "error getting the object at path: " + ref;
}
}
assert false : "Only local JSON paths are supported (path that begins with \"#\").";
return null;
};
return convertRefToSchema;
}
}
|
package org.research.flume.interceptor;
import com.google.common.collect.Lists;
import org.apache.flume.Context;
import org.apache.flume.Event;
import org.apache.flume.interceptor.Interceptor;
import java.util.List;
import java.util.Map;
/**
* @fileName: TypeInterceptor.java
* @description: 自定义Flume拦截器
* @author: by echo huang
* @date: 2020-07-31 00:12
*/
public class TypeInterceptor implements Interceptor {
/**
* 添加过头的事件
*/
private List<Event> addHeaderEvents;
@Override
public void initialize() {
this.addHeaderEvents = Lists.newArrayList();
}
/**
* 单个事件拦截
*
* @param event
* @return
*/
@Override
public Event intercept(Event event) {
Map<String, String> headers = event.getHeaders();
String body = new String(event.getBody());
//如果event的body包含hello则向header添加一个标签
if (body.contains("hello")) {
headers.put("type", "yes");
} else {
headers.put("type", "no");
}
return event;
}
/**
* 批量事件拦截
*
* @param list
* @return
*/
@Override
public List<Event> intercept(List<Event> list) {
this.addHeaderEvents.clear();
list.forEach(event -> addHeaderEvents.add(intercept(event)));
return this.addHeaderEvents;
}
@Override
public void close() {
}
public static class InterceptorBulder implements Interceptor.Builder {
@Override
public Interceptor build() {
return new TypeInterceptor();
}
/**
* 传递配置,可以将外部配置传递至内部
*
* @param context 配置上下文
*/
@Override
public void configure(Context context) {
}
}
}
|
/*
* TCSS 305 - Shapes
*
*/
package model;
import java.awt.Color;
import java.awt.Shape;
/**
* Shape class holds various shapes.
*
* @author mohibkohi
* @version 1.0.
*/
public class Shapes {
/**
* Instance field shape.
*/
private final Shape myShape;
/**
* Instance field color.
*/
private final Color myColor;
/**
* Instance field stroke.
*/
private final int myStroke;
/**
* Constructor shape initializes shape, color and the stroke.
*
* @param theShape current shape.
* @param theColor current color.
* @param theStroke current stroke.
*/
public Shapes(final Shape theShape, final Color theColor, final int theStroke) {
myShape = theShape;
myColor = theColor;
myStroke = theStroke;
}
/**
* Return current shape.
*
* @return the shape.
*/
public Shape getShape() {
return myShape;
}
/**
* Return current color.
*
* @return the color.
*/
public Color getColor() {
return myColor;
}
/**
* Return current stroke.
*
* @return the stroke.
*/
public int getStroke() {
return myStroke;
}
}
|
package com.jt.collections;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Deque;
import java.util.LinkedList;
import java.util.List;
import org.junit.Ignore;
import org.junit.Test;
public class ListExamples extends MyFormatter{
@Ignore
@Test
public void addelements() {
List<String> a1 = new ArrayList<String>();
a1.add("Tom");
a1.add("Ram");
a1.add("Bam");
a1.add("Sham");
//Print list items in different ways
//System.out.println(a1);
//System.out.println(a1.get(1));
for(String s: a1) {
System.out.println(s);
}
}
@Ignore
@Test
public void removingElements() {
List<String> a1 = new ArrayList<String>();
a1.add("Tom");
a1.add("Ram");
a1.add("Bam");
a1.add("Sham");
System.out.println(a1);
a1.remove(0);
System.out.println(a1);
a1.removeIf(e -> e.equals("Sham"));
System.out.println(a1);
List<String> a2 = new ArrayList<String>();
a2.add("Tom");
a2.add("Ram");
a2.add("Bam");
a2.add("Sham");
a2.retainAll(a1);
System.out.println(a2);
}
@Ignore
@Test
public void addAllTest() {
List<Integer> a2 = new ArrayList<>();
a2.add(2);
a2.add(4);
a2.add(6);
List<Integer> a1 = new ArrayList<>();
a1.addAll(a2);
System.out.println(a1);
System.out.println(a2);
}
@Ignore
@Test
public void sortCollection() {
List<String> a1 = new ArrayList<>();
a1.add("Tom");
a1.add("Ram");
a1.add("Bam");
a1.add("Sham");
Collections.sort(a1);
//Print list items in different ways
//System.out.println(a1);
//System.out.println(a1.get(1));
for(String s: a1) {
System.out.println(s);
}
}
@Test
public void LinkedListExamples() {
//Linked list implements the DeQue Interface
Deque<String> a1 = new LinkedList<>();
a1.add("Tom");
a1.add("Ram");
a1.add("Bam");
a1.add("Sham");
System.out.println(a1);
a1.addFirst("addFirst_e");
a1.addLast("addLast.e");
System.out.println(a1);
System.out.println(a1.peekFirst() +" " + a1.peekLast() );
a1.push("Bina");
System.out.println(a1);
a1.pop();
System.out.println(a1);
a1.poll();
System.out.println(a1);
//a1.forEach( e -> System.out.println(e));
//Removing all the elements from a queue
while(a1.peek() != null) {
System.out.println(a1.pop());
}
System.out.println(a1);
}
}
|
package fr.lteconsulting.formations;
import java.io.IOException;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class Vues
{
public static void afficherEmptyMessage( HttpServletRequest req, HttpServletResponse resp )
throws ServletException, IOException
{
req.getRequestDispatcher( "/WEB-INF/empty.jsp" ).forward( req, resp );
}
public static void afficherMessages( List<String> messages, HttpServletRequest req, HttpServletResponse resp )
throws ServletException, IOException
{
req.setAttribute( "messages", messages );
req.getRequestDispatcher( "/WEB-INF/messages.jsp" ).forward( req, resp );
}
}
|
package top.wangruns.nowcoder.sword2offer;
/**
*
* 题目描述
牛客最近来了一个新员工Fish,每天早晨总是会拿着一本英文杂志,写些句子在本子上。
同事Cat对Fish写的内容颇感兴趣,有一天他向Fish借来翻看,但却读不懂它的意思。例如,“student. a am I”。
后来才意识到,这家伙原来把句子单词的顺序翻转了,正确的句子应该是“I am a student.”。
Cat对一一的翻转这些单词顺序可不在行,你能帮助他么?
*
*/
public class P44_翻转单词顺序列 {
public String ReverseSentence(String str) {
if(str==null||str.length()==0) return "";
char[] c=str.toCharArray();
//先翻转整个句子
reverse(c,0,c.length-1);
//再翻转每个单词
int start=-1,end=0;
for(int i=0;i<c.length;i++) {
if(c[i]==' ') {
end=i;
reverse(c, start+1, end-1);
start=end;
}
}
reverse(c, start+1, c.length-1);
return new String(c);
}
private void reverse(char[] c, int i, int j) {
while(i<j) {
char t=c[i];c[i]=c[j];c[j]=t;
i++;j--;
}
}
}
|
package collection;
import java.util.*;
/**
* Created with IntelliJ IDEA.
* User: mt
* Date: 13-7-1
* Time: 下午4:46
*/
public class MapScoreMap<K extends Comparable, V extends Comparable<? super V>> extends TreeMap<K, V> {
private final HashMap<K, V> base;
public MapScoreMap(final HashMap<K, V> base) {
super(new Comparator<K>() {
@Override
public int compare(K o1, K o2) {
if (o1.compareTo(o2)==0){
return 0;
}
int res = base.get(o2).compareTo(base.get(o1));
return res != 0 ? res : 1;
}
});
this.base = base;
for (Map.Entry<K, V> entry : base.entrySet()) {
super.put(entry.getKey(), entry.getValue());
}
}
public V put(K k, V v) {
if (base.containsKey(k)) {
super.remove(k);
}
base.put(k, v);
return super.put(k, v);
}
public void output() {
for (Map.Entry<K, V> entry : base.entrySet()) {
System.out.println(entry.getKey() + ":" + entry.getValue());
}
}
}
|
package com.example.springlearning;
import java.io.IOException;
import com.google.gson.TypeAdapter;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
public class StringTypeAdapter {
/*
* TypeAdapterEnum - Enum type to hold all types of Adapter /
*/
public enum TypeAdapterEnum{
STRING_TO_INT_PRIM(new StringToIntegerAdapter(true)) ,
STRING_TO_INT(new StringToIntegerAdapter(false)),
STRING_TO_FLOAT_PRIM(new StringToFloatAdapter(true)) ,
STRING_TO_FLOAT(new StringToIntegerAdapter(false)) ,
STRING_TO_DOUBLE_PRIM(new StringToIntegerAdapter(true)),
STRING_TO_DOUBLE(new StringToIntegerAdapter(false));
private TypeAdapter<Number> typeAdapter;
TypeAdapterEnum(TypeAdapter<Number> typeAdapter) {
this.typeAdapter = typeAdapter;
}
public TypeAdapter<Number> getType(){
return typeAdapter;
}
}
/*
* StringToIntegerAdapter - To handle Runtime Exception by returning 0 /
* null
*/
public static class StringToIntegerAdapter extends TypeAdapter<Number> {
private boolean mIsPrimitive;
public StringToIntegerAdapter(boolean isPrimitive) {
mIsPrimitive = isPrimitive;
}
@Override
public void write(JsonWriter out, Number value) throws IOException {
if (value == null) {
out.nullValue();
return;
}
out.value(value);
}
@Override
public Number read(JsonReader in) throws IOException {
String value = in.nextString();
Integer result = null;
try {
result = Integer.parseInt(value);
} catch (NumberFormatException e) {
if (mIsPrimitive) {
return 0;
}
return result;
}
return result;
}
}
/*
* StringToIntegerAdapter - To handle Runtime Exception by returning 0 /
* null
*/
public static class StringToDouble extends TypeAdapter<Number> {
private boolean mIsPrimitive;
public StringToDouble(boolean isPrimitive) {
mIsPrimitive = isPrimitive;
}
@Override
public void write(JsonWriter out, Number value) throws IOException {
if (value == null) {
out.nullValue();
return;
}
out.value(value);
}
@Override
public Number read(JsonReader in) throws IOException {
String value = in.nextString();
Double result = null;
try {
result = Double.valueOf(value);
} catch (NumberFormatException e) {
if (mIsPrimitive) {
return (double) 0;
}
return result;
}
return result;
}
}
/*
* To handle Runtime Exception by returning 0 / 1 null
*/
public static class StringToFloatAdapter extends TypeAdapter<Number> {
private boolean mIsPrimitive;
public StringToFloatAdapter(boolean isPrimitive) {
mIsPrimitive = isPrimitive;
}
@Override
public void write(JsonWriter out, Number value) throws IOException {
if (value == null) {
out.nullValue();
return;
}
out.value(value);
}
@Override
public Number read(JsonReader in) throws IOException {
String value = in.nextString();
Float result = null;
try {
result = Float.valueOf(value);
} catch (NumberFormatException e) {
if (mIsPrimitive) {
return 0f;
}
return result;
}
return result;
}
}
}
|
package com.huashun.lockerrobot.exception;
public class InvalidTicketException extends RuntimeException {
}
|
package com.ifli.mbcp.service;
import java.util.List;
import org.springframework.stereotype.Component;
import com.ifli.mbcp.domain.AudioVideo;
@Component
public interface AudioVideoService extends LookupService {
/**
* gets list of audio video by criteria
* @param languageName
* @param type
* @param urlType
* @return {@link List}
* @throws Exception
*
*/
public List<AudioVideo> getAudioVideoBy(String languageName, int type, String urlType) throws Exception;
/**
* gets list of audio video by criteria
* @param languageId
* @param type
* @param urlType
* @return {@link List}
* @throws Exception
*
*/
public List<AudioVideo> getAudioVideoBy(long languageId, int type, String urlType) throws Exception;
}
|
public class Anagram1 {
static int[] chars = new int[26];
public static void main(String[] args) {
isAnagram(null);
isAnagram("");
isAnagram("abc");
isAnagram("aabb");
isAnagram("ababababa");
isAnagram("abcdcbbs");
isAnagram("abbccscsabcb");
}
private static void isAnagram(String str) {
if (str == null || "".equals(str) || str.length() % 2 == 1) {
System.out.println(str + " is invalid.");
} else {
for (int i = 0; i < 26; i++)
chars[i] = 0;
int len = str.length();
for (int i = 0; i < len / 2; i++) {
int ind = str.charAt(i);
chars[ind-97]++;
}
for (int i = len / 2; i < len; i++) {
int ind = str.charAt(i);
chars[ind-97]--;
}
int sum = 0;
for (int i = 0; i < 26; i++) {
sum += Math.abs(chars[i]);
}
if (sum/2 > 0) {
System.out.println(str + " is not anagram and differ by " + sum/2 + " letters.");
} else {
System.out.println(str + " is anagram.");
}
}
}
}
|
package exer;
public class Day06 {
public static void main(String[] args) {
// compare(100,120);
// getSum(6, 7, 2, 12, 2121);
getString('a','c','b');
}
// 比较两个整数是否相等
public static boolean compare(int a, int b) {
/*if (a == b) {
return true;
} else {
return false;
}*/
// return a == b ? true : false;
return a == b;
}
// 计算1-100的和
public static int getSum1() {
int sum = 0;
for (int i = 1; i <= 100; i++) {
sum += i;
}
return sum;
}
// 不确定的打印次数
public static void printHelloWorld(int n) {
for (int i = 0; i <= n;i++) {
System.out.println("HelloWorld");
}
}
// 打印1到指定范围内所有的质数
public static void printPrime(int n) {
boolean isFlag = true;
for (int i = 2; i <= n; i++) {
isFlag = true;
for (int j = 2; j <= Math.sqrt(i); j++) {
if (i % j == 0) {
isFlag = false;
break;
}
}
if (isFlag) {
System.out.println(i);
}
}
}
//可变形参的使用
public static int getSum(int...arr){
int sum = 0;
for (int i = 0; i < arr.length; i++) {
sum += arr[i];
}
return sum;
}
public static void getString(char...c){
String s = "";
for(int i = 0;i < c.length;i++){
s += c[i];
}
System.out.println(s);
}
}
|
// Copyright (c) FIRST and other WPILib contributors.
// Open Source Software; you can modify and/or share it under the terms of
// the WPILib BSD license file in the root directory of this project.
package frc.robot.commands.Auto;
import edu.wpi.first.wpilibj.command.CommandGroup;
import java.util.List;
import edu.wpi.first.wpilibj.geometry.Pose2d;
import edu.wpi.first.wpilibj.geometry.Rotation2d;
import edu.wpi.first.wpilibj.geometry.Translation2d;
import edu.wpi.first.wpilibj.trajectory.Trajectory;
import edu.wpi.first.wpilibj.trajectory.TrajectoryConfig;
import edu.wpi.first.wpilibj.trajectory.TrajectoryGenerator;
import frc.robot.commands.*;
import edu.wpi.first.wpilibj.controller.PIDController;
import edu.wpi.first.wpilibj.controller.ProfiledPIDController;
import frc.robot.Constants.AutoConstants;
import frc.robot.Constants.SwerveDriveConstants;
import frc.robot.subsystems.*;
public class BouncePath extends CommandGroup {
/** Add your docs here. */
public BouncePath(SwerveDrive swerveDrive, ProfiledPIDController theta) {
// Create config for trajectory
TrajectoryConfig config1 = new TrajectoryConfig(1,
AutoConstants.kMaxAccelerationMetersPerSecondSquared)
// Add kinematics to ensure max speed is actually obeyed
// .setKinematics(SwerveDriveConstants.kDriveKinematics)
.setEndVelocity(0);
TrajectoryConfig config2 = new TrajectoryConfig(1,
AutoConstants.kMaxAccelerationMetersPerSecondSquared)
// Add kinematics to ensure max speed is actually obeyed
// .setKinematics(SwerveDriveConstants.kDriveKinematics)
.setStartVelocity(0);
TrajectoryConfig config3 = new TrajectoryConfig(1,
AutoConstants.kMaxAccelerationMetersPerSecondSquared)
// Add kinematics to ensure max speed is actually obeyed
// .setKinematics(SwerveDriveConstants.kDriveKinematics)
.setStartVelocity(0);
//loop 1 (top)
Trajectory tStep1 = TrajectoryGenerator.generateTrajectory(
new Pose2d(0, 0, new Rotation2d(-Math.PI / 2)), List.of(
new Translation2d(0, -0.567971)
),
//direction robot moves
new Pose2d(1.20986, -.769512, new Rotation2d(0)), config1);
//look 2 (bottom)
Trajectory tStep2 = TrajectoryGenerator.generateTrajectory(
new Pose2d(1.20986, -.769512, new Rotation2d(-Math.PI)), List.of(
new Translation2d(0.45, -0.567971),
new Translation2d(0.023366, -1.626955),
new Translation2d(-1.35086, -1.606955),
new Translation2d(-1.255086, -2.872373)
),
//direction robot moves
new Pose2d(1.607909, -3.350157, new Rotation2d(0)), config2);
//loop 3 (top)
Trajectory tStep3 = TrajectoryGenerator.generateTrajectory(
new Pose2d(1.607909, -3.350157, new Rotation2d(-Math.PI)), List.of(
new Translation2d(-.985376, -3.333096),
new Translation2d(-1.355086,-5.396242),
new Translation2d(1.605086,-5.396242),
new Translation2d(0.85,-5.396242)
),
//direction robot moves
new Pose2d(.85,-6.396242, new Rotation2d(0)), config3);
//end: .402495,-6.396242
SwerveControllerCommand swerveControllerCommand1 = new SwerveControllerCommand(tStep1,
(0), swerveDrive::getPose, // Functional interface to feed supplier
SwerveDriveConstants.kDriveKinematics,
// Position controllers
new PIDController(AutoConstants.kPXController, 1, AutoConstants.kDXController),
new PIDController(AutoConstants.kPYController, 1, AutoConstants.kDYController), theta,
swerveDrive::setModuleStates,
swerveDrive
);
SwerveControllerCommand swerveControllerCommand2 = new SwerveControllerCommand(tStep2,
(0), swerveDrive::getPose, // Functional interface to feed supplier
SwerveDriveConstants.kDriveKinematics,
// Position controllers
new PIDController(AutoConstants.kPXController, 1, AutoConstants.kDXController),
new PIDController(AutoConstants.kPYController, 1, AutoConstants.kDYController), theta,
swerveDrive::setModuleStates,
swerveDrive
);
SwerveControllerCommand swerveControllerCommand3 = new SwerveControllerCommand(tStep3,
(0), swerveDrive::getPose, // Functional interface to feed supplier
SwerveDriveConstants.kDriveKinematics,
// Position controllers
new PIDController(AutoConstants.kPXController, 1, AutoConstants.kDXController),
new PIDController(AutoConstants.kPYController, 1, AutoConstants.kDYController), theta,
swerveDrive::setModuleStates,
swerveDrive
);
addSequential(swerveControllerCommand1);
addSequential(swerveControllerCommand2);
addSequential(swerveControllerCommand3);
}
}
|
package ru.itis.springboot.security;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import ru.itis.springboot.security.filter.JwtFilter;
import ru.itis.springboot.security.provider.JwtAuthenticationProvider;
/**
* created: 19-04-2021 - 9:32
* project: SpringBoot
*
* @author dinar
* @version v0.1
*/
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private JwtFilter jwtTokenAuthenticationFilter;
@Autowired
private JwtAuthenticationProvider jwtTokenAuthenticationProvider;
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
.sessionManagement().disable()
.addFilterAt(jwtTokenAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.authenticationProvider(jwtTokenAuthenticationProvider);
}
}
|
package com.gtfs.action;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import com.gtfs.bean.LicOblApplicationMst;
import com.gtfs.bean.LicRequirementDtls;
import com.gtfs.service.interfaces.LicMarkingToQcDtlsService;
@Component
@Scope("session")
public class IndividualMarkingForReqAction implements Serializable{
private Logger log = Logger.getLogger(IndividualMarkingForReqAction.class);
@Autowired
private LicMarkingToQcDtlsService licMarkingToQcDtlsService;
@Autowired
private LoginAction loginAction;
private Date bnsFromDate;
private Date bnsToDate;
private Boolean renderedindMark;
private List<LicRequirementDtls> licRequirementDtlsList = new ArrayList<LicRequirementDtls>();
private List<LicRequirementDtls> selectedList = new ArrayList<LicRequirementDtls>();
public void refresh(){
renderedindMark = false;
bnsFromDate = null;
bnsToDate = null;
if(licRequirementDtlsList!=null){
licRequirementDtlsList.clear();
}
if(selectedList!=null){
selectedList.clear();
}
}
public String onLoad(){
refresh();
return "/licHubActivity/individualMarkingForReq.xhtml";
}
public void save(){
try{
if(selectedList == null || selectedList.size()==0){
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR,
"Error : ", "Please Select an Application to Save"));
return;
}
Date now = new Date();
for(LicRequirementDtls obj : selectedList){
obj.setDispatchReadyFlag("Y");
obj.getLicMarkingToQcDtls().setIndMrkBy(loginAction.getUserList().get(0).getUserid());
obj.getLicMarkingToQcDtls().setIndMrkDate(now);
obj.getLicMarkingToQcDtls().setIndMrkFlag("Y");
obj.getLicMarkingToQcDtls().setModifiedBy(loginAction.getUserList().get(0).getUserid());
obj.getLicMarkingToQcDtls().setModifiedDate(now);
}
Boolean status = licMarkingToQcDtlsService.updateForIndividualMarkingForReq(selectedList);
if(status){
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO,
"Save Successful : ", "REQ POD Tagging Successfully Completed."));
onLoad();
}else{
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR,
"Save UnSuccessful : ", "REQ POD Tagging Unsuccessful"));
}
}catch(Exception e){
log.info("IndividualMarkingForReqAction save Error : ", e);
}
}
public void search(){
try{
renderedindMark = true;
licRequirementDtlsList = licMarkingToQcDtlsService.findIndividualMArkingDtlsByDateForReq(bnsFromDate, bnsToDate, loginAction.findHubForProcess("POS"), loginAction.getUserList().get(0).getBranchMst());
if(licRequirementDtlsList == null || licRequirementDtlsList.size() == 0 || licRequirementDtlsList.contains(null)){
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR,
"Error : ", "No Record(s) Found"));
return;
}
}catch(Exception e){
log.info("IndividualMarkingAction search Error : ", e);
}
}
/* GETTER SETTER */
public Date getBnsFromDate() {
return bnsFromDate;
}
public void setBnsFromDate(Date bnsFromDate) {
this.bnsFromDate = bnsFromDate;
}
public Date getBnsToDate() {
return bnsToDate;
}
public void setBnsToDate(Date bnsToDate) {
this.bnsToDate = bnsToDate;
}
public Boolean getRenderedindMark() {
return renderedindMark;
}
public void setRenderedindMark(Boolean renderedindMark) {
this.renderedindMark = renderedindMark;
}
public List<LicRequirementDtls> getLicRequirementDtlsList() {
return licRequirementDtlsList;
}
public void setLicRequirementDtlsList(
List<LicRequirementDtls> licRequirementDtlsList) {
this.licRequirementDtlsList = licRequirementDtlsList;
}
public List<LicRequirementDtls> getSelectedList() {
return selectedList;
}
public void setSelectedList(List<LicRequirementDtls> selectedList) {
this.selectedList = selectedList;
}
}
|
package com.stryksta.swtorcentral.util;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.ColorFilter;
import android.graphics.ColorMatrixColorFilter;
import android.support.annotation.Nullable;
import android.util.TypedValue;
import android.view.View;
public class Utils {
public static String toTitleCase(String string) {
char[] chars = string.toLowerCase().toCharArray();
boolean found = false;
for (int i = 0; i < chars.length; i++) {
if (!found && Character.isLetter(chars[i])) {
chars[i] = Character.toUpperCase(chars[i]);
found = true;
} else if (Character.isWhitespace(chars[i]) || chars[i]=='.' || chars[i]=='\'') { // You can add other chars here
found = false;
}
}
return String.valueOf(chars);
}
public static String capitalizeFirstOnly (String line)
{
return Character.toUpperCase(line.charAt(0)) + line.substring(1);
}
public static String subStringBetween(String sentence, String before, String after) {
int startSub = subStringStartIndex(sentence, before);
int stopSub = subStringEndIndex(sentence, after);
String newWord = sentence.substring(startSub, stopSub);
return newWord;
}
public static String subStringBefore(String sentence, String after) {
int stopSub = subStringEndIndex(sentence, after);
/*
int idx = beginsTxt.indexOf("AT");
if (idx < 0)
throw new IllegalArgumentException("Word not found.");
String before = beginsTxt.substring(0, idx);
*/
String newWord = sentence.substring(0, stopSub);
return newWord;
}
public static int subStringStartIndex(String sentence, String delimiterBeforeWord) {
int startIndex = 0;
String newWord = "";
int x = 0, y = 0;
for (int i = 0; i < sentence.length(); i++) {
newWord = "";
if (sentence.charAt(i) == delimiterBeforeWord.charAt(0)) {
startIndex = i;
for (int j = 0; j < delimiterBeforeWord.length(); j++) {
try {
if (sentence.charAt(startIndex) == delimiterBeforeWord.charAt(j)) {
newWord = newWord + sentence.charAt(startIndex);
}
startIndex++;
} catch (Exception e) {
}
}
if (newWord.equals(delimiterBeforeWord)) {
x = startIndex;
}
}
}
return x;
}
public static int subStringEndIndex(String sentence, String delimiterAfterWord) {
int startIndex = 0;
String newWord = "";
int x = 0;
for (int i = 0; i < sentence.length(); i++) {
newWord = "";
if (sentence.charAt(i) == delimiterAfterWord.charAt(0)) {
startIndex = i;
for (int j = 0; j < delimiterAfterWord.length(); j++) {
try {
if (sentence.charAt(startIndex) == delimiterAfterWord.charAt(j)) {
newWord = newWord + sentence.charAt(startIndex);
}
startIndex++;
} catch (Exception e) {
}
}
if (newWord.equals(delimiterAfterWord)) {
x = startIndex;
x = x - delimiterAfterWord.length();
}
}
}
return x;
}
public static ColorFilter getColoredMatrix(int targetColor) {
int red = (targetColor & 0xFF0000) / 0xFFFF;
int green = (targetColor & 0xFF00) / 0xFF;
int blue = targetColor & 0xFF;
float[] matrix = { 0, 0, 0, 0, red
, 0, 0, 0, 0, green
, 0, 0, 0, 0, blue
, 0, 0, 0, 1, 0 };
ColorFilter colorFilter = new ColorMatrixColorFilter(matrix);
return colorFilter;
}
/**
* Convert Dp to Pixel
*/
public static int dpToPx(float dp, Resources resources){
float px = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, resources.getDisplayMetrics());
return (int) px;
}
public static int dp2px(Context context, float dipValue) {
final float scale = context.getResources().getDisplayMetrics().density;
return (int) (dipValue * scale + 0.5f);
}
public static int getRelativeTop(View myView) {
// if (myView.getParent() == myView.getRootView())
if(myView.getId() == android.R.id.content)
return myView.getTop();
else
return myView.getTop() + getRelativeTop((View) myView.getParent());
}
public static int getRelativeLeft(View myView) {
// if (myView.getParent() == myView.getRootView())
if(myView.getId() == android.R.id.content)
return myView.getLeft();
else
return myView.getLeft() + getRelativeLeft((View) myView.getParent());
}
public static boolean isEmptyString(String text) {
return (text == null || text.trim().equals("null") || text.trim()
.length() <= 0);
}
public static boolean isEmptyTest(@Nullable CharSequence text) {
if (text == null || text.length() == 0) return true;
return text.toString().isEmpty();
}
}
|
package org.ebmdev.junitapp.ejemplos.models;
import org.ebmdev.junitapp.ejemplos.exceptions.DineroInsuficienteException;
import org.junit.jupiter.api.*;
import org.junit.jupiter.api.condition.*;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvFileSource;
import org.junit.jupiter.params.provider.CsvSource;
import org.junit.jupiter.params.provider.MethodSource;
import org.junit.jupiter.params.provider.ValueSource;
import java.math.BigDecimal;
import java.time.Duration;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.TimeUnit;
import static org.junit.jupiter.api.Assertions.*;
import static org.junit.jupiter.api.Assumptions.*;
class CuentaTest {
Cuenta cuenta;
private TestInfo testInfo;
private TestReporter testReporter;
@BeforeAll //Añade cierta funcionalidad antes de ejecutar cualquier método de la clase
static void beforeAll() {
System.out.println("Inicializando el test.");
}
@AfterAll //Añade cierta funcionalidad después de ejecutar todos los métodos de la clase
static void afterAll() {
System.out.println("Finalizando el test.");
}
@BeforeEach
//Añade cierta funcionalidad antes de ejecutar cada uno de los métodos de la clase test.
void setUp(TestInfo testInfo, TestReporter testReporter) {
this.cuenta = new Cuenta("Ebmdev", new BigDecimal("1000.00"));
this.testInfo = testInfo;
this.testReporter = testReporter;
System.out.println("Iniciando el test.");
testReporter.publishEntry("ejecutando: " + testInfo.getDisplayName() + " " + testInfo.getTestMethod().get().getName() + " con las etiquetas " + testInfo.getTags());
}
@AfterEach
//Añade cierta funcionalidad antes de ejecutar cada uno de los métodos de la clases test.
void tearDown() {
System.out.println("Finalizando el test.");
}
@Nested
class CuentaBancoTest {
@Test
@DisplayName("Test para el nombre de la cuenta")
void testNombreCuenta() {
assertEquals("Ebmdev", cuenta.getPersona(), () -> "El nombre de la cuenta no es el esperado, se esperaba: Ebmdev, sin embargo fue: " + cuenta.getPersona());
}
@Test
@DisplayName("Test para el saldo de la cuenta")
void testSaldoCuenta() {
assertNotNull(cuenta.getSaldo());
assertEquals(cuenta.getSaldo().doubleValue(), 1000.00);
assertFalse(cuenta.getSaldo().compareTo(BigDecimal.ZERO) < 0);
assertTrue(cuenta.getSaldo().compareTo(BigDecimal.ZERO) > 0);
}
@Test
@DisplayName("Test para la referencia entre dos cuentas")
void testReferenciaCuenta() {
cuenta = new Cuenta("John Doe", new BigDecimal("1200.00"));
Cuenta cuenta2 = new Cuenta("John Doe", new BigDecimal("1200.00"));
assertEquals(cuenta2, cuenta);
}
@Test
@DisplayName("Test para el método debito() de la cuenta")
void testDebitoCuenta() {
cuenta.debito(new BigDecimal(100));
assertNotNull(cuenta.getSaldo());
assertEquals(900, cuenta.getSaldo().intValue());
assertEquals("900.00", cuenta.getSaldo().toPlainString());
}
@Test
@DisplayName("Test para el método credito() de la cuenta")
void testCreditoCuenta() {
cuenta.credito(new BigDecimal(100));
assertNotNull(cuenta.getSaldo());
assertEquals(1100, cuenta.getSaldo().intValue());
assertEquals("1100.00", cuenta.getSaldo().toPlainString());
}
@Test
@DisplayName("Test para la excepción DineroInsuficienteException")
void testDineroInsuficienteExceptionCuenta() {
Exception exception = assertThrows(DineroInsuficienteException.class, () -> {
cuenta.debito(new BigDecimal(1500));
});
assertEquals(exception.getMessage(), "Dinero Insuficiente");
}
@Test
@DisplayName("Test para el método transferir() de la cuenta")
void testTransferirDineroCuenta() {
Cuenta cuentaOrigen = new Cuenta("Empresa", new BigDecimal("1200.00"));
Cuenta cuentaDestino = new Cuenta("Ebmdev", new BigDecimal("1000.00"));
Banco banco = new Banco();
banco.setNombre("La Caixa");
banco.transferir(cuentaOrigen, cuentaDestino, new BigDecimal(500));
assertEquals("700.00", cuentaOrigen.getSaldo().toPlainString());
assertEquals("1500.00", cuentaDestino.getSaldo().toPlainString());
}
@Test
@DisplayName("Test para la relación entre Cuenta y Banco")
//@Disabled -- Esta anotación nos permite evitar la ejecución de algunos test de una clase si fuera necesario.
void testRelacionBancoCuentas() {
Cuenta cuentaOrigen = new Cuenta("Empresa", new BigDecimal("1200.00"));
Cuenta cuentaDestino = new Cuenta("Ebmdev", new BigDecimal("1000.00"));
Banco banco = new Banco();
banco.anadirCuenta(cuentaOrigen);
banco.anadirCuenta(cuentaDestino);
banco.setNombre("La Caixa");
assertAll(() -> assertEquals(2, banco.getCuentas().size()),
() -> assertEquals("La Caixa", cuentaOrigen.getBanco().getNombre()),
() -> assertEquals("Ebmdev", banco.getCuentas().stream().filter(c -> c.getPersona().equals("Ebmdev")).findFirst().get().getPersona()),
() -> assertTrue(banco.getCuentas().stream().anyMatch(c -> c.getPersona().equals("Ebmdev")))
);
}
}
@Nested
class SOTest {
@Test
@EnabledOnOs(OS.WINDOWS)
void testSoloWindows() {
}
@Test
@EnabledOnOs({OS.MAC, OS.LINUX})
void testSoloLinuxMac() {
}
@Test
@DisabledOnOs(OS.WINDOWS)
void testNoWindows() {
}
}
@Nested
class JavaVersionTest {
@Test
@EnabledOnJre(JRE.JAVA_8)
void testSoloJDK8() {
}
@Test
@EnabledOnJre(JRE.JAVA_16)
void testSoloJDK16() {
}
}
@Nested
class SystemPropertiesTest {
@Test
void imprimirSystemProperties() {
Properties properties = System.getProperties();
properties.forEach((k, v) -> System.out.println(k + " : " + v));
}
@Test
@EnabledIfSystemProperty(named = "os.arch", matches = ".*64.*")
void test64BitsArch() {
}
@Test
@EnabledIfSystemProperty(named = "user.name", matches = "Emilio")
void testUsernameProperty() {
}
@Test
@EnabledIfSystemProperty(named = "ENV", matches = "dev")
void testDev() {
}
}
@Nested
class EnvVariableTest {
@Test
void imprimirVariablesAmbiente() {
Map<String, String> env = System.getenv();
env.forEach((k, v) -> System.out.println(k + " : " + v));
}
@Test
@EnabledIfEnvironmentVariable(named = "JAVA_HOME", matches = ".*jdk-16.*")
void testJavaHome() {
}
@Test
@EnabledIfEnvironmentVariable(named = "NUMBER_OF_PROCESSORS", matches = "4")
void testNumeroProcesadores() {
}
}
@Nested
class CuentaNombreSaldoTest {
@Test
void testSaldoCuentaDev() {
boolean esDev = "dev".equals(System.getProperty("ENV"));
assumeTrue(esDev);
assertNotNull(cuenta.getSaldo());
assertEquals(cuenta.getSaldo().doubleValue(), 1000.00);
assertFalse(cuenta.getSaldo().compareTo(BigDecimal.ZERO) < 0);
assertTrue(cuenta.getSaldo().compareTo(BigDecimal.ZERO) > 0);
}
@Test
void testSaldoCuentaDev2() {
boolean esDev = "dev".equals(System.getProperty("ENV"));
assumingThat(esDev, () -> {
assertNotNull(cuenta.getSaldo());
assertEquals(cuenta.getSaldo().doubleValue(), 1000.00);
assertFalse(cuenta.getSaldo().compareTo(BigDecimal.ZERO) < 0);
assertTrue(cuenta.getSaldo().compareTo(BigDecimal.ZERO) > 0);
}
);
}
}
@Nested
class RepeatedTests {
@RepeatedTest(value = 5, name = "repetición {currentRepetition}/{totalRepetitions}")
//Con esta anotación se repite el test tantas veces como se le pase por parámetros, esto solo tendría sentido cuando se generara algún parámetro de forma aleatoria dentro del metodo, como podría ser un Math.random();
@DisplayName("Test para el método debito() de la cuenta")
void testDebitoCuentaRepetir(RepetitionInfo info) {
if (info.getCurrentRepetition() == 3) {
System.out.println("Es la 3ª repetición");
}
cuenta.debito(new BigDecimal(100));
assertNotNull(cuenta.getSaldo());
assertEquals(900, cuenta.getSaldo().intValue());
assertEquals("900.00", cuenta.getSaldo().toPlainString());
}
}
@Tag("param")
@Nested
class ParameterizedTests {
@ParameterizedTest(name = "nº {index} ejecutando con valor {0} - {argumentsWithNames}")
@ValueSource(strings = {"100", "200", "300", "700", "900"})
void testDebitoCuentaValueSource(String cantidad) {
cuenta.debito(new BigDecimal(cantidad));
assertNotNull(cuenta.getSaldo());
assertTrue(cuenta.getSaldo().compareTo(BigDecimal.ZERO) > 0);
}
@ParameterizedTest(name = "nº {index} ejecutando con valor {0}")
@CsvSource({"1,100", "2,200", "3,300", "4,700", "5,900"})
void testDebitoCuentaCsvSource(String index, String cantidad) {
System.out.println(index + " -> " + cantidad);
cuenta.debito(new BigDecimal(cantidad));
assertNotNull(cuenta.getSaldo());
assertTrue(cuenta.getSaldo().compareTo(BigDecimal.ZERO) > 0);
}
@ParameterizedTest(name = "nº {index} ejecutando con valor {0}")
@CsvFileSource(resources = "/data.csv")
void testDebitoCuentaCsvFileSource(String cantidad) {
cuenta.debito(new BigDecimal(cantidad));
assertNotNull(cuenta.getSaldo());
assertTrue(cuenta.getSaldo().compareTo(BigDecimal.ZERO) > 0);
}
@ParameterizedTest(name = "nº {index} ejecutando con valor {0}")
@MethodSource("cantidadList")
void testDebitoCuentaMethodSource(String cantidad) {
cuenta.debito(new BigDecimal(cantidad));
assertNotNull(cuenta.getSaldo());
assertTrue(cuenta.getSaldo().compareTo(BigDecimal.ZERO) > 0);
}
private static List<String> cantidadList() {
return Arrays.asList("100", "200", "300", "700", "900");
}
@ParameterizedTest(name = "nº {index} ejecutando con valor {0}")
@CsvSource({"150,100", "250,200", "320,300", "780,700", "980,900"})
void testDebitoCuentaCsvSource2(String saldo, String cantidad) {
cuenta.setSaldo(new BigDecimal(saldo));
cuenta.debito(new BigDecimal(cantidad));
assertNotNull(cuenta.getSaldo());
assertTrue(cuenta.getSaldo().compareTo(BigDecimal.ZERO) > 0);
}
@ParameterizedTest(name = "nº {index} ejecutando con valor {0}")
@CsvFileSource(resources = "/data2.csv")
void testDebitoCuentaCsvFileSource2(String saldo, String cantidad) {
cuenta.setSaldo(new BigDecimal(saldo));
cuenta.debito(new BigDecimal(cantidad));
assertNotNull(cuenta.getSaldo());
assertTrue(cuenta.getSaldo().compareTo(BigDecimal.ZERO) > 0);
}
}
@Nested
class timeOutTests {
@Test
@Timeout(1)
void timeOutTest() throws InterruptedException {
TimeUnit.MILLISECONDS.sleep(950);
}
@Test
@Timeout(value = 1000, unit = TimeUnit.MILLISECONDS)
void timeOutTest2() throws InterruptedException {
TimeUnit.MILLISECONDS.sleep(950);
}
@Test
void timeOutAssertionsTest() {
assertTimeout(Duration.ofMillis(1000l),() -> {
TimeUnit.MILLISECONDS.sleep(950);
} );
}
}
}
|
package abstract_interface;
public interface ThongTinGiaDinh extends ThongTinGiaDinhChiTiet {
String maSo = "XYZ305";
void updateThongTin(String thongTinGiaDinh);
}
|
package org.nishkarma.book.model;
public enum Cover {
PAPERBACK, HARDCOVER, DUST_JACKET
}
|
package com.espendwise.ocean.common.emails.objects;
public interface AccountEmailObject extends EmailObject {
public String getName();
}
|
package interviews.amazon.myoa;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
public class ClosestCommonManager {
public static class Employee {
public int id;
public String name;
public List<Employee> reporters;
public Employee(String name) {
this.name = name;
this.reporters = new ArrayList<Employee>();
}
public Employee(int id) {
this.id = id;
this.reporters = new ArrayList<Employee>();
}
}
public Employee closestCommonManager(Employee ceo, Employee e1, Employee e2) {
if (ceo == null || e1 == null || e2 == null) return null;
Queue<Employee> workingQueue = new LinkedList<Employee>();
workingQueue.offer(ceo);
Employee closestKnownManager = null;
while (!workingQueue.isEmpty()) {
Employee employee = workingQueue.poll();
if (covers(employee, e1) && covers(employee, e2)) {
closestKnownManager = employee;
for (Employee em : employee.reporters) {
workingQueue.offer(em);
}
}
}
return closestKnownManager;
}
public boolean covers(Employee manager, Employee employee) {
if (manager == null) return false;
if (manager.name.equals(employee.name)) return true;
if (manager.reporters == null) return false;
for (Employee em : manager.reporters) {
if(covers(em, employee)) return true;
}
return false;
}
public static void main(String[] args) {
ClosestCommonManager app = new ClosestCommonManager();
Employee samir = new Employee("samir");
Employee dom = new Employee("dom");
Employee michael = new Employee("michael");
Employee peter = new Employee("peter");
Employee porter = new Employee("porter");
Employee bob = new Employee("bob");
dom.reporters = Arrays.asList(bob, peter, porter);
Employee milton = new Employee("milton");
Employee nina = new Employee("nina");
peter.reporters = Arrays.asList(milton, nina);
Employee bill = new Employee("bill");
bill.reporters = Arrays.asList(dom, samir, michael);
Employee none = new Employee("none");
// System.out.println(app.closestCommonManager(bill, milton, nina).name);
// System.out.println(app.closestCommonManager(bill, nina, porter).name);
// System.out.println(app.closestCommonManager(bill, nina, samir).name);
// System.out.println(app.closestCommonManager(bill, peter, nina).name);
System.out.println(app.closestCommonManager(bill, peter, none) == null);
}
}
|
package assemAssist.model.factoryline.assemblyLine;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import org.joda.time.Duration;
import assemAssist.model.clock.clock.Clock;
import assemAssist.model.company.VehicleModel;
import assemAssist.model.factoryline.workStation.WorkStation;
import assemAssist.model.operations.task.Task;
import assemAssist.model.order.order.Order;
import com.google.common.base.Optional;
/**
* A protection proxy for a {@link ModifiableAssemblyLine}. This implements the
* {@link AssemblyLine} interface.
*
* @author SWOP Group 3
* @version 3.0
*/
final class AssemblyLineProxy implements AssemblyLine {
/**
* Initialises this assembly line proxy with the given
* {@link ModifiableAssemblyLine}.
*
* @param line
* The {@link ModifiableAssemblyLine} which will be represented by
* this proxy
* @throws IllegalArgumentException
* Thrown when the given assembly line is invalid
*/
public AssemblyLineProxy(ModifiableAssemblyLine line) {
if (!isValidAssemblyLine(line)) {
throw new IllegalArgumentException("The given assembly line is invalid.");
}
this.line = line;
}
/**
* Check whether the given assembly line is valid.
*
* @param line
* The {@link AssemblyLine} to check
* @return True if and only if the given line is effective
*/
public boolean isValidAssemblyLine(AssemblyLine line) {
return line != null;
}
private final ModifiableAssemblyLine line;
/**
* {@inheritDoc}
*/
@Override
public Collection<VehicleModel> getProducableModels() {
return line.getProducableModels();
}
/**
* {@inheritDoc}
*/
@Override
public boolean isValidProducableModels(Collection<VehicleModel> producableModels) {
return line.isValidProducableModels(producableModels);
}
/**
* {@inheritDoc}
*/
@Override
public AssemblyLineStatus getStatus() {
return line.getStatus();
}
/**
* {@inheritDoc}
*/
@Override
public boolean isValidStatus(AssemblyLineStatus status) {
return line.isValidStatus(status);
}
/**
* {@inheritDoc}
*/
@Override
public List<WorkStation> getStations() {
return line.getStations();
}
/**
* {@inheritDoc}
*/
@Override
public boolean isValidStations(List<WorkStation> stations) {
return line.isValidStations(stations);
}
/**
* {@inheritDoc}
*/
@Override
public boolean isValidStation(WorkStation station) {
return line.isValidStation(station);
}
/**
* {@inheritDoc}
*/
@Override
public List<Optional<Order>> getBelt() {
return line.getBelt();
}
/**
* {@inheritDoc}
*/
public Clock getClock() {
return line.getClock();
}
/**
* {@inheritDoc}
*/
@Override
public int getNumberOfOrdersOnBelt() {
return line.getNumberOfOrdersOnBelt();
}
/**
* {@inheritDoc}
*/
@Override
public Optional<Order> getOrder(WorkStation station) throws IllegalArgumentException {
return line.getOrder(station);
}
/**
* {@inheritDoc}
*/
@Override
public WorkStation getWorkStation(Optional<Order> order) throws IllegalArgumentException {
return line.getWorkStation(order);
}
/**
* {@inheritDoc}
*/
@Override
public Map<WorkStation, List<Task>> getPendingWorkStations() {
return line.getPendingWorkStations();
}
/**
* {@inheritDoc}
*/
@Override
public Map<WorkStation, List<Task>> getWorkStationsOverview() {
return line.getWorkStationsOverview();
}
/**
* {@inheritDoc}
*/
@Override
public Duration getWorkedTime() {
return line.getWorkedTime();
}
/**
* {@inheritDoc}
*/
@Override
public Duration getExpectedTimeOfStep() {
return line.getExpectedTimeOfStep();
}
/**
* {@inheritDoc}
*/
@Override
public AssemblyLine getAssemblyLineProxy() {
return this;
}
/**
* {@inheritDoc}
*/
@Override
public ModifiableAssemblyLine getModifiableAssemblyLine() {
return line;
}
/**
* {@inheritDoc}
*/
public boolean isValidOrder(Optional<Order> order) {
return line.isValidOrder(order);
}
}
|
package me.punish;
import org.bukkit.Bukkit;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.plugin.PluginManager;
import org.bukkit.plugin.RegisteredServiceProvider;
import org.bukkit.plugin.java.JavaPlugin;
import me.punish.Cache.CacheManager;
import me.punish.Commands.CheckIPCommand;
import me.punish.Commands.ClearIPCommand;
import me.punish.Commands.ClearPunishCommand;
import me.punish.Commands.IPCommand;
import me.punish.Commands.PunishCommand;
import me.punish.Commands.PunishIPCommand;
import me.punish.Commands.UnpunishIPCommand;
import me.punish.Database.Database;
import me.punish.Manager.PunishGUIEvents;
import me.punish.Manager.TempGUIEvents;
import me.punish.Manager.HistoryGUIEvents;
import me.punish.Manager.OptionsGUIEvents;
import me.punish.Manager.PlayerEvents;
import net.milkbowl.vault.permission.Permission;
public class Punish extends JavaPlugin {
public static Punish instance;
public static Permission perms;
public static CacheManager manager;
public void onEnable() {
instance = this;
manager = new CacheManager();
loadConfig();
Database.openDatabaseConnection();
registerCommands();
registerEvents();
setupPermissions();
Bukkit.getMessenger().registerOutgoingPluginChannel(this, "BungeeCord");
}
public void onDisable() {
Bukkit.getScheduler().cancelAllTasks();
Bukkit.getScheduler().getPendingTasks().clear();
Database.closeConnection();
}
private void registerCommands() {
getCommand("punish").setExecutor(new PunishCommand());
getCommand("puniship").setExecutor(new PunishIPCommand());
getCommand("unpuniship").setExecutor(new UnpunishIPCommand());
getCommand("iplookup").setExecutor(new IPCommand());
getCommand("checkip").setExecutor(new CheckIPCommand());
getCommand("clearpunish").setExecutor(new ClearPunishCommand());
getCommand("clearip").setExecutor(new ClearIPCommand());
}
private void registerEvents() {
PluginManager manager = Bukkit.getPluginManager();
manager.registerEvents(new PlayerEvents(), this);
manager.registerEvents(new PunishGUIEvents(), this);
manager.registerEvents(new OptionsGUIEvents(), this);
manager.registerEvents(new TempGUIEvents(), this);
manager.registerEvents(new HistoryGUIEvents(), this);
}
private void loadConfig() {
FileConfiguration cfg = getConfig();
cfg.options().copyDefaults(true);
saveDefaultConfig();
}
private boolean setupPermissions() {
RegisteredServiceProvider<Permission> rsp = getServer().getServicesManager().getRegistration(Permission.class);
perms = rsp.getProvider();
return perms != null;
}
public static Permission getPermissions() {
return perms;
}
public static Punish getInstance() {
return instance;
}
public static CacheManager getCache() {
return manager;
}
}
|
package powermocking;
/**
* Created by RCEAZ31 on 9/03/2016.
*/
public class IntValue {
private int value;
public IntValue(int value) {
this.value = value;
}
public int getValue() {
return value;
}
}
|
package chat.errors;
/**
*/
public interface ChatErrorCodes {
public static final int CODE_CORE = 10000;
public static final int ERROR_ONLINESERVER_NOT_FOUND = CODE_CORE + 121;
public static final int ERROR_ONLINESERVER_UPDATE_FAILED = CODE_CORE + 122;
public static final int ERROR_ONLINESERVER_DELETE_FAILED = CODE_CORE + 123;
public static final int ERROR_ONLINESERVER_ADD_FAILED = CODE_CORE + 124;
public static final int ERROR_ONLINESERVER_QUERY_FAILED = CODE_CORE + 125;
public static final int ERROR_USERPRESENT_ADD_FAILED = CODE_CORE + 126;
public static final int ERROR_USERPRESENT_UPDATE_FAILED = CODE_CORE + 127;
public static final int ERROR_USERPRESENT_QUERY_FAILED = CODE_CORE + 128;
public static final int ERROR_USERPRESENT_NOTFOUND = CODE_CORE + 129;
public static final int ERROR_USERPRESENT_DELETE_FAILED = CODE_CORE + 130;
public static final int ERROR_ILLEGAL_PARAMETER = CODE_CORE + 131;
public static final int ERROR_SSH_CONNECT_FAILED = CODE_CORE + 132;
public static final int ERROR_SSH_EXEC_FAILED = CODE_CORE + 133;
public static final int ERROR_MESSAGEADD_FAILED = CODE_CORE + 134;
public static final int ERROR_ITERATOR_NULL = CODE_CORE + 135;
public static final int ERROR_UNKNOWN = CODE_CORE + 136;
public static final int ERROR_CORE_LOADRESOURCE_FAILED = CODE_CORE + 137;
public static final int ERROR_CORE_LOADRESOURCE_NOT_EXIST = CODE_CORE + 138;
public static final int ERROR_CORE_UPLOAD_DB_FAILED = CODE_CORE + 139;
public static final int ERROR_CORE_ZKDATA_PERSISTENT_FAILED = CODE_CORE + 140;
public static final int ERROR_CORE_ZKENSUREPATH_FAILED = CODE_CORE + 141;
public static final int ERROR_CORE_ZKGETDATA_FAILED = CODE_CORE + 142;
public static final int ERROR_CORE_ZKDATA_RESURRECT_FAILED = CODE_CORE + 143;
public static final int ERROR_CORE_ZKDATA_NEWINSTANCE_FAILED = CODE_CORE + 144;
public static final int ERROR_CORE_ZKADDWATCHEREX_FAILED = CODE_CORE + 145;
public static final int ERROR_ZK_DISCONNECTED = CODE_CORE + 146;
public static final int ERROR_CORE_SERVERPORT_ILLEGAL = CODE_CORE + 147;
public static final int ERROR_DAOINIT_FAILED = CODE_CORE + 148;
public static final int ERROR_ILLEGAL_ENCODE = CODE_CORE + 149;
public static final int ERROR_READCONTENT_FAILED = CODE_CORE + 150;
public static final int ERROR_UPLOAD_FAILED = CODE_CORE + 151;
public static final int ERROR_PARSE_REQUEST_FAILED = CODE_CORE + 152;
public static final int ERROR_ACCOUNTNAME_ILLEGAL = CODE_CORE + 153;
public static final int ERROR_ACCOUNTDOMAIN_ILLEGAL = CODE_CORE + 154;
public static final int ERROR_IO_FAILED = CODE_CORE + 155;
public static final int ERROR_LOGINUSER_NOT_FOUND = CODE_CORE + 156;
public static final int ERROR_BALANCER_NOT_READY = CODE_CORE + 157;
public static final int ERROR_CHARACTER_OVER_MAXIMUM_LIMITS = CODE_CORE + 158;
public static final int ERROR_TASKADD_FAILED = CODE_CORE + 159;
public static final int ERROR_FILE_EMPTY = CODE_CORE + 160;
//Groovy related codes.
public static final int ERROR_GROOVY_CLASSNOTFOUND = CODE_CORE + 8001;
public static final int ERROR_GROOY_NEWINSTANCE_FAILED = CODE_CORE + 8002;
public static final int ERROR_GROOY_CLASSCAST = CODE_CORE + 8003;
public static final int ERROR_GROOVY_INVOKE_FAILED = CODE_CORE + 8004;
public static final int ERROR_GROOVYSERVLET_SERVLET_NOT_INITIALIZED = CODE_CORE + 8005;
public static final int ERROR_URL_PARAMETER_NULL = CODE_CORE + 8006;
public static final int ERROR_URL_VARIABLE_NULL = CODE_CORE + 8007;
public static final int ERROR_GROOVY_PARSECLASS_FAILED = CODE_CORE + 8008;
public static final int ERROR_GROOVY_UNKNOWN = CODE_CORE + 8009;
public static final int ERROR_GROOVY_CLASSLOADERNOTFOUND = CODE_CORE + 8010;
public static final int ERROR_JAVASCRIPT_LOADFILE_FAILED = CODE_CORE + 8011;
public static final int ERROR_URL_HEADER_NULL = CODE_CORE + 8012;
}
|
package com.tencent.mm.pluginsdk.ui.chat;
import android.os.Message;
import android.view.ViewGroup.LayoutParams;
import com.tencent.mm.sdk.platformtools.ag;
class ChatFooter$24 extends ag {
final /* synthetic */ ChatFooter qMv;
ChatFooter$24(ChatFooter chatFooter) {
this.qMv = chatFooter;
}
public final void handleMessage(Message message) {
super.handleMessage(message);
switch (message.what) {
case 4097:
ChatFooter.f(this.qMv, true);
LayoutParams layoutParams = ChatFooter.m(this.qMv).getLayoutParams();
int bottom = ChatFooter.m(this.qMv).getBottom() - ChatFooter.m(this.qMv).getTop();
if (this.qMv.ceI()) {
if (ChatFooter.n(this.qMv) != null) {
ChatFooter.n(this.qMv).setVisibility(8);
}
this.qMv.setAppPanelVisible(8);
ChatFooter.m(this.qMv).setVisibility(4);
}
if (bottom <= 3) {
ChatFooter.f(this.qMv, false);
ChatFooter.m(this.qMv).setVisibility(8);
ChatFooter.c(this.qMv, this.qMv.getKeyBordHeightPX());
return;
}
layoutParams.height = Math.max(bottom - 60, 1);
ChatFooter.m(this.qMv).setLayoutParams(layoutParams);
ChatFooter.J(this.qMv);
return;
default:
return;
}
}
}
|
package pucrs.java.maven.pets;
import static org.junit.Assert.assertNotNull;
import org.junit.Test;
import pucrs.java.maven.pets.Pet;
import pucrs.java.maven.pets.PetCatalog;
import pucrs.java.maven.pets.model.Cat;
public class PetsCatalogTest {
@Test
public void testCatCatalogIsAvailable() {
PetCatalog cats = new PetCatalog();
assertNotNull(cats);
}
@Test
public void testAddGarfieldIntoCatCatalog() {
PetCatalog cats = new PetCatalog();
Cat garfield = new Cat("Garfield", Pet.Gender.MALE);
cats.add(garfield);
}
}
|
package com.capgemini.tournament;
import com.capgemini.tournament.model.Play;
import com.capgemini.tournament.model.Team;
import com.capgemini.tournament.model.TeamList;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
public class App {
// Set the fields
// Runs the application
public static void main(String[] args) {
// Starts with printing the introduction to the tournament.
System.out.println("Welcome to the soccer tournament of Capgemini! \n");
System.out.println("In this tournament four professional and four amateur teams will contest for the cup.");
System.out.println("Eight different cities in the Netherlands are represented.");
System.out.println("Goodluck to everyone!\n\n\n");
// Get the teams from TeamList.
TeamList teamList = new TeamList();
List<Team> tournamentParticipants = teamList.teams();
// Create a new ArrayList containing the winners of round 1.
List<Team> winnerRound1 = new ArrayList<>();
// Run game 1, round 1
System.out.println("The quarter final will start now!\n\n\n");
System.out.println("The first match of today is:");
System.out.println(tournamentParticipants.get(0).getTeamName() + " against " + tournamentParticipants.get(1).getTeamName() + "\n");
winnerRound1.add(match(tournamentParticipants.get(0), tournamentParticipants.get(1)));
System.out.println();
System.out.println("The winner of this game is: " + winnerRound1.get(0).getTeamName() + "!\n");
// Run game 2, round 1
System.out.println("The second match of today is:");
System.out.println(tournamentParticipants.get(2).getTeamName() + " against " + tournamentParticipants.get(3).getTeamName() + "\n");
winnerRound1.add(match(tournamentParticipants.get(2), tournamentParticipants.get(3)));
System.out.println("The winner of this game is: " + winnerRound1.get(1).getTeamName() + "!\n");
// Run game 3, round 1
System.out.println("The third match of today is:");
System.out.println(tournamentParticipants.get(4).getTeamName() + " against " + tournamentParticipants.get(5).getTeamName() + "\n");
winnerRound1.add(match(tournamentParticipants.get(4), tournamentParticipants.get(5)));
System.out.println("The winner of this game is: " + winnerRound1.get(2).getTeamName() + "!\n");
// Run game 4, round 1
System.out.println("The last match of today is:");
System.out.println(tournamentParticipants.get(6).getTeamName() + " against " + tournamentParticipants.get(7).getTeamName() + "\n");
winnerRound1.add(match(tournamentParticipants.get(6), tournamentParticipants.get(7)));
System.out.println("The winner of this game is: " + winnerRound1.get(3).getTeamName() + "!\n\n\n\n");
// Store winners in a new Arraylist
List<Team> winnerRound2 = new ArrayList<>();
// Run game 1, round 2
System.out.println("The semi-finals will start now! All winners compete here for the grand final\n");
System.out.println("The first semi-final is:");
System.out.println(winnerRound1.get(0).getTeamName() + " against " + winnerRound1.get(1).getTeamName() + "\n");
winnerRound2.add(match(winnerRound1.get(0), winnerRound1.get(1)));
System.out.println(winnerRound2.get(0).getTeamName() + " goes to the final! \n\n\n");
// Rune game 2, round 2
System.out.println("The second semi-final is:\n");
System.out.println(winnerRound1.get(2).getTeamName() + " against " + winnerRound1.get(3).getTeamName() + "\n");
winnerRound2.add(match(winnerRound1.get(2), winnerRound1.get(3)));
System.out.println(winnerRound2.get(1).getTeamName() + " goes to the final! \n\n\n");
// Store winners in a new ArrayList
List<Team> winnerRound3 = new ArrayList<>();
// Play the grand final
System.out.println("The grand final starts now!\n\n\n");
System.out.println(winnerRound2.get(0).getTeamName() + " against " + winnerRound2.get(1).getTeamName() + "\n");
winnerRound3.add(match(winnerRound2.get(0), winnerRound2.get(1)));
System.out.println("The final winner is: " + (winnerRound3.get(0).getTeamName()));
System.out.println("Congratulations " + winnerRound3.get(0).getTeamName() + "!\n");
System.out.println(winnerRound3.get(0).getTeamName() + " is celebrating the victory with their " + winnerRound3.get(0).getSupport());
}
// The play method that simulates randomly which team wins
public static Team match(Team homeTeam, Team awayTeam){
int homeTeamGoals = 0;
int awayTeamGoals = 0;
Random random = new Random();
homeTeamGoals += random.nextInt(5);
awayTeamGoals += random.nextInt(5);
System.out.println("The final result is:");
System.out.println((homeTeamGoals)+ " vs. " + (awayTeamGoals));
if (homeTeamGoals == awayTeamGoals) {
System.out.println("It's a draw, it will come to penalties now!");
double team1 = Math.random();
double team2 = Math.random();
if (team1 > team2) {
return homeTeam;
} else return awayTeam;
} else {
if ((homeTeamGoals > awayTeamGoals))
return homeTeam;
else
return awayTeam;
}
}
}
|
package ca.antonious.habittracker.addhabit;
import ca.antonious.habittracker.interactions.HabitInteractionsFactory;
import ca.antonious.habittracker.IController;
/**
* Created by George on 2016-09-04.
*
* AddHabitController is an implementation of IController that controls
* an IAddHabitView. It exposes a method to add a habit, and notifies the view
* if the habit has been successfully added
*/
public class AddHabitController implements IController<IAddHabitView> {
private IAddHabitView addHabitView;
private HabitInteractionsFactory habitInteractionsFactory;
public AddHabitController(HabitInteractionsFactory habitInteractionsFactory) {
this.habitInteractionsFactory = habitInteractionsFactory;
}
public void addHabit(AddHabitRequest addHabitRequest) {
habitInteractionsFactory.addHabit().add(addHabitRequest.getName(), addHabitRequest.getStartDate(), addHabitRequest.getDaysOfTheWeek());
dispatchOnHabitAdded();
}
@Override
public void attachView(IAddHabitView view) {
this.addHabitView = view;
}
@Override
public void detachView() {
this.addHabitView = null;
}
private void dispatchOnHabitAdded() {
if (addHabitView != null) {
addHabitView.onHabitAdded();
}
}
}
|
package com.example.icebuild2;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.squareup.picasso.Picasso;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
public class boardsFragment extends Fragment {
////////////////////////////////////////////////////////////////////////////////////////////////
private View boardsFragmentView;
private ListView listView;
private ArrayAdapter<String> arrayAdapter;
private ArrayList<String> list_of_Boards= new ArrayList<>();
////////////////////////////////////////////////////////////////////////////////////////////////
private DatabaseReference boardRef;
private FirebaseAuth mAuth;
private DatabaseReference usersRef;
private DatabaseReference boardMembersRef;
////////////////////////////////////////////////////////////////////////////////////////////////
String UserType="";
////////////////////////////////////////////////////////////////////////////////////////////////
public boardsFragment() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
////////////////////////////////////////////////////////////////////////////////////////////
Toast.makeText(getContext(), "Check 0 : "+UserType, Toast.LENGTH_SHORT).show();
////////////////////////////////////////////////////////////////////////////////////////////
boardsFragmentView= inflater.inflate(R.layout.fragment_boards, container, false);
////////////////////////////////////////////////////////////////////////////////////////////
boardRef= FirebaseDatabase.getInstance().getReference().child("Boards");
mAuth=FirebaseAuth.getInstance();
usersRef= FirebaseDatabase.getInstance().getReference().child("Users");
boardMembersRef= FirebaseDatabase.getInstance().getReference().child("Board Members");
////////////////////////////////////////////////////////////////////////////////////////////
String email=mAuth.getCurrentUser().getEmail();
if(email.contains("-")){
UserType="Student";
}else {
UserType="Teacher";
}
////////////////////////////////////////////////////////////////////////////////////////////
usersRef.child(mAuth.getCurrentUser().getUid()).addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
String checkName=dataSnapshot.child("name").getValue().toString();
retrieveAndDisplayBoards(checkName);
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
initializeFields();
////////////////////////////////////////////////////////////////////////////////////////////
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String currentBoardName=parent.getItemAtPosition(position).toString();
////////////////////////////////////////////////////////////////////////////////////
Intent BoardDocumentIntent=new Intent(getContext(),MainDrawerActivity.class);
BoardDocumentIntent.putExtra("BoardName",currentBoardName);
startActivity(BoardDocumentIntent);
////////////////////////////////////////////////////////////////////////////////////
}
});
////////////////////////////////////////////////////////////////////////////////////////////
return boardsFragmentView;
}
private void initializeFields() {
listView = (ListView)boardsFragmentView.findViewById(R.id.list_view);
arrayAdapter=new ArrayAdapter<String>(getContext(), android.R.layout.simple_list_item_1,list_of_Boards);
listView.setAdapter(arrayAdapter);
}
private void retrieveAndDisplayBoards(final String checkName) {
if (UserType.equals("Teacher")){
boardRef.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
checkBoardsForCreator(dataSnapshot, checkName);
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
}else{
boardMembersRef.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
checkBoardsForMembers(dataSnapshot);
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
}
}
private void checkBoardsForMembers(DataSnapshot dataSnapshot) {
Set<String> set=new HashSet<>();
for(DataSnapshot ds : dataSnapshot.getChildren()){
if(ds.child("members").hasChild(mAuth.getCurrentUser().getUid())){
set.add(ds.getKey());
}
list_of_Boards.clear();
list_of_Boards.addAll(set);
arrayAdapter.notifyDataSetChanged();
}
}
private void checkBoardsForCreator(DataSnapshot dataSnapshot, String checkName) {
Set<String> set=new HashSet<>();
for(DataSnapshot ds : dataSnapshot.getChildren()){
String creatorCheck=ds.child("creator").getValue().toString();
if(creatorCheck.equals(checkName)){
set.add(ds.getKey());
}
list_of_Boards.clear();
list_of_Boards.addAll(set);
arrayAdapter.notifyDataSetChanged();
}
}
}
|
package com.philippe.app.domain;
import lombok.Data;
/**
* A Notification with 2 mandatory fields: code and description, 1 optional field: action.
*/
@Data
public class Notification {
private final String code;
private final String description;
private String action;
}
|
package de.propra2.ausleiherino24.features.imageupload;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.file.Files;
import javax.servlet.http.HttpServletResponse;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
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.RequestParam;
import org.springframework.web.multipart.MultipartFile;
@Controller
public class ImageController {
private static final String URL = "/imageUpload";
private final ImageService imageService;
@Autowired
public ImageController(final ImageService imageService) {
this.imageService = imageService;
}
@GetMapping(URL)
public String fileUpload() {
return URL;
}
@PostMapping(URL)
public String handleFileUpload(final @RequestParam("file") MultipartFile file) {
imageService.store(file, null);
return "redirect:" + URL;
}
/**
* Provides a method to receive images stored by the ImageService. Those are responded using
* HttpServletResponse.
*/
@GetMapping("/images/{fileName}")
public void getImage(final @PathVariable String fileName, final HttpServletResponse response)
throws IOException {
final File requestedFile = imageService.getFile(fileName, null);
if (requestedFile == null) {
response.setStatus(404);
return;
}
response.setContentType(Files.probeContentType(requestedFile.toPath()));
try (DataInputStream dataInputStream = new DataInputStream(
new FileInputStream(requestedFile))) {
IOUtils.copy(dataInputStream, response.getOutputStream());
}
}
}
|
package com.xwechat.api.wxapp;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import okhttp3.RequestBody;
import okhttp3.Response;
import com.xwechat.api.Apis;
import com.xwechat.api.AuthorizedApi;
import com.xwechat.api.Method;
import com.xwechat.core.Wechat;
import com.xwechat.util.JsonUtil;
/**
* 获取小程序二维码
*
* @Note 适用于需要的码数量较少的业务场景,每个appid最多10w次
* @url https://api.weixin.qq.com/wxa/getwxacode?access_token=ACCESS_TOKEN
* @see https://mp.weixin.qq.com/debug/wxadoc/dev/api/qrcode.html
* @author zqs
*/
public class QRCodeApi extends AuthorizedApi<WxappApiResp> {
public QRCodeApi() {
super(Apis.WXAPP_QR_CODE_SEND, Method.POST);
}
public QRCodeApi setMessage(QRCodeReq req) {
setRequestBody(RequestBody.create(JSON_MEDIA_TYPE,
JsonUtil.writeAsString(JsonUtil.DEFAULT_OBJECT_MAPPER, req)));
return this;
}
@Override
public Class<WxappApiResp> getResponseClass() {
return WxappApiResp.class;
}
public static void main(String[] args) {
String token =
"LXymL_c1KI8_AKv77CqhrBLPoOXbjByiPOOIO32tb8CFDx-bPKFKxQvkjTFhW-X7IifTtbViK2fgwJymHCYxphx1IXNQfANmk3RdpFjtAI2fkkYTImiLHKHhp4TP3SZ6XILhAIASDG";
QRCodeApi api = new QRCodeApi();
QRCodeReq msg = new QRCodeReq();
msg.setScene("abcdef");
msg.setPage("pages/kol-home/kol-home");
api.setMessage(msg);
api.setAccessToken(token);
try {
Response response = Wechat.get().rawCall(api);
InputStream inputStream = response.body().byteStream();
Files.copy(inputStream, Paths.get("~/Desktop/a.jpg"), StandardCopyOption.REPLACE_EXISTING);
} catch (IOException e) {
e.printStackTrace();
}
}
}
|
/**
*
*/
package com.spower.business.therapy.service.spring;
import java.lang.reflect.InvocationTargetException;
import java.util.Date;
import java.util.List;
import com.spower.basesystem.common.Tools;
import com.spower.basesystem.common.command.Page;
import com.spower.basesystem.manage.valueobject.User;
import com.spower.basesystem.oplog.service.OperateLogHelper;
import com.spower.basesystem.oplog.valueobject.OperateLog;
import com.spower.business.therapy.command.TherapyEditInfo;
import com.spower.business.therapy.command.TherapyQueryInfo;
import com.spower.business.therapy.service.ITherapyService;
import com.spower.business.therapy.service.dao.ITherapyDao;
import com.spower.business.therapy.valueobject.Therapy;
import com.spower.utils.NullBeanUtils;
/* *************************************************************
* @Title SpringTherapyService.java
* @Describe 对治疗信息实体类持久化操作的实现类
*
* @Company 南宁超创信息工程科技有限公司
* @Copyright ChaoChuang (c) 2014
* @Author 廖浩添
* @CreateDate 2014-11-18
* @LastModify 2014-11-18
* @Remark 暂无备注...
*
* ************************************************************/
public class SpringTherapyService implements ITherapyService{
private ITherapyDao therapyDao;
/* 删除 */
public void deleteTherapy(Therapy therapy) {
therapyDao.delete(therapy);
}
/* 查询 */
public Page selectTherapyList(TherapyQueryInfo info) {
return therapyDao.selectTherapyList(info);
}
/* 保存 */
public Long saveTherapy(TherapyEditInfo info) {
Therapy therapy = null;
if(info.getId()==null){
therapy = new Therapy();
try {
NullBeanUtils.copyProperties(therapy, info);
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
therapy.setId(Tools.getIdentityNumber15());
}
else{
therapy = this.selectTherapy(info.getId());
try {
NullBeanUtils.copyProperties(therapy, info);
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
try{
this.therapyDao.save(therapy);
}
catch(Exception e){
e.printStackTrace();
}
OperateLogHelper.getInstance().registLog(OperateLog.LOG_APPDATA, "新增或修改治疗信息,编号:/"
+ therapy.getId(), (User)info.getCurrentUser());
return therapy.getId();
}
public void saveTherapy(Therapy therapy) {
this.therapyDao.save(therapy);
}
/* 指定查询 */
public Therapy selectTherapy(Long therapyId) {
return therapyDao.selectTherapy(therapyId);
}
/* getter & setter */
public ITherapyDao getTherapyDao() {
return therapyDao;
}
public void setTherapyDao(ITherapyDao therapyDao) {
this.therapyDao = therapyDao;
}
@Override
public List<Therapy> selectTherapyByPersonId(Long personId) {
// TODO Auto-generated method stub
return therapyDao.selectTherapyByPersonId(personId);
}
}
|
package com.coldenergia.springcontextsharedamongwars.app2.controller;
import com.coldenergia.springcontextsharedamongwars.app2.processing.App2NothingProcessor;
import com.coldenergia.springcontextsharedamongwars.common.Nothing;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
/**
* User: coldenergia
* Date: 3/8/15
* Time: 7:45 PM
*/
@RestController
public class SimpleController {
@Autowired
private App2NothingProcessor app2NothingProcessor;
@RequestMapping(value = "nothing", method = RequestMethod.GET)
public Nothing processedNothings() {
app2NothingProcessor.processNothings();
return new Nothing(4, "nothing");
}
}
|
package com.mes.old.meta;
// Generated 2017-5-22 1:25:24 by Hibernate Tools 5.2.1.Final
/**
* MdsBomForMes generated by hbm2java
*/
public class MdsBomForMes implements java.io.Serializable {
private MdsBomForMesId id;
public MdsBomForMes() {
}
public MdsBomForMes(MdsBomForMesId id) {
this.id = id;
}
public MdsBomForMesId getId() {
return this.id;
}
public void setId(MdsBomForMesId id) {
this.id = id;
}
}
|
package com.tencent.mm.plugin.account.bind.ui;
import android.content.Intent;
import com.tencent.mm.bg.d;
import com.tencent.mm.plugin.account.bind.ui.d.1;
import com.tencent.mm.plugin.account.friend.a.a;
import com.tencent.mm.pluginsdk.ui.applet.a.b;
import com.tencent.mm.ui.e;
class d$1$2 implements b {
final /* synthetic */ 1 eIF;
final /* synthetic */ a eIx;
d$1$2(1 1, a aVar) {
this.eIF = 1;
this.eIx = aVar;
}
public final boolean pm(String str) {
Intent intent = new Intent();
intent.putExtra("Contact_User", this.eIx.getUsername());
intent.putExtra("Contact_Nick", this.eIx.Xm());
intent.putExtra("Contact_Scene", 13);
intent.putExtra("sayhi_with_sns_perm_send_verify", true);
intent.putExtra("sayhi_with_sns_perm_add_remark", true);
intent.putExtra("sayhi_with_jump_to_profile", true);
intent.putExtra(e.a.ths, str);
d.b(d.b(this.eIF.eIE), "profile", ".ui.SayHiWithSnsPermissionUI", intent, 1);
return true;
}
}
|
import java.io.*;
import java.util.StringTokenizer;
public class Sort012 {
public static void main(String[] args) throws Exception {
FastScanner fs = new FastScanner();
Print printer = new Print();
int t = fs.nextInt();
while (t > 0) {
int n = fs.nextInt();
long[] arr = new long[n];
for (int i = 0; i < n; i++) {
arr[i] = fs.nextLong();
}
int lo = 0, mid = 0, hi = n - 1;
while (mid <= hi) {
if (arr[mid] == 0) {
if (arr[lo] == 0) {
lo++;
mid++;
} else {
long tmp = arr[lo];
arr[lo] = arr[mid];
arr[mid] = tmp;
lo++;
mid++;
}
} else if (arr[mid] == 1) {
mid++;
} else {
if (arr[hi] == 2) {
hi--;
} else {
long tmp = arr[mid];
arr[mid] = arr[hi];
arr[hi] = tmp;
hi--;
}
}
}
for (int i = 0; i < n; i++) {
printer.print(arr[i] + " ");
}
printer.print('\n');
t--;
}
printer.close();
}
public static class FastScanner {
BufferedReader br;
StringTokenizer st;
public FastScanner(String s) {
try {
br = new BufferedReader(new FileReader(s));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public FastScanner() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String nextToken() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(nextToken());
}
long nextLong() {
return Long.parseLong(nextToken());
}
double nextDouble() {
return Double.parseDouble(nextToken());
}
}
static class Print {
private final BufferedWriter bw;
public Print() {
this.bw = new BufferedWriter(new OutputStreamWriter(System.out));
}
public void print(Object object) throws IOException {
bw.append("" + object);
}
public void println(Object object) throws IOException {
print(object);
bw.append("\n");
}
public void close() throws IOException {
bw.close();
}
}
}
|
package tasks;
public class Palindrome {
/**
* Сheck whether the string is palindrome
*
* @param string
* @return true if string is palindrome, false if no
*/
public static boolean isPalindrome(String string) {
char[] charArray = string.replaceAll("[^A-Za-zА-Яа-я0-9]", "").toLowerCase().toCharArray();
int length = charArray.length;
boolean flag = false;
for (int i = 0; i < length; i++) {
if (charArray[i] == charArray[length - 1]) {
flag = true;
} else {
flag = false;
break;
}
length--;
}
System.out.println(flag);
return flag;
}
}
|
package com.takshine.wxcrm.service;
/**
* 微信调用siebel接口服务
* @author liulin
*
*/
public interface Wx2SiebelService {
}
|
package com.tencent.mm.g.c;
import android.content.ContentValues;
import android.database.Cursor;
import com.tencent.mm.sdk.e.c;
public abstract class dn extends c {
private static final int cMm = "productId".hashCode();
private static final int cMn = "xmlContent".hashCode();
private static final int cMo = "ScanTime".hashCode();
private static final int cMp = "funcType".hashCode();
private static final int cMq = "qrcodeUrl".hashCode();
public static final String[] ciG = new String[0];
private static final int ciP = "rowid".hashCode();
private static final int ckw = "scene".hashCode();
private boolean cMh = true;
private boolean cMi = true;
private boolean cMj = true;
private boolean cMk = true;
private boolean cMl = true;
private boolean cku = true;
public long field_ScanTime;
public int field_funcType;
public String field_productId;
public String field_qrcodeUrl;
public int field_scene;
public String field_xmlContent;
public final void d(Cursor cursor) {
String[] columnNames = cursor.getColumnNames();
if (columnNames != null) {
int length = columnNames.length;
for (int i = 0; i < length; i++) {
int hashCode = columnNames[i].hashCode();
if (cMm == hashCode) {
this.field_productId = cursor.getString(i);
this.cMh = true;
} else if (cMn == hashCode) {
this.field_xmlContent = cursor.getString(i);
} else if (cMo == hashCode) {
this.field_ScanTime = cursor.getLong(i);
} else if (cMp == hashCode) {
this.field_funcType = cursor.getInt(i);
} else if (cMq == hashCode) {
this.field_qrcodeUrl = cursor.getString(i);
} else if (ckw == hashCode) {
this.field_scene = cursor.getInt(i);
} else if (ciP == hashCode) {
this.sKx = cursor.getLong(i);
}
}
}
}
public final ContentValues wH() {
ContentValues contentValues = new ContentValues();
if (this.cMh) {
contentValues.put("productId", this.field_productId);
}
if (this.cMi) {
contentValues.put("xmlContent", this.field_xmlContent);
}
if (this.cMj) {
contentValues.put("ScanTime", Long.valueOf(this.field_ScanTime));
}
if (this.cMk) {
contentValues.put("funcType", Integer.valueOf(this.field_funcType));
}
if (this.cMl) {
contentValues.put("qrcodeUrl", this.field_qrcodeUrl);
}
if (this.cku) {
contentValues.put("scene", Integer.valueOf(this.field_scene));
}
if (this.sKx > 0) {
contentValues.put("rowid", Long.valueOf(this.sKx));
}
return contentValues;
}
}
|
package secuenciasIterables;
//Solo es visible dentro del paquete
//class NodoDoble<Informacion extends iCloneableComparable> {
class NodoDoble<Informacion> {
private Informacion dato=null;
private NodoDoble<Informacion> siguiente=null;
private NodoDoble<Informacion> anterior=null;
NodoDoble (Informacion dato, NodoDoble<Informacion> anterior, NodoDoble<Informacion> siguiente)
{
this.dato=dato;
this.setSiguiente(siguiente);
this.setAnterior(anterior);
}
public Informacion getDato() {
return dato;
}
public NodoDoble<Informacion> getSiguiente() {
return siguiente;
}
public NodoDoble<Informacion> getAnterior() {
return anterior;
}
public void setSiguiente(NodoDoble<Informacion> siguiente) {
this.siguiente = siguiente;
}
public void setAnterior(NodoDoble<Informacion> anterior) {
this.anterior = anterior;
}
}
|
package aula3exercicio10;
public class Piloto {
String nome;
String scuderia;
int volta;
}
|
package models.forms;
public class AbstractFormModel {
}
|
package com.mrhan.database;
import com.mrhan.database.mrhanDaos.ColumType;
import java.lang.annotation.*;
/**
* 作用于实体的注解,表示,当前实体类所对应的数据库表
*/
@Target(ElementType.FIELD)
@Inherited
@Documented
@Retention(RetentionPolicy.RUNTIME)
public @interface Colum {
/**
* 对应隐射的字段名称
*
* @return
*/
String col() default "";
/**
* 字段数据类型!
*
* @return
*/
ColumType type() default ColumType.AUTO;
/**
* 是否是自动增长列
*/
boolean isAuto() default false;
/**是否为空*/
boolean isNull() default true;
/**
* 当前字段所属表
* @return
*/
String table() default "";
}
|
package syntax;
public class Evaluator {
public Term step(Term t) {
return t.evaluateSingleStep();
}
// evaluate reduces a term to normal form.
public Term evaluate(Term t) {
// FIXME this is gross.
try {
while (true) {
System.out.println(t);
t = t.evaluateSingleStep();
}
} catch (Exception e) {
// ignored
}
return t;
}
}
|
package com.design.pattern.listener.source;
import com.design.pattern.listener.MyEvent;
import com.design.pattern.listener.handler.EventListener;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
/**
* @author zhangbingquan
* @desc 事件源实现类
* @time 2019/8/23 0:45
*/
public class MySource implements EventSource {
private List<EventListener> listeners = new ArrayList<>();
private int value;
@Override
public void addListener(EventListener listener) {
listeners.add(listener);
}
@Override
public void notifyListener() {
for (EventListener listener : listeners) {
MyEvent event = new MyEvent();
event.setSource(this);
event.setWhen(new Date());
event.setMessage("setValue " + value);
listener.handlerEvent(event);
}
}
public void setValue(int value) {
this.value = value;
notifyListener();
}
}
|
package com.tencent.mm.plugin.appbrand.jsapi.version;
import com.tencent.mm.ipcinvoker.c;
import com.tencent.mm.ipcinvoker.extension.XIPCInvoker;
import com.tencent.mm.ipcinvoker.type.IPCString;
import com.tencent.mm.plugin.appbrand.config.r;
import com.tencent.mm.plugin.appbrand.l;
import org.json.JSONObject;
public final class JsApiUpdateApp extends com.tencent.mm.plugin.appbrand.jsapi.a {
private static final int CTRL_INDEX = 359;
private static final String NAME = "updateApp";
private static final class a implements com.tencent.mm.ipcinvoker.a<IPCString, SyncResult> {
private a() {
}
public final /* synthetic */ void a(Object obj, c cVar) {
r.a(((IPCString) obj).value, true, new 1(this, cVar));
}
}
public final void a(l lVar, JSONObject jSONObject, int i) {
XIPCInvoker.a("com.tencent.mm", new IPCString(lVar.fdO.fcu.bGy), a.class, new 1(this, lVar, i));
}
}
|
package StepDefinitions;
import static org.junit.Assert.*;
import Exceptions.ActivityAlreadyExistsException;
import Exceptions.ActivityNotFoundException;
import Exceptions.AdminNotFoundException;
import Exceptions.DeveloperNotFoundException;
import Exceptions.NotAuthorizedException;
import Exceptions.OperationNotAllowedException;
import Exceptions.OutOfBoundsException;
import Exceptions.ProjectAlreadyExistsException;
import Exceptions.ProjectNotFoundException;
import io.cucumber.java.en.*;
import SoftwareAS.Controller.ErrorMessageHolder;
import SoftwareAS.Controller.SoftwareAS;
import SoftwareAS.Model.*;
//This class is made by Peter - s204484
public class AssignDeveloperToActivitySteps {
private DataBase database;
private Admin admin;
private Project project;
private Developer developer;
private Developer developer2;
private String adminID = "adID";
private int activityID;
private ErrorMessageHolder errorMessageHolder;
public AssignDeveloperToActivitySteps(SoftwareAS softwareAS, ErrorMessageHolder errorMessageHolder) {
this.database = softwareAS.getDataBase();
this.errorMessageHolder = errorMessageHolder;
}
//Scenario: Successfully assign developer to activity
@Given("1- there is a project with project name {string}")
public void thereIsAProject(String projectName) throws AdminNotFoundException, NumberFormatException, ProjectAlreadyExistsException, ProjectNotFoundException, NotAuthorizedException, OutOfBoundsException {
database.createAdmin(adminID);
admin = database.getAdminById(adminID);
admin.createProject(projectName);
project = database.getProjectByName(projectName);
assertTrue(database.containsProject(projectName));
}
@Given("1- there is a user with ID {string} and database")
public void thereIsAUserWithIDAndDataBase(String developerID) throws DeveloperNotFoundException, OutOfBoundsException {
admin.createDeveloper(developerID);
developer = database.getDeveloperById(developerID);
assertTrue(database.containsDeveloper(developerID));
}
@Given("1- the user is a project leader")
public void theUserIsAProjectLeader() throws NotAuthorizedException, DeveloperNotFoundException {
project.assignDeveloperToProject(admin, developer);
project.setProjectLeader(admin, developer);
assertTrue(project.isProjectLeader(developer));
}
@Given("1- there is a second developer with ID {string} and database")
public void thereIsASecondDeveloperWithIDAndDatabase(String developer2ID) throws DeveloperNotFoundException, OutOfBoundsException {
admin.createDeveloper(developer2ID);
developer2 = database.getDeveloperById(developer2ID);
assertTrue(database.containsDeveloper(developer2ID));
}
@Given("1- the second developer is part of the project")
public void theSecondDeveloperIsPartOfTheProject() throws OperationNotAllowedException, ProjectNotFoundException, NotAuthorizedException {
project.assignDeveloperToProject(admin, developer2);
assertTrue(project.isDeveloperOnProject(developer2.getId()));
}
@Given("1- there is an activity with ID {int}")
public void thereIsAnActivity(int activityID) throws NotAuthorizedException, ActivityAlreadyExistsException, DeveloperNotFoundException, OutOfBoundsException {
this.activityID = activityID;
if (project.isProjectLeader(developer)) {
project.createActivity(activityID, developer);
} else {
String developer3ID = "Ian";
admin.createDeveloper(developer3ID);
Developer developer3 = database.getDeveloperById(developer3ID);
project.assignDeveloperToProject(admin, developer3);
project.setProjectLeader(admin, developer3);
project.createActivity(activityID, developer3);
}
assertTrue(project.containsActivityWithId(activityID));
}
@When("1- the second developer is assigned to the activity")
public void theSecondDeveloperIsAssignedToTheActivity() {
try {
project.getActivityById(activityID).assignDeveloperToActivity(developer, developer2);
} catch(DeveloperNotFoundException | OperationNotAllowedException | ActivityNotFoundException e) {
errorMessageHolder.setErrorMessage(e.getMessage());
}
}
@Then("1- the second developer is listed under the activity")
public void activityIsListedUnderTheProject() throws ActivityNotFoundException {
assertTrue(project.getActivityById(activityID).isDeveloperOnAcitivty(developer2.getId()));
}
//Scenario: Successfully assign developer to activity
// Given 1- there is a project with project name "1- Scenario 1"
// And 1- there is a user with ID "John" and database
// And 1- the user is a project leader
// And 1- there is a second developer with ID "Joe" and database
// And 1- the second developer is part of the project
// And 1- there is an activity with ID 924
// When 1- the second developer is assigned to the activity
// Then 1- the second developer is listed under the activity
//Scenario: Assign developer not on project to an activity
@Given("1- the second developer is not part of the project")
public void theSecondDeveloperIsNotPartOfTheProject() {
assertFalse(project.isDeveloperOnProject(developer2.getId()));
}
@Then("1- a DeveloperNotFoundException is thrown")
public void aDeveloperNotFoundExceptionIsThrown() {
assertEquals("Developer not on project.", errorMessageHolder.getErrorMessage());
}
@Then("1- the second developer is not listed under activity")
public void theSecondDeveloperIsNotListedUnderActivity() throws ActivityNotFoundException {
assertFalse(project.getActivityById(activityID).isDeveloperOnAcitivty(developer2.getId()));
}
//Scenario: Assign developer not on project to an activity
// Given 1- there is a project with project name "1- Scenario 2"
// And 1- there is a user with ID "John" and database
// And 1- the user is a project leader
// And 1- there is a second developer with ID "Joe" and database
// And 1- the second developer is not part of the project
// And 1- there is an activity with ID 924
// When 1- the second developer is assigned to the activity
// Then 1- a DeveloperNotFoundException is thrown
// And 1- the second developer is not listed under activity
//Scenario: Assign developer to an activity that does not exist
@Given("1- there is not an activity with ID {int}")
public void thereIsNotAnActivityWithID(int activity2ID) {
try {
project.getActivityById(activity2ID);
} catch (ActivityNotFoundException e) {
errorMessageHolder.setErrorMessage(e.getMessage());
}
assertEquals("No activity with described ID", errorMessageHolder.getErrorMessage());
}
@Then("1- an ActivityNotFoundException is thrown")
public void anActivityNotFoundExceptionIsThrown() {
assertEquals("No activity with described ID", errorMessageHolder.getErrorMessage());
}
//Scenario: Assign developer to an activity that does not exist
// Given 1- there is a project with project name "1- Scenario 3"
// And 1- there is a user with ID "John" and database
// And 1- the user is a project leader
// And 1- there is a second developer with ID "Joe" and database
// And 1- there is not an activity with ID 924
// When 1- the second developer is assigned to the activity
// Then 1- an ActivityNotFoundException is thrown
//Scenario: Developer assigns developer to an activity
@Given("1- the user is not a project leader")
public void theUserIsNotAProjectLeader() {
assertFalse(project.isProjectLeader(developer));
}
@Then("1- an OperationNotAllowedException is thrown")
public void anOperationNotAllowedExceptionIsThrown() {
assertEquals("Only a project leader or admin can assign developer to activity", errorMessageHolder.getErrorMessage());
}
@Then("1- the second developer is not listed under the activity")
public void theSecondDeveloperIsNotListedUnderTheActivity() throws ActivityNotFoundException {
assertFalse(project.getActivityById(activityID).isDeveloperOnAcitivty(developer2.getId()));
}
//Scenario: Developer assigns developer to an activity
// Given 1- there is a project with project name "1- Scenario 4"
// And 1- there is a user with ID "John" and database
// And 1- the user is not a project leader
// And 1- there is a second developer with ID "Joe" and database
// And 1- the second developer is part of the project
// And 1- there is an activity with ID 924
// When 1- the second developer is assigned to the activity
// Then 1- an OperationNotAllowedException is thrown
// And 1- the second developer is not listed under the activity
}
|
package couchbase.sample.dao;
import couchbase.sample.exception.ArgException;
public class CustomerDAO extends BaseDAO{
public CustomerDAO() throws ArgException {
super();
}
/**
*
* @param host - Couchbase server FQDN
* @param user - RBAC user that has access to access data from the bucket
* @param passwd - User credential password
* @param bucket - Couchabse bucket name where data need to be accessed from
* @throws ArgException
*/
public CustomerDAO(String host, String user, String passwd, String bucket) throws ArgException {
super(host, user, passwd, bucket);
}
/**
* When SSL is enabled then use this constructor to set all the required fields
* @param host - Couchbase server FQDN
* @param user - RBAC user that has access to access data from the bucket
* @param passwd - User credential password
* @param bucket - Couchabse bucket name where data need to be accessed from
* @param sslEnabled - true if SSL is enabled
* @param ksFilePath - Keystore File path
* @param ksPwd - Keystore password
* @throws ArgException
*/
public CustomerDAO(String host, String user, String passwd, String bucket,
boolean sslEnabled, String ksFilePath, String ksPwd) throws ArgException
{
super(host, user, passwd, bucket, sslEnabled, ksFilePath, ksPwd);
}
}
|
package miniProject;
import java.util.Calendar;
import java.util.Date;
public class ParkDomain {
private String carNum;//차량번호
private Date inTime;//들어온시간
private Date outTime;//나간시간
public ParkDomain() {
this.carNum = "";
this.inTime = Calendar.getInstance().getTime();
// this.outTime = Calendar.getInstance().getTime();
this.outTime = inTime;
}
public String getCarNum() {
return carNum;//this. 안써도됨.
}
public void setCarNum(String carNum) {
this.carNum = carNum;// 이름이 같은것이 있으면 지역변수가 우선시되기떄문에 this를 써야함
}
public Date getInTime() {
return inTime;
}
public void setInTime(Date inTime) {
this.inTime = inTime;
}
public Date getOutTime() {
return outTime;
}
public void setOutTime(Date outTime) {
this.outTime = outTime;
}
}
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.net.pop3;
import java.io.IOException;
import java.net.InetAddress;
import junit.framework.TestCase;
/**
*
* The POP3* tests all presume the existence of the following parameters: mailserver: localhost (running on the default port 110) account: username=test;
* password=password account: username=alwaysempty; password=password. mail: At least four emails in the test account and zero emails in the alwaysempty account
*
* If this won't work for you, you can change these parameters in the TestSetupParameters class.
*
* The tests were originally run on a default installation of James. Your mileage may vary based on the POP3 server you run the tests against. Some servers are
* more standards-compliant than others.
*/
public class POP3ClientTest extends TestCase {
POP3Client p;
String user = POP3Constants.user;
String emptyUser = POP3Constants.emptyuser;
String password = POP3Constants.password;
String mailhost = POP3Constants.mailhost;
public POP3ClientTest(final String name) {
super(name);
}
private void connect() throws Exception {
p.connect(InetAddress.getByName(mailhost));
assertTrue(p.isConnected());
assertEquals(POP3.AUTHORIZATION_STATE, p.getState());
}
private void login() throws Exception {
assertTrue(p.login(user, password));
assertEquals(POP3.TRANSACTION_STATE, p.getState());
}
private void reset() throws IOException {
// Case where this is the first time reset is called
if (p == null) {
// Do nothing
} else if (p.isConnected()) {
p.disconnect();
}
p = null;
p = new POP3Client();
}
public void testInvalidLoginWithBadName() throws Exception {
reset();
connect();
// Try with an invalid user that doesn't exist
assertFalse(p.login("badusername", password));
}
public void testInvalidLoginWithBadPassword() throws Exception {
reset();
connect();
// Try with a bad password
assertFalse(p.login(user, "badpassword"));
}
/*
* Test to try to run the login method from the disconnected, transaction and update states
*/
public void testLoginFromWrongState() throws Exception {
reset();
// Not currently connected, not in authorization state
// Try to login with good name/password
assertFalse(p.login(user, password));
// Now connect and set the state to 'transaction' and try again
connect();
p.setState(POP3.TRANSACTION_STATE);
assertFalse(p.login(user, password));
p.disconnect();
// Now connect and set the state to 'update' and try again
connect();
p.setState(POP3.UPDATE_STATE);
assertFalse(p.login(user, password));
p.disconnect();
}
public void testLogoutFromAllStates() throws Exception {
// From 'transaction' state
reset();
connect();
login();
assertTrue(p.logout());
assertEquals(POP3.UPDATE_STATE, p.getState());
// From 'update' state
reset();
connect();
login();
p.setState(POP3.UPDATE_STATE);
assertTrue(p.logout());
}
/*
* Simple test to logon to a valid server using a valid user name and password.
*/
public void testValidLoginWithNameAndPassword() throws Exception {
reset();
connect();
// Try with a valid user
login();
}
}
|
package com.xampy.namboo.api.firestoreNamboo;
import com.xampy.namboo.api.dataModel.UserNambooFirestore;
import com.google.android.gms.tasks.Task;
import com.google.firebase.firestore.CollectionReference;
import com.google.firebase.firestore.DocumentSnapshot;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.firestore.GeoPoint;
import com.google.firebase.firestore.Query;
public class FirestoreNambooUserHelper {
private static final String COLLECTION_NAME = "users";
public static CollectionReference getUsersCollection() {
return FirebaseFirestore.getInstance().collection(COLLECTION_NAME);
}
public static Task<Void> createUser(
String uid,
//String userName, Not necessary for the first time creation
String phoneNUmber
//String urlPicture, Not necessary for the first time creation
//String amount Not necessary for the first time creation
){
UserNambooFirestore userNambooFirestore = new UserNambooFirestore(
uid,
"@none",
"@none", //Passwor is default at cration
phoneNUmber,
"@none",
"0",
"",
"",
"");
//By default all users are particular
return FirestoreNambooUserHelper.getUsersCollection().document(uid).set(userNambooFirestore);
}
/**
* get activated user by service name
* @param service
* @return
*/
public static Query getUsersByServices(String service){
return getUsersCollection()
.limit(50)
.whereEqualTo("activated", true)
.whereEqualTo("serviceType", service);
}
/**
* Get users who ectivated thier service with parameters
* @param service
* @param city
* @param district
* @return
*/
public static Query getSearchUsersByServicesParams(String service, String city, String district){
return getUsersCollection()
.limit(50)
.whereEqualTo("activated", true)
.whereEqualTo("serviceType", service)
.whereEqualTo("city", city)
.whereEqualTo("district", district);
}
public static Task<DocumentSnapshot> getUser(String uid){
return FirestoreNambooUserHelper.getUsersCollection().document(uid).get();
}
public static Task<Void> updateUsername(String username, String uid){
return FirestoreNambooUserHelper.getUsersCollection()
.document(uid).update("username", username);
}
public static Task<Void> updateUserPassword(String pass, String uid){
return FirestoreNambooUserHelper.getUsersCollection()
.document(uid).update("password", pass);
}
public static Task<Void> updateUserServiceType(String username, String uid){
return FirestoreNambooUserHelper.getUsersCollection()
.document(uid).update("serviceType", username);
}
public static Task<Void> updateUserImageURl(String url, String uid){
return FirestoreNambooUserHelper.getUsersCollection()
.document(uid).update("urlPicture", url);
}
public static Task<Void> updateUserCity(String city, String uid){
return FirestoreNambooUserHelper.getUsersCollection()
.document(uid).update("city", city);
}
public static Task<Void> updateUserDistrict(String district, String uid){
return FirestoreNambooUserHelper.getUsersCollection()
.document(uid).update("district", district);
}
public static Task<Void> updateUserPosition(String pos, String uid){
return FirestoreNambooUserHelper.getUsersCollection()
.document(uid).update("position", pos);
}
public static Task<Void> updateUserActivationState(boolean state, String uid){
return FirestoreNambooUserHelper.getUsersCollection()
.document(uid).update("activated", state);
}
public static Task<Void> updateUserAmount(int new_amount, String uid){
return FirestoreNambooUserHelper.getUsersCollection()
.document(uid).update("accountAmount", new_amount);
}
public static Task<Void> deleteUser(String uid) {
return FirestoreNambooUserHelper.getUsersCollection().document(uid).delete();
}
//Implementing others here;
}
|
package fi.jjc.graphics.buffers;
import org.lwjgl.opengl.GL11;
/**
* Enumeration of buffer types.
*
* @see fi.jjc.graphics.buffers.BufferHandler
* @author Jens ┼kerblom
*/
public enum Buffer
{
/** Current color buffer. */
BUFFER_COLOR(null, GL11.GL_COLOR_BUFFER_BIT),
/** Depth buffer. */
BUFFER_DEPTH(new Integer(GL11.GL_DEPTH_TEST), GL11.GL_DEPTH_BUFFER_BIT),
/** Stencil buffer. */
BUFFER_STENCIL(new Integer(GL11.GL_STENCIL_TEST), GL11.GL_STENCIL_BUFFER_BIT),
/** Accumulation buffer. */
BUFFER_ACCUM(null, GL11.GL_ACCUM_BUFFER_BIT);
/**
* Constant for enabling / disable buffer, or null if buffer cannot be disabled.
*/
private final Integer glEnableConstant;
/**
* Constant for clearing buffer.
*/
private final int glClearConstant;
/**
* @param glEnableConstant
* OpenGL's constant for enabling / disabling buffer.
* @param glClearConstant
* OpenGL's constant for clearing buffer.
*/
private Buffer(Integer glEnableConstant, int glClearConstant)
{
this.glEnableConstant = glEnableConstant;
this.glClearConstant = glClearConstant;
}
/**
* @return the glEnableConstant
*/
public Integer getGLEnableConstant()
{
return this.glEnableConstant;
}
/**
* @return the glClearConstant
*/
public int getGlClearConstant()
{
return this.glClearConstant;
}
}
|
package com.gtfs.bean;
import java.io.Serializable;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.persistence.UniqueConstraint;
import org.hibernate.annotations.Cascade;
import org.hibernate.annotations.CascadeType;
@Entity
@Table(name = "LIC_PRINT_RCPT_DTLS")
public class LicPrintRcptDtls implements Serializable{
private Long id;
private String prefix;
private Long receiptNo;
private String remarks;
private PrintRcptMst printRcptMst;
private Long tableId;
private String tableName;
private String processName;
private Long createdBy;
private Long modifiedBy;
private Long deletedBy;
private Date createdDate;
private Date modifiedDate;
private Date deletedDate;
private String deleteFlag;
@Id
@Column(name = "ID", nullable = false, precision = 22, scale = 0)
@SequenceGenerator(name="LIC_PRINT_RCPT_DTLS_SEQ",sequenceName="LIC_PRINT_RCPT_DTLS_SEQ")
@GeneratedValue(generator="LIC_PRINT_RCPT_DTLS_SEQ",strategy=GenerationType.AUTO)
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
@Column(name = "PREFIX", length=20)
public String getPrefix() {
return prefix;
}
public void setPrefix(String prefix) {
this.prefix = prefix;
}
@Column(name = "RECEIPT_NO", precision = 22, scale = 0)
public Long getReceiptNo() {
return receiptNo;
}
public void setReceiptNo(Long receiptNo) {
this.receiptNo = receiptNo;
}
@Column(name="REMARKS",length=500)
public String getRemarks() {
return remarks;
}
public void setRemarks(String remarks) {
this.remarks = remarks;
}
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "PRINT_RCPT_MST_ID")
public PrintRcptMst getPrintRcptMst() {
return printRcptMst;
}
public void setPrintRcptMst(PrintRcptMst printRcptMst) {
this.printRcptMst = printRcptMst;
}
@Column(name = "CREATED_BY", precision = 22, scale = 0)
public Long getCreatedBy() {
return this.createdBy;
}
public void setCreatedBy(Long createdBy) {
this.createdBy = createdBy;
}
@Column(name = "MODIFIED_BY", precision = 22, scale = 0)
public Long getModifiedBy() {
return this.modifiedBy;
}
public void setModifiedBy(Long modifiedBy) {
this.modifiedBy = modifiedBy;
}
@Column(name = "DELETED_BY", precision = 22, scale = 0)
public Long getDeletedBy() {
return this.deletedBy;
}
public void setDeletedBy(Long deletedBy) {
this.deletedBy = deletedBy;
}
@Temporal(TemporalType.DATE)
@Column(name = "CREATED_DATE", length = 7)
public Date getCreatedDate() {
return this.createdDate;
}
public void setCreatedDate(Date createdDate) {
this.createdDate = createdDate;
}
@Temporal(TemporalType.DATE)
@Column(name = "MODIFIED_DATE", length = 7)
public Date getModifiedDate() {
return this.modifiedDate;
}
public void setModifiedDate(Date modifiedDate) {
this.modifiedDate = modifiedDate;
}
@Temporal(TemporalType.DATE)
@Column(name = "DELETED_DATE", length = 7)
public Date getDeletedDate() {
return this.deletedDate;
}
public void setDeletedDate(Date deletedDate) {
this.deletedDate = deletedDate;
}
@Column(name = "DELETE_FLAG", length = 1)
public String getDeleteFlag() {
return this.deleteFlag;
}
public void setDeleteFlag(String deleteFlag) {
this.deleteFlag = deleteFlag;
}
@Column(name = "TABLE_ID", precision = 22, scale = 0)
public Long getTableId() {
return tableId;
}
public void setTableId(Long tableId) {
this.tableId = tableId;
}
@Column(name="TABLE_NAME",length=50)
public String getTableName() {
return tableName;
}
public void setTableName(String tableName) {
this.tableName = tableName;
}
@Column(name="PROCESS_NAME",length=10)
public String getProcessName() {
return processName;
}
public void setProcessName(String processName) {
this.processName = processName;
}
}
|
package org.apache.hadoo.yarn.server.resourcemanager.dockermonitor;
import java.util.List;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.yarn.api.records.ApplicationId;
import org.apache.hadoop.yarn.api.records.ContainerId;
import org.apache.hadoop.yarn.api.records.Resource;
public interface DockerMonitor{
public boolean Init(Configuration config);
public boolean DehydrateContainer(ContainerId containerId);
public boolean ResumeContainer(ContainerId containerId);
public boolean UpdateContainerResource(ContainerId containerId, Resource resource);
public List<DockerInfo> pollAppContainerStatus(ApplicationId applicationId);
public List<DockerInfo> pollContainersStatus(List<ContainerId> containerIds);
}
|
package category.linkedList;
public class ReverseBetween {
public ListNode reverseBetween2(ListNode head, int m, int n) {
ListNode dummy = new ListNode(0);
dummy.next = head;
ListNode p = dummy;
for (int i = 1; i < m; i++)
p = p.next;
p.next = reverse(p.next, n - m + 1);
return dummy.next;
}
private ListNode reverse(ListNode head, int n) {
ListNode node = head, prev = null;
for (int i = 0; i < n; i++) {
ListNode next = node.next;
node.next = prev;
prev = node;
node = next;
}
head.next = node;
return prev;
}
public static void main(String[] args) {
ListNode head = new ListNode(1);
head.next = new ListNode(2);
head.next.next = new ListNode(3);
head.next.next.next = new ListNode(4);
head.next.next.next.next = new ListNode(5);
ListNode node = new ReverseBetween().reverseBetween2(head, 2, 4);
while (node.next != null) {
System.out.println(node.val);
node = node.next;
}
System.out.println(node.val);
}
}
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.example.codetribe1.constructionappsuite.dto;
import java.io.Serializable;
/**
* @author aubreyM
*/
public class InvoiceItemDTO implements Serializable {
private static final long serialVersionUID = 1L;
private Integer invoiceItemID;
private Integer quantity;
private Double unitPrice, nettPrice, tax;
private Integer invoiceID;
private ProjectSiteTaskDTO task;
private ProjectSiteDTO projectSite;
public Double getUnitPrice() {
return unitPrice;
}
public void setUnitPrice(Double unitPrice) {
this.unitPrice = unitPrice;
}
public Double getNettPrice() {
return nettPrice;
}
public void setNettPrice(Double nettPrice) {
this.nettPrice = nettPrice;
}
public Double getTax() {
return tax;
}
public void setTax(Double tax) {
this.tax = tax;
}
public ProjectSiteTaskDTO getTask() {
return task;
}
public void setTask(ProjectSiteTaskDTO task) {
this.task = task;
}
public Integer getInvoiceItemID() {
return invoiceItemID;
}
public void setInvoiceItemID(Integer invoiceItemID) {
this.invoiceItemID = invoiceItemID;
}
public Integer getInvoiceID() {
return invoiceID;
}
public void setInvoiceID(Integer invoiceID) {
this.invoiceID = invoiceID;
}
public ProjectSiteDTO getProjectSite() {
return projectSite;
}
public void setProjectSite(ProjectSiteDTO projectSite) {
this.projectSite = projectSite;
}
public Integer getQuantity() {
return quantity;
}
public void setQuantity(Integer quantity) {
this.quantity = quantity;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.