text
stringlengths
10
2.72M
package Parte04.P4PG47; public class NavioDeGuerra extends Navio{ protected double blindagem; protected double ataque; public NavioDeGuerra(int numTripulantes, String nome, double blindagem, double ataque) { super(numTripulantes, nome); this.blindagem = blindagem; this.ataque = ataque; } public double getBlindagem() { return blindagem; } public double getAtaque() { return ataque; } public void setBlindagem(double blindagem) { this.blindagem = blindagem; } public void setAtaque(double ataque) { this.ataque = ataque; } public void exibirArmas() { super.exibirInfoGeral(); System.out.println("Blindagem..........:"+blindagem); poderDeFogo(); } public void poderDeFogo() { System.out.println("Poder de Fogo......:"+ataque); } }
package edu.gatech.snickers.techflixandchill; import org.junit.Test; import static org.junit.Assert.*; /** * Created by nirajsuresh on 4/5/16. */ public class testCalculateNewRating { @Test public void testNullComment() throws Exception { try { MovieRatingActivity.calculateNewRating(0, 0, "test"); } catch (IllegalArgumentException e){ assertEquals(e.getMessage(), "Input rating cannot be null"); } assertEquals(true, false); } @Test public void testSameRating() throws Exception { assertEquals(MovieRatingActivity.calculateNewRating(5, 5, "test"), 5, 0.1); } @Test public void testWordLengthNormal() throws Exception { assertEquals(MovieRatingActivity .calculateNewRating(3, 5, "This movie could have been better"), 4.6, 0.1); } @Test public void testWordLengthZero() throws Exception { assertEquals(MovieRatingActivity .calculateNewRating(3, 5, ""), 4.95, 0.1); } @Test public void testWordLengthNine() throws Exception { assertEquals(MovieRatingActivity .calculateNewRating(3, 5, ""), 4.6, 0.1); } @Test public void testZeroRating() throws Exception { assertEquals(MovieRatingActivity .calculateNewRating(0, 4, ""), 4, 0.1); } }
package com.gaoshin.onsaleflyer.service.impl; import org.springframework.beans.factory.annotation.Autowired; import common.db.dao.ConfigDao; import common.db.dao.impl.CommonDaoImpl; import common.util.web.BusinessException; import common.util.web.ServiceError; public class ServiceBaseImpl { @Autowired protected CommonDaoImpl dao; @Autowired protected ConfigDao configDao; protected void assertNotNull(Object obj) { if(obj == null) throw new BusinessException(ServiceError.InvalidInput); } }
package me.rext.example.spring_vue_oauth2.web.security; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Primary; import org.springframework.core.env.Environment; import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer; import org.springframework.security.oauth2.provider.token.AuthorizationServerTokenServices; import org.springframework.security.oauth2.provider.token.DefaultTokenServices; import org.springframework.security.oauth2.provider.token.TokenStore; import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter; import org.springframework.security.oauth2.provider.token.store.JwtTokenStore; @Configuration @EnableAuthorizationServer class AuthorizationServerConfiguration { @Primary @Bean public AuthorizationServerTokenServices tokenServices(TokenStore tokenStore, JwtAccessTokenConverter tokenConverter) { DefaultTokenServices tokenServices = new DefaultTokenServices(); tokenServices.setTokenStore(tokenStore); tokenServices.setTokenEnhancer(tokenConverter); return tokenServices; } @Bean TokenStore tokenStore(JwtAccessTokenConverter tokenConverter) { return new JwtTokenStore(tokenConverter); } @Bean public JwtAccessTokenConverter tokenConverter(Environment env) { JwtAccessTokenConverter tokenConverter = new JwtAccessTokenConverter(); tokenConverter.setSigningKey(env.getRequiredProperty("security.oauth2.signingKey")); return tokenConverter; } }
package edu.upc.eetac.dsa.models; import java.util.Queue; public class Laboratorio { private String idLab; private String nombre; private Queue<Muestra> muestrasPendientes; public Laboratorio(String id, String nom){ this.idLab = id; this.nombre = nom; } public String getIdLab() { return idLab; } public void setIdLab(String idLab) { this.idLab = idLab; } public String getNombre() { return nombre; } public void setNombre(String nombre) { this.nombre = nombre; } public void añadirMuestra(Muestra m){ this.muestrasPendientes.add(m); } public Muestra generaInforme(){ Muestra m = this.muestrasPendientes.poll(); m.setResultado(); m.setComentario(); return m; } }
package EXAMS.E05.spaceStation.models.mission; import EXAMS.E05.spaceStation.models.astronauts.Astronaut; import EXAMS.E05.spaceStation.models.planets.Planet; import java.util.List; public class MissionImpl implements Mission { @Override public void explore(Planet planet, List<Astronaut> astronauts) { // for (int i = 0; i < astronauts.size(); i++) { // Astronaut astronaut = astronauts.get(0); // if (astronaut.canBreath()) { // while (!planet.getItems().isEmpty()) { // String currentItem = planet.getItems().get(0); // // if (astronaut.canBreath()) { // astronaut.getBag().getItems().add(currentItem); // planet.getItems().remove(currentItem); // astronaut.breath(); // // } else { // // astronauts.remove(astronaut); // break; // } // } // } // } for (int i = 0; i < astronauts.size(); i++) { Astronaut astronaut = astronauts.get(i); for (int j = 0; j < planet.getItems().size(); j++) { String currentItem = planet.getItems().get(j); astronaut.getBag().getItems().add(currentItem); planet.getItems().remove(currentItem); j--; astronaut.breath(); if (!astronaut.canBreath()) { astronauts.remove(astronaut); i--; break; } } } } }
public class animal { public static void eat() { System.out.println("I am eating"); } }
/* * Copyright (c) 2013 ICM Uniwersytet Warszawski All rights reserved. * See LICENCE.txt file for licensing information. */ package pl.edu.icm.unity.webadmin.reg.reqman; import java.text.SimpleDateFormat; import java.util.Collection; import java.util.List; import pl.edu.icm.unity.Constants; import pl.edu.icm.unity.exceptions.EngineException; import pl.edu.icm.unity.server.api.EnquiryManagement; import pl.edu.icm.unity.server.api.RegistrationsManagement; import pl.edu.icm.unity.server.utils.UnityMessageSource; import pl.edu.icm.unity.types.basic.IdentityParam; import pl.edu.icm.unity.types.registration.EnquiryResponse; import pl.edu.icm.unity.types.registration.EnquiryResponseState; import pl.edu.icm.unity.types.registration.RegistrationRequest; import pl.edu.icm.unity.types.registration.RegistrationRequestAction; import pl.edu.icm.unity.types.registration.RegistrationRequestState; import pl.edu.icm.unity.types.registration.RegistrationRequestStatus; import pl.edu.icm.unity.types.registration.UserRequestState; import pl.edu.icm.unity.webui.WebSession; import pl.edu.icm.unity.webui.bus.EventsBus; import pl.edu.icm.unity.webui.common.ComponentWithToolbar; import pl.edu.icm.unity.webui.common.ConfirmDialog; import pl.edu.icm.unity.webui.common.ErrorComponent; import pl.edu.icm.unity.webui.common.Images; import pl.edu.icm.unity.webui.common.NotificationPopup; import pl.edu.icm.unity.webui.common.SingleActionHandler; import pl.edu.icm.unity.webui.common.SmallTable; import pl.edu.icm.unity.webui.common.Toolbar; import pl.edu.icm.unity.webui.forms.enquiry.EnquiryResponseChangedEvent; import pl.edu.icm.unity.webui.forms.reg.RegistrationRequestChangedEvent; import com.google.common.collect.Lists; import com.vaadin.data.Property.ValueChangeEvent; import com.vaadin.data.Property.ValueChangeListener; import com.vaadin.data.util.BeanItemContainer; import com.vaadin.event.Action; import com.vaadin.shared.ui.Orientation; import com.vaadin.ui.CustomComponent; import com.vaadin.ui.Table; /** * Component showing a table with the registration requests. It is possible to register selection change * listener and there is one action implemented to refresh the list. * @author K. Benedyczak */ public class RequestsTable extends CustomComponent { private RegistrationsManagement registrationsManagement; private EnquiryManagement enquiryManagement; private UnityMessageSource msg; private EventsBus bus; private Table requestsTable; public RequestsTable(RegistrationsManagement regMan, EnquiryManagement enquiryManagement, UnityMessageSource msg) { this.registrationsManagement = regMan; this.enquiryManagement = enquiryManagement; this.msg = msg; this.bus = WebSession.getCurrent().getEventBus(); initUI(); } private void initUI() { requestsTable = new SmallTable(); requestsTable.setNullSelectionAllowed(false); requestsTable.setImmediate(true); requestsTable.setSizeFull(); BeanItemContainer<TableRequestBean> tableContainer = new BeanItemContainer<>(TableRequestBean.class); tableContainer.removeContainerProperty("element"); requestsTable.setSelectable(true); requestsTable.setMultiSelect(true); requestsTable.setContainerDataSource(tableContainer); requestsTable.setVisibleColumns(new Object[] {"type", "form", "requestId", "submitTime", "status", "requestedIdentity"}); requestsTable.setColumnHeaders(new String[] { msg.getMessage("RegistrationRequest.type"), msg.getMessage("RegistrationRequest.form"), msg.getMessage("RegistrationRequest.requestId"), msg.getMessage("RegistrationRequest.submitTime"), msg.getMessage("RegistrationRequest.status"), msg.getMessage("RegistrationRequest.requestedIdentity")}); requestsTable.setSortContainerPropertyId(requestsTable.getContainerPropertyIds().iterator().next()); requestsTable.setSortAscending(true); RefreshActionHandler refreshA = new RefreshActionHandler(); BulkProcessActionHandler acceptA = new BulkProcessActionHandler( RegistrationRequestAction.accept, Images.ok); BulkProcessActionHandler deleteA = new BulkProcessActionHandler( RegistrationRequestAction.drop, Images.trashBin); BulkProcessActionHandler rejectA = new BulkProcessActionHandler( RegistrationRequestAction.reject, Images.delete); Toolbar toolbar = new Toolbar(requestsTable, Orientation.HORIZONTAL); addAction(refreshA, toolbar); addAction(acceptA, toolbar); addAction(rejectA, toolbar); addAction(deleteA, toolbar); ComponentWithToolbar tableWithToolbar = new ComponentWithToolbar(requestsTable, toolbar); tableWithToolbar.setSizeFull(); setCompositionRoot(tableWithToolbar); refresh(); } private void addAction(SingleActionHandler action, Toolbar toolbar) { requestsTable.addActionHandler(action); toolbar.addActionHandler(action); } public void addValueChangeListener(final RequestSelectionListener listener) { requestsTable.addValueChangeListener(new ValueChangeListener() { @Override public void valueChange(ValueChangeEvent event) { TableRequestBean selected = getOnlyOneSelected(); if (selected == null) listener.deselected(); else if (selected.request instanceof RegistrationRequestState) listener.registrationChanged((RegistrationRequestState) selected.request); else listener.enquiryChanged((EnquiryResponseState) selected.request); } }); } private TableRequestBean getOnlyOneSelected() { Collection<?> beans = (Collection<?>) requestsTable.getValue(); return beans == null || beans.isEmpty() || beans.size() > 1 ? null : ((TableRequestBean)beans.iterator().next()); } public void refresh() { try { TableRequestBean selected = getOnlyOneSelected(); requestsTable.removeAllItems(); fill(selected, registrationsManagement.getRegistrationRequests()); fill(selected, enquiryManagement.getEnquiryResponses()); } catch (Exception e) { ErrorComponent error = new ErrorComponent(); error.setError(msg.getMessage("RequestsTable.errorGetRequests"), e); setCompositionRoot(error); } } private void fill(TableRequestBean selected, List<? extends UserRequestState<?>> requests) { for (UserRequestState<?> req: requests) { TableRequestBean item = new TableRequestBean(req, msg); requestsTable.addItem(item); if (selected != null && selected.request.getRequestId().equals(req.getRequestId())) requestsTable.setValue(Lists.newArrayList(item)); } } public void process(Collection<?> items, RegistrationRequestAction action) { for (Object item: items) { try { processSingle((TableRequestBean) item, action); } catch (EngineException e) { String info = msg.getMessage("RequestsTable.processError." + action.toString(), ((TableRequestBean)item).request.getRequestId()); NotificationPopup.showError(msg, info, e); break; } } } private void processSingle(TableRequestBean item, RegistrationRequestAction action) throws EngineException { UserRequestState<?> request = item.request; if (request instanceof RegistrationRequestState) { registrationsManagement.processRegistrationRequest(request.getRequestId(), (RegistrationRequest) request.getRequest(), action, null, null); bus.fireEvent(new RegistrationRequestChangedEvent(request.getRequestId())); } else { enquiryManagement.processEnquiryResponse(request.getRequestId(), (EnquiryResponse) request.getRequest(), action, null, null); bus.fireEvent(new EnquiryResponseChangedEvent(request.getRequestId())); } } private class RefreshActionHandler extends SingleActionHandler { public RefreshActionHandler() { super(msg.getMessage("RequestsTable.refreshAction"), Images.refresh.getResource()); setNeedsTarget(false); } @Override public void handleAction(Object sender, final Object target) { refresh(); } } private class BulkProcessActionHandler extends SingleActionHandler { private final RegistrationRequestAction action; public BulkProcessActionHandler(RegistrationRequestAction action, Images image) { super(msg.getMessage("RequestProcessingPanel." + action.toString()), image.getResource()); this.action = action; setMultiTarget(true); } @Override public Action[] getActions(Object target, Object sender) { if (action != RegistrationRequestAction.drop && target instanceof Collection<?>) { Collection<?> t = (Collection<?>) target; boolean hasPending = t.stream().allMatch(o -> { TableRequestBean bean = (TableRequestBean) o; return bean.request.getStatus() == RegistrationRequestStatus.pending; }); return hasPending ? super.getActions(target, sender) : EMPTY; } return super.getActions(target, sender); } @Override public void handleAction(Object sender, Object target) { final Collection<?> items = (Collection<?>) requestsTable.getValue(); new ConfirmDialog(msg, msg.getMessage( "RequestsTable.confirmAction."+action, items.size()), new ConfirmDialog.Callback() { @Override public void onConfirm() { process(items, action); } }).show(); } } public static class TableRequestBean { private UserRequestState<?> request; private UnityMessageSource msg; public TableRequestBean(UserRequestState<?> request, UnityMessageSource msg) { this.request = request; this.msg = msg; } public String getType() { boolean enquiry = request instanceof EnquiryResponseState; return msg.getMessage("RequestsTable.type." + (enquiry ? "enquiry" : "registration")); } public String getForm() { return request.getRequest().getFormId(); } public String getRequestId() { return request.getRequestId(); } public String getSubmitTime() { return new SimpleDateFormat(Constants.SIMPLE_DATE_FORMAT).format(request.getTimestamp()); } public String getStatus() { return msg.getMessage("RegistrationRequestStatus." + request.getStatus()); } public String getRequestedIdentity() { List<IdentityParam> identities = request.getRequest().getIdentities(); if (identities.isEmpty()) return "-"; IdentityParam id = identities.get(0); return id == null ? "-" : id.toString(); } } public interface RequestSelectionListener { void registrationChanged(RegistrationRequestState request); void enquiryChanged(EnquiryResponseState request); void deselected(); } }
package com.geniusgithub.lookaround.fragment; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import roboguice.inject.InjectView; import com.geniusgithub.lookaround.LAroundApplication; import com.geniusgithub.lookaround.R; import com.geniusgithub.lookaround.adapter.InfoContentAdapter; import com.geniusgithub.lookaround.content.ContentActivity; import com.geniusgithub.lookaround.content.ContentCache; import com.geniusgithub.lookaround.model.BaseType; import com.geniusgithub.lookaround.model.BaseType.InfoItem; import com.geniusgithub.lookaround.proxy.InfoRequestProxy; import com.geniusgithub.lookaround.util.CommonLog; import com.geniusgithub.lookaround.util.CommonUtil; import com.geniusgithub.lookaround.util.LogFactory; import com.geniusgithub.lookaround.widget.RefreshListView; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.Button; import android.widget.AdapterView.OnItemClickListener; public class CommonFragmentEx extends CommonFragment implements InfoRequestProxy.IRequestResult, RefreshListView.IOnRefreshListener, RefreshListView.IOnLoadMoreListener, OnItemClickListener{ private static final CommonLog log = LogFactory.createLog(); @InjectView (R.id.invalid_view) View mInvalidView; @InjectView (R.id.load_view) View mLoadView; @InjectView (R.id.content_view) View mContentView; @InjectView (R.id.listview) RefreshListView mListView; private BaseType.ListItem mTypeData; private InfoContentAdapter mAdapter; private Context mContext; private List<BaseType.InfoItem> mContentData = new ArrayList<BaseType.InfoItem>(); private InfoRequestProxy mInfoRequestProxy; private Handler mHandler; private boolean loginStatus = false; public CommonFragmentEx(BaseType.ListItem data){ mTypeData = data; } public CommonFragmentEx(){ } @Override public void onCreate(Bundle savedInstanceState) { log.e("CommonFragmentEx onCreate"); super.onCreate(savedInstanceState); loginStatus = LAroundApplication.getInstance().getLoginStatus(); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { log.e("CommonFragmentEx onCreateView"); View view = inflater.inflate(R.layout.common_layout, null); return view; } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); log.e("CommonFragmentEx onActivityCreated"); if (loginStatus){ setupViews(); initData(); mInfoRequestProxy.requestRefreshInfo(); } } private void setupViews(){ switchToLoadView(); } private void initData(){ mContext = getActivity(); mAdapter = new InfoContentAdapter(mContext, mContentData); mListView.setAdapter(mAdapter); mListView.setOnRefreshListener(this); mListView.setOnLoadMoreListener(this); mListView.setOnItemClickListener(this); mInfoRequestProxy = new InfoRequestProxy(mContext, mTypeData, this); mHandler = new Handler(){ }; } @Override public void onDestroy() { log.e("CommonFragmentEx onDestroy"); if (loginStatus){ mInfoRequestProxy.cancelRequest(); } super.onDestroy(); } public BaseType.ListItem getData(){ return mTypeData; } private void switchToFailView(){ mInvalidView.setVisibility(View.VISIBLE); mLoadView.setVisibility(View.GONE); mContentView.setVisibility(View.GONE); } private void switchToLoadView(){ mInvalidView.setVisibility(View.GONE); mLoadView.setVisibility(View.VISIBLE); mContentView.setVisibility(View.GONE); } private void switchToContentView(){ mInvalidView.setVisibility(View.GONE); mLoadView.setVisibility(View.GONE); mContentView.setVisibility(View.VISIBLE); } @Override public void OnLoadMore() { mInfoRequestProxy.requestMoreInfo(); } @Override public void OnRefresh() { mInfoRequestProxy.requestRefreshInfo(); } private boolean isFirst = true; @Override public void onSuccess(boolean isLoadMore) { switchToContentView(); mContentData = mInfoRequestProxy.getData(); mAdapter.refreshData(mContentData); log.e("onSuccess isLoadMore = " + isLoadMore + ", isfrist = " + isFirst); if (isLoadMore){ mListView.onLoadMoreComplete(false); }else{ mListView.onRefreshComplete(); } } @Override public void onRequestFailure(boolean isLoadMore) { CommonUtil.showToast(R.string.toast_getdata_fail, mContext); if (mContentData.size() == 0){ switchToFailView(); return ; } switchToContentView(); if (isLoadMore){ mListView.onLoadMoreComplete(false); }else{ mListView.onRefreshComplete(); } } @Override public void onAnylizeFailure(boolean isLoadMore) { CommonUtil.showToast(R.string.toast_anylizedata_fail, mContext); if (mContentData.size() == 0){ switchToFailView(); return ; } switchToContentView(); if (isLoadMore){ mListView.onLoadMoreComplete(false); }else{ mListView.onRefreshComplete(); } } @Override public void onItemClick(AdapterView<?> adapter, View arg1, int pos, long arg3) { BaseType.InfoItem item = (InfoItem) adapter.getItemAtPosition(pos); BaseType.InfoItemEx itemEx = new BaseType.InfoItemEx(item, mTypeData); ContentCache.getInstance().setTypeItem(mTypeData); ContentCache.getInstance().setInfoItem(itemEx); HashMap<String, String> map = new HashMap<String, String>(); map.put(BaseType.ListItem.KEY_TYPEID, mTypeData.mTypeID); map.put(BaseType.ListItem.KEY_TITLE, itemEx.mTitle); LAroundApplication.getInstance().onEvent("UMID0002", map); goContentActivity(); } private void goContentActivity(){ Intent intent = new Intent(); intent.setClass(mContext, ContentActivity.class); startActivity(intent); } }
package algorithms.graph.process; import java.util.BitSet; import java.util.Collection; import java.util.LinkedList; import java.util.Queue; import algorithms.graph.Graph; import org.springframework.stereotype.Component; @Component public class BreadthFirstPaths extends AbstractIntPaths { @Override public void init(Graph graph, int sourceVertex) { bitSet = new BitSet(graph.verticesCount()); edgesTo = new int[graph.verticesCount()]; this.sourceVertex = sourceVertex; this.graph = graph; Queue<Integer> queue = new LinkedList<>(); bitSet.set(sourceVertex); queue.add(sourceVertex); while (!queue.isEmpty()) { Integer v = queue.poll(); Collection<Integer> adjacentVertices = graph.adjacentVertices(v); for (Integer adjacentVertex : adjacentVertices) { if (!bitSet.get(adjacentVertex)) { bitSet.set(adjacentVertex); edgesTo[adjacentVertex] = v; queue.offer(adjacentVertex); } } } } }
package uri; import java.util.Scanner; /** * IMPORTANT: * O nome da classe deve ser "Main" para que a sua solução execute * Class name must be "Main" for your solution to execute * El nombre de la clase debe ser "Main" para que su solución ejecutar */ public class URI { public static void main(String[] args) { Scanner scan = new Scanner(System.in); int n1 = scan.nextInt(); int n2 = scan.nextInt(); int resultado = 0; for(int i = 1; i <=n2; i++){ resultado += n1; } System.out.println(resultado); } }
package de.meetpub.telegrambot.commands.events; public interface EventCommand { public void execute(); }
package com.codecool.stampcollection.controller; import com.codecool.stampcollection.DTO.MyModelMapper; import com.codecool.stampcollection.DTO.StampCommand; import com.codecool.stampcollection.DTO.StampDTO; import com.codecool.stampcollection.assembler.StampModelAssembler; import com.codecool.stampcollection.model.Stamp; import com.codecool.stampcollection.service.StampService; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import org.springframework.hateoas.CollectionModel; import org.springframework.hateoas.EntityModel; import org.springframework.http.HttpStatus; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.*; import javax.validation.Valid; import javax.validation.constraints.NotBlank; import javax.validation.constraints.Size; import java.util.HashSet; @RestController @RequestMapping("/api/stamp") @Validated @Api(tags = "Stamps") public class StampController { private final StampService service; private final StampModelAssembler assembler; private final MyModelMapper myModelMapper; public StampController(StampService service, StampModelAssembler assembler, MyModelMapper myModelMapper) { this.service = service; this.assembler = assembler; this.myModelMapper = myModelMapper; } @ApiOperation(value = "View a list of possessed stamps") @GetMapping public CollectionModel<EntityModel<StampDTO>> findAll() { return assembler.toCollectionModel(service.findAll()); } @ApiOperation(value = "View details of the selected stamp") @GetMapping("/{stamp_id}") public EntityModel<StampDTO> findById(@PathVariable("stamp_id") Long id) { return assembler.toModel(service.findById(id)); } @ApiOperation(value = "View list of possessed stamps filtered by given country") @GetMapping("/country") public CollectionModel<EntityModel<StampDTO>> findAllByCountry(@RequestParam @NotBlank @Size(min = 3, max = 3, message = "Use three-letter Alpha-3 code.") String country) { return assembler.toCollectionModel(service.findAllByCountry(country)); } @ApiOperation(value = "View list of possessed stamps filtered by given year") @GetMapping("/year") public CollectionModel<EntityModel<StampDTO>> findAllByYear(@RequestParam Integer year) { return assembler.toCollectionModel(service.findAllByYear(year)); } @ApiOperation(value = "View list of possessed stamps filtered by given country and year") @GetMapping("/countryandyear") public CollectionModel<EntityModel<StampDTO>> findAllByCountryAndYear(@RequestParam @NotBlank @Size(min = 3, max = 3, message = "Use three-letter Alpha-3 code.") String country, @RequestParam Integer year) { return assembler.toCollectionModel(service.findAllByCountryAndYear(country, year)); } @ApiOperation(value = "Create a new stamp object") @PostMapping @ResponseStatus(HttpStatus.CREATED) public EntityModel<StampDTO> addNew(@Valid @RequestBody StampCommand command) { Stamp stamp = myModelMapper.dtoToEntity(command); stamp.setDenominations(new HashSet<>()); return assembler.toModel(service.addNew(stamp)); } @ApiOperation(value = "Update an existing stamp") @PutMapping("/{stamp_id}") public EntityModel<StampDTO> update(@PathVariable("stamp_id") Long id, @Valid @RequestBody StampCommand command) { Stamp stamp = service.findById(id); stamp.setYearOfIssue(command.getYearOfIssue()); stamp.setName(command.getName()); stamp.setCountry(command.getCountry()); return assembler.toModel(service.addNew(stamp)); } @ApiOperation(value = "Delete the selected stamp from collection", notes = "It can only be deleted if its denominations have been deleted previously") @DeleteMapping("/{stamp_id}") @ResponseStatus(HttpStatus.NO_CONTENT) public void deleteById(@PathVariable("stamp_id") Long id) { service.deleteById(id); } }
import java.util.Scanner; public class CheckingAccountTest { public static void main(String[] args) { // TODO Auto-generated method stub Scanner input = new Scanner(System.in); double debit; double deposit; String err; CheckingAccount account1 = new CheckingAccount(100.0,-100,0.01,0.07); // 참조자 생성 CheckingAccount account2 = new CheckingAccount(100.0,-100,0.01,0.07); // 참조자 생성 System.out.printf("Account1 balance %.2f\n",account1.getBalance()); // 계좌 내역 확인 System.out.printf("Account2 balance %.2f\n",account2.getBalance()); // 계좌 내역 확인 // 계좌 내역 확인 System.out.print("Enter deposit amount for Account1 : "); deposit = input.nextDouble(); // 예급 할 금액 입력 account1.credit(deposit); System.out.printf("Account1 balance %.2f\n",account1.getBalance()); // 계좌 내역 확인 System.out.printf("Account2 balance %.2f\n",account2.getBalance()); // 계좌 내역 확인 System.out.print("Enter withdrawal amount for account2 : "); debit = input.nextDouble(); // 예급 할 금액 입력 err=account2.debit(debit); if(err!=null) { System.out.println(err); // 한도초과 } System.out.printf("Account1 balance %.2f\n",account1.getBalance()); // 계좌 내역 확인 System.out.printf("Account2 balance %.2f\n",account2.getBalance()); // 계좌 내역 확인 System.out.println("next month!"); account1.nextMonth(); account2.nextMonth(); System.out.printf("Account1 balance %.2f\n",account1.getBalance()); // 계좌 내역 확인 System.out.printf("Account2 balance %.2f\n",account2.getBalance()); // 계좌 내역 확인 input.close(); // 가비지 컬렉터가 있으면서도 이것을 사용하는 이유는 프로그램이 순차적으로 작동하는 도중에 계속해서 여러가지가 만들어지고 열리는데, 이때 안 닫히는 무언가가 다른 프로세스를 방해 할 수있기 때문에 미리 미리 닫아줘서 그런 충돌을 방지시킨다. } }
/** * Makes an Alien that attacks the base * @author Rishav Bose * @version 1.00 */ public class Alien3 extends Monster { /** * Makes an alien with health 350 */ public Alien3() { super(350, "provided/res/Pixel-Alien-3.png"); } /** * Attacks the base with 150 attack * @param a the base to hurt */ public void attack(Base a) { a.hurt(150); } }
package async; import java.io.IOException; import java.net.InetSocketAddress; import java.net.SocketAddress; import java.net.StandardSocketOptions; import java.nio.ByteBuffer; import java.nio.channels.AsynchronousServerSocketChannel; import java.nio.channels.AsynchronousSocketChannel; import java.nio.channels.CompletionHandler; import java.util.Arrays; import bayou.http.HttpClient; import bayou.http.HttpClientConf; import bayou.http.HttpRequest; import bayou.http.HttpResponse; import bayou.async.Async; import bayou.http.HttpProxy; import java.io.ByteArrayOutputStream; public class EchoServer { static void action2(HttpResponse x, AsynchronousSocketChannel connection){ System.out.println("TEST"); Async<String> resp = x.bodyString(1024*500); resp.peek(val -> System.out.println(val)) .peek(val -> action3(val.getBytes(),connection)); try{ System.out.println(connection.getLocalAddress()); }catch(Exception e){} } static void action3(byte[] data, AsynchronousSocketChannel connection){ System.out.println(data); final ByteBuffer buffer = ByteBuffer.wrap(data); // callback 3 connection.write(buffer, null, new CompletionHandler<Integer, ByteBuffer>() { @Override public void completed(Integer result, ByteBuffer bbAttachment) { System.out.println("Writing client completed"); buffer.flip(); System.out.println(result); /*if (buffer.hasRemaining()) { System.out.println("Data Left"); connection.write(buffer, null, this); } else { */ System.out.println("Writing client completed"); //bbAttachment.clear(); action4(connection); //} } @Override public void failed(Throwable t, ByteBuffer bbAttachment) { t.printStackTrace(); } }); } static void action4(AsynchronousSocketChannel connection){ final ByteBuffer buffer = ByteBuffer.allocate(2); // callback 2 System.out.println("Waiting for Client"); connection.read(buffer, connection, new CompletionHandler<Integer, AsynchronousSocketChannel>() { @Override public void completed(Integer result, final AsynchronousSocketChannel scAttachment) { System.out.println("Reading from client completed"); System.out.println("Result for Read: " + result); System.out.println("Has Remaining " + buffer.remaining()); System.out.println("Remaining " + buffer.remaining()); buffer.clear(); if (result == -1) { System.out.println("No data... "); connection.read(buffer, connection, this); } //try { String message = new String(buffer.array()).trim(); System.out.println(message); System.out.println(Arrays.toString(buffer.array())); HttpClient client = new HttpClientConf() .proxy(new HttpProxy("proxy.cognizant.com", 6050,"414612","Fourvees@19832712")) .trafficDump(System.err::print) .newClient(); HttpRequest request = HttpRequest.toPost("http://s3.amazonaws.com/ssd","application/x-www-form-urlencoded",message.getBytes()); Async<HttpResponse> asyncRes = client.send( request ); asyncRes.peek( response -> action2(response,connection)); //} catch (IOException e) { //e.printStackTrace(); //} //byte [] message1 = new String("OVER").getBytes(); //buffer.wrap(message1); } @Override public void failed(Throwable t, AsynchronousSocketChannel scAttachment) { t.printStackTrace(); } }); } public static void main(String[] args) { try (final AsynchronousServerSocketChannel listener = AsynchronousServerSocketChannel.open()) { listener.setOption(StandardSocketOptions.SO_REUSEADDR, true); listener.bind(new InetSocketAddress("localhost", 3883)); while (true) { // callback 1 listener.accept(null, new CompletionHandler<AsynchronousSocketChannel, Void>() { @Override public void completed(AsynchronousSocketChannel connection, Void v) { listener.accept(null, this); // get ready for next connection final ByteBuffer buffer = ByteBuffer.allocate(32); System.out.println("Client connected..."); HttpClient client = new HttpClientConf() .proxy(new HttpProxy("proxy.cognizant.com", 6050,"414612","Fourvees@19832712")) .trafficDump(System.err::print) .newClient(); HttpRequest request = HttpRequest.toPost("http://s3.amazonaws.com/ssd","application/x-www-form-urlencoded", "a=1&b=2".getBytes()); Async<HttpResponse> asyncRes = client.send( request ); asyncRes.peek( response -> action2(response,connection)); } @Override public void failed(Throwable t, Void v) { t.printStackTrace(); } }); System.in.read(); // so we don't exit before a connection is established } } catch (IOException e) { e.printStackTrace(); } } }
/* * Copyright (c) 2020 Nikifor Fedorov * 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. * SPDX-License-Identifier: Apache-2.0 * Contributors: * Nikifor Fedorov and others */ package ru.krivocraft.tortoise.android.thumbnail; import android.content.Context; import android.graphics.Color; import androidx.core.content.res.ResourcesCompat; import ru.krivocraft.tortoise.R; import java.util.ArrayList; import java.util.List; import java.util.Random; public class Colors { private final Context context; private final List<Integer> availableColors; public static final int RED = 0; public static final int PINK = 1; public static final int PURPLE = 2; public static final int DEEP_PURPLE = 3; public static final int INDIGO = 4; public static final int BLUE = 5; public static final int LIGHT_BLUE = 6; public static final int CYAN = 7; public static final int TEAL = 8; public static final int GREEN = 9; public static final int LIGHT_GREEN = 10; public static final int LIME = 11; public static final int YELLOW = 12; public static final int AMBER = 13; public static final int ORANGE = 14; public static final int DEEP_ORANGE = 15; public static final String ACTION_RESULT_COLOR = "result_color"; public static final String ACTION_REQUEST_COLOR = "request_color"; public static final String EXTRA_COLOR = "color"; public Colors(Context context) { this.context = context; this.availableColors = new ArrayList<>(); fillAvailableColors(); } public static int getRandomColor() { return new Random().nextInt(16); } public int getColor(int color) { int colorResource = ResourcesCompat.getColor(context.getResources(), availableColors.get(color), null); return Color.rgb(Color.red(colorResource), Color.green(colorResource), Color.blue(colorResource)); } public int getColorResource(int color) { return availableColors.get(color); } private void fillAvailableColors() { availableColors.add(R.color.red700); availableColors.add(R.color.pink700); availableColors.add(R.color.purple700); availableColors.add(R.color.deep_purple700); availableColors.add(R.color.indigo700); availableColors.add(R.color.blue700); availableColors.add(R.color.light_blue700); availableColors.add(R.color.cyan700); availableColors.add(R.color.teal700); availableColors.add(R.color.green700); availableColors.add(R.color.light_green700); availableColors.add(R.color.lime700); availableColors.add(R.color.yellow700); availableColors.add(R.color.amber700); availableColors.add(R.color.orange00); availableColors.add(R.color.deep_orange700); } }
package com.esum.ebms.v2.service.transport; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.esum.ebms.v2.ConstantsDisplayUtil; import com.esum.ebms.v2.service.transport.clazz.ClassTransport; /** * ebms가 adapter를 위해 제공하는 Transport는 Http/file/class타입이다. * 각 transport들은 ebms로 부터 데이터를 송신/수신할 수 있는 기능을 가지고서 Adapter 인터페이스를 구현한 객체에게 데이터를 * 전송하는 역할을 한다. * * 이 클래스는 제공되는 transport의 인스턴스를 생성하여 리턴한다. * * Copyright(c) eSum Technologies, Inc. All rights reserved. */ public class TransportBuilder { private static Logger log = LoggerFactory.getLogger(TransportBuilder.class); /** * TransportType에 따라 Transportable 인터페이스를 구현한 객체를 생성한 후 리턴한다. */ public synchronized static Transportable newInstance(TransportType type) throws TransportException{ int transType = type.getTransportType(); log.debug("Creating Transport instance... Type: " + ConstantsDisplayUtil.getTransportStr(transType)); if (transType == TransportType.TRANSPORT_CLASS) { log.debug("Created ClassTransport instance."); return new ClassTransport(); } else throw new TransportException(TransportException.ERROR_NOT_SUPPORT_TRANSPORT_TYPE, "newInstance()", "Not supported " + ConstantsDisplayUtil.getTransportStr(transType) + " type."); } }
package com.syscxp.biz.entity.redmine; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; /** * @Author: sunxuelong. * @Cretion Date: 2018-09-17. * @Description: . */ @Entity(name = "trackers") public class Tracker { @Id @Column(name = "id") private Long id; @Column(name = "name") private String name; @Column(name = "is_in_chlog") private Boolean isInChlog; @Column(name = "position") private Long position; @Column(name = "is_in_roadmap") private Boolean isInRoadmap; @Column(name = "fields_bits") private Long fieldsbits; @Column(name = "default_status_id") private Long defaultStatusId; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Boolean getInChlog() { return isInChlog; } public void setInChlog(Boolean inChlog) { isInChlog = inChlog; } public Long getPosition() { return position; } public void setPosition(Long position) { this.position = position; } public Boolean getInRoadmap() { return isInRoadmap; } public void setInRoadmap(Boolean inRoadmap) { isInRoadmap = inRoadmap; } public Long getFieldsbits() { return fieldsbits; } public void setFieldsbits(Long fieldsbits) { this.fieldsbits = fieldsbits; } public Long getDefaultStatusId() { return defaultStatusId; } public void setDefaultStatusId(Long defaultStatusId) { this.defaultStatusId = defaultStatusId; } }
package com.gmail.filoghost.holographicdisplays.api.handler; import org.bukkit.entity.Player; /** * Interface to handle touch holograms. */ public interface TouchHandler { /** * Called when a player interacts with the hologram (right click). * @param player the player who interacts */ public void onTouch(Player player); }
package org.royalmc.bungee_signs; import com.google.common.io.ByteArrayDataInput; import com.google.common.io.ByteStreams; import org.bukkit.Bukkit; import org.bukkit.block.Sign; import org.bukkit.configuration.ConfigurationSection; import org.bukkit.entity.Player; import org.bukkit.plugin.java.JavaPlugin; import org.bukkit.plugin.messaging.PluginMessageListener; import org.royalmc.bungee_signs.commands.CommandBS; import org.royalmc.bungee_signs.listeners.PlayerListener; import org.royalmc.bungee_signs.sign.SignManager; import org.royalmc.bungee_signs.sign.StatusSign; import org.royalmc.bungee_signs.storage.YMLManager; import java.io.ByteArrayInputStream; import java.io.DataInputStream; import java.io.IOException; import java.util.HashMap; public class BungeeSigns extends JavaPlugin implements PluginMessageListener { public static HashMap<StatusSign, Boolean> signInProgress = new HashMap<>(); // need to find a better method private YMLManager ymlManager; private SignManager signManager; @Override public void onEnable() { Bukkit.getServer().getMessenger().registerOutgoingPluginChannel(this, "BungeeCord"); Bukkit.getServer().getMessenger().registerIncomingPluginChannel(this, "BungeeCord", this); ymlManager = new YMLManager(this); signManager = new SignManager(this); getServer().getPluginManager().registerEvents(new PlayerListener(this), this); getCommand("bungeesigns").setExecutor(new CommandBS(this)); } @Override public void onDisable() { signInProgress.clear(); } public YMLManager getYmlManager() { return ymlManager; } public SignManager getSignManager() { return signManager; } @Override public void onPluginMessageReceived(String channel, Player player, byte[] message) { if (!channel.equals("BungeeCord")) return; ByteArrayDataInput in = ByteStreams.newDataInput(message); String subChannel = in.readUTF(); short len = in.readShort(); byte[] msgbytes = new byte[len]; in.readFully(msgbytes); DataInputStream msgin = new DataInputStream(new ByteArrayInputStream(msgbytes)); try { String gameState = msgin.readUTF(); String serverName = msgin.readUTF(); msgin.readShort(); if (gameState.equalsIgnoreCase("isjoinable")) { // update sign ConfigurationSection signsSection = this.ymlManager.getDatabaseFile().getConfigurationSection("Signs"); String signName; for (String keys : signsSection.getKeys(false)) { if (keys.equalsIgnoreCase(serverName)) { signName = serverName; StatusSign s = signManager.getSign(signName); Sign b = s.getSign(); b.setLine(1, SignManager.formatText("&8In Queue")); if (signInProgress.containsKey(s)) signInProgress.replace(s, false); else signInProgress.put(s, false); signManager.update(s); } } } else if (gameState.equalsIgnoreCase("notjoinable")) { // update sign ConfigurationSection signsSection = this.ymlManager.getDatabaseFile().getConfigurationSection("Signs"); String signName; for (String keys : signsSection.getKeys(false)) { if (keys.equalsIgnoreCase(serverName)) { signName = serverName; StatusSign s = signManager.getSign(signName); Sign b = s.getSign(); b.setLine(1, SignManager.formatText("&8In Progress")); if (signInProgress.containsKey(s)) signInProgress.replace(s, true); else signInProgress.put(s, true); signManager.update(s); } } } } catch (IOException e) { e.printStackTrace(); } } }
package com.software3.servlet; import java.io.IOException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.software3.service.BookService; import com.software3.service.impl.BookServiceImpl; @WebServlet("/recommendbook") public class RecommendBookServlet extends HttpServlet { /** * */ private static final long serialVersionUID = 1L; BookService bs = new BookServiceImpl(); protected void doGet(HttpServletRequest request,HttpServletResponse response) throws IOException{ response.setCharacterEncoding("utf-8"); if(bs.recommendBook(request.getParameter("bookid"))){ response.getWriter().write("推荐成功"); } else{ response.getWriter().write("操作失败了"); } } }
package com.spring.testable.mock; import org.mybatis.spring.annotation.MapperScan; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.openfeign.EnableFeignClients; /** * @author caijie */ @MapperScan("com.spring.testable.mock.mapper") @SpringBootApplication @EnableFeignClients public class MockApplication { public static void main(String[] args) { SpringApplication.run(MockApplication.class, args); } }
package ShopLite.entity; import ShopLite.exception.InvalidChooseValueException; import ShopLite.exception.InvalidKeyException; import java.util.*; public class Shop { private final HashMap<Integer, Product> productMap = new HashMap<>(); public void add(Product product, int id) throws InvalidKeyException { if (!productMap.containsKey(id)) { productMap.put(id, product); } else { throw new InvalidKeyException("Товар с таким id уже присутствует."); } } public Collection<Product> getAllProducts() { return productMap.values(); } public void remove(int id) throws InvalidChooseValueException { if (!productMap.isEmpty()) if (productMap.containsKey(id)) { productMap.remove(id); } else { throw new InvalidChooseValueException("Товар с таким id не найден."); } } public void edit(int id, Product product) throws InvalidChooseValueException { if (productMap.containsKey(id)) { productMap.put(id, product); } else { throw new InvalidChooseValueException("Товар с таким id не найден."); } } public int getKeyByValue(Product value) { int key = 0; for (Map.Entry<Integer, Product> entry : productMap.entrySet()) { if (Objects.equals(value, entry.getValue())) { key = entry.getKey(); } } return key; } /* public void add(Product product) { Optional<Product> first = productList.stream().filter(product1 -> product1.getId() == product.getId()).findFirst(); if (first.isEmpty()) { productList.add(product); } } public ArrayList<Product> getAllProducts() { return productList; } public void remove(int id) { Optional<Product> first = productList.stream().filter(product1 -> product1.getId() == id).findFirst(); first.ifPresent(productList::remove); } public void edit(int id, Product product) { Optional<Product> first = productList.stream().filter(product1 -> product1.getId() == product.getId()).findFirst(); first.ifPresent(value -> productList.set(productList.indexOf(value), product)); } */ }
/*package br.com.acme.agenda.service; import java.util.ArrayList; import java.util.List; import br.com.acme.agenda.model.Usuario; import br.com.acme.agenda.service.ServiceLogin; public class UsuarioService { public class ServiceLogin { public static List<Usuario> usuarios = new ArrayList<Usuario>(); public static boolean login(String nome, String senha) { for(Usuario usuario : ServiceLogin.usuarios) { if((usuario.getNome().equals(nome)) && (usuario.getSenha().equals(senha))) { return true; } } return false; } public static void adicionarUsuario() { if (!ServiceLogin.login("angelo", "123")) { usuarios.add(new Usuario("angelo","angelo@iesp.edu.br","32233203","aaaaaaa 520","123")); } } } public class ServiceLogin { public static List<Usuario> usuarios = new ArrayList<Usuario>(); public static boolean login(String nome, String senha) { for(Usuario usuario : ServiceLogin.usuarios) { if((usuario.getNome().equals(nome)) && (usuario.getSenha().equals(senha))) { return true; } } return false; } public static void adicionarUsuario() { if (!ServiceLogin.login("angelo", "123")) { usuarios.add(new Usuario("angelo","angelo@iesp.edu.br","32233203","aaaaaaa 520","123")); } } //public void removerUsuario() { // //} /* public static boolean removeUsuario(String nome) { for(Usuario u:usuarios) { if(u.getNome().equals(nome)) usuarios.remove(u); return true; } return false; } public static void removendoUsuario(String nome) { for(int i = 0; i < usuarios.size(); i++) { Usuario u = usuarios.get(i); if(u.getNome().equals(nome)) { // Remove. usuarios.remove(u); break; } } } } */
package us.gibb.dev.gwt.server.inject; import us.gibb.dev.gwt.server.command.handler.CommandHandlerRegistry; import us.gibb.dev.gwt.server.command.handler.DefaultDispatch; import com.google.inject.Inject; import com.google.inject.Provider; public class DefaultDispatchProvider implements Provider<DefaultDispatch>{ private CommandHandlerRegistry handlerRegistry; @Inject public DefaultDispatchProvider(CommandHandlerRegistry handlerRegistry) { this.handlerRegistry = handlerRegistry; } @Override public DefaultDispatch get() { return new DefaultDispatch(handlerRegistry); } }
package base.interf; public interface Common { void tipo(); void info(); void status(); }
package com.culturaloffers.maps; import com.culturaloffers.maps.controllers.CulturalOfferControllerTest; import com.culturaloffers.maps.controllers.OfferNewsControllerTest; import com.culturaloffers.maps.controllers.SearchControllerIntegrationTest; import com.culturaloffers.maps.model.OfferNews; import com.culturaloffers.maps.repositories.CulturalOfferRepositoryTest; import com.culturaloffers.maps.repositories.OfferNewsRepositoryTest; import com.culturaloffers.maps.repositories.SearchRepositoryIntegrationTest; import com.culturaloffers.maps.services.CulturalOfferServiceIntegrationTest; import com.culturaloffers.maps.services.OfferNewsServiceIntegrationTest; import com.culturaloffers.maps.services.SearchServiceIntegrationTest; import com.culturaloffers.maps.services.SearchServiceUnitTest; import org.junit.runner.RunWith; import org.junit.runners.Suite; import org.springframework.test.context.TestPropertySource; @RunWith(Suite.class) @Suite.SuiteClasses({ CulturalOfferRepositoryTest.class, OfferNewsRepositoryTest.class, CulturalOfferServiceIntegrationTest.class, OfferNewsServiceIntegrationTest.class, CulturalOfferControllerTest.class, OfferNewsControllerTest.class, SearchRepositoryIntegrationTest.class, SearchServiceUnitTest.class, SearchServiceIntegrationTest.class, SearchControllerIntegrationTest.class }) @TestPropertySource("classpath:test-offer.properties") public class SuiteOffer { }
package HakerRank.SherlockandAnagrams; import java.io.*; import java.math.*; import java.security.*; import java.text.*; import java.util.*; import java.util.concurrent.*; import java.util.regex.*; public class Solution { // Complete the sherlockAndAnagrams function below. static int sherlockAndAnagrams(String s) { int result = 0; for(int i=0; i<s.length()-1; i++) { int stringLength = 1; for(int j=i; j<s.length()-1; j++) { LinkedList<String> perCharacter = new LinkedList<>(); for(int k=i; k<i+stringLength; k++){ perCharacter.add(String.valueOf(s.charAt(k))); } for(int k=i+1; k<s.length(); k++){ boolean matchFlag = true; LinkedList<String> dummyCharacter = new LinkedList<>(); if(k+stringLength > s.length()){ break; } for(int l=0; l<perCharacter.size(); l++) { dummyCharacter.add(perCharacter.get(l)); } for(int l=k; l<k+stringLength; l++) { String comparingChar = String.valueOf(s.charAt(l)); if(dummyCharacter.contains(comparingChar)) { dummyCharacter.remove(comparingChar); } else { matchFlag = false; break; } } if(matchFlag){ result++; } } stringLength++; } } return result; } private static final Scanner scanner = new Scanner(System.in); public static void main(String[] args) throws IOException { // BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH"))); int q = scanner.nextInt(); scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?"); for (int qItr = 0; qItr < q; qItr++) { String s = scanner.nextLine(); int result = sherlockAndAnagrams(s); System.out.println(result); // bufferedWriter.write(String.valueOf(result)); // bufferedWriter.newLine(); } // bufferedWriter.close(); scanner.close(); } }
package jp.ac.kyushu_u.csce.modeltool.vdmrtEditor.editor; import jp.ac.kyushu_u.csce.modeltool.vdmrtEditor.constants.VdmrteditorConstants; import jp.ac.kyushu_u.csce.modeltool.vdmrtEditor.editor.VdmrtColorManager; import org.eclipse.ui.editors.text.TextEditor; /** * VDMエディタークラス * * @author KBK yoshimura */ public class VdmrtEditor extends TextEditor { /** カラーマネージャ */ private VdmrtColorManager colorManager; /** * コンストラクタ */ public VdmrtEditor() { super(); colorManager = new VdmrtColorManager(); setSourceViewerConfiguration(new VdmrtConfiguration(colorManager)); setDocumentProvider(new VdmrtDocumentProvider()); } /** * @see TextEditor#dispose() */ public void dispose() { colorManager.dispose(); // カラーマネージャのdispose super.dispose(); } /** * @see TextEditor#initializeKeyBindingScopes */ protected void initializeKeyBindingScopes() { setKeyBindingScopes(new String[] {VdmrteditorConstants.SCOPE_ID_VDMRT_EDITOR}); } }
package so.team.bukkitlejyon.cmdBlock.plugin; import com.comphenix.protocol.ProtocolLibrary; import com.comphenix.protocol.events.PacketContainer; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.block.Block; import org.bukkit.entity.Player; import org.bukkit.plugin.Plugin; import org.bukkit.scheduler.BukkitRunnable; import org.bukkit.util.Vector; import so.team.bukkitlejyon.cmdBlock.api.InputGui; import so.team.bukkitlejyon.cmdBlock.api.InputGuiBase; import so.team.bukkitlejyon.cmdBlock.api.InputGuiSign; import so.team.bukkitlejyon.cmdBlock.api.InputPlayer; public class InputGuiPlayer implements InputPlayer { private boolean checkPackets; private boolean checkMove; private BukkitRunnable checkPacketsTask; private BukkitRunnable checkMoveTask; private Location fakeBlockLoc = null; private Plugin plugin; private Player player; private InputGuiBase<?> gui; public InputGuiPlayer(Plugin plugin, Player player) { this.plugin = plugin; this.player = player; } public void openTileEditor(Block block) { setCancelled(); try { PacketContainer packet = InputGuiUtils.getOpenGuiPacket(block .getLocation()); ProtocolLibrary.getProtocolManager().sendServerPacket(this.player, packet); } catch (Exception e) { e.printStackTrace(); } } public Player getPlayer() { return this.player; } public boolean isGuiOpen() { return this.gui != null; } public InputGuiBase<?> getCurrentGui() { return this.gui; } public boolean closeGui() { if (this.gui == null) { return false; } try { ProtocolLibrary.getProtocolManager().sendServerPacket(this.player, InputGuiUtils.getCloseGuiPacket()); } catch (Exception e) { e.printStackTrace(); } return true; } public void openGui(InputGuiBase<?> gui) { openGui(gui, 17, 3); } @SuppressWarnings("deprecation") public void openGui(InputGuiBase<?> gui, int moveCheckTicks, int packetCheckTicks) { setCancelled(); this.gui = gui; Location playerLoc = this.player.getLocation(); Vector direction = playerLoc.getDirection().normalize().multiply(-5); this.fakeBlockLoc = playerLoc.add(direction); this.checkPackets = false; this.checkMove = false; if ((gui instanceof InputGuiSign)) { String[] lines = (String[])gui.getDefaultText(); try { ProtocolLibrary.getProtocolManager().sendServerPacket( this.player, InputGuiUtils.getSignPacket(this.fakeBlockLoc, lines)); } catch (Exception e) { e.printStackTrace(); } } else if ((gui instanceof InputGui)) { this.player.sendBlockChange(this.fakeBlockLoc, Material.COMMAND, (byte)0); String text = (String)gui.getDefaultText(); try { ProtocolLibrary.getProtocolManager().sendServerPacket( this.player, InputGuiUtils.getTileDataPacket(this.fakeBlockLoc, text)); } catch (Exception e) { e.printStackTrace(); } } else { throw new IllegalArgumentException("Unsupported gui: '" + gui.getClass().getSimpleName() + "'!"); } try { ProtocolLibrary.getProtocolManager().sendServerPacket(this.player, InputGuiUtils.getOpenGuiPacket(this.fakeBlockLoc)); } catch (Exception e) { e.printStackTrace(); } this.checkPacketsTask = new BukkitRunnable() { public void run() { InputGuiPlayer.this.checkPackets = true; InputGuiPlayer.this.checkPacketsTask = null; } }; this.checkMoveTask = new BukkitRunnable() { public void run() { InputGuiPlayer.this.checkMove = true; InputGuiPlayer.this.checkMoveTask = null; } }; this.checkPacketsTask.runTaskLater(this.plugin, packetCheckTicks); this.checkMoveTask.runTaskLater(this.plugin, moveCheckTicks); } @SuppressWarnings("deprecation") public void setCancelled() { if (this.checkMoveTask != null) { this.checkMoveTask.cancel(); this.checkMoveTask = null; } if (this.gui != null) { this.gui.onCancel(this); this.gui = null; } if (this.fakeBlockLoc != null) { Block block = this.fakeBlockLoc.getBlock(); this.player.sendBlockChange(this.fakeBlockLoc, block.getTypeId(), block.getData()); } } public void setConfirmed(Object input) { if (this.checkMoveTask != null) { this.checkMoveTask.cancel(); this.checkMoveTask = null; } if ((this.gui instanceof InputGuiSign)) { ((InputGuiSign)this.gui).onConfirm(this, (String[])input); } else if (((this.gui instanceof InputGui)) && (this.gui != null) && (input != null)) { try { ((InputGui)this.gui).onConfirm(this, (String)input); } catch (Exception localException) {} } this.gui = null; } public boolean isCheckingMovement() { return this.checkMove; } public boolean isCheckingPackets() { return this.checkPackets; } public Location getFakeBlockLocation() { return this.fakeBlockLoc; } }
package com.hristofor.mirchev.outfittery.challenge.reservedtime.controller; import com.hristofor.mirchev.outfittery.challenge.reservedtime.dtos.DTOtoEntityConverter; import com.hristofor.mirchev.outfittery.challenge.reservedtime.dtos.ReservedTimeDTO; import com.hristofor.mirchev.outfittery.challenge.reservedtime.repository.ReservedTime; import com.hristofor.mirchev.outfittery.challenge.reservedtime.service.ReservedTimeService; import com.hristofor.mirchev.outfittery.challenge.stylists.controller.StylistController; import com.hristofor.mirchev.outfittery.challenge.stylists.dtos.StylistDTO; import com.hristofor.mirchev.outfittery.challenge.stylists.repository.StylistStatus; import com.hristofor.mirchev.outfittery.challenge.stylists.service.StylistServiceImpl; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import java.time.OffsetDateTime; import java.util.ArrayList; import java.util.List; import java.util.Objects; import java.util.Set; import java.util.function.Predicate; import java.util.stream.Collectors; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.lang.NonNull; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; @Api(description = "Operations regarding all reserved times.") @RestController @RequestMapping("/v1") public class ReservedTimeController { private static final Logger log = LoggerFactory.getLogger(StylistServiceImpl.class); @Autowired private ReservedTimeService reservedTimeService; @Autowired private StylistController stylistController; @ApiOperation(value = "Gets a list of all reserved times between the provided range.", response = List.class) @GetMapping(value = "/reservedTimes", produces = "application/json") public List<ReservedTimeDTO> getAllReservedTimesBetween( @RequestParam(value = "start") String start, @RequestParam(value = "end") String end) { final OffsetDateTime startTime = OffsetDateTime.parse(start); final OffsetDateTime endTime = OffsetDateTime.parse(end); final List<ReservedTime> reservedTimesBetween = reservedTimeService .getAllReservedTimeBetween(startTime, endTime); return reservedTimesBetween.stream().map(DTOtoEntityConverter::convert) .collect(Collectors.toList()); } /** * I don't believe in doing this method. I think it breaks the REST representation, as "available * time" is not a resource we operate with, we operate with the inverse. */ @ApiOperation(value = "Gets a list of all available times for an appointment between the provided range.", response = List.class) @GetMapping(value = "/availableTimes", produces = "application/json") public List<ReservedTimeDTO> getAllAvailableTimesBetween( @RequestParam(value = "start") String start, @RequestParam(value = "end") String end) { final OffsetDateTime startTime = OffsetDateTime.parse(start); final OffsetDateTime endTime = OffsetDateTime.parse(end); final List<ReservedTime> reservedTimesBetween = reservedTimeService .getAllReservedTimeBetween(startTime, endTime); final Predicate<StylistDTO> readyToStyleStatus = stylistDTO -> stylistDTO.getStatus() == StylistStatus.READY_TO_STYLE; final List<ReservedTime> reservedTimesOfReadyStylists = filterReservedTimesBasedOnStylistWith( reservedTimesBetween, readyToStyleStatus); final List<ReservedTimeDTO> availableTimes = new ArrayList<>(); for (OffsetDateTime i = startTime; i.isBefore(endTime); i = i.plusMinutes(30)) { // find reserved times that overlap with the current time slot: [i, i.plusMinutes(30)] final OffsetDateTime currentStartTime = i; final OffsetDateTime currentEndTime = i.plusMinutes(30); final Predicate<ReservedTime> overlappingTime = reservedTime -> reservedTime.getEnd().isAfter(currentStartTime) && reservedTime.getStart() .isBefore(currentEndTime); final List<ReservedTime> overlappedReservedTimes = reservedTimesOfReadyStylists.stream() .filter(overlappingTime) .collect(Collectors.toList()); if (overlappedReservedTimes.isEmpty()) { availableTimes.add(new ReservedTimeDTO().setStart(currentStartTime).setEnd(currentEndTime)); } } return availableTimes; } /** * Takes a list of reserved times and a predicate on the {@link StylistDTO} and filters those * reserved times, whose stylist fulfil the predicate. * * @param reservedTimes a list of {@link ReservedTime} * @param predicate a predicate on the {@link StylistDTO} who we want to be fulfilled. * @return a filtered list of {@link ReservedTime}. */ private List<ReservedTime> filterReservedTimesBasedOnStylistWith( @NonNull final List<ReservedTime> reservedTimes, @NonNull final Predicate<StylistDTO> predicate) { Objects.requireNonNull(reservedTimes, "The reserved times should not be null here."); Objects.requireNonNull(predicate, "The predicate should not be null here."); // ids of the stylists that have the provided reserved times final Set<Long> stylistIds = reservedTimes.stream().map(ReservedTime::getStylistId) .collect(Collectors.toSet()); // simulating the call to the stylist microservice here final List<StylistDTO> stylists = stylistController .getStylistsByIds(new ArrayList<>(stylistIds)); // filter the stylists with the predicate and gather their ids final Set<Long> filteredOutStylistsIds = stylists.stream() .filter(predicate).map(StylistDTO::getId).collect(Collectors.toSet()); // return just those reserved times that have a stylist id among the filtered out return reservedTimes.stream() .filter(reservedTime -> filteredOutStylistsIds.contains(reservedTime.getStylistId())) .collect(Collectors.toList()); } }
package baseline; import java.util.Arrays; import java.util.Scanner; /* * UCF COP3330 Fall 2021 Assignment 3 Solutions * Copyright 2021 Federico Abreu Seymour */ public class Solution24 { //calculate Anagram using boolean public boolean isAnagram(String string1, String string2){ //If first string doesn't have same length return false if (string1.length() != string2.length()){ return false; } //ELSE Create a char[] array = to BOTH the strings else{ char[] array1 = string1.toLowerCase().toCharArray(); char[] array2 = string2.toLowerCase().toCharArray(); //Then array.sort BOTH Arrays.sort(array1); Arrays.sort(array2); //then return array.equals(arrays) return Arrays.equals(array1, array2); } } public static void main(String[] args) { Scanner input = new Scanner(System.in); Solution24 sol = new Solution24(); //Display Enter two strings, and I'll tell if they are anagrams: System.out.println("Enter two Strings and I'll tell you if they are anagrams: "); //Display Enter the first string: Scan the user input as a String System.out.print("Enter the first string: "); String string1 = input.nextLine(); //Display Enter the second string: Scan in as String System.out.print("Enter the second string: "); String string2 = input.nextLine(); //If true Display "string 1 and string 2 are anagrams if(sol.isAnagram(string1, string2)){ System.out.print(string1 + " and " + string2 + " are anagrams. "); } //else Display string 1 adn string2 are not anagrams else{ System.out.print(string1 + " and " + string2 + " are not anagrams. "); } } }
package org.zhq.box; import org.zhq.core.Packet; import org.zhq.core.SendPacket; import java.io.InputStream; public class StreamDirectSendPacket extends SendPacket<InputStream> { private InputStream inputStream; public StreamDirectSendPacket(InputStream inputStream) { this.inputStream = inputStream; this.length = MAX_PACKET_SIZE; } @Override protected InputStream createStream() { return inputStream; } @Override public byte type() { return Packet.TYPE_MEMORY_DIRECT; } }
package com.smartlead.api.lead.repository; import com.smartlead.common.entity.DocumentType; import org.springframework.data.repository.CrudRepository; import java.util.List; public interface DocumentTypeRepository extends CrudRepository<DocumentType, Integer> { List<DocumentType> findAll(); }
package com.oxymore.practice.configuration.ui; import com.oxymore.practice.configuration.parse.Deserializer; import com.oxymore.practice.configuration.parse.Parser; import lombok.AllArgsConstructor; import org.bukkit.configuration.ConfigurationSection; import org.bukkit.configuration.file.YamlConfiguration; import java.util.ArrayList; import java.util.List; import java.util.Map; @AllArgsConstructor public class ViewConfiguration { public final int rows; public final String title; public final List<ViewPlaceholder> placeholders; public static class Deserialize implements Deserializer<ViewConfiguration> { @Override public ViewConfiguration deserialize(Parser parser, ConfigurationSection configuration, String _path) throws DeserializeException { final int rows = configuration.getInt("rows", 3); final String title = configuration.getString("title", ""); final List<ViewPlaceholder> placeholders = new ArrayList<>(); for (Map<?, ?> sectionMap : configuration.getMapList("layout")) { final ConfigurationSection viewSection = new YamlConfiguration().createSection("view", sectionMap); try { placeholders.add(parser.parse(ViewPlaceholder.class, viewSection)); } catch (Deserializer.DeserializeException e) { throw e.parent("could not parse layout"); } } return new ViewConfiguration(rows, title, placeholders); } } }
package Utils; import org.openqa.selenium.By; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.Select; import org.openqa.selenium.support.ui.WebDriverWait; public class Utils extends BrowserFactory { public static WebDriverWait wait; public static void selectByVisibleText(WebElement element, String value) { Select select = new Select(element); select.selectByVisibleText(value); } public static void waitForElementVisible(WebElement element,int time) { wait = new WebDriverWait(driver,AutomationConstants.timeout); wait.until(ExpectedConditions.visibilityOf(element)); } }
package service.member; import java.text.SimpleDateFormat; import javax.servlet.http.HttpServletRequest; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.stereotype.Service; import org.springframework.ui.Model; import command.member.MemberCommand; import model.dto.member.MemberDTO; import repository.member.MemberRepository; @Service public class MemberCreateService { @Autowired private MemberRepository memberRepository; @Autowired private BCryptPasswordEncoder bCryptPasswordEncoder; public String execute(MemberCommand memberCommand, HttpServletRequest request) { String result = null; MemberDTO dto = new MemberDTO(); SimpleDateFormat dt = new SimpleDateFormat("yyyy-MM-DD"); dto.setMemId(memberCommand.getUserId()); String memId = memberCommand.getUserId(); MemberDTO chk = memberRepository.idChk(memId); //중복 있어서 가입 불가 if(chk != null) { result = "0"; return result; //중복 없음 가입 가능 } else { dto.setMemId(memberCommand.getUserId()); dto.setMemPw(bCryptPasswordEncoder.encode(memberCommand.getUserPw())); dto.setMemName(memberCommand.getUserName()); dto.setMemEmail(memberCommand.getUserEmail()); dto.setMemAddr(memberCommand.getUserAddr()); dto.setMemTel(memberCommand.getUserPh()); dto.setMemIp(request.getRemoteAddr()); memberRepository.memInsert(dto); result = "1"; return result; } } //중복 체크 service public String idChkPop(HttpServletRequest request, String memId) { String result = null; MemberDTO dto = memberRepository.idChk(memId); System.out.println("중복체크 아이디입력값 체크 시작"); System.out.println("중복체크 아이디입력값 체크 값 : " + memId); System.out.println("체크 끝"); //중복되는 id 있음 -> 가입불가 if(dto != null) { result = "0"; return result; } //아이디 조회결과 아무것도없음 -> 중복안되므로 가입가능 else { result = "1"; return result; } } public void memberDetail(String userId,Model model) { MemberDTO dto = memberRepository.memberDetail(userId); model.addAttribute("detail",dto); } }
package classstructureio; import java.util.Scanner; public class Registration { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.println("Felhasználó regisztráció:"); System.out.println("Kérem adja meg a felhasználó nevét:"); String name= scanner.nextLine(); System.out.println("Kérem adja meg a felhasználó e-mail címét:"); String email= scanner.nextLine(); System.out.println("\nA regisztrációnál megadott adatok:"); System.out.println("Név: "+name); System.out.println("E-mail: "+email); } }
package com.cinema.sys.service; import java.util.List; import java.util.Map; import com.cinema.sys.model.Role; import com.cinema.sys.model.base.TRole; public interface RoleService { Role getDetail(String id); List<Role> getList(Map<String, Object> paraMap); /**获得全部角色*/ List<Role> getAllList(); boolean exist(String id,String name); int delete(String id); int insert(TRole t); int update(TRole t); }
package model; public class Mulher extends Usuario{ public Mulher(String nome) { super(nome); } public String saudacao() { return "Olá Sra. " + getNome(); } }
package demo; import akka.actor.Props; import akka.actor.UntypedAbstractActor; import akka.event.Logging; import akka.event.LoggingAdapter; public class MyActor extends UntypedAbstractActor{ // Logger attached to actor private final LoggingAdapter log = Logging.getLogger(getContext().getSystem(), this); public MyActor() {} // Static function creating actor public static Props createActor() { return Props.create(MyActor.class, () -> { return new MyActor(); }); } static public class Request { public final String data; public Request(String data) { this.data = data; } } static public class Response { public final String data; public Response(String data) { this.data = data; } } @Override public void onReceive(Object message) throws Throwable { if(message instanceof Request){ Request rq = (Request) message; log.info("["+getSelf().path().name()+"] received request from ["+ getSender().path().name() +"] with data: ["+rq.data+"]"); Response rp = new Response ("Response to " + rq.data); getSender().tell(rp, getSelf()); } if(message instanceof Response){ Response rp = (Response) message; log.info("["+getSelf().path().name()+"] received response from ["+ getSender().path().name() +"] with data: ["+rp.data+"]"); } } }
package com.WebLearning.fuckJdbc; public class TKDstudent { private String id; private String Name; private int times; TKDstudent(String id,String Name, int times) { this.id = id; this.Name = Name; this.times = times; } public String getId() { return id; } public void setId(String Id) { this.id = Id; } public String getName() { return Name; } public void setName(String Name) { this.Name = Name; } public void setTimes(int i){ this.times = i; } public int getTimes(){ return this.times; } }
package com.cinema.common.service.impl; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.cinema.common.dao.DataImportMapper; import com.cinema.common.model.ImportError; import com.cinema.common.service.DataimportService; @Service public class DataImportServiceImpl implements DataimportService{ @Autowired private DataImportMapper dataImportDao; @Override public List<ImportError> importFilm() { //先执行getImportError,再执行import,执行顺序不能相反 List<ImportError> list=dataImportDao.getImportErrorFilm_postgresql(); dataImportDao.importFilm(); return list; } }
/* AuDecoder.java Purpose: Description: History: Tue Jul 20 19:48:15 TST 2010, Created by tomyeh Copyright (C) 2010 Potix Corporation. All Rights Reserved. */ package org.zkoss.zk.au; import java.util.List; import org.zkoss.zk.ui.WebApp; import org.zkoss.zk.ui.Desktop; /** * Used to decode the custom format of the AU requests. * By default, the AU request is sent in the JSON format. * If you prefer to use another format, you have to do as follows. * <ul> * <li>Implement this interface to decode the custom format.</li> * <li>Register the implementation by specifying it in <code>WEB-INF/zk.xml</code></li> * <li>Override a JavaScript method called <a href="http://www.zkoss.org/javadoc/latest/jsdoc/_global_/zAu.html#encode%28int,%20zk.Event,%20zk.Desktop%29">zAu.encode()</a> * to encode to the custom format</li> * </ul> * @author tomyeh * @since 5.0.4 */ public interface AuDecoder { /** Returns the desktop ID. * @param request the request. For HTTP, it is HttpServletRequest. */ public String getDesktopId(Object request); /** Returns the first command. * It is called if a desktop is not found. * @param request the request. For HTTP, it is HttpServletRequest. */ public String getFirstCommand(Object request); /** Returns a list of {@link AuRequest} by decoding the request. * @param request the request. For HTTP, it is HttpServletRequest. */ public List decode(Object request, Desktop desktop); /** Returns if the request is ignorable when an error occurs. * If true is returned, the request is simply ignored. * Otherwise, an error message, depending on the configuration, * is sent to the client. */ public boolean isIgnorable(Object request, WebApp wapp); }
package psoft.backend.service; import org.springframework.stereotype.Service; import psoft.backend.dao.ComentarioDAO; import psoft.backend.exception.comentario.ComentarioDeleteException; import psoft.backend.exception.comentario.ComentarioInvalidoException; import psoft.backend.exception.comentario.ComentarioNotFoundException; import psoft.backend.exception.comentario.ComentarioNullException; import psoft.backend.exception.perfil.PerfilNotFoundException; import psoft.backend.model.Comentario; import psoft.backend.model.Perfil; import psoft.backend.model.User; import java.time.ZoneId; import java.time.ZonedDateTime; import java.time.format.DateTimeFormatter; import java.util.ArrayList; import java.util.List; @Service public class ComentarioService { private final ComentarioDAO comentarioDAO; public ComentarioService(ComentarioDAO comentarioDAO) { this.comentarioDAO = comentarioDAO; } public Comentario create(Perfil perfil, User user, String text, long comentarioId) { if (text == null) throw new ComentarioNullException("O comentário não pode ser Null"); if (text.trim().equals("")) throw new ComentarioInvalidoException("O comentário não pode ser vazio, insira um comentário valido"); if (user == null) throw new ComentarioNullException("O usuário não pode ser Null"); if (perfil == null) throw new ComentarioNullException("O perfil não pode ser Null"); String hora = ZonedDateTime.now(ZoneId.of("America/Sao_Paulo")).format(DateTimeFormatter.ofPattern("HH:mm")); String data = ZonedDateTime.now(ZoneId.of("America/Sao_Paulo")).format(DateTimeFormatter.ofPattern("dd/MM/yyyy")); Comentario comentario = new Comentario(perfil, user, text, hora, data, new ArrayList<Comentario>()); if (comentarioId == 0) { perfil.addComentario(comentario); } else { Comentario comentarioPai = findById(comentarioId); comentarioPai.addResposta(comentario); } return comentarioDAO.save(comentario); } public Comentario findById(long id) { Comentario comentario = comentarioDAO.findById(id); if (comentario == null) { throw new ComentarioNullException("Comentário não existe!"); } if (comentario.isApagado()) { throw new ComentarioDeleteException("Comentário apagado!"); } return comentario; } public List<Comentario> findAll() { List<Comentario> comentarios = comentarioDAO.findAll(); if (comentarios.isEmpty()) { throw new PerfilNotFoundException("Não há disciplinas cadastradas"); } return comentarios; } public Comentario deleteUpdate(long comentarioId, String userMail) { Comentario comentario = comentarioDAO.findById(comentarioId); if (comentario == null) { throw new ComentarioNotFoundException("Comentário não encontrado!!"); } if (!(comentario.getUser().getEmail().equals(userMail))) { throw new ComentarioDeleteException("Esse comentário não pertece ao usuário passado no token"); } comentario.setApagado(true); return comentarioDAO.save(comentario); } }
package com.dbanalyzer.commands; import com.db.persistence.remote_exception.QueryRemoteException; import com.db.persistence.scheme.BaseObject; import com.db.persistence.wsSoap.QueryRequestRemote; import com.db.persistence.wsSoap.QueryResponseRemote; import com.dbanalyzer.QuerySvcRemoteWrapper; import com.dronedb.persistence.scheme.Mission; import com.generic_tools.Pair.Pair; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import javax.annotation.PostConstruct; import java.util.*; @Component public class ShowMission implements RunnablePayload { @Autowired private QuerySvcRemoteWrapper querySvcRemote; private List<Pair<String, String>> usage; @PostConstruct public void init() { usage = new ArrayList<>(); usage.add(new Pair<>("ms","Show mission in DB")); usage.add(new Pair<>("mission","Show mission in DB")); } @Override public boolean isRelevant(String payload) { for (Pair pair : usage) { if (pair.getFirst().equals(payload)) return true; } return false; } @Override public List<Pair<String, String>> getUsage() { return usage; } @Override public String run(String payload) { String ans = ""; try { QueryRequestRemote queryRequestRemote = new QueryRequestRemote(); queryRequestRemote.setClz(Mission.class.getCanonicalName()); queryRequestRemote.setQuery("GetAllMissions"); QueryResponseRemote queryResponseRemote = querySvcRemote.query(queryRequestRemote); List<BaseObject> missionList = queryResponseRemote.getResultList(); ans += "Total Mission: " + missionList.size() + "\n"; for (BaseObject msn : missionList) { Mission mission = (Mission) msn; ans += "Mission Name: " + mission.getName() + "\n"; ans += "Default Alt: " + mission.getDefaultAlt() + "m" + "\n"; List<String> uids = mission.getMissionItemsUids(); ans += "Mission Items (" + uids.size() + "):" + "\n"; for (String uuid : uids) { // ResponseEntity<MissionItem> missionItemResponseEntity = objectCrudSvcRemote.read(uuid); // MissionItem missionItem = missionItemResponseEntity.getBody(); // System.out.println(missionItem.toString()); } ans += "\n"; } } catch (QueryRemoteException e) { ans += "ERROR: " + e.getMessage() + "\n"; } return ans; } }
package com.codegym.controller; import com.codegym.model.Customer; import com.codegym.model.Province; import com.codegym.service.ICustomerService; import com.codegym.service.ProvinceService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.web.PageableDefault; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.*; import org.springframework.web.servlet.ModelAndView; import java.util.Optional; @Controller @RequestMapping("/customer") public class CustomerController { @ModelAttribute(name = "provinces") public Iterable<Province> provinces() { return provinceService.findAll(); } @Autowired private ProvinceService provinceService; @Autowired private ICustomerService customerService; @GetMapping("/create") public ModelAndView create() { ModelAndView modelAndView = new ModelAndView("/customer/create"); modelAndView.addObject("customer", new Customer()); return modelAndView; } @PostMapping("/create") public ModelAndView create(@ModelAttribute Customer customer) { customerService.save(customer); return new ModelAndView("redirect:/customer"); } @GetMapping public ModelAndView index(@RequestParam(name = "q") Optional<String> q, @PageableDefault(size = 5) Pageable pageable) { Page<Customer> customerList; if (q.isPresent()) { customerList = customerService.findAllByFirstNameContaining(q.get(), pageable); } else { customerList = customerService.findAll(pageable); } ModelAndView modelAndView = new ModelAndView("/customer/index"); modelAndView.addObject("customerList", customerList); return modelAndView; } @GetMapping("/edit/{id}") public ModelAndView edit(@PathVariable Long id) { Optional<Customer> customer = customerService.findById(id); ModelAndView modelAndView; if (customer.isPresent()) { modelAndView = new ModelAndView("/customer/edit"); modelAndView.addObject("customer", customer.get()); } else { modelAndView = new ModelAndView("/error-404"); } return modelAndView; } @PostMapping("/edit/{id}") public ModelAndView edit(@ModelAttribute Customer customer) { customerService.save(customer); return new ModelAndView("redirect:/customer"); } @GetMapping("/delete/{id}") public ModelAndView delete(@PathVariable Long id) { Optional<Customer> customer = customerService.findById(id); ModelAndView modelAndView; if (customer.isPresent()) { modelAndView = new ModelAndView("/customer/delete"); modelAndView.addObject("customer", customer); } else { modelAndView = new ModelAndView("/error-404"); } return modelAndView; } @PostMapping("/delete/{id}") public ModelAndView delete(@ModelAttribute Customer customer) { customerService.remove(customer.getId()); return new ModelAndView("redirect:/customer"); } }
/** * Created by DELL on 2018/10/12. * * 用户态和内核态: * 用户态:通常指应用程序运行的环境。 * 内核态:操作系统运行的环境,可以用来操作硬件设备。 * 如果我们的应用程序需要操作内核态中的资源,比如关机操作,应用程序是无法直接做到的,需要通过内核态的操作系统完成, * 应用程序主要通过系统调用(系统调用:内核态给用户态开放的一个中断来实现的)向操作系统发送消息,来完成例如关机的操作。 * 那么,在用户态的应用程序通过系统调用操作内核态中资源的过程,其实就涉及到了,用户态到内核态再到用户态的一个切换过程。 * 用户态和内核态的切换过程相对只在用户态或只在内核态来说还是挺耗时的。 * *synchronized在jdk1.6之前,很重,主要重在多次的用户态到内核态的切换上, * 1.由于synchronized使用底层os互斥量实现,获取锁(无论成功与否)会切换一次内核态,获取这个互斥量。 * 2.当有竞争时,线程被挂起/阻塞,会涉及到用户态到内核态的一次切换。 * 3.当释放锁时,会涉及到一次用户态和内核态的切换,当线程被唤醒时同样也会涉及到内核切换。 * * 在1.6中对synchronized进行了优化,主要就是在减少用户态到内核态切换次数上下功夫。 * 在没有锁竞争的情况下,获取锁是不需要使用到互斥量的,而是修改锁对象上的标记字段来表示对象获取到锁。 * 只有在有竞争的情况下,才会使用到需要内核切换的重量级锁。 * * 在1.6进行优化后,针对不同的情况(线程的个数多少,是否存在竞争),对synchronized进行了不同的实现,实现的根本目的就是减少 * 内核切换的次数。 * 具体优化的的方式,主要对锁对象的标记字段(对象头的markword)来标记锁的状态。 * 偏向锁:主要针对自始至终只有一个线程进入同步代码快的情况。不涉及到内核切换。 * 轻量级锁:主要针对多个线程交替进入同步代码块(不存在重叠)的情况,具体工作流程: * 当进行加锁操作时,Java 虚拟机会判断是否已经是重量级锁。如果不是,它会在当前线程的当前栈 桢中划出一块空间,作为该锁的锁记录,并且将锁对象的标记字段复制到该锁记录中。 然后,Java 虚拟机会尝试用 CAS(compare-and-swap)操作替换锁对象的标记字段。这里解释 一下,CAS 是一个原子操作,它会比较目标地址的值是否和期望值相等,如果相等,则替换为一个 新的值。 假设当前锁对象的标记字段为 X…XYZ,Java 虚拟机会比较该字段是否为 X…X01。如果是,则替换 为刚才分配的锁记录的地址。由于内存对齐的缘故,它的最后两位为 00。此时,该线程已成功获得 这把锁,可以继续执行了。 如果不是 X…X01,那么有两种可能。第一,该线程重复获取同一把锁。此时,Java 虚拟机会将锁 记录清零(清零前,当前栈帧锁记录的值为复制锁对象标记字段的值,也就四当前线程的地址,栈帧 并不是该线程第一次获取锁的栈帧了, 清零也不是清第一次获取锁的那个栈帧),以代表该锁被重复获取。第二,其他线程持有该锁。此时,Java 虚拟机会将这把锁膨胀 为重量级锁,并且阻塞当前线程。 当进行解锁操作时,如果当前锁记录(你可以将一个线程的所有锁记录想象成一个栈结构,每次加 锁压入一条锁记录,解锁弹出一条锁记录,当前锁记录指的便是栈顶的锁记录)的值为 0,则代表 重复进入同一把锁,直接返回即可。 否则,Java 虚拟机会尝试用 CAS 操作,比较锁对象的标记字段的值是否为当前锁记录的地址。如 果是,则替换为锁记录中的值,也就是锁对象原本的标记字段。此时,该线程已经成功释放这把 锁。 如果不是,则意味着这把锁已经被膨胀为重量级锁。此时,Java 虚拟机会进入重量级锁的释放过 程,唤醒因竞争该锁而被阻塞了的线程 * * * * * */ package lock;
package com.syl.example.proxy; /** * Created by shenyunlong on 2017/4/22. */ public interface AppRegistry extends JavaScriptModule { void runApplication(String appKey); }
import java.util.Scanner; public class Homework21 { public static void main(String[] args) { Scanner input = new Scanner(System.in); int age1=30; int age2 = age1+=10; int age3 = 10; System.out.println("Enter your age"); age1 = input.nextInt(); System.out.println("Your age after " + age3 + " is " + age2); } } //age+10 /*Write a program that asks the user's age: "Enter your age " * Then display it by adding 10 (i.e age + 10) in your final output. Example Output: Enter your age 30 Your age after 10 years is 40 */
package com.gen.serve; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import junit.framework.TestCase; public class ValidateuserTest extends TestCase { public void test_type() throws Exception { // TODO auto-generated by JUnit Helper. assertNotNull(Validateuser.class); } public void test_instantiation() throws Exception { // TODO auto-generated by JUnit Helper. Validateuser target = new Validateuser(); assertNotNull(target); } public void test_doGet_A$HttpServletRequest$HttpServletResponse() throws Exception { // TODO auto-generated by JUnit Helper. Validateuser target = new Validateuser(); HttpServletRequest request = null; HttpServletResponse response = null; target.doGet(request, response); } public void test_doGet_A$HttpServletRequest$HttpServletResponse_T$ServletException() throws Exception { // TODO auto-generated by JUnit Helper. HttpServletRequest request = mock(HttpServletRequest.class); HttpServletResponse response = mock(HttpServletResponse.class); when(request.getParameter("password")).thenReturn("hello"); when(request.getParameter("username")).thenReturn("hello"); PrintWriter writer = new PrintWriter("somefile.txt"); when(response.getWriter()).thenReturn(writer); Validateuser target = new Validateuser(); try { target.doPost(request, response); } catch (ServletException e) { fail("UnExpected exception was thrown!"); } } public void test_doPost_A$HttpServletRequest$HttpServletResponse() throws Exception { // TODO auto-generated by JUnit Helper. HttpServletRequest request = mock(HttpServletRequest.class); HttpServletResponse response = mock(HttpServletResponse.class); when(request.getParameter("passwd")).thenReturn(""); when(request.getParameter("username")).thenReturn(""); PrintWriter writer = new PrintWriter("somefile.txt"); when(response.getWriter()).thenReturn(writer); Validateuser target = new Validateuser(); try { target.doPost(request, response); } catch (ServletException e) { fail("UnExpected exception was thrown!"); } } public void test_doPost_A$HttpServletRequest$HttpServletResponse_T$IOException() throws Exception { // TODO auto-generated by JUnit Helper. HttpServletRequest request = mock(HttpServletRequest.class); HttpServletResponse response = mock(HttpServletResponse.class); when(request.getParameter("password")).thenReturn("h1e2l3l4o"); when(request.getParameter("username")).thenReturn("hello"); PrintWriter writer = new PrintWriter("somefile.txt"); when(response.getWriter()).thenReturn(writer); Validateuser target = new Validateuser(); try { target.doPost(request, response); } catch (ServletException e) { fail("UnExpected exception was thrown!"); } } }
package com.example.trialattemptone.Creators; import android.content.ContentValues; import com.example.trialattemptone.database.CoursesTable; public class Course { private int courseId; private String courseTitle; private String courseStart; private String courseEnd; private int courseTermId; private int courseStatusID; private int mentorId; public Course() { } public Course(String titleString, String startDateString, String endDateString, int termId, int statusId, int mentorID) { this.courseTitle = titleString; this.courseStart = startDateString; this.courseEnd = endDateString; this.courseTermId = termId; this.courseStatusID = statusId; this.mentorId = mentorID; } public void setCourseId (int cId) { this.courseId = cId; } public int getCourseId() { return this.courseId; } public void setCourseTitle(String cTitle) { this.courseTitle = cTitle; } public String getCourseTitle() { return this.courseTitle; } public void setCourseStart(String cStart) { this.courseStart = cStart; } public String getCourseStart() { return this.courseStart; } public void setCourseEnd(String cEnd) { this.courseEnd = cEnd; } public String getCourseEnd() { return this.courseEnd; } public void setCourseTermId(int cTiD) { this.courseTermId = cTiD; } public int getCourseTermId() { return this.courseTermId; } public void setCourseStatusID(int csID) { this.courseStatusID = csID; } public int getCourseStatusId() { return this.courseStatusID; } public void setMentorId(int mId) { this.mentorId = mId; } public int getMentorId() { return this.mentorId; } public ContentValues toValues() { ContentValues values = new ContentValues(6); values.put(CoursesTable.COLUMN_NAME, courseTitle); values.put(CoursesTable.COLUMN_START, courseStart); values.put(CoursesTable.COLUMN_END, courseEnd); values.put(CoursesTable.COLUMN_TERM_ID, courseTermId); values.put(CoursesTable.COLUMN_COURSE_STATUS, courseStatusID); values.put(CoursesTable.COLUMN_COURSE_MENTOR_ID, mentorId); return values; } }
package de.mvbonline.tools.restapidoc; import de.mvbonline.tools.restapidoc.doclet.model.ApiDescription; import de.mvbonline.tools.restapidoc.model.Blacklist; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.core.io.Resource; import javax.xml.bind.JAXB; import java.io.IOException; /** * @author Markus M. May <m.may@mvb-online.de> */ public class BlacklistLoader { private Blacklist blacklist = new Blacklist(); private static BlacklistLoader loader = new BlacklistLoader(); private BlacklistLoader() { super(); try { loadBlacklist(); } catch (IOException e) { e.printStackTrace(); } } public static BlacklistLoader getInstance() { return loader; } private void loadBlacklist() throws IOException { ApplicationContext applicationContext = new AnnotationConfigApplicationContext(); Resource[] blacklistsRes = applicationContext.getResources("classpath*:/blacklist.xml"); blacklist = new Blacklist(); for (Resource blacklistRes : blacklistsRes) { Blacklist tmpBlacklist = JAXB.unmarshal(blacklistRes.getInputStream(), Blacklist.class); blacklist.getAnnotationsOnBlacklist().addAll(tmpBlacklist.getAnnotationsOnBlacklist()); blacklist.getClassesOnBlacklist().addAll(tmpBlacklist.getClassesOnBlacklist()); blacklist.getMethodsOnBlacklist().addAll(tmpBlacklist.getMethodsOnBlacklist()); blacklist.getFieldsOnBlacklist().addAll(tmpBlacklist.getFieldsOnBlacklist()); } } public boolean methodInBlacklist(String methodName) { return this.blacklist.getMethodsOnBlacklist().contains(methodName); } public boolean fieldInBlacklist(String fieldName) { return this.blacklist.getFieldsOnBlacklist().contains(fieldName); } public boolean classInBlacklist(String className) { return this.blacklist.getClassesOnBlacklist().contains(className); } public boolean annotationInBlacklist(String annotationName) { return this.blacklist.getAnnotationsOnBlacklist().contains(annotationName); } }
package org.dimigo.vaiohazard; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.InputMultiplexer; import com.badlogic.gdx.ScreenAdapter; import com.badlogic.gdx.audio.Music; import com.badlogic.gdx.graphics.GL20; import com.badlogic.gdx.graphics.OrthographicCamera; import com.badlogic.gdx.graphics.Texture; import com.badlogic.gdx.graphics.g2d.TextureAtlas; import com.badlogic.gdx.maps.tiled.TiledMap; import com.badlogic.gdx.maps.tiled.TiledMapRenderer; import com.badlogic.gdx.maps.tiled.TmxMapLoader; import com.badlogic.gdx.maps.tiled.renderers.OrthogonalTiledMapRenderer; import com.badlogic.gdx.scenes.scene2d.*; import com.badlogic.gdx.scenes.scene2d.ui.*; import org.dimigo.library.DialogGenerator; import org.dimigo.library.GameCoordinate; import org.dimigo.vaiohazard.Object.*; import com.badlogic.gdx.scenes.scene2d.InputEvent; import com.badlogic.gdx.scenes.scene2d.Stage; import com.badlogic.gdx.scenes.scene2d.ui.Button; import com.badlogic.gdx.scenes.scene2d.ui.Skin; import com.badlogic.gdx.scenes.scene2d.utils.ClickListener; import org.dimigo.library.NameGenerator; import org.dimigo.vaiohazard.Object.Customer; import org.dimigo.vaiohazard.conversation.Conversation; /** * Created by YuTack on 2015-11-09. */ public class GameScreen extends ScreenAdapter { VaioHazardGame currentGame; TiledMap tiledMap; TiledMapRenderer tiledMapRenderer; OrthographicCamera camera; Stage stage; UserInterface ui; Music music; boolean cleaned = false; public GameScreen(VaioHazardGame game) { this.currentGame = game; init(); } private void init() { stage = new Stage(); ServiceCenter.getInstance().setCurrentStage(stage); camera = new OrthographicCamera(); camera.setToOrtho(false, 1280, 720); camera.update(); tiledMap = new TmxMapLoader().load("resources/map.tmx"); tiledMapRenderer = new OrthogonalTiledMapRenderer(tiledMap); NameGenerator nameGenerator = NameGenerator.getInstance(); //ConversationParser parser = new ConversationParser(stage); Button newGameButton; Button.ButtonStyle buttonStyle; TextureAtlas buttonAtlas; Skin skin; Customer test = new Customer(nameGenerator.getName(), "mario.png", 4, 1); test.setPosition(100, 400); final Conversation conversation = new Conversation(stage, test); buttonStyle = new Button.ButtonStyle(); buttonStyle.up = GameResource.getInstance().getDrawable("new_button"); buttonStyle.down = GameResource.getInstance().getDrawable("new_button_pressed"); newGameButton = new Button(buttonStyle); newGameButton.addListener(new ClickListener() { @Override public void clicked(InputEvent event, float x, float y) { conversation.start(); } }); //stage.addActor(img); stage.addActor(newGameButton); ui = new UserInterface(); //stage.addActor(mario); stage.addActor(test); stage.addActor(ui); } @Override public void show() { Gdx.input.setCatchMenuKey(true); Gdx.input.setCatchBackKey(true); InputMultiplexer inputMultiplexer = new InputMultiplexer(); inputMultiplexer.addProcessor(stage); Gdx.input.setInputProcessor(inputMultiplexer); Image clerkTester = new Image(new Texture("resources/Actor/Creeper.png")); clerkTester.setScale(0.6f, 0.6f); clerkTester.setPosition(GameCoordinate.toRealPos(105), GameCoordinate.toRealPos(105)); music = Gdx.audio.newMusic(Gdx.files.internal("resources/music/game.mp3")); music.setLooping(true); music.setVolume(0.7f); music.play(); ServiceCenter.getInstance().updateDate(); stage.addActor(clerkTester); } @Override public void render(float delta) { if(cleaned == true) { stage.setDebugAll(false); } if(cleaned == false) { stage.setDebugAll(true); cleaned = true; } Gdx.gl.glClearColor(92 / 255f, 167 / 255f, 244 / 255f, 1); Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT); stage.act(delta); ServiceCenter.getInstance().update(delta); camera.update(); tiledMapRenderer.setView(camera); tiledMapRenderer.render(); stage.draw(); } }
public class ReportBatchController { public ReportBatchController(){} public String theTerms { get;set; } public String theFilter { get;set; } public String theAddresses { get;set; } public ReportBatchController(String a, String b, String c){ this.theTerms = a; this.theFilter = b; this.theAddresses = c; } public PageReference action(){ database.executebatch(new ReportBatch(theTerms, theFilter, theAddresses), 10000); return null; } }
package com.example.smdemo1.aop; import javax.servlet.http.HttpServletRequest; import java.lang.reflect.Method; import java.util.Date; import com.example.smdemo1.annoation.OperLog; import com.example.smdemo1.dao.Log; import org.aspectj.lang.JoinPoint; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.Signature; import org.aspectj.lang.annotation.After; import org.aspectj.lang.annotation.AfterReturning; import org.aspectj.lang.annotation.AfterThrowing; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Before; import org.aspectj.lang.annotation.Pointcut; import org.aspectj.lang.reflect.MethodSignature; import org.springframework.stereotype.Component; import org.springframework.web.context.request.RequestContextHolder; import org.springframework.web.context.request.ServletRequestAttributes; /** * @author xp-dc * @date 2018/12/26 */ @Aspect @Component public class OperationLogAop { //获取开始时间 private Date actionStartDate; //获取结束时间 private Date actionEndDate; //定义log实体 private Log log = new Log(); //@Pointcut("execution(* com.example.smdemo1.controller.*.*(..))") @Pointcut("@annotation(com.example.smdemo1.annoation.OperLog)") //@Pointcut("@annotation(com.example.smdemo1.annoation.Log)") private void controllerAspect(){} /** * 方法开始执行 */ @Before("controllerAspect()") public void doBefore(){ actionStartDate = new Date(); System.out.println("开始:"+actionStartDate); } /** * 方法执行结束 */ @After("controllerAspect()") public void after(JoinPoint pjp){ //拦截的实体类,就是当前正在执行的controller Object target = pjp.getTarget(); //拦截的放参数类型 Signature signature = pjp.getSignature(); //拦截的方法名称,就是当前执行的方法 String methodName = signature.getName(); //拦截的方法参数 Object[] args = pjp.getArgs(); MethodSignature msig = null; if(!(signature instanceof MethodSignature)){ throw new IllegalArgumentException("该注解只能用于方法"); } msig = (MethodSignature) signature; Class[] parameterTypes = msig.getMethod().getParameterTypes(); Object object = null; Method method = null; try{ method = target.getClass().getMethod(methodName, parameterTypes); }catch(NoSuchMethodException e){ e.printStackTrace(); }catch(SecurityException e1){ e1.printStackTrace(); } if(null != method){ //判断是否包含自定义的注解 if(method.isAnnotationPresent(OperLog.class)){ OperLog operLog = method.getAnnotation(OperLog.class); log.setModule(operLog.module()); } } actionEndDate = new Date(); System.out.println("结束:"+actionEndDate); } /** * 方法执行结束后的操作 */ @AfterReturning("controllerAspect()") public void doAfter(JoinPoint pjp) { //拦截的实体类,就是当前正在执行的controller Object target = pjp.getTarget(); //拦截的放参数类型 Signature signature = pjp.getSignature(); //拦截的方法名称,就是当前执行的方法 String methodName = signature.getName(); //拦截的方法参数 Object[] args = pjp.getArgs(); MethodSignature msig = null; if(!(signature instanceof MethodSignature)){ throw new IllegalArgumentException("该注解只能用于方法"); } msig = (MethodSignature) signature; Class[] parameterTypes = msig.getMethod().getParameterTypes(); Object object = null; Method method = null; try{ method = target.getClass().getMethod(methodName, parameterTypes); }catch(NoSuchMethodException e){ e.printStackTrace(); }catch(SecurityException e1){ e1.printStackTrace(); } if(null != method){ //判断是否包含自定义的注解 if(method.isAnnotationPresent(OperLog.class)){ OperLog operLog = method.getAnnotation(OperLog.class); log.setModule(operLog.module()); } } if(log.getState() >= 0){ log.setActionStartDate(actionStartDate); log.setActionEndDate(actionEndDate); System.out.println(log); System.out.println(">>>>>>>>>>>>>存入log数据库"); }else{ System.out.println(log); System.out.println("<<<<<<<<<<<<<<不存入log数据库"); } } /** * 方法有异常操作 */ @AfterThrowing("controllerAspect()") public void doAfterThrow(){ if(log.getState() == 2){ log.setActionStartDate(actionStartDate); log.setActionEndDate(actionEndDate); System.out.println(log); System.out.println(">>>>>>>>>>>>>存入log数据库"); }else{ System.out.println(log); System.out.println("<<<<<<<<<<<<<<不存入log数据库"); } } @Around("controllerAspect()") public Object around(ProceedingJoinPoint pjp){ //日志实体对象 HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest(); //获取当前登录用户信息 //todo //String userName = null; //拦截的实体类,就是当前正在执行的controller Object target = pjp.getTarget(); //拦截的放参数类型 Signature signature = pjp.getSignature(); //拦截的方法名称,就是当前执行的方法 String methodName = signature.getName(); //拦截的方法参数 Object[] args = pjp.getArgs(); MethodSignature msig = null; if(!(signature instanceof MethodSignature)){ throw new IllegalArgumentException("该注解只能用于方法"); } msig = (MethodSignature)signature; Class[] parameterTypes = msig.getMethod().getParameterTypes(); Object object = null; Method method = null; try{ method = target.getClass().getMethod(methodName, parameterTypes); }catch(NoSuchMethodException e){ e.printStackTrace(); }catch(SecurityException e1){ e1.printStackTrace(); } if(null != method){ //判断是否包含自定义的注解 if(method.isAnnotationPresent(OperLog.class)){ OperLog operLog = method.getAnnotation(OperLog.class); log.setModule(operLog.module()); log.setMethod(operLog.method()); log.setIp(getIp(request)); log.setUrl(request.getRequestURI()); try{ object = pjp.proceed(); log.setDesc("执行成功"); log.setState(0); }catch(Throwable e){ log.setDesc("执行失败"); log.setState(1); } }else{ //没有包含注解 try{ object = pjp.proceed(); log.setDesc("此操作不包含注解,执行成功"); log.setState(0); }catch(Throwable e){ log.setDesc("此操作不包含注解,执行失败"); log.setState(1); } } }else{ //不需要拦截直接执行 try{ object = pjp.proceed(); log.setDesc("不需要拦截直接执行,执行成功"); log.setState(0); }catch(Throwable e){ log.setDesc("不需要拦截直接执行,执行失败"); log.setState(1); } } return object; } private String getIp(HttpServletRequest request){ String ip = request.getHeader("x-forwarded-for"); if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)){ ip = request.getHeader("Proxy-Client-IP"); } if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)){ ip = request.getHeader("WL-Proxy-Client-IP"); } if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)){ ip = request.getRemoteAddr(); } return ip; } }
package com.jd.bdp.hdfs.mergefiles; import com.hadoop.compression.lzo.DistributedLzoIndexer; import com.hadoop.compression.lzo.LzopCodec; import com.jd.bdp.hdfs.mergefiles.exception.UnsupportedTypeException; import com.jd.bdp.hdfs.mergefiles.mapreduce.MergeFilesMapper; import com.jd.bdp.hdfs.mergefiles.mapreduce.MergePath; import com.jd.bdp.hdfs.mergefiles.mapreduce.OrcMergeFilesMapper; import com.jd.bdp.hdfs.mergefiles.mapreduce.lib.*; import com.jd.bdp.utils.LogHelper; import com.jd.bdp.utils.Utils; import org.apache.avro.mapreduce.AvroKeyInputFormat; import org.apache.avro.mapreduce.AvroKeyValueOutputFormat; import org.apache.commons.lang.exception.ExceptionUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FSDataOutputStream; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.hive.ql.io.CombineHiveInputFormat; import org.apache.hadoop.hive.ql.io.orc.OrcOutputFormat; import org.apache.hadoop.io.NullWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapred.JobClient; import org.apache.hadoop.mapred.JobConf; import org.apache.hadoop.mapred.JobPriority; import org.apache.hadoop.mapred.RunningJob; import org.apache.hadoop.mapreduce.Counter; import org.apache.hadoop.mapreduce.Job; import org.apache.hadoop.mapreduce.JobStatus; import org.apache.hadoop.mapreduce.lib.input.FileInputFormat; import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat; import org.apache.hadoop.mapreduce.lib.output.TextOutputFormat; import org.apache.hadoop.util.ToolRunner; import java.io.IOException; import java.util.concurrent.atomic.AtomicLong; /** * TaskRunner implementation. */ public class TaskRunner extends Thread { private final static Log log = LogFactory.getLog(TaskRunner.class); private final LogHelper console; private final String PREFIX; protected Job job; private String jobId; private MergePath mergePath; private Path input; private Path output; private Path targetPath; private FileType inputType; private FileType outputType; protected int result; protected Exception exception; protected boolean isRunning; private JobStatus.State jobstatus; private MergeContext context; private Configuration conf; private FileSystem fs; private FSDataOutputStream out; private static AtomicLong taskCounter = new AtomicLong(0); private static ThreadLocal<Long> taskRunnerID = new ThreadLocal<Long>() { @Override protected Long initialValue() { return taskCounter.incrementAndGet(); } }; protected Thread runner; public TaskRunner(MergePath mergePath, MergeContext context) throws IOException { setRunning(true); this.mergePath = mergePath; this.input = mergePath.getPath(); this.output = new Path(mergePath.getTmpDir().getParent(), mergePath.getTmpDir().getName() + "_merge"); this.inputType = mergePath.getType(); this.outputType = mergePath.getType(); this.context = context; this.console = new LogHelper(log, true); this.PREFIX = "[" + input + "]Merge Task===>"; this.conf = new Configuration(); this.fs = FileSystem.get(conf); this.out = fs.create(new Path(mergePath.getLogDir(), "error.log")); if (Config.getMergeTargePath() != null) { targetPath = new Path(Utils.cutSuffix(Config.getMergeTargePath().toString(), "/") + Path.getPathWithoutSchemeAndAuthority(input)); fs.mkdirs(targetPath); } else { targetPath = input; } } public String getJobId() { return jobId; } public void setJobId(String jobId) { this.jobId = jobId; } public String getPREFIX() { return PREFIX; } public MergePath getMergePath() { return mergePath; } public Path getTargetPath() { return targetPath; } public void setTargetPath(Path targetPath) { this.targetPath = targetPath; } public FileType getInputType() { return inputType; } public void setInputType(FileType inputType) { this.inputType = inputType; } public FileType getOutputType() { return outputType; } public void setOutputType(FileType outputType) { this.outputType = outputType; } public Exception getException() { return exception; } public void setException(Exception exception) { this.exception = exception; } public Path getInput() { return input; } public void setInput(Path input) { this.input = input; } public Path getOutput() { return output; } public void setOutput(Path output) { this.output = output; } public JobStatus.State getJobstatus() { return jobstatus; } public void setJobstatus(JobStatus.State jobstatus) { this.jobstatus = jobstatus; } public Job getJob() { return job; } public void setJob(Job job) { this.job = job; } public int getResult() { return result; } public void setResult(int result) { this.result = result; } public boolean isRunning() { return isRunning; } public void setRunning(boolean isRunning) { this.isRunning = isRunning; } @Override public void run() { runner = Thread.currentThread(); try { result = runMergeJob(input, output); } finally { runner = null; setRunning(false); } } /** * 启动合并job */ public int runMergeJob(Path input, Path output) { try { console.printInfo("Start Merge(" + getTaskRunnerID() + "/" + context.getTotal() + "): " + input + " ,Type:" + inputType); conf.set("mapreduce.job.priority", JobPriority.VERY_HIGH.name()); conf.set("mapred.job.priority", JobPriority.VERY_HIGH.name()); conf.setInt("mapreduce.job.max.split.locations", Integer.MAX_VALUE); conf.setBoolean("mapreduce.map.speculative", false); //关闭推测执行,防止写文件冲突 conf.setLong("mapreduce.input.fileinputformat.split.minsize.per.node", Config.getMergeMaxSize()); conf.setLong("mapreduce.input.fileinputformat.split.maxsize", Config.getMergeMaxSize()); conf.setLong("mapreduce.input.fileinputformat.split.minsize.per.rack", Config.getMergeMaxSize()); Job job = null; JobConf jobconf = null; if (isOldMR(inputType)) { jobconf = new JobConf(conf, TaskRunner.class); jobconf.setJobName("MergeFiles:" + input); } else { job = Job.getInstance(conf, "MergeFiles:" + input); job.setJarByClass(TaskRunner.class); } //根据文件类型选择输入输出类型 if (inputType.equals(FileType.TEXT)) { job.setInputFormatClass(CombineMergeTextInputFormat.class); job.setOutputFormatClass(TextOutputFormat.class); } else if (inputType.equals(FileType.LZO)) { job.setInputFormatClass(CompressedCombineFileInputFormat.class); conf.set("io.compression.codecs", "com.hadoop.compression.lzo.LzopCodec"); FileOutputFormat.setCompressOutput(job, true); FileOutputFormat.setOutputCompressorClass(job, LzopCodec.class); } else if (inputType.equals(FileType.ORC)) { jobconf.setInputFormat(CombineMergeOrcInputFormat.class); jobconf.setOutputFormat(NoOutputFormat.class); } else if (inputType.equals(FileType.AVRO)) { job.setInputFormatClass(AvroKeyInputFormat.class); job.setOutputFormatClass(AvroKeyValueOutputFormat.class);//todo throw new UnsupportedTypeException(); } else if (inputType.equals(FileType.UNKNOWN)) { throw new UnsupportedTypeException("UnKnow file type.If you make sure it is a text format.add -t run this path[" + input + "] again."); } int res = 0; Counter mapInput; Counter mapOutput; if (isOldMR(inputType)) { jobconf.setMapOutputValueClass(NullWritable.class); jobconf.setOutputValueClass(NullWritable.class); jobconf.setMapperClass(OrcMergeFilesMapper.class); jobconf.setMapOutputKeyClass(NullWritable.class); jobconf.setOutputKeyClass(NullWritable.class); jobconf.setNumReduceTasks(0); OrcFileStripeMergeInputFormat.setInputPaths(jobconf, input); OrcOutputFormat.setOutputPath(jobconf, output); RunningJob rj = JobClient.runJob(jobconf); setJobId(rj.getID().toString()); mapInput = rj.getCounters().findCounter(("org.apache.hadoop.mapreduce.TaskCounter"), "MAP_INPUT_RECORDS"); mapOutput = rj.getCounters().findCounter(("org.apache.hadoop.mapreduce.TaskCounter"), "MAP_OUTPUT_RECORDS"); setJobstatus(rj.getJobStatus().getState()); } else { job.setMapOutputValueClass(Text.class); job.setOutputValueClass(Text.class); job.setMapperClass(MergeFilesMapper.class); job.setMapOutputKeyClass(NullWritable.class); job.setOutputKeyClass(NullWritable.class); job.setNumReduceTasks(0); FileInputFormat.setInputPaths(job, input); FileOutputFormat.setOutputPath(job, output); res = job.waitForCompletion(true) ? 0 : 1; setJobId(job.getJobID().toString()); // 开始moveTask mapInput = job.getCounters().findCounter(("org.apache.hadoop.mapreduce.TaskCounter"), "MAP_INPUT_RECORDS"); mapOutput = job.getCounters().findCounter(("org.apache.hadoop.mapreduce.TaskCounter"), "MAP_OUTPUT_RECORDS"); setJobstatus(job.getJobState()); } if (res == 0 && jobstatus.equals(JobStatus.State.SUCCEEDED)) { console.printInfo(this.PREFIX + "Merge Job finished successfully"); //创建索引 int exitCode = 1; if (inputType.equals(FileType.LZO)) { console.printInfo(PREFIX + "Start build Lzo Index..."); exitCode = ToolRunner.run(new DistributedLzoIndexer(), new String[]{output.toString()}); if (exitCode != 0) { console.printError(PREFIX + "build Lzo Index Failed"); throw new Exception(PREFIX + "build Lzo Index Failed,exitCode:" + exitCode); } } if (mapInput != null) { mergePath.setMapInput(mapInput.getValue()); } if (mapOutput != null) { mergePath.setMapOutput(mapOutput.getValue()); } if (mergePath.getMapInput() != mergePath.getMapOutput()) { console.printError(this.PREFIX + " mapInput Records not equals mapOutput Records."); throw new Exception(this.PREFIX + " mapInput Records not equals mapOutput Records.MapInput Records:" + mergePath.getMapInput() + ",MapOutputRecords:" + mergePath.getMapOutput()); } //备份原数据到tmpDir目录 Path moveLog = new Path(mergePath.getLogDir(), "mv.log"); console.printInfo(this.PREFIX + "Start move file:" + targetPath + " to " + mergePath.getTmpDir()); FSDataOutputStream out = fs.create(moveLog); out.writeBytes("JobId: " + jobId + "\n"); out.writeBytes("move " + targetPath + " to " + mergePath.getTmpDir() + "\n"); fs.rename(targetPath, mergePath.getTmpDir()); console.printInfo(this.PREFIX + "move file:" + targetPath + " to " + mergePath.getTmpDir() + " success"); console.printInfo(this.PREFIX + "Start move file:" + output + " to " + targetPath); fs.rename(output, targetPath); out.writeBytes("move " + output + " to " + targetPath + "\n"); console.printInfo(this.PREFIX + "move file " + output + " to " + targetPath + " success"); out.close(); } return res; } catch (Exception e) { exception = e; return 200; } finally { try { fs.delete(new Path(input, ".stage"),true); fs.delete(new Path(getTargetPath(), "_SUCCESS"), true); } catch (IOException e) { log.warn("delete tmp .stage failed."); try { errorRecorder("delete tmp .stage Path [" + new Path(input, ".stage") + "] failed."); } catch (IOException e1) { } } } } public void errorRecorder(String msg) throws IOException { out.writeBytes(msg + "\n"); } public void shutdown() { try { out.close(); } catch (IOException e) { console.printError(ExceptionUtils.getFullStackTrace(e)); } } public static long getTaskRunnerID() { return taskRunnerID.get(); } public static boolean isOldMR(FileType type) { return type.equals(FileType.ORC); } }
/* * Copyright 2019 Red Hat, Inc. and/or its affiliates. * * 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.kie.workbench.common.dmn.backend.editors.common; import org.junit.Before; import org.junit.Test; import org.kie.workbench.common.dmn.api.definition.v1_1.DRGElement; import org.kie.workbench.common.dmn.api.definition.v1_1.Decision; import org.kie.workbench.common.dmn.api.editors.included.DMNIncludedModel; import org.kie.workbench.common.dmn.api.editors.included.DMNIncludedNode; import org.kie.workbench.common.dmn.api.property.dmn.Id; import org.kie.workbench.common.dmn.api.property.dmn.Name; import org.uberfire.backend.vfs.Path; import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public class DMNIncludedNodeFactoryTest { private DMNIncludedNodeFactory factory; @Before public void setup() { factory = new DMNIncludedNodeFactory(); } @Test public void testMakeDMNIncludeModel() { final Path path = mock(Path.class); final DMNIncludedModel includedModel = mock(DMNIncludedModel.class); final String expectedId = "0000-1111-3333-4444"; final String expectedDrgElementName = "Can Drive?"; final String expectedFileName = "file.dmn"; final String expectedModelName = "model"; final String expectedImportedElementId = "model:0000-1111-3333-4444"; final DRGElement importedElementId = makeDecision(expectedId, expectedDrgElementName); when(path.getFileName()).thenReturn(expectedFileName); when(includedModel.getModelName()).thenReturn(expectedModelName); final DMNIncludedNode node = factory.makeDMNIncludeModel(path, includedModel, importedElementId); assertEquals(expectedId, node.getDrgElementId()); assertEquals(expectedDrgElementName, node.getDrgElementName()); assertEquals(expectedImportedElementId, node.getImportedElementId()); assertEquals(expectedFileName, node.getFileName()); assertEquals(expectedModelName, node.getModelName()); assertEquals(Decision.class, node.getDrgElementClass()); } private Decision makeDecision(final String id, final String name) { final Decision decision = new Decision(); decision.setId(new Id(id)); decision.setName(new Name(name)); return decision; } }
package org.giddap.dreamfactory.leetcode.onlinejudge; /** * http://leetcode.com/onlinejudge#question_43 * <p/> * Given two numbers represented as strings, return multiplication of the numbers as a string. * <p/> * Note: The numbers can be arbitrarily large and are non-negative. * <p/> * Links: * http://discuss.leetcode.com/questions/221/multiply-strings */ public interface MultiplyStrings { String multiply(String num1, String num2); }
package hello; public class ClassAndObject { String name; double speed; int gear; static String copyright; public ClassAndObject() { System.out.println("construct method" + this); } public ClassAndObject(String name) { this.name = name; } public ClassAndObject(String name,double speed){ this(name); this.speed = speed; } public static void start(){ System.out.println("engine start"); } public void setName(String name) { name = name; } public void setName2(String classname){ name = classname; } public void setName3(String name){ this.name = name; } public static void main(String[] args) { // TODO Auto-generated method stub new ClassAndObject(); ClassAndObject co = new ClassAndObject(); ClassAndObject co1 = co; ClassAndObject co2 = co; //co,co1,co2三个引用,都指向同一个对象 ClassAndObject occ = new ClassAndObject(); occ = new ClassAndObject(); //一个引用,同一时间只能指向一个对象 ClassAndObject occ1 = new ClassAndObject("haha"); // ClassAndObject occ2 = new ClassAndObject(); 提供有参构造方法后,无参的就不能使用了 occ1.setName("a"); System.out.println(occ1.name); occ1.setName2("b"); System.out.println(occ1.name); occ1.setName3("c"); System.out.println(occ1.name); ClassAndObject.copyright = "bob"; ClassAndObject.start(); } }
package es.zamorano.popularmovielist.ui; import android.content.res.Resources; import android.os.Bundle; import android.support.design.widget.FloatingActionButton; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.GridLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.View; import com.androidnetworking.AndroidNetworking; import com.androidnetworking.common.Priority; import com.androidnetworking.error.ANError; import com.androidnetworking.interfaces.JSONObjectRequestListener; import com.google.gson.Gson; import org.json.JSONObject; import java.util.List; import butterknife.BindView; import butterknife.ButterKnife; import es.zamorano.popularmovielist.R; import es.zamorano.popularmovielist.models.Movie; import io.realm.Realm; public class MainActivity extends AppCompatActivity { public static final String API_KEY = "b66ffea8276ce576d60df52600822c88"; @BindView(R.id.rv_movies) RecyclerView mRecyclerView; @BindView(R.id.fab_main_activity) FloatingActionButton mFab; private MoviesAdapter mMovieAdapter; private Realm mRealm; private List<Movie> mMovieFavouriteList; private Boolean favorite = true; private Movie.MovieList responseArray; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ButterKnife.bind(this); Realm.init(getApplicationContext()); mRealm = Realm.getDefaultInstance(); mRecyclerView.setLayoutManager(new GridLayoutManager(this, 3)); mMovieAdapter = new MoviesAdapter(this); mRecyclerView.setAdapter(mMovieAdapter); loadMovies(); mFab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (favorite) { mMovieFavouriteList = mRealm.copyFromRealm(mRealm.where(Movie.class).findAll()); mMovieAdapter.setMovieList(mMovieFavouriteList); mFab.setImageResource(R.drawable.ic_favorite); } else { mMovieAdapter.setMovieList(responseArray.getResults()); mFab.setImageResource(R.drawable.ic_favorite_border); } favorite = !favorite; } }); } public void loadMovies() { AndroidNetworking.get("https://api.themoviedb.org/3/movie/popular?api_key=" + API_KEY + "&language=" + Resources.getSystem().getConfiguration().locale.getLanguage()) .setPriority(Priority.HIGH) .build() .getAsJSONObject(new JSONObjectRequestListener() { @Override public void onResponse(JSONObject response) { Gson gson = new Gson(); responseArray = gson.fromJson(response.toString(), Movie.MovieList.class); //In the responseArray, we have only the first page of the films, in the future, could be nice add an OnScrollListener and load the next page mMovieAdapter.setMovieList(responseArray.getResults()); } @Override public void onError(ANError anError) { } }); } @Override protected void onDestroy() { super.onDestroy(); mRealm.close(); } }
package com.esum.web.monitor.dao; import java.util.HashMap; import java.util.List; import java.util.Map; import com.esum.appetizer.dao.AbstractDao; import com.esum.appetizer.util.PageUtil; import com.esum.web.monitor.vo.MonVmStatus; import com.esum.web.monitor.vo.MonVmStatusSearch; public class MonVmStatusDao extends AbstractDao { public List<MonVmStatus> selectList(MonVmStatusSearch monVmStatusSearch, PageUtil pu) { Map<String, Object> paramMap = new HashMap<String, Object>(); paramMap.put("sDate", monVmStatusSearch.getStartDate()); paramMap.put("eDate", monVmStatusSearch.getEndDate()); paramMap.put("searchValueNode", monVmStatusSearch.getSearchValueNode()); paramMap.put("startRow", pu.getStartRow()); paramMap.put("endRow", pu.getEndRow()); return getSqlSession().selectList("monVmStatus.selectList", paramMap); } public int count(MonVmStatusSearch monVmStatusSearch) { Map<String, Object> paramMap = new HashMap<String, Object>(); paramMap.put("sDate", monVmStatusSearch.getStartDate()); paramMap.put("eDate", monVmStatusSearch.getEndDate()); paramMap.put("searchValueNode", monVmStatusSearch.getSearchValueNode()); return (Integer)getSqlSession().selectOne("monVmStatus.countList", paramMap); } public List<MonVmStatus> selectUsageList(String nodeId, String sDate, String eDate) { Map<String, Object> paramMap = new HashMap<String, Object>(); paramMap.put("sDate", sDate); paramMap.put("eDate", eDate); paramMap.put("nodeId", nodeId); return getSqlSession().selectList("monVmStatus.selectUsageList", paramMap); } }
package com.zhicai.byteera.activity.community.dynamic.entity; import org.litepal.crud.DataSupport; import java.io.Serializable; /** Created by bing on 2015/5/29. */ public class ImgEntity extends DataSupport implements Serializable { private String imgUrl; private int dynamicitementity_id; public ImgEntity() { } public int getDynamicitementity_id() { return dynamicitementity_id; } public void setDynamicitementity_id(int dynamicitementity_id) { this.dynamicitementity_id = dynamicitementity_id; } public String getImgUrl() { return imgUrl; } public void setImgUrl(String imgUrl) { this.imgUrl = imgUrl; } }
package jianzhioffer; /** * @ClassName : Solution42 * @Description : 连续子数组的最大和 * 基于数组中有正有负的情况,不然,如果同号,那么就直接排序取最小,不存在连续最大和的问题 * @Date : 2019/9/19 19:51 */ public class Solution42 { public int FindGreatestSumOfSubArray(int[] array) { if (array==null || array.length==0) return 0; int max=Integer.MIN_VALUE; int cur=0; for (int x:array){ if (cur<=0) cur=x; else cur+=x; max=Math.max(cur,max); } return max; } }
package Algorithm.March; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.StringTokenizer; public class tweentyThree { public static void main(String[] args) throws IOException{ //1978(¼Ò¼ö ã±â) answer_1978(); } private static void answer_1978() throws IOException{ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int cnt = Integer.parseInt(br.readLine()); int count = 0; StringTokenizer st = new StringTokenizer(br.readLine(), " "); for(int i=0;i<cnt;i++) { int num = Integer.parseInt(st.nextToken()); if(num == 1) { continue; } for(int j=2;j<Math.sqrt(num);j++) { if(num%j==0) { break; } } count++; } System.out.print(count); } }
package com.xx.base.project.util.file; /** * 文件名称常量 * Created by lixingxing on 2019/6/11. */ public class ProFileConfig { public static void init(String APP_ROOT_DIRs, String SHAREPREFERENCESs){ APP_ROOT_DIR = APP_ROOT_DIRs; SHAREPREFERENCES = SHAREPREFERENCESs; } /** * 默认 APP SharedPreferences文件夹路径 */ public static String SHAREPREFERENCES = "xbaseframex_default"; /** * 默认APP文件目录 **/ public static String APP_ROOT_DIR = "xbaseframex"; /** * 默认APP下载根目录. */ public static String DOWNLOAD_ROOT_DIR = "download"; /** * 默认下载图片文件地址. */ public static String DOWNLOAD_IMAGE_DIR = "images"; /** * 默认下载文件地址. */ public static String DOWNLOAD_FILE_DIR = "files"; /** * 默认放置临时文件目录 */ public static String FILE_TEMPORARY_DIR = "temporary"; /** * APP缓存目录. */ public static String CACHE_DIR = "cache"; /** * DB目录. */ public static String DB_DIR = "db"; }
package com.zpf.dto; import org.springframework.data.jpa.repository.JpaRepository; import java.util.List; /** * Created by LoseMyself * on 2017/3/13 14:03 */ // 对象类型,主键类型 public interface girlRepository extends JpaRepository<girl,Long> { public List<girl> findByAge(Long age); }
/** * @author Duc Minh Le (s3651764) */ public class Util { public static String[] splitAndTrimTokens(String s, String regex) { String[] tokens = s.split(regex); for (int i = 0; i < tokens.length; i++) { tokens[i] = tokens[i].trim(); } return tokens; } }
package com.example.myapplication.circle; import android.content.ContentValues; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.database.sqlite.SQLiteDatabase; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import android.widget.Toast; import androidx.annotation.NonNull; import androidx.recyclerview.widget.RecyclerView; import com.example.myapplication.R; import com.example.myapplication.SqlHelper; import java.util.List; import static android.content.Context.MODE_PRIVATE; public class CircleRecycleAdapter extends RecyclerView.Adapter<CircleRecycleAdapter.myHolder> { private Context context; private List<CircleInfo> menuInfos; public CircleRecycleAdapter(Context context, List<CircleInfo> menuInfos) { this.context = context; this.menuInfos = menuInfos; } @NonNull @Override public myHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.circle_item, parent, false); final myHolder myHolder = new myHolder(view); return myHolder; } @Override public void onBindViewHolder(@NonNull final myHolder myHolder, final int position) { myHolder.show_username.setText(menuInfos.get(position).username); myHolder.show_time.setText(menuInfos.get(position).time); myHolder.show_content.setText(menuInfos.get(position).content); myHolder.show_comment_number.setText("回答" + menuInfos.get(position).discuss_number); myHolder.click_show_number.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { SharedPreferences sp = context.getSharedPreferences("CurrentLogin", MODE_PRIVATE); String LoginUserName = sp.getString("username", "none"); Intent intent = new Intent(context, WriteAnswerActivity.class); //flag: 0:回复发帖人 1:回复其他的人 // intent.putExtra("flag", 0); intent.putExtra("circle_id", menuInfos.get(position).id); intent.putExtra("reply_people_name", menuInfos.get(position).username); context.startActivity(intent); } }); if (menuInfos.get(position).IsFav == 1) { myHolder.show_favourite.setImageResource(R.drawable.ic_favorite_black_24dp); myHolder.show_fav_state.setText("已收藏"); myHolder.click_to_fav.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { SharedPreferences sp = context.getSharedPreferences("CurrentLogin", MODE_PRIVATE); String LoginUserName = sp.getString("username", "none"); SqlHelper myDatabaseHelper = new SqlHelper(context); SQLiteDatabase sqLiteDatabase = myDatabaseHelper.getWritableDatabase(); sqLiteDatabase.delete("favourite", "information_id = ? and username = ?", new String[]{String.valueOf(menuInfos.get(position).id), LoginUserName}); menuInfos.get(position).IsFav = 0; sqLiteDatabase.close(); notifyDataSetChanged(); Toast.makeText(context, "取消收藏!", Toast.LENGTH_LONG).show(); } }); } else { myHolder.show_favourite.setImageResource(R.drawable.ic_favorite_border_red_200_24dp); myHolder.show_fav_state.setText("收藏"); myHolder.click_to_fav.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { SharedPreferences sp = context.getSharedPreferences("CurrentLogin", MODE_PRIVATE); String LoginUserName = sp.getString("username", "none"); SqlHelper myDatabaseHelper = new SqlHelper(context); SQLiteDatabase sqLiteDatabase = myDatabaseHelper.getWritableDatabase(); ContentValues contentValues = new ContentValues(); contentValues.put("information_id", menuInfos.get(position).id); contentValues.put("username", LoginUserName); sqLiteDatabase.insert("favourite", null, contentValues); menuInfos.get(position).IsFav = 1; sqLiteDatabase.close(); notifyDataSetChanged(); Toast.makeText(context, "已收藏!", Toast.LENGTH_LONG).show(); } }); } myHolder.ItemView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent intent = new Intent(context, ShowDiscussAcitvity.class); intent.putExtra("id", menuInfos.get(position).id); intent.putExtra("reply_people_name", menuInfos.get(position).username); context.startActivity(intent); } }); } @Override public int getItemCount() { return menuInfos.size(); } class myHolder extends RecyclerView.ViewHolder { ImageView show_favourite; TextView show_username, show_time, show_content, show_comment_number, show_fav_state; View ItemView; LinearLayout click_to_fav, click_show_number; private myHolder(View itemView) { super(itemView); show_favourite = itemView.findViewById(R.id.show_favourite); show_username = itemView.findViewById(R.id.show_username); show_time = itemView.findViewById(R.id.show_time); show_content = itemView.findViewById(R.id.show_content); show_comment_number = itemView.findViewById(R.id.show_comment_number); click_to_fav = itemView.findViewById(R.id.click_to_fav); click_show_number = itemView.findViewById(R.id.click_show_number); show_fav_state = itemView.findViewById(R.id.show_fav_state); ItemView = itemView; } } }
package by.epam.javatraining.aliakseibuslau.tasks.maintask.model.Exception; public class NullArrayEx extends BasicExeption { public NullArrayEx() { super("NOT DEFINED!"); } }
package com.jgchk.haven.utils.typeconverters; import android.arch.persistence.room.TypeConverter; import android.location.Location; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import java.lang.reflect.Type; @SuppressWarnings("UtilityClass") public class LocationTypeConverter { @TypeConverter public static Location toLocation(String value) { @SuppressWarnings("EmptyClass") Type t = new TypeToken<Location>() {}.getType(); return new Gson().fromJson(value, t); } @TypeConverter public static String toString(Location location) { return new Gson().toJson(location); } }
package cn.wormholestack.eventnice.core; import java.util.Collection; import java.util.Iterator; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.CopyOnWriteArraySet; /** * @description: 事件接收器注册中心 * @Author MRyan * @Date 2021/10/8 23:38 * @Version 1.0 */ public class ReceiverRegistry implements Registry { private final ConcurrentMap<Class<?>, CopyOnWriteArraySet<EventReceiver>> registry = new ConcurrentHashMap<>(); /** * method捕猎者 */ private final Hunter methodHunter; public ReceiverRegistry() { this.methodHunter = new AnnotationMethodHunter(); } /** * register event target * 注册事件接收器的目标对象 * 保证后续调度时 可以触发该事件接收器定义的事件 * * @param receiver * @return */ @Override public boolean register(Object receiver) { Map<Class<?>, Collection<EventReceiver>> receivers = huntingAllEventReceiver(receiver); for (Map.Entry<Class<?>, Collection<EventReceiver>> entry : receivers.entrySet()) { Class<?> eventType = entry.getKey(); Collection<EventReceiver> eventReceivers = entry.getValue(); CopyOnWriteArraySet<EventReceiver> registeredEventReceivers = registry.get(eventType); if (registeredEventReceivers == null) { registry.putIfAbsent(eventType, new CopyOnWriteArraySet<>()); registeredEventReceivers = registry.get(eventType); } registeredEventReceivers.addAll(eventReceivers); } return true; } /** * 注销已注册的事件接受器 * 保证后续调度时,不在触发该事件接收器定义的事件 * * @param receiver * @return */ @Override public boolean unregister(Object receiver) { Map<Class<?>, Collection<EventReceiver>> receivers = huntingAllEventReceiver(receiver); for (Map.Entry<Class<?>, Collection<EventReceiver>> entry : receivers.entrySet()) { Class<?> eventType = entry.getKey(); if (registry.get(eventType) == null) { throw new IllegalArgumentException( "missing event subscriber for an annotated method. Is " + receiver + " registered?"); } registry.remove(eventType); } return true; } /** * 捕获当前EventReceive所有事件接收器 * * @param receiver * @return */ private Map<Class<?>, Collection<EventReceiver>> huntingAllEventReceiver(Object receiver) { return methodHunter.huntingAllEventReceiver(receiver); } /** * 捕获指定匹配事件接收器 * * @param event * @return */ public Iterator<EventReceiver> huntingMatchedEventReceivers(Object event) { CopyOnWriteArraySet<EventReceiver> eventReceivers = methodHunter.huntingMatchedEventReceivers(this, event); if (eventReceivers == null) { return new Iterator<EventReceiver>() { @Override public boolean hasNext() { return false; } @Override public EventReceiver next() { return null; } }; } return eventReceivers.iterator(); } public ConcurrentMap<Class<?>, CopyOnWriteArraySet<EventReceiver>> getRegistry() { return registry; } }
package com.sai.one.algorithms.arrays; import java.util.PriorityQueue; /** * Created by shravan on 18/8/16. * http://www.programcreek.com/2014/05/leetcode-kth-largest-element-in-an-array-java/ */ public class KLargestArray { public static void main(String args[]){ int[] arr = {1,4,5,22,7,88,9}; System.out.print(findKthLargest(arr,2)); } public static int findKthLargest(int[] nums, int k) { PriorityQueue<Integer> pq = new PriorityQueue<Integer>(); for(int val:nums){ pq.offer(val); if(nums.length-k+1==pq.size()){ return val; } } return -1; } }
package com.datalinks.rsstool.util; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.util.Properties; import java.util.logging.Logger; public class RssUtil { public final static Logger LOGGER = Logger.getLogger(RssUtil.class.getName()); static Properties prop = null; static{ prop = new Properties(); String propFileName = "config.properties"; try { prop.load(new FileInputStream(propFileName)); } catch (FileNotFoundException e) { LOGGER.severe("File "+propFileName+" not found, while initializing properties "+e.getMessage()); } catch (IOException e) { LOGGER.severe("IOException for File "+propFileName+" while initializing properties "+e.getMessage()); } } public static String getProp(String propertyName){ return prop.getProperty(propertyName); } }
/* * 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.xag.util; /** * * @author agunga */ public class MailObject { private String to; private String messageSubject; private String messageBody; public String getTo() { return to; } public void setTo(String to) { this.to = to; } public String getMessageSubject() { return messageSubject; } public void setMessageSubject(String messageSubject) { this.messageSubject = messageSubject; } public String getMessageBody() { return messageBody; } public void setMessageBody(String messageBody) { this.messageBody = messageBody; } }
/* * 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 uttec; /** * * @author vicin */ public class MenuPrincipal extends javax.swing.JFrame { /** * Creates new form MenuPrincipal */ public MenuPrincipal() { initComponents(); setLocationRelativeTo(null); setResizable(false); setTitle("Menu Principal"); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jPanel1 = new uttec.Fondo("yy.jpg"); BtnProfesor = new javax.swing.JButton(); BtnAdministrador = new javax.swing.JButton(); BtnAlumnos = new javax.swing.JButton(); jLabel1 = new javax.swing.JLabel(); jLabel2 = new javax.swing.JLabel(); jLabel3 = new javax.swing.JLabel(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); BtnProfesor.setBackground(new java.awt.Color(204, 204, 204)); BtnProfesor.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N BtnProfesor.setText("PROFESOR"); BtnProfesor.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { BtnProfesorActionPerformed(evt); } }); BtnAdministrador.setBackground(new java.awt.Color(204, 204, 204)); BtnAdministrador.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N BtnAdministrador.setText("ADMINISTRADOR"); BtnAdministrador.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { BtnAdministradorActionPerformed(evt); } }); BtnAlumnos.setBackground(new java.awt.Color(204, 204, 204)); BtnAlumnos.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N BtnAlumnos.setText("ALUMNO"); BtnAlumnos.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { BtnAlumnosActionPerformed(evt); } }); jLabel1.setFont(new java.awt.Font("Tahoma", 0, 24)); // NOI18N jLabel1.setText("MENU PRINCIPAL"); jLabel2.setForeground(new java.awt.Color(255, 255, 255)); jLabel2.setText("version 0.0.1"); jLabel3.setForeground(new java.awt.Color(255, 51, 51)); jLabel3.setText("datos de los desarrolladores"); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(89, 89, 89) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel1) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false) .addComponent(BtnAlumnos, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(BtnProfesor, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(BtnAdministrador, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))) .addContainerGap(59, Short.MAX_VALUE)) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap() .addComponent(jLabel2) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jLabel3) .addContainerGap()) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jLabel1) .addGap(87, 87, 87) .addComponent(BtnAdministrador) .addGap(18, 18, 18) .addComponent(BtnProfesor) .addGap(18, 18, 18) .addComponent(BtnAlumnos) .addGap(0, 119, Short.MAX_VALUE)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup() .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel2) .addComponent(jLabel3)) .addContainerGap()) ); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); pack(); }// </editor-fold>//GEN-END:initComponents private void BtnProfesorActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BtnProfesorActionPerformed // TODO add your handling code here: PasswordProfesor pro=new PasswordProfesor(); pro.setVisible(true); dispose(); }//GEN-LAST:event_BtnProfesorActionPerformed private void BtnAlumnosActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BtnAlumnosActionPerformed // TODO add your handling code here: PasswordAlumno alu=new PasswordAlumno(); alu.setVisible(true); dispose(); }//GEN-LAST:event_BtnAlumnosActionPerformed private void BtnAdministradorActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BtnAdministradorActionPerformed // TODO add your handling code here: PasswordAdmin ad=new PasswordAdmin(); ad.setVisible(true); dispose(); }//GEN-LAST:event_BtnAdministradorActionPerformed /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(MenuPrincipal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(MenuPrincipal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(MenuPrincipal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(MenuPrincipal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new MenuPrincipal().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton BtnAdministrador; private javax.swing.JButton BtnAlumnos; private javax.swing.JButton BtnProfesor; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JPanel jPanel1; // End of variables declaration//GEN-END:variables }
package com.egswebapp.egsweb.dto; import javax.validation.constraints.NotBlank; public abstract class AbstractPageDto { @NotBlank(message = "title must not be empty") private String title; @NotBlank(message = "description must not be empty") private String description; @NotBlank(message = "languages must not be empty") private String languages; public AbstractPageDto() { } public AbstractPageDto(String title, String description, String languages) { this.title = title; this.description = description; this.languages = languages; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getLanguages() { return languages; } public void setLanguages(String languages) { this.languages = languages; } }
public interface Valuable { // 각 사물의 가치를 추산하는 메소드 , 사물에 따라 가치를 추산하는 공식이 다르다. public abstract double estimateValue(int month); public abstract double estimateValue(); }
package com.citibank.newcpb.persistence.dao; import java.sql.ResultSet; import java.sql.SQLException; import java.util.Date; import org.apache.commons.lang.StringUtils; import com.citibank.newcpb.enums.TableTypeEnum; import com.citibank.newcpb.exception.UnexpectedException; import com.citibank.newcpb.vo.OfficerBankerVO; import com.citibank.ods.common.connection.rdb.ManagedRdbConnection; import com.citibank.ods.common.persistence.dao.rdb.oracle.BaseOracleDAO; import com.citibank.ods.persistence.pl.dao.rdb.oracle.factory.OracleODSDAOFactory; import com.citibank.ods.persistence.util.CitiStatement; public class TplPrvtOfficerMovDAO extends BaseOracleDAO { public void insert(OfficerBankerVO vo) { ManagedRdbConnection connection = null; CitiStatement preparedStatement = null; StringBuffer sqlQuery = new StringBuffer(); try { connection = OracleODSDAOFactory.getConnection(); sqlQuery.append(" INSERT INTO " + C_PL_SCHEMA + " TPL_PRVT_OFFICER_MOV ( " ); sqlQuery.append(" OFFICER_SOEID , "); sqlQuery.append(" SUPERVISOR_SOEID , "); sqlQuery.append(" ASSOCIATE_SOEID , "); sqlQuery.append(" LAST_UPD_DATE , "); sqlQuery.append(" LAST_UPD_USER_ID , "); sqlQuery.append(" LAST_AUTH_DATE , "); sqlQuery.append(" LAST_AUTH_USER_ID , "); sqlQuery.append(" REC_STAT_CODE "); sqlQuery.append( ") VALUES ( " ); sqlQuery.append( " ?, ?, ?, ?, ?, ?, ?, ? ) "); preparedStatement = new CitiStatement(connection.prepareStatement(sqlQuery.toString())); int count = 1; if (!StringUtils.isBlank(vo.getEmployeeSOEID())) { preparedStatement.setString(count++, vo.getEmployeeSOEID()); } else { throw new UnexpectedException(C_ERROR_EXECUTING_STATEMENT, null); } if (!StringUtils.isBlank(vo.getSupervisorSOEID())) { preparedStatement.setString(count++, vo.getSupervisorSOEID()); } else { preparedStatement.setString(count++, null); } if (!StringUtils.isBlank(vo.getAssociateSOEID())) { preparedStatement.setString(count++, vo.getAssociateSOEID()); } else { preparedStatement.setString(count++, null); } if (vo.getLastUpdDate()!=null) { preparedStatement.setTimestamp(count++, new java.sql.Timestamp(vo.getLastUpdDate().getTime())); } else { preparedStatement.setString(count++, null); } if (!StringUtils.isBlank(vo.getLastUpdUser())) { preparedStatement.setString(count++, vo.getLastUpdUser()); } else { preparedStatement.setString(count++, null); } if (vo.getLastAuthDate()!=null) { preparedStatement.setTimestamp(count++, new java.sql.Timestamp(vo.getLastAuthDate().getTime())); } else { preparedStatement.setString(count++, null); } if (!StringUtils.isBlank(vo.getLastAuthUser())) { preparedStatement.setString(count++, vo.getLastAuthUser()); } else { preparedStatement.setString(count++, null); } if (!StringUtils.isBlank(vo.getRecStatCode())) { preparedStatement.setString(count++, vo.getRecStatCode()); } else { preparedStatement.setString(count++, null); } preparedStatement.replaceParametersInQuery(sqlQuery.toString()); preparedStatement.execute(); } catch (SQLException e) { throw new UnexpectedException(e.getErrorCode(), C_ERROR_EXECUTING_STATEMENT, e); } finally { closeStatement(preparedStatement); closeConnection(connection); } } public OfficerBankerVO getOfficer(String employeeSOEID) { ManagedRdbConnection connection = null; CitiStatement preparedStatement = null; ResultSet rs = null; StringBuffer query = new StringBuffer(); OfficerBankerVO result = null; try { connection = OracleODSDAOFactory.getConnection(); query.append(" SELECT TPL_PRVT_OFFICER_MOV.OFFICER_SOEID, " + " TPL_PRVT_OFFICER_MOV.SUPERVISOR_SOEID, " + " TPL_PRVT_OFFICER_MOV.ASSOCIATE_SOEID, " + " TPL_PRVT_OFFICER_MOV.LAST_AUTH_DATE, " + " TPL_PRVT_OFFICER_MOV.LAST_AUTH_USER_ID, " + " TPL_PRVT_OFFICER_MOV.LAST_UPD_DATE, " + " TPL_PRVT_OFFICER_MOV.LAST_UPD_USER_ID, " + " TPL_PRVT_OFFICER_MOV.REC_STAT_CODE" + " FROM " + C_PL_SCHEMA + "TPL_PRVT_OFFICER_MOV " + " WHERE 1=1 "); if(employeeSOEID!=null){ if (!StringUtils.isBlank(employeeSOEID)) { query.append(" AND UPPER(TPL_PRVT_OFFICER_MOV.OFFICER_SOEID) = TRIM(?) "); } } preparedStatement = new CitiStatement(connection.prepareStatement( query.toString() )); int count = 1; if(employeeSOEID!=null){ if (!StringUtils.isBlank(employeeSOEID)) { preparedStatement.setString(count++, employeeSOEID.toUpperCase()); } } preparedStatement.replaceParametersInQuery(query.toString()); rs = preparedStatement.executeQuery(); if(rs!=null){ while (rs.next()){ result = new OfficerBankerVO(); result.setEmployeeSOEID(rs.getString("OFFICER_SOEID") != null ? rs.getString("OFFICER_SOEID").toString() : null); result.setSupervisorSOEID(rs.getString("SUPERVISOR_SOEID") != null ? rs.getString("SUPERVISOR_SOEID").toString() : null); result.setAssociateSOEID(rs.getString("ASSOCIATE_SOEID") != null ? rs.getString("ASSOCIATE_SOEID").toString() : null); result.setLastAuthDate(rs.getDate("LAST_AUTH_DATE") != null ? new Date(rs.getDate("LAST_AUTH_DATE").getTime()) : null); result.setLastAuthUser(rs.getString("LAST_AUTH_USER_ID") != null ? rs.getString("LAST_AUTH_USER_ID").toString() : null); result.setLastUpdDate(rs.getDate("LAST_UPD_DATE") != null ? new Date(rs.getDate("LAST_UPD_DATE").getTime()) : null); result.setLastUpdUser(rs.getString("LAST_UPD_USER_ID") != null ? rs.getString("LAST_UPD_USER_ID").toString() : null); result.setRecStatCode(rs.getString("REC_STAT_CODE") != null ? rs.getString("REC_STAT_CODE").toString() : null); result.setTableOrigin(TableTypeEnum.MOVEMENT); } } rs.close(); } catch (SQLException e) { throw new UnexpectedException(e.getErrorCode(), C_ERROR_EXECUTING_STATEMENT, e); } finally { closeStatement(preparedStatement); closeConnection(connection); } return result; } public OfficerBankerVO update(OfficerBankerVO vo) { ManagedRdbConnection connection = null; CitiStatement preparedStatement = null; StringBuffer sqlQuery = new StringBuffer(); try { connection = OracleODSDAOFactory.getConnection(); sqlQuery.append("UPDATE " + C_PL_SCHEMA + "TPL_PRVT_OFFICER_MOV "); sqlQuery.append(" SET SUPERVISOR_SOEID = ? , "); sqlQuery.append(" ASSOCIATE_SOEID = ? , "); sqlQuery.append(" LAST_UPD_DATE = ? , "); sqlQuery.append(" LAST_UPD_USER_ID = ? , "); sqlQuery.append(" LAST_AUTH_DATE = ? , "); sqlQuery.append(" LAST_AUTH_USER_ID = ? , "); sqlQuery.append(" REC_STAT_CODE = ? "); sqlQuery.append(" WHERE OFFICER_SOEID = ? "); preparedStatement = new CitiStatement(connection.prepareStatement(sqlQuery.toString())); int count = 1; if (!StringUtils.isBlank(vo.getSupervisorSOEID())) { preparedStatement.setString(count++, vo.getSupervisorSOEID()); } else { preparedStatement.setString(count++, null); } if (!StringUtils.isBlank(vo.getAssociateSOEID())) { preparedStatement.setString(count++, vo.getAssociateSOEID()); } else { preparedStatement.setString(count++, null); } if (vo.getLastUpdDate()!=null) { preparedStatement.setTimestamp(count++, new java.sql.Timestamp(vo.getLastUpdDate().getTime())); } else { preparedStatement.setString(count++, null); } if (!StringUtils.isBlank(vo.getLastUpdUser())) { preparedStatement.setString(count++, vo.getLastUpdUser()); } else { preparedStatement.setString(count++, null); } if (vo.getLastAuthDate()!=null) { preparedStatement.setTimestamp(count++, new java.sql.Timestamp(vo.getLastAuthDate().getTime())); } else { preparedStatement.setString(count++, null); } if (!StringUtils.isBlank(vo.getLastAuthUser())) { preparedStatement.setString(count++, vo.getLastAuthUser()); } else { preparedStatement.setString(count++, null); } if (!StringUtils.isBlank(vo.getRecStatCode())) { preparedStatement.setString(count++, vo.getRecStatCode()); } else { preparedStatement.setString(count++, null); } if (!StringUtils.isBlank(vo.getEmployeeSOEID())) { preparedStatement.setString(count++, vo.getEmployeeSOEID()); } else { throw new UnexpectedException(C_ERROR_EXECUTING_STATEMENT, null); } preparedStatement.replaceParametersInQuery(sqlQuery.toString()); preparedStatement.execute(); } catch (SQLException e) { throw new UnexpectedException(e.getErrorCode(), C_ERROR_EXECUTING_STATEMENT, e); } finally { closeStatement(preparedStatement); closeConnection(connection); } return vo; } public void delete(String employeeSOEID) { ManagedRdbConnection connection = null; CitiStatement preparedStatement = null; StringBuffer query = new StringBuffer(); try { connection = OracleODSDAOFactory.getConnection(); query.append(" DELETE FROM " + C_PL_SCHEMA + "TPL_PRVT_OFFICER_MOV" + " WHERE OFFICER_SOEID = ? "); preparedStatement = new CitiStatement(connection.prepareStatement(query.toString())); if (!StringUtils.isBlank(employeeSOEID)) { preparedStatement.setString(1, employeeSOEID); } else { throw new UnexpectedException(C_ERROR_EXECUTING_STATEMENT, null); } preparedStatement.replaceParametersInQuery(query.toString()); preparedStatement.executeUpdate(); } catch (SQLException e) { throw new UnexpectedException(e.getErrorCode(), C_ERROR_EXECUTING_STATEMENT, e); } finally { closeStatement(preparedStatement); closeConnection(connection); } } }
package com.javawebtutor.Models.Classes; public class ClientCarCheck { private String model; private String mark; private String repairCauses; private String state; private int price; public ClientCarCheck(String model, String mark, String repairCauses, String state, int price) { this.model = model; this.mark = mark; this.repairCauses = repairCauses; this.state = state; this.price = price; } public String getModel() { return model; } public void setModel(String model) { this.model = model; } public String getMark() { return mark; } public void setMark(String mark) { this.mark = mark; } public String getRepairCauses() { return repairCauses; } public void setRepairCauses(String repairCauses) { this.repairCauses = repairCauses; } public String getState() { return state; } public void setState(String state) { this.state = state; } public int getPrice() { return price; } public void setPrice(int price) { this.price = price; } }
package com.dangdang.ddframe.test; import com.dangdang.ddframe.concurrent.ForkBlur; import org.apache.commons.codec.binary.StringUtils; import org.apache.commons.codec.digest.DigestUtils; import org.apache.commons.lang3.LocaleUtils; import org.apache.commons.lang3.RandomStringUtils; import org.apache.commons.lang3.StringEscapeUtils; import org.apache.commons.lang3.RandomUtils; import org.apache.commons.lang3.builder.ReflectionToStringBuilder; import org.junit.Test; import java.util.Arrays; import java.util.concurrent.ForkJoinPool; import java.util.concurrent.Future; import java.util.concurrent.RecursiveAction; import java.util.concurrent.RecursiveTask; /** * Created by zruan on 2015/12/23. */ public class SegmentTest { @Test public void testStringUtils() { System.out.println(RandomStringUtils.random(20)); System.out.println(RandomStringUtils.random(20, true, true)); System.out.println(RandomStringUtils.randomAlphabetic(20)); System.out.println(RandomStringUtils.randomAscii(20)); System.out.println(RandomStringUtils.randomNumeric(20)); System.out.println(StringEscapeUtils.escapeJson("{\"app\":\"dd\"}")); System.out.println(LocaleUtils.availableLocaleList()); int n = 8; n *= 8; System.out.println(n); System.out.println(1 / 9); } @Test public void test002() { int number = 10; //原始数二进制 this.printNumber(number); //左移一位 number = number << 1; this.printNumber(number); number = 10; //右移一位 number = number >> 1; this.printNumber(number); number = 10; this.printNumber(number); //无符号右移一位 number = number >>> 1; this.printNumber(number); } private void printNumber(int number) { System.out.println("Original ==> [" + number + "], hex ==> [" + Integer.toBinaryString(number) + "]"); } @Test public void testDigest() { System.out.println(DigestUtils.sha512Hex("123456789")); System.out.println(DigestUtils.sha512Hex(DigestUtils.sha512Hex("123456789"))); System.out.println(DigestUtils.md5Hex("Oracle123")); } // 归并排序的实现 @Test public void testMergeSort() { int[] nums = {2, 7, 8, 3, 1, 6, 9, 0, 5, 4}; SortTask.sort(nums, 0, nums.length - 1); System.out.println(Arrays.toString(nums)); } @Test public void testForkJoinSum() { // source image pixels are in src // destination image pixels are in dst int len = (int) Math.pow(10, 2); int[] src = new int[len], dst = new int[len]; for (int i = 0; i < len; i++) { src[i] = RandomUtils.nextInt(1, 10000); } ForkBlur fb = new ForkBlur(src, 0, src.length, dst); ForkJoinPool pool = new ForkJoinPool(); pool.invoke(fb); for (int i = 0; i < src.length; i++) { System.out.println(src[i]); } for (int i = 0; i < dst.length; i++) { System.out.println(dst[i]); } } /** * Not passed */ @Test public void testForkJoinMergeSort() { // source image pixels are in src // destination image pixels are in dst int len = (int) Math.pow(10, 2); int[] src = new int[len]; for (int i = 0; i < len; i++) { src[i] = RandomUtils.nextInt(1, 1000); } SortTask st = new SortTask(src, 0, src.length - 1); ForkJoinPool pool = new ForkJoinPool(); pool.invoke(st); System.out.println(ReflectionToStringBuilder.toString(src)); } @Test public void testSum() { ForkJoinPool fjPool = new ForkJoinPool(); int[] array = new int[100000]; for (int i = 0; i < array.length; i++) { array[i] = i; } long sum = fjPool.invoke(new Sum(array, 0, array.length, "all")); System.out.println(sum); } @Test public void testSumOfSquares() { ForkJoinPool fjPool = new ForkJoinPool(); int len = (int) Math.pow(10, 2); double[] src = new double[len]; for (int i = 0; i < len; i++) { src[i] = RandomUtils.nextDouble(0.0, 10000.0); } System.out.println(sumOfSquares(fjPool, src)); } double sumOfSquares(ForkJoinPool pool, double[] array) { int n = array.length; Applyer a = new Applyer(array, 0, n, null); pool.invoke(a); return a.result; } @Test public void testCountTask() { long beginTime = System.nanoTime(); System.out.println("The sum from 1 to 1000 is " + sum(1, 1000)); System.out.println("Time consumed(nano second) By recursive algorithm : " + (System.nanoTime() - beginTime)); beginTime = System.nanoTime(); System.out.println("The sum from 1 to 1000000000 is " + sum1(1, 1000000000)); System.out.println("Time consumed(nano second) By loop algorithm : " + (System.nanoTime() - beginTime)); ForkJoinPool forkJoinPool = new ForkJoinPool(); CountTask task = new CountTask(1, 1000000000); beginTime = System.nanoTime(); Future<Long> result = forkJoinPool.submit(task); try { System.out.println("The sum from 1 to 1000000000 is " + result.get()); } catch (Exception e) { e.printStackTrace(); } System.out.println("Time consumed(nano second) By ForkJoin algorithm : " + (System.nanoTime() - beginTime)); } public static long sum1(long start, long end) { long s = 0l; for (long i = start; i <= end; i++) { s += i; } return s; } public static long sum(long start, long end) { if (end > start) { return end + sum(start, end - 1); } else { return start; } } } class Sum extends RecursiveTask<Long> { static final int SEQUENTIAL_THRESHOLD = 5000; int low; int high; int[] array; String flag; Sum(int[] arr, int lo, int hi, String flag) { array = arr; low = lo; high = hi; this.flag = flag; } protected Long compute() { if (high - low <= SEQUENTIAL_THRESHOLD) { long sum = 0; for (int i = low; i < high; ++i) sum += array[i]; return sum; } int mid = low + (high - low) / 2; System.out.println("flag ==>" + this.flag + ", low ==>" + low + ", mid ==>" + mid + ", high==>" + high); Sum left = new Sum(array, low, mid, "left"); Sum right = new Sum(array, mid, high, "right"); left.fork(); long rightAns = right.compute(); long leftAns = left.join(); return leftAns + rightAns; } } class SortTask extends RecursiveAction { static final int THRESHOLD = 50; final int[] array; final int lo; final int hi; SortTask(int[] array, int lo, int hi) { this.array = array; this.lo = lo; this.hi = hi; } protected void compute() { if (hi - lo < THRESHOLD) { System.out.println("------------------------"); sort(array, lo, hi); } else { int mid = (lo + hi) >>> 1; invokeAll(new SortTask(array, lo, mid), new SortTask(array, mid, hi)); merge(array, lo, mid, hi); } } /** * 归并排序 * 简介:将两个(或两个以上)有序表合并成一个新的有序表 即把待排序序列分为若干个子序列,每个子序列是有序的。然后再把有序子序列合并为整体有序序列 * 时间复杂度为O(nlogn) * 稳定排序方式 * * @param nums 待排序数组 * @return 输出有序数组 */ public static int[] sort(int[] nums, int low, int high) { int mid = (low + high) / 2; if (low < high) { // 左边 sort(nums, low, mid); // 右边 sort(nums, mid + 1, high); // 左右归并 merge(nums, low, mid, high); } return nums; } public static void merge(int[] nums, int low, int mid, int high) { int[] temp = new int[high - low + 1]; int i = low;// 左指针 int j = mid + 1;// 右指针 int k = 0; // 把较小的数先移到新数组中 while (i <= mid && j <= high) { System.out.println("==>" + temp.length + ", " + i + ", " + j + ", number len ==>" + nums.length); if (nums[i] < nums[j]) { temp[k++] = nums[i++]; } else { temp[k++] = nums[j++]; } } // 把左边剩余的数移入数组 while (i <= mid) { temp[k++] = nums[i++]; } // 把右边边剩余的数移入数组 while (j <= high) { temp[k++] = nums[j++]; } // 把新数组中的数覆盖nums数组 for (int k2 = 0; k2 < temp.length; k2++) { nums[k2 + low] = temp[k2]; } } } class IncrementTask extends RecursiveAction { static final int THRESHOLD = 5000; final long[] array; final int lo; final int hi; IncrementTask(long[] array, int lo, int hi) { this.array = array; this.lo = lo; this.hi = hi; } protected void compute() { if (hi - lo < THRESHOLD) { for (int i = lo; i < hi; ++i) array[i]++; } else { int mid = (lo + hi) >>> 1; invokeAll(new IncrementTask(array, lo, mid), new IncrementTask(array, mid, hi)); } } } class Applyer extends RecursiveAction { final double[] array; final int lo, hi; double result; Applyer next; // keeps track of right-hand-side tasks Applyer(double[] array, int lo, int hi, Applyer next) { this.array = array; this.lo = lo; this.hi = hi; this.next = next; } double atLeaf(int l, int h) { double sum = 0; for (int i = l; i < h; ++i) // perform leftmost base step sum += array[i] * array[i]; return sum; } protected void compute() { int l = lo; int h = hi; Applyer right = null; while (h - l > 1 && getSurplusQueuedTaskCount() <= 3) { int mid = (l + h) >>> 1; right = new Applyer(array, mid, h, right); right.fork(); h = mid; } double sum = atLeaf(l, h); while (right != null) { if (right.tryUnfork()) // directly calculate if not stolen sum += right.atLeaf(right.lo, right.hi); else { right.join(); sum += right.result; } right = right.next; } result = sum; } } class Fibonacci extends RecursiveTask<Integer> { final int n; Fibonacci(int n) { this.n = n; } protected Integer compute() { if (n <= 1) return n; Fibonacci f1 = new Fibonacci(n - 1); f1.fork(); Fibonacci f2 = new Fibonacci(n - 2); return f2.compute() + f1.join(); } } class CountTask extends RecursiveTask<Long> { private static final int THRESHOLD = 10000; private int start; private int end; public CountTask(int start, int end) { this.start = start; this.end = end; } protected Long compute() { //System.out.println("Thread ID: " + Thread.currentThread().getId()); Long sum; if ((end - start) <= THRESHOLD) { sum = SegmentTest.sum1(start, end); } else { int middle = (start + end) / 2; CountTask leftTask = new CountTask(start, middle); CountTask rightTask = new CountTask(middle + 1, end); leftTask.fork(); rightTask.fork(); Long leftResult = leftTask.join(); Long rightResult = rightTask.join(); sum = leftResult + rightResult; } return sum; } }
package network.nerve.converter; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; import io.nuls.core.exception.NulsException; import io.nuls.core.io.IoUtils; import io.nuls.core.log.Log; import io.nuls.core.parse.JSONUtils; import network.nerve.converter.constant.ConverterErrorCode; import network.nerve.converter.enums.HeterogeneousChainTxType; import network.nerve.converter.heterogeneouschain.bch.context.BchContext; import network.nerve.converter.heterogeneouschain.iotx.context.IotxContext; import network.nerve.converter.heterogeneouschain.klay.context.KlayContext; import network.nerve.converter.heterogeneouschain.lib.context.HtgContext; import network.nerve.converter.heterogeneouschain.lib.core.HtgWalletApi; import network.nerve.converter.heterogeneouschain.lib.model.HtgSendTransactionPo; import network.nerve.converter.heterogeneouschain.lib.utils.HtgUtil; import network.nerve.converter.heterogeneouschain.metis.context.MetisContext; import network.nerve.converter.heterogeneouschain.optimism.context.OptimismContext; import network.nerve.converter.model.bo.HeterogeneousCfg; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import org.web3j.abi.FunctionEncoder; import org.web3j.abi.TypeReference; import org.web3j.abi.datatypes.Address; import org.web3j.abi.datatypes.Function; import org.web3j.abi.datatypes.Type; import org.web3j.crypto.Credentials; import org.web3j.crypto.RawTransaction; import org.web3j.crypto.Sign; import org.web3j.crypto.TransactionEncoder; import org.web3j.protocol.Web3j; import org.web3j.protocol.core.methods.response.EthEstimateGas; import org.web3j.protocol.core.methods.response.EthSendTransaction; import org.web3j.protocol.http.HttpService; import org.web3j.utils.Numeric; import java.lang.reflect.Field; import java.math.BigInteger; import java.util.*; import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; public class Protocol21Test { // 设置环境 static boolean MAIN = true; @BeforeClass public static void beforeClass() { ObjectMapper objectMapper = JSONUtils.getInstance(); objectMapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true); objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); } Map<Integer, HtgContext> contextMap = contextMap(); Map<Integer, String[]> multyMap = multyMap(); Map<Integer, HeterogeneousCfg> cfgMap = cfgMap(); Map<Integer, HtgWalletApi> htgWalletApiMap = new HashMap<>(); String contractForCreateERC20Minter; String contractForCreateERC20Minter_IOTX; private Map<Integer, HtgContext> contextMap() { Map<Integer, HtgContext> map = new HashMap<>(); map.put(113, new MetisContext()); map.put(114, new IotxContext()); map.put(115, new OptimismContext()); map.put(116, new KlayContext()); map.put(117, new BchContext()); return map; } @Before public void before() { try { if (MAIN) { contractForCreateERC20Minter = "0x63ae3cea2225be3390854e824a65bbbb02616bb4"; contractForCreateERC20Minter_IOTX = "0x616feEA47576c410689C66855B4132412c1BEFa7"; } else { contractForCreateERC20Minter = "0x1EA3FfD41c3ed3e3f788830aAef553F8F691aD8C"; contractForCreateERC20Minter_IOTX = "0x2e5822a3c651b1c31a60d7c6e0641c113e98c98c"; } for (int i = 113; i <= 117; i++) { int htgChainId = i; HeterogeneousCfg cfg = cfgMap.get(htgChainId); HtgWalletApi htgWalletApi = new HtgWalletApi(); Web3j web3j = Web3j.build(new HttpService(cfg.getMainRpcAddress())); htgWalletApi.setWeb3j(web3j); htgWalletApi.setEthRpcAddress(cfg.getMainRpcAddress()); HtgContext htgContext = contextMap.get(htgChainId); // 设置新的签名版本号 byte newVersion = 3; htgContext.SET_VERSION(newVersion); htgContext.setLogger(Log.BASIC_LOGGER); htgContext.setConfig(cfg); Field field = htgWalletApi.getClass().getDeclaredField("htgContext"); field.setAccessible(true); field.set(htgWalletApi, htgContext); htgWalletApiMap.put(htgChainId, htgWalletApi); } } catch (Exception e) { throw new RuntimeException(e); } } /** * 读取每个链的新旧多签合约 */ private Map<Integer, String[]> multyMap() { if (MAIN) { return multyMapMainnet(); } else { return multyMapTestnet(); } } /** * 测试网: 配置每个链的新旧多签合约 */ private Map<Integer, String[]> multyMapTestnet() { /* 101 eth, 102 bsc, 103 heco, 104 oec, 105 Harmony(ONE), 106 Polygon(MATIC), 107 kcc(KCS), 108 TRX, 109 CRO, 110 AVAX, 111 AETH, 112 FTM, 113 METIS, 114 IOTX, 115 OETH, 116 KLAY, 117 BCH */ Map<Integer, String[]> map = new HashMap<>(); // 前旧后新 map.put(113, new String[]{"0x03Cf96223BD413eb7777AFE3cdb689e7E851CB32", "0x03Cf96223BD413eb7777AFE3cdb689e7E851CB32"}); map.put(114, new String[]{"0x3F1f3D17619E916C4F04707BA57d8E0b9e994fB0", "0x3F1f3D17619E916C4F04707BA57d8E0b9e994fB0"}); map.put(115, new String[]{"0x56F175D48211e7D018ddA7f0A0B51bcfB405AE69", "0x56F175D48211e7D018ddA7f0A0B51bcfB405AE69"}); map.put(116, new String[]{"0x2eDCf5f18D949c51776AFc42CDad667cDA2cF862", "0x2eDCf5f18D949c51776AFc42CDad667cDA2cF862"}); map.put(117, new String[]{"0x830befa62501F1073ebE2A519B882e358f2a0318", "0x830befa62501F1073ebE2A519B882e358f2a0318"}); return map; } /** * 主网: 配置每个链的新旧多签合约 */ private Map<Integer, String[]> multyMapMainnet() { /* 101 eth, 102 bsc, 103 heco, 104 oec, 105 Harmony(ONE), 106 Polygon(MATIC), 107 kcc(KCS), 108 TRX, 109 CRO, 110 AVAX, 111 AETH, 112 FTM, 113 METIS, 114 IOTX, 115 OETH, 116 KLAY, 117 BCH */ // 配置每个链的新旧多签合约 Map<Integer, String[]> map = new HashMap<>(); // 前旧后新 map.put(113, new String[]{"0x3758AA66caD9F2606F1F501c9CB31b94b713A6d5", "0x3758AA66caD9F2606F1F501c9CB31b94b713A6d5"}); map.put(114, new String[]{"0xf0e406c49c63abf358030a299c0e00118c4c6ba5", "0xf0e406c49c63abf358030a299c0e00118c4c6ba5"}); map.put(115, new String[]{"0x3758AA66caD9F2606F1F501c9CB31b94b713A6d5", "0x3758AA66caD9F2606F1F501c9CB31b94b713A6d5"}); map.put(116, new String[]{"0x3758AA66caD9F2606F1F501c9CB31b94b713A6d5", "0x3758AA66caD9F2606F1F501c9CB31b94b713A6d5"}); map.put(117, new String[]{"0x3758AA66caD9F2606F1F501c9CB31b94b713A6d5", "0x3758AA66caD9F2606F1F501c9CB31b94b713A6d5"}); return map; } /** * 读取异构链基本信息 */ private Map<Integer, HeterogeneousCfg> cfgMap() { try { String configJson; if (MAIN) { configJson = IoUtils.read("heterogeneous_mainnet.json"); } else { configJson = IoUtils.read("heterogeneous_testnet.json"); } List<HeterogeneousCfg> config = JSONUtils.json2list(configJson, HeterogeneousCfg.class); Map<Integer, HeterogeneousCfg> cfgMap = config.stream().collect(Collectors.toMap(HeterogeneousCfg::getChainId, java.util.function.Function.identity())); return cfgMap; } catch (Exception e) { throw new RuntimeException(e); } } /** 注册跨链网络 registerheterogeneousmainasset NERVEepb69uqMbNRufoPz6QGerCMtDG4ybizAA 113 registerheterogeneousmainasset NERVEepb69uqMbNRufoPz6QGerCMtDG4ybizAA 114 registerheterogeneousmainasset NERVEepb69uqMbNRufoPz6QGerCMtDG4ybizAA 115 registerheterogeneousmainasset NERVEepb69uqMbNRufoPz6QGerCMtDG4ybizAA 116 registerheterogeneousmainasset NERVEepb69uqMbNRufoPz6QGerCMtDG4ybizAA 117 */ /** * 补齐管理员 */ @Test public void managerChangeSignData() throws Exception { List<String> seedList = new ArrayList<>(); seedList.add("???"); seedList.add("???"); seedList.add("???"); String txKey = "aaa1000000000000000000000000000000000000000000000000000000000000"; String[] adds = new String[]{ "0xb12a6716624431730c3ef55f80c458371954fa52", "0x1f13e90daa9548defae45cd80c135c183558db1f", "0x66fb6d6df71bbbf1c247769ba955390710da40a5", "0x6c9783cc9c9ff9c0f1280e4608afaadf08cfb43d", "0xaff68cd458539a16b932748cf4bdd53bf196789f", "0xc8dcc24b09eed90185dbb1a5277fd0a389855dae", "0xa28035bb5082f5c00fa4d3efc4cb2e0645167444", "0x10c17be7b6d3e1f424111c8bddf221c9557728b0", "0x5c44e5113242fc3fe34a255fb6bdd881538e2ad1", "0x15cb37aa4d55d5a0090966bef534c89904841065", "0x8255a0e99456f45f8b85246ef6a9b1895c784c9f", "0x25955965648cd5c017d6d4644bf65830645ef2f2" }; String[] removes = new String[]{}; int txCount = 1; int signCount = seedList.size(); for (int i = 113; i <= 117; i++) { int htgChainId = i; HtgWalletApi htgWalletApi = htgWalletApiMap.get(htgChainId); HtgContext htgContext = contextMap.get(htgChainId); htgContext.setEthGasPrice(htgWalletApi.getCurrentGasPrice()); String[] multyArray = multyMap.get(htgChainId); String newMulty = multyArray[1]; String multySignContractAddress = newMulty; String hash = this.sendChange(htgWalletApi, htgContext, seedList, multySignContractAddress, txKey, adds, txCount, removes, signCount); System.out.println(String.format("htgId: %s, 管理员添加%s个,移除%s个,hash: %s", htgChainId, adds.length, removes.length, hash)); } } @Test public void setupMinterOnCreateERC20MinterTest() { // 更新工具合约中的minter地址为新多签地址,异构链113~117 String prikey = "???"; // 遍历所有异构链 for (int i = 113; i <= 117; i++) { String _contractForCreateERC20Minter = contractForCreateERC20Minter; Integer htgChainId = i; if (htgChainId == 114) { _contractForCreateERC20Minter = contractForCreateERC20Minter_IOTX; } HeterogeneousCfg cfg = cfgMap.get(htgChainId); long networkChainId = cfg.getChainIdOnHtgNetwork(); HtgWalletApi htgWalletApi = htgWalletApiMap.get(htgChainId); String[] multyArray = multyMap.get(htgChainId); String newMulty = multyArray[1]; try { Function setupMinter = new Function("setupMinter", Arrays.asList(new Address(newMulty)), List.of()); Credentials credentials = Credentials.create(prikey); String from = credentials.getAddress(); EthEstimateGas ethEstimateGas = htgWalletApi.ethEstimateGas(from, _contractForCreateERC20Minter, setupMinter); if (ethEstimateGas.getError() != null) { System.err.println(String.format("验证失败[setupMinter] - HtgChainId: %s, newMultyContract: %s, Failed to setupMinter, error: %s", htgChainId, newMulty, ethEstimateGas.getError().getMessage())); continue; } BigInteger nonce = htgWalletApi.getNonce(from); String data = FunctionEncoder.encode(setupMinter); BigInteger gasLimit = ethEstimateGas.getAmountUsed().add(BigInteger.valueOf(10000L)); BigInteger gasPrice = htgWalletApi.getCurrentGasPrice(); RawTransaction rawTransaction = RawTransaction.createTransaction( nonce, gasPrice, gasLimit, _contractForCreateERC20Minter, BigInteger.ZERO, data); //签名Transaction,这里要对交易做签名 byte[] signMessage = TransactionEncoder.signMessage(rawTransaction, networkChainId, credentials); String hexValue = Numeric.toHexString(signMessage); //发送交易 EthSendTransaction send = htgWalletApi.ethSendRawTransaction(hexValue); if (send.hasError()) { System.err.println(String.format("广播失败[setupMinter] - HtgChainId: %s, multyContract: %s, errorMsg: %s, errorCode: %s, errorData: %s", htgChainId, newMulty, send.getError().getMessage(), send.getError().getCode(), send.getError().getData() )); } else { System.out.println(String.format("广播成功[setupMinter] - HtgChainId: %s, multyContract: %s, hash: %s", htgChainId, newMulty, send.getTransactionHash())); } TimeUnit.MILLISECONDS.sleep(500); } catch (Exception e) { System.err.println(String.format("Failed to [setupMinter], HtgChainId: %s, multyContract: %s, error: %s", htgChainId, newMulty, e.getMessage())); } } } protected String changeSignData(HtgContext htgContext, List<String> seedList, String txKey, String[] adds, int count, String[] removes) throws Exception { String vHash = HtgUtil.encoderChange(htgContext, txKey, adds, count, removes, htgContext.VERSION()); String signData = this.ethSign(seedList, vHash, seedList.size()); return signData; } protected String sendChangeWithSignData(String priKey, HtgWalletApi htgWalletApi, String signData, String multySignContractAddress, String txKey, String[] adds, int count, String[] removes) throws Exception { List<Address> addList = Arrays.asList(adds).stream().map(a -> new Address(a)).collect(Collectors.toList()); List<Address> removeList = Arrays.asList(removes).stream().map(r -> new Address(r)).collect(Collectors.toList()); Function function = HtgUtil.getCreateOrSignManagerChangeFunction(txKey, addList, removeList, count, signData); String address = Credentials.create(priKey).getAddress(); return this.sendTx(htgWalletApi, multySignContractAddress, address, priKey, function, HeterogeneousChainTxType.CHANGE); } protected String sendChange(HtgWalletApi htgWalletApi, HtgContext htgContext, List<String> seedList, String multySignContractAddress, String txKey, String[] adds, int count, String[] removes, int signCount) throws Exception { String vHash = HtgUtil.encoderChange(htgContext, txKey, adds, count, removes, htgContext.VERSION()); String signData = this.ethSign(seedList, vHash, signCount); List<Address> addList = Arrays.asList(adds).stream().map(a -> new Address(a)).collect(Collectors.toList()); List<Address> removeList = Arrays.asList(removes).stream().map(r -> new Address(r)).collect(Collectors.toList()); Function function = HtgUtil.getCreateOrSignManagerChangeFunction(txKey, addList, removeList, count, signData); String priKey = seedList.get(0); String address = Credentials.create(priKey).getAddress(); return this.sendTx(htgWalletApi, multySignContractAddress, address, priKey, function, HeterogeneousChainTxType.CHANGE); } protected String sendTx(HtgWalletApi htgWalletApi, String multySignContractAddress, String fromAddress, String priKey, Function txFunction, HeterogeneousChainTxType txType) throws Exception { return this.sendTx(htgWalletApi, fromAddress, priKey, txFunction, txType, null, multySignContractAddress); } protected String sendTx(HtgWalletApi htgWalletApi, String fromAddress, String priKey, Function txFunction, HeterogeneousChainTxType txType, BigInteger value, String contract) throws Exception { // 估算GasLimit EthEstimateGas estimateGasObj = htgWalletApi.ethEstimateGas(fromAddress, contract, txFunction, value); BigInteger estimateGas = estimateGasObj.getAmountUsed(); if (estimateGas.compareTo(BigInteger.ZERO) == 0) { if (estimateGasObj.getError() != null) { Log.error("Failed to estimate gas, error: {}", estimateGasObj.getError().getMessage()); } else { Log.error("Failed to estimate gas"); } throw new NulsException(ConverterErrorCode.HETEROGENEOUS_TRANSACTION_CONTRACT_VALIDATION_FAILED, txType.toString() + ", 估算GasLimit失败"); } BigInteger gasLimit = estimateGas.add(BigInteger.valueOf(50000L)); HtgSendTransactionPo htSendTransactionPo = htgWalletApi.callContract(fromAddress, priKey, contract, gasLimit, txFunction, value, null, null); String ethTxHash = htSendTransactionPo.getTxHash(); return ethTxHash; } protected String ethSign(List<String> seedList, String hashStr, int signCount) { String result = ""; List<String> addressList = new ArrayList<>(); byte[] hash = Numeric.hexStringToByteArray(hashStr); for (int i = 0; i < signCount; i++) { String prikey = seedList.get(i); Credentials credentials = Credentials.create(prikey); String address = credentials.getAddress(); Sign.SignatureData signMessage = Sign.signMessage(hash, credentials.getEcKeyPair(), false); byte[] signed = new byte[65]; System.arraycopy(signMessage.getR(), 0, signed, 0, 32); System.arraycopy(signMessage.getS(), 0, signed, 32, 32); System.arraycopy(signMessage.getV(), 0, signed, 64, 1); String signedHex = Numeric.toHexStringNoPrefix(signed); result += signedHex; addressList.add(address); } return result; } }
package Servlet; import java.io.IOException; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.Calendar; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; //import javax.servlet.http.HttpSession; import connection.ConnectionClass; @WebServlet(name="Checkout",urlPatterns={"jsp/Checkout"}) public class Checkout extends HttpServlet { private static final long serialVersionUID = 1L; public Checkout() { super(); } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { ConnectionClass obj = new ConnectionClass(); Connection con = null; try { con = obj.getConnection(); } catch (Exception e1) { // TODO Auto-generated catch block e1.printStackTrace(); } //check if user has three books issued: String query1="Select count(*) from book_loans where Date_in IS NULL AND Card_id='"+request.getParameter("cardid")+"'"; PreparedStatement preparedStmtcheck; try { preparedStmtcheck = con.prepareStatement(query1); ResultSet rs=preparedStmtcheck.executeQuery(); int count=0; if(rs.next()) { count=rs.getInt(1); System.out.println("count of active book loans: "+ count); } if(count<3) { //add tuple in book_loan // the mysql insert statement String query = " insert into Book_Loans (isbn, card_id, date_out, due_date)" + " values (?, ?, ?, ?)"; // create the mysql insert preparedstatement PreparedStatement preparedStmt; PreparedStatement preparedStmt2; try { preparedStmt = con.prepareStatement(query); preparedStmt.setString (1, request.getParameter("isbn")); preparedStmt.setString (2, request.getParameter("cardid")); java.sql.Date sqlDate = new java.sql.Date(new java.util.Date().getTime()); preparedStmt.setDate(3, sqlDate); // return date Calendar cal = Calendar.getInstance(); System.out.println("current date: " + cal.getTime()); cal.add(Calendar.DATE, 14); System.out.println("14 days later: " + cal.getTime()); java.sql.Date javaSqlDate = new java.sql.Date(cal.getTime().getTime()); preparedStmt.setDate(4, javaSqlDate); preparedStmt.execute(); //update the book availability String query2= "update book set Availability='no' where isbn='"+request.getParameter("isbn")+"'"; preparedStmt2 = con.prepareStatement(query2); preparedStmt2.executeUpdate(); response.setContentType("text/html;charset=UTF-8"); response.getWriter().write("Checkout Successfull!"); } catch (SQLException e1) { response.setContentType("text/html;charset=UTF-8"); response.getWriter().write("Checkout Failed!"); // TODO Auto-generated catch block e1.printStackTrace(); } }else { response.setContentType("text/html;charset=UTF-8"); response.getWriter().write("Checkout Failed as the borrower has reached maximum limited of book loans!"); } } catch (SQLException e) { response.setContentType("text/html;charset=UTF-8"); response.getWriter().write("Checkout Failed!"); // TODO Auto-generated catch block e.printStackTrace(); } } }
package be.odisee.pajotter.dao; import java.util.List; import org.springframework.stereotype.Repository; import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.annotation.Propagation; import be.odisee.pajotter.domain.Partij; import be.odisee.pajotter.domain.Vraag; import be.odisee.pajotter.utilities.RolNotFoundException; @Repository("vraagDao") @Transactional(propagation= Propagation.SUPPORTS, readOnly=true) public class VraagHibernateDao extends HibernateDao implements VraagDao { @Override public Vraag saveVraag(Vraag vraag) { sessionSaveObject(vraag); return vraag; } /*@Override public Vraag saveVraag(Vraag vraag, int partijid) { sessionSaveObject(vraag); return vraag; }*/ @Override public Vraag getVraagById(int vraagId) { return (Vraag) sessionGetObjectById("Vraag", vraagId); } @SuppressWarnings("unchecked") @Override public List<Vraag> getAllVraag(int id) { //return (List<Vraag>) sessionGetAllObjects("Vraag"); return (List<Vraag>) sessionGetAllObjectsBySpecificId("Vraag", "partij_id", id); } public List<Vraag> getAllVraag() { //return (List<Vraag>) sessionGetAllObjects("Vraag"); return (List<Vraag>) sessionGetAllObjects("Vraag"); } @Override public void updateVraag(Vraag vraag) { sessionUpdateObject(vraag); } @Override public void deleteVraag(int vraagId) { Vraag prodObj = getVraagById(vraagId); sessionDeleteObject(prodObj); } }
package com.social.server.controller; import com.social.server.dto.UserDto; import com.social.server.http.ErrorCode; import com.social.server.http.Response; import com.social.server.service.UserService; 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.RequestParam; import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping("/api/v1") public class LoginController { private final UserService userService; @Autowired public LoginController(UserService userService) { this.userService = userService; } @GetMapping("/login") public Response login(@RequestParam String email, @RequestParam String password) { UserDto userDto = userService.findBy(email, password); if (userDto != null) { return Response.authorized(userDto); } return Response.error(ErrorCode.LOGIN_CREDENTIALS_ERROR); } }
package com.neu.spring; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import javax.servlet.http.HttpServletRequest; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.servlet.ModelAndView; import com.neu.spring.dao.StockDao; import com.neu.spring.pojo.StockCurrentInfo; import com.neu.spring.pojo.StockInfo; @Controller public class DeleteStockController { @Autowired @Qualifier("stockDao") StockDao stockDao; @RequestMapping(method=RequestMethod.GET,value="/deletestock.htm") protected ModelAndView intializeForm(HttpServletRequest request) { StockInfo stockInfo=null; long id=Long.parseLong(request.getParameter("id")); List stockList = new ArrayList(); // List stockList1 = new ArrayList(); try { stockDao.deleteUser(id); stockList=stockDao.list(); // Iterator eventIterator = stockList.iterator(); // // while (eventIterator.hasNext()) // { // StockInfo stockCurrentInfo = (StockInfo) eventIterator.next(); // stockList1.add(stockInfo); // } } catch (Exception e) { System.out.println(e.getMessage()); } ModelAndView mv = new ModelAndView("stockeventsoffering", "stocks", stockList); return mv; } }
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class main { public static void main(String[] args){ InputStreamReader input = new InputStreamReader(System.in); BufferedReader tastiera = new BufferedReader(input); String modello = ""; int cilindrata = 0; float prezzo = 0; boolean err = true; System.out.println("Inserisci il modello"); try { modello = tastiera.readLine(); } catch (IOException e) { System.out.println("Errore di IO"); //e.printStackTrace(); } do { System.out.println("Inserisci cilindrata"); try { cilindrata = Integer.parseInt(tastiera.readLine()); err = false; } catch (IOException e) { System.out.println("Errore di IO"); } catch (NumberFormatException e) { System.out.println("non hai inserito un numero intero"); } }while(err || cilindrata <0); err = true; do { System.out.println("Inserisci prezzo"); try { prezzo = Float.parseFloat(tastiera.readLine()); } catch (IOException e) { System.out.println("Errore di IO"); } catch (NumberFormatException e) { System.out.println("non hai inserito un numero decimale o intero\n"); } }while(err || prezzo>0); AutoVenduta av1 = new AutoVenduta(modello, cilindrata, prezzo); AutoVenduta av2 = new AutoVenduta("bmw" , 2000, 80000); AutoVenduta av3 = new AutoVenduta("fiat" , 4000, 30000); if(av1.isPiuCara(av2)){ System.out.println("av1 e' piu' cara di av2"); }else{ System.out.println("av2 e' piu' cara di av1"); } Venduta v = new Venduta("tommy" , "genovese"); v.add(av1); v.add(av2); v.add(av3); v.getMediaPrezzo(); System.out.println(v.toString()); } }
package com.appdevgenie.practiceproject.ui.main; import android.util.Log; import androidx.lifecycle.LiveData; import androidx.lifecycle.MutableLiveData; import androidx.lifecycle.ViewModel; import com.appdevgenie.practiceproject.models.Skill; import com.appdevgenie.practiceproject.service.LearnerDataInterface; import com.appdevgenie.practiceproject.service.RetrofitInstance; import java.util.List; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; public class SkillsViewModel extends ViewModel { public static final String TAG = "SkillsViewModel"; private MutableLiveData<List<Skill>> skillsListMutableLiveData; public LiveData<List<Skill>> getSkillsData() { if (skillsListMutableLiveData == null) { skillsListMutableLiveData = new MutableLiveData<>(); loadSkillsInfo(); } return skillsListMutableLiveData; } private void loadSkillsInfo() { LearnerDataInterface learnerDataInterface = RetrofitInstance.getServiceInterface(); Call<List<Skill>> skillCall = learnerDataInterface.getLearnerSkills(); skillCall.enqueue(new Callback<List<Skill>>() { @Override public void onResponse(Call<List<Skill>> call, Response<List<Skill>> response) { Log.d(TAG, "onResponse:" + response.toString()); if (response.isSuccessful()) { List<Skill> skillsList = response.body(); skillsListMutableLiveData.setValue(skillsList); } } @Override public void onFailure(Call<List<Skill>> call, Throwable t) { Log.d(TAG, "onResponse: failed" + t.getMessage()); } }); } }
package com.example.itime; import android.content.DialogInterface; import android.content.Intent; import android.os.Bundle; import com.google.android.material.appbar.AppBarLayout; import com.google.android.material.floatingactionbutton.FloatingActionButton; import com.google.android.material.snackbar.Snackbar; import androidx.annotation.Nullable; import androidx.appcompat.app.AppCompatActivity; import androidx.appcompat.widget.Toolbar; import android.os.CountDownTimer; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.animation.AlphaAnimation; import android.widget.Chronometer; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import java.util.Timer; import java.util.TimerTask; public class ContentActivity extends AppCompatActivity { public static final int REQUEST_CODE_EDIT = 903; private TextView textView_contentTitle,textView_contentDdl,textView_contentCount; private int editPosition,photoId; private String ddl,title; private CountDownTimer countDownTimer; private Chronometer countUpTimer; private TimerTask timerTask; private long timeMillis_now,timeMillis_set,diff; private ImageView imageView; private long day; public static String dateFormatYMDofChinese = "yyyy年MM月dd日"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_content); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); textView_contentCount=findViewById(R.id.textView_contentCount); textView_contentTitle=findViewById(R.id.textView_contentTitle); textView_contentDdl=findViewById(R.id.textView_contentDdl); imageView=findViewById(R.id.imageView_toolbar); AppBarLayout appBarLayout=findViewById(R.id.app_bar); Bundle bundle=getIntent().getExtras(); title=bundle.getString("title"); ddl=bundle.getString("ddl"); editPosition =bundle.getInt("position"); photoId=bundle.getInt("photoId"); imageView.setImageResource(photoId); /*AlphaAnimation alpha = new AlphaAnimation(0.5F, 0.5F); alpha.setDuration(0); alpha.setFillAfter(true); imageView.startAnimation(alpha);*/ //getWindow().setBackgroundDrawableResource(photoId); getSupportActionBar().setDisplayHomeAsUpEnabled(true);//左侧添加一个默认的返回图标 getSupportActionBar().setHomeButtonEnabled(true); //设置返回键可用 transToMillis(); initData(); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.menu_content, menu); return true; } public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: finish(); break; case R.id.item_edit://进入编辑界面 Intent intent=new Intent(ContentActivity.this,AddNewActivity.class); intent.putExtra("title",title); intent.putExtra("ddl",ddl); setResult(RESULT_OK, intent); startActivityForResult(intent,1); break; case R.id.item_delete: new android.app.AlertDialog.Builder(this) .setIcon(android.R.drawable.ic_dialog_alert) .setTitle("询问") .setMessage("是否删除该计时?") .setPositiveButton("确定", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { Intent intent = new Intent(ContentActivity.this,MainActivity.class); intent.putExtra("info",0); startActivity(intent); } }) .setNegativeButton("取消", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { } }) .create().show(); break; } return true; } @Override protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) { super.onActivityResult(requestCode, resultCode, data); switch(requestCode) { case 1:{ if(resultCode==1) { Intent intent = new Intent(); String title=data.getStringExtra("biaoti"); String riqi=data.getStringExtra("riqi"); intent.putExtra("title",title); intent.putExtra("ddl",riqi); intent.putExtra("day",day); setResult(3,intent); Toast.makeText(this, "修改成功", Toast.LENGTH_SHORT).show(); finish(); } break; } } } public void initData() { textView_contentTitle.setText(title); textView_contentDdl.setText(ddl); countDownTimer = new CountDownTimer(diff, 1000) { @Override public void onTick(long millisUntilFinished) { if (!ContentActivity.this.isFinishing()) { day = millisUntilFinished / (1000 * 24 * 60 * 60); //单位天 long hour = (millisUntilFinished - day * (1000 * 24 * 60 * 60)) / (1000 * 60 * 60); //单位时 long minute = (millisUntilFinished - day * (1000 * 24 * 60 * 60) - hour * (1000 * 60 * 60)) / (1000 * 60); //单位分 long second = (millisUntilFinished - day * (1000 * 24 * 60 * 60) - hour * (1000 * 60 * 60) - minute * (1000 * 60)) / 1000; //单位秒 textView_contentCount.setText(day + "天" + hour + "小时" + minute + "分钟" + second + "秒"); } } /** * 倒计时结束后调用的 */ @Override public void onFinish() { } }; countDownTimer.start(); } @Override protected void onDestroy() { super.onDestroy(); if (countDownTimer != null) { countDownTimer.cancel(); countDownTimer = null; } } @Override protected void onStop() { super.onStop(); if (countDownTimer != null) { countDownTimer.cancel(); countDownTimer = null; } } public void transToMillis() { try{ Calendar calendar = Calendar.getInstance(); timeMillis_now=calendar.getTimeInMillis(); calendar.setTime(new SimpleDateFormat("yyyy年MM月dd日").parse(ddl)); timeMillis_set=calendar.getTimeInMillis(); diff=timeMillis_set-timeMillis_now; }catch(ParseException e){ e.printStackTrace(); } } /** * 取指定日期为星期几 * * @param strDate 指定日期 * @param inFormat 指定日期格式 * @return String 星期几 */ public static String getWeekNumber(String strDate, String inFormat) { String week = "星期日"; Calendar calendar = new GregorianCalendar(); DateFormat df = new SimpleDateFormat(inFormat); try { calendar.setTime(df.parse(strDate)); } catch (Exception e) { return "错误"; } int intTemp = calendar.get(Calendar.DAY_OF_WEEK) - 1; switch (intTemp) { case 0: week = "星期日"; break; case 1: week = "星期一"; break; case 2: week = "星期二"; break; case 3: week = "星期三"; break; case 4: week = "星期四"; break; case 5: week = "星期五"; break; case 6: week = "星期六"; break; } return week; } }
package org.shujito.cartonbox.view.adapter; import java.text.DecimalFormat; import java.util.ArrayList; import java.util.List; import org.shujito.cartonbox.R; import org.shujito.cartonbox.controller.listener.OnTagsFetchedListener; import org.shujito.cartonbox.model.Tag; import org.shujito.cartonbox.view.PostsFilter.FilterCallback; import org.shujito.cartonbox.view.TagsFilter; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.Filter; import android.widget.Filterable; import android.widget.TextView; public class TagsAdapter extends BaseAdapter implements OnTagsFetchedListener, Filterable, FilterCallback<List<Tag>> { private Filter filter = null; private Context context = null; private List<Tag> tags = null; public TagsAdapter(Context context) { this.context = context; this.tags = new ArrayList<Tag>(); } @Override public int getCount() { // number of entries if(this.tags != null) return this.tags.size(); return 0; } @Override public Object getItem(int pos) { Tag tag = this.tags.get(pos); if(tag != null) { // returns the tag name instead of the tags object's tostring value return tag.getName(); } return null; } @Override public long getItemId(int pos) { // why do we need this? return this.tags.get(pos).hashCode(); } @Override public View getView(int pos, View v, ViewGroup dad) { if(v == null) { LayoutInflater inf = LayoutInflater.from(this.context); v = inf.inflate(R.layout.item_tag, dad, false); } // ah, there we go... Tag tag = this.tags.get(pos); DecimalFormat formatter = new DecimalFormat("#,###"); int color = 0; switch(tag.getCategory()) { case General: color = 0xFF50C0E9; break; case Artist: color = 0xFFFF5F5F; break; case Copyright: color = 0xFFC182E0; break; case Character: color = 0xFF99CC00; break; case Other1: // circle/model color = 0xFFFFD060; break; case Other2: // faults/photoset color = 0xFFCCCCCC; break; default: color = 0xFFCCCCCC; break; } ((TextView)v.findViewById(R.id.tvName)).setText(tag.getName()); ((TextView)v.findViewById(R.id.tvName)).setTextColor(color); ((TextView)v.findViewById(R.id.tvCount)).setText(formatter.format(tag.getCount())); return v; } @Override public Filter getFilter() { // when a filter is absent, create one if(this.filter == null) this.filter = new TagsFilter(this); return this.filter; } @Override public void onFilter(List<Tag> result) { this.tags = result; this.notifyDataSetChanged(); } @Override public void onTagsFetchedListener(List<Tag> tags) { this.tags = tags; this.notifyDataSetChanged(); } }
package com.masters; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.ConfigurableApplicationContext; @SpringBootApplication public class MyServiceApplication { public static void main(String[] args) { ConfigurableApplicationContext ctx = SpringApplication.run(MyServiceApplication.class, args); /*System.out.println("Inspect beans:"); String[] beanNames = ctx.getBeanDefinitionNames(); Arrays.sort(beanNames); for(String beanName : beanNames) System.out.println(beanName);*/ } }
package com.auro.scholr.home.presentation.viewmodel; import static com.auro.scholr.core.common.Status.DASHBOARD_API; import android.util.Log; import androidx.lifecycle.LiveData; import androidx.lifecycle.MutableLiveData; import androidx.lifecycle.ViewModel; import com.auro.scholr.R; import com.auro.scholr.core.application.AuroApp; import com.auro.scholr.core.common.MessgeNotifyStatus; import com.auro.scholr.core.common.ResponseApi; import com.auro.scholr.core.common.Status; import com.auro.scholr.core.database.AppPref; import com.auro.scholr.core.database.PrefModel; import com.auro.scholr.home.data.model.AuroScholarDataModel; import com.auro.scholr.home.data.model.AuroScholarInputModel; import com.auro.scholr.home.data.model.DynamiclinkResModel; import com.auro.scholr.home.data.model.FetchStudentPrefReqModel; import com.auro.scholr.home.data.model.SendOtpReqModel; import com.auro.scholr.home.data.model.UpdatePrefReqModel; import com.auro.scholr.home.data.model.VerifyOtpReqModel; import com.auro.scholr.home.domain.usecase.HomeDbUseCase; import com.auro.scholr.home.domain.usecase.HomeRemoteUseCase; import com.auro.scholr.home.domain.usecase.HomeUseCase; import com.auro.scholr.util.AppLogger; import com.auro.scholr.util.TextUtil; import io.reactivex.android.schedulers.AndroidSchedulers; import io.reactivex.disposables.CompositeDisposable; import io.reactivex.disposables.Disposable; import io.reactivex.functions.Consumer; import io.reactivex.schedulers.Schedulers; public class HomeViewModel extends ViewModel { HomeUseCase homeUseCase; HomeDbUseCase homeDbUseCase; HomeRemoteUseCase homeRemoteUseCase; CompositeDisposable compositeDisposable; public MutableLiveData<ResponseApi> serviceLiveData = new MutableLiveData<>(); public HomeViewModel(HomeUseCase homeUseCase, HomeDbUseCase homeDbUseCase, HomeRemoteUseCase homeRemoteUseCase) { this.homeUseCase = homeUseCase; this.homeDbUseCase = homeDbUseCase; this.homeRemoteUseCase = homeRemoteUseCase; } private CompositeDisposable getCompositeDisposable() { if (compositeDisposable == null) { compositeDisposable = new CompositeDisposable(); } return compositeDisposable; } public LiveData<ResponseApi> serviceLiveData() { return serviceLiveData; } public void getDynamicData(DynamiclinkResModel reqmodel) { Log.i("Dynamiclink","Working"); Disposable disposable = homeRemoteUseCase.isAvailInternet().subscribe(hasInternet -> { if (hasInternet) { getDynamicDataApi(reqmodel); } else { // please check your internet serviceLiveData.setValue(new ResponseApi(Status.NO_INTERNET, AuroApp.getAppContext().getResources().getString(R.string.internet_check), Status.NO_INTERNET)); } }); getCompositeDisposable().add(disposable); } private void defaultError() { serviceLiveData.setValue(new ResponseApi(Status.FAIL, AuroApp.getAppContext().getResources().getString(R.string.default_error), null)); } private void defaultError(Status status) { serviceLiveData.setValue(new ResponseApi(Status.FAIL, AuroApp.getAppContext().getResources().getString(R.string.default_error), null)); } private void getDynamicDataApi(DynamiclinkResModel model) { getCompositeDisposable() .add(homeRemoteUseCase.getDynamicDataApi(model) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(new Consumer<ResponseApi>() { @Override public void accept(ResponseApi responseApi) throws Exception { serviceLiveData.setValue(responseApi); } }, new Consumer<Throwable>() { @Override public void accept(Throwable throwable) throws Exception { defaultError(); } })); } public void verifyOtpApi(VerifyOtpReqModel reqModel){ Disposable disposable = homeRemoteUseCase.isAvailInternet().subscribe(hasInternet ->{ if(hasInternet){ verifyOtpRxApi(reqModel); }else { serviceLiveData.setValue(new ResponseApi(Status.NO_INTERNET, AuroApp.getAppContext().getString(R.string.internet_check), Status.SEND_OTP)); } }); getCompositeDisposable().add(disposable); } private void verifyOtpRxApi(VerifyOtpReqModel reqModel) { getCompositeDisposable().add(homeRemoteUseCase.verifyOtpApi(reqModel).subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(new Consumer<ResponseApi>() { @Override public void accept(ResponseApi responseApi) throws Exception { serviceLiveData.setValue(responseApi); } }, new Consumer<Throwable>() { @Override public void accept(Throwable throwable) throws Exception { defaultError(); } })); } public void sendOtpApi(SendOtpReqModel reqModel){ Disposable disposable = homeRemoteUseCase.isAvailInternet().subscribe(hasInternet ->{ if(hasInternet){ sendOtpRxApi(reqModel); }else { serviceLiveData.setValue(new ResponseApi(Status.NO_INTERNET, AuroApp.getAppContext().getString(R.string.internet_check), Status.SEND_OTP)); } }); getCompositeDisposable().add(disposable); } private void sendOtpRxApi(SendOtpReqModel reqModel) { getCompositeDisposable().add(homeRemoteUseCase.sendOtpApi(reqModel).subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(new Consumer<ResponseApi>() { @Override public void accept(ResponseApi responseApi) throws Exception { serviceLiveData.setValue(responseApi); } }, new Consumer<Throwable>() { @Override public void accept(Throwable throwable) throws Exception { defaultError(); } })); } public void checkInternetForApi(Status status, Object reqmodel) { Disposable disposable = homeRemoteUseCase.isAvailInternet().subscribe(hasInternet -> { if (hasInternet) { switch (status) { case SUBJECT_PREFRENCE_LIST_API: preferenceSubjectList(); break; case DYNAMIC_LINK_API: getDynamicDataApi((DynamiclinkResModel) reqmodel); break; case UPDATE_PREFERENCE_API: updateStudentPreference((UpdatePrefReqModel) reqmodel); break; case FETCH_STUDENT_PREFERENCES_API: fetchStudentPreference((FetchStudentPrefReqModel) reqmodel); break; case DASHBOARD_API: getDashboardData((AuroScholarDataModel) reqmodel); break; case LANGUAGE_LIST: languageListApiCall(); break; } } else { // please check your internet serviceLiveData.setValue(new ResponseApi(Status.NO_INTERNET, AuroApp.getAppContext().getResources().getString(R.string.internet_check), Status.NO_INTERNET)); } }); getCompositeDisposable().add(disposable); } private void preferenceSubjectList() { getCompositeDisposable() .add(homeRemoteUseCase.preferenceSubjectList() .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(new Consumer<ResponseApi>() { @Override public void accept(ResponseApi responseApi) throws Exception { serviceLiveData.setValue(responseApi); } }, new Consumer<Throwable>() { @Override public void accept(Throwable throwable) throws Exception { defaultError(); } })); } private void updateStudentPreference(UpdatePrefReqModel reqModel) { getCompositeDisposable() .add(homeRemoteUseCase.updateStudentPreference(reqModel) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(new Consumer<ResponseApi>() { @Override public void accept(ResponseApi responseApi) throws Exception { serviceLiveData.setValue(responseApi); } }, new Consumer<Throwable>() { @Override public void accept(Throwable throwable) throws Exception { defaultError(); } })); } public void fetchStudentPreference(FetchStudentPrefReqModel reqModel) { getCompositeDisposable().add(homeRemoteUseCase.fetchStudentPreferenceApi(reqModel).subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(new Consumer<ResponseApi>() { @Override public void accept(ResponseApi responseApi) throws Exception { AppLogger.e("fetchStudentPreference--","responseApi "); serviceLiveData.setValue(responseApi); } }, new Consumer<Throwable>() { @Override public void accept(Throwable throwable) throws Exception { AppLogger.e("fetchStudentPreference--","Exception "); defaultError(); } })); } public void getDashboardData(AuroScholarDataModel inputModel) { /* AuroScholarDataModel auroScholarDataModel = new AuroScholarDataModel(); auroScholarDataModel.setMobileNumber(inputModel.getMobileNumber()); auroScholarDataModel.setStudentClass(inputModel.getStudentClass()); auroScholarDataModel.setRegitrationSource(inputModel.getRegitrationSource()); auroScholarDataModel.setActivity(inputModel.getActivity()); auroScholarDataModel.setFragmentContainerUiId(inputModel.getFragmentContainerUiId()); auroScholarDataModel.setReferralLink(inputModel.getReferralLink());*/ /* if (TextUtil.isEmpty(inputModel.getPartnerSource())) { inputModel.setPartnerSource(""); } else { inputModel.setPartnerSource(inputModel.getPartnerSource()); }*/ PrefModel prefModel = AppPref.INSTANCE.getModelInstance(); if (prefModel.getDeviceToken() != null && !TextUtil.isEmpty(prefModel.getDeviceToken())) { inputModel.setDevicetoken(prefModel.getDeviceToken()); } else { inputModel.setDevicetoken(""); } dashBoardApi(inputModel); } private void dashBoardApi(AuroScholarDataModel model) { getCompositeDisposable() .add(homeRemoteUseCase.getDashboardData(model) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(new Consumer<ResponseApi>() { @Override public void accept(ResponseApi responseApi) throws Exception { serviceLiveData.setValue(responseApi); } }, new Consumer<Throwable>() { @Override public void accept(Throwable throwable) throws Exception { defaultError(DASHBOARD_API); } })); } private void languageListApiCall() { getCompositeDisposable() .add(homeRemoteUseCase.getLanguageList() .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe( new Consumer<ResponseApi>() { @Override public void accept(ResponseApi responseApi) throws Exception { serviceLiveData.setValue(responseApi); } }, new Consumer<Throwable>() { @Override public void accept(Throwable throwable) throws Exception { defaultError(); } } )); } }
package tests.main_view_partner; import baseplatformANDROID.BaseTest; import baseplatform.DataClass; import objects_partner.MainViewPartner; import org.testng.annotations.*; import utility.ReusMeth; import java.io.IOException; import static org.testng.Assert.assertEquals; /* by Sergey */ public class UiElementsTextConsistencyTest extends BaseTest { private MainViewPartner mvp; String testName = null; @BeforeClass public void setUpLaunching() { testName = this.getClass().getSimpleName(); mvp = new MainViewPartner(driver); } @BeforeMethod public void onStartingMethodWithinClass() { driver.launchApp(); } @AfterMethod public void onFinishingMethodWithinCLass() { driver.closeApp(); } @Test public void verifyUiElementsTextConsistency() throws IOException, InterruptedException { //Check Text on the Display Image Button assertEquals(mvp.getTextDisplayImageButton(), "Display Image"); //Check Text on the Display Video Button assertEquals(mvp.getTextDisplayVideoButton(),"Display Video"); //Check Text on the Display OFF Button assertEquals(mvp.getTextDisplayOffButton(),"Display OFF"); //Check Text on the Send Text Button assertEquals(mvp.getTextFromSendTextButton(),"Send Text"); } @AfterClass public void tearDown() throws InterruptedException { ReusMeth.waiting(5); } }
package com.citibank.ods.persistence.pl.dao; import java.math.BigInteger; import com.citibank.ods.common.dataset.DataSet; import com.citibank.ods.entity.pl.TplRelationPrvtEntity; // //©2002-2007 Accenture. All rights reserved. // /** * [Class description] * * @see package com.citibank.ods.persistence.pl.dao; * @version 1.0 * @author gerson.a.rodrigues,Mar 29, 2007 * * <PRE> * * <U>Updated by: </U> <U>Description: </U> * * </PRE> */ public interface TplRelationPrvtDAO extends BaseTplRelationPrvtDAO { public DataSet list( BigInteger reltnNbr_, BigInteger reltnCust1Nbr_, String custFullNameText_, String ownerSelected_, BigInteger acctNbr_, BigInteger custCpfCnpjNbr_ ); public boolean existsActive( TplRelationPrvtEntity tplRelationPrvtEntity_ ); }
package model; import java.util.ArrayList; import model.*; public class Company { //attributes private String name; //constants public static final int MAXCLIENTS = 5; public static final String MORGAN = "Morgan"; //relation public Client [] clients; //methods /** *This method is the constructor of company. * *<b>pre:</b> <br> * *@param name is the name of the company called "Morgan" * *<b>post:</b> Returns an object of company type. <br> *<b>post:</b> Create the array of clients. <br> */ public Company(){ this.name = MORGAN; clients = new Client[MAXCLIENTS]; } /** * This method add a new client depending of the result of the method searchClient * * @param name is the name of the client to create * @param kgSent is the kgSent of the client to create * @param valuePaid is the value paid of the client to create * @param clientType is the type of the client to create * @param register is the mercantile register number of the client to create * @param expDay is the day of expedition of the register of the client to create * @param expMonth is the month of expedition of the register of the client to create * @param expYear is the year of expedition of the register of the client to create * @return returns a message that says what happened with the client */ public String addClient(String name, int kgSent, double valuePaid, String clientType, int register, int expDay, int expMonth, int expYear) { String message = ""; boolean addClient=false; Client objSearch=searchClient(register); if (objSearch!=null) message="The client already exists"; else { for (int i=0;i<clients.length && !addClient;i++){ if (clients[i]== null){ clients[i] = new Client(name, kgSent, valuePaid, clientType, register, expDay, expMonth, expYear); addClient=true; message="The new client was successfully registered"; } } if (addClient==false) message="The client arrangement has reached its maximum capacity"; } return message; } /** *This is method search the client by his name. * *<b>pre:</b>A client was created as minimum. <br> *<b>pre:</b>The client has successfully submitted a load at least. <br> * *@param name the name of client to search * *<b>post:</b> Returns objSearch as an object of Client type. <br> */ public Client searchClient(int register){ Client objSearch=null; boolean findClient=false; for (int i=0;i<clients.length&&!findClient;i++){ if (clients[i]!= null){ if(clients[i].getRegister()==register) { objSearch=clients[i]; findClient=true; } } } return objSearch; } /** *This is method adds a new load weight to the historical kilograms transported by client. * *<b>pre:</b>A client was created as minimum. <br> *<b>pre:</b>The client has successfully submitted a load at least. <br> * *@param name the name of client to search *@param x is the weight of the load of a client */ public void totalKgAccumulate(int x, String name) { for (int i = 0; i < clients.length; i++) { if(clients[i].getName().equalsIgnoreCase(name)) { double a = clients[i].getKgSent(); a+=x; clients[i].setKgSent(a); } } } /** * This method save the historical value paid by the client * * @param x is the total value paid at the moment of add loads to the ship * @param name is the name of the client */ public void totalValuePaidAccumulate(double x, String name) { for (int i = 0; i < clients.length; i++) { if(clients[i].getName().equalsIgnoreCase(name)) { double a = clients[i].getValuePaid(); a+=x; clients[i].setValuePaid(a); } } } /** *This is method calculate the type of client. * *<b>pre:</b>A load of client was created as minimum. <br> *<b>pre:</b>The client has successfully submitted a load at least. <br> * *@param kgSent is the attribute of client about the historical kilograms sent *@param totalValue is value with discount to pay *@param select is the position of the array of clients * *<b>post:</b> Returns updated as boolean that means if the client was upgraded to a new category or not. <br> *<b>post:</b> Sets the new category of client or not. <br> */ public boolean calculateClientType(double kgSent, double valuePaid, int position) { boolean updated = false; if(kgSent>=35000 && clients[position].getClientType() == "NORMAL") { clients[position].setClientType("SILVER"); updated = true; } else if(kgSent>=55000||valuePaid>=2000000 && clients[position].getClientType() == "SILVER") { clients[position].setClientType("GOLD"); updated = true; } else if(valuePaid>=5000000 && clients[position].getClientType() == "GOLD") { clients[position].setClientType("PLATINUM"); updated = true; } return updated; } /** *This is method shows if the client was upgraded or not. * *<b>pre:</b>A load of client was created as minimum. <br> *<b>pre:</b>The client has successfully submitted a load at least. <br> * *@param updated is a boolean that means if the client was upgraded to a new category or not *@param select is the position of the array of clients * *<b>post:</b> Returns message if the client was upgraded to a new category or not. <br> */ public String notifyNewClientType(boolean updated, int position) { String message = ""; int a = position; a+=1; if(updated == true) { message = "The client #"+ a + " called " +clients[position].getName()+" has the new category: "+clients[position].getClientType()+" \n"; } else if (updated == false) { message = "The client #"+ a + " called " +clients[position].getName()+" cannot upgrade his category, remains on: "+clients[position].getClientType()+" \n"; } return message; } }
package ru.geekbrains.lesson2; import lesson2.Array; import java.util.Arrays; public class HomeworkArrayImpl<E extends Comparable<? super E>> implements Array<E> { private static final int DEFAULT_CAPACITY = 8; protected E[] data; protected int size; public HomeworkArrayImpl() { this.data = (E[]) new Comparable[DEFAULT_CAPACITY]; } public HomeworkArrayImpl(int initialCapacity) { this.data = (E[]) new Comparable[initialCapacity]; } public HomeworkArrayImpl(Array<E> copy) { this.data = (E[]) new Comparable[copy.size()]; for (int i = 0; i < copy.size(); i++) { add(copy.get(i)); } } @Override public void add(E value) { checkAndGrow(); data[size] = value; size++; } protected void checkAndGrow() { if (data.length == size) { data = Arrays.copyOf(data, size == 0 ? 1 : size * 2); } } @Override public E get(int index) { checkIndex(index); return data[index]; } private void checkIndex(int index) { if (index < 0 || index >= size) { String errorMsg = String.format("Incorrect 'index': %d; max value is %d", index, size - 1); throw new IndexOutOfBoundsException(errorMsg); } } @Override public boolean remove(E value) { int index = indexOf(value); checkAndShrink(); return index != -1 && remove(index) != null; } @Override public E remove(int index) { checkIndex(index); E removedValue = data[index]; System.arraycopy(data, index + 1, data, index, size - index - 1); data[--size] = null; checkAndShrink(); return removedValue; } protected void checkAndShrink() { if (data.length >= size / 2 + size % 2) { data = Arrays.copyOf(data, size - size / 4); } } @Override public int indexOf(E value) { for (int i = 0; i < size; i++) { if (value.equals(data[i])) { return i; } } return -1; } @Override public boolean contains(E value) { return indexOf(value) > -1; } @Override public int size() { return size; } @Override public boolean isEmpty() { return size == 0; } @Override public void display() { System.out.println(this); } @Override public void sortBubble() { for (int i = 0; i < size - 1; i++) { for (int j = 0; j < size - 1 - i; j++) { if (data[j].compareTo(data[j + 1]) > 0) { E temp = data[j]; data[j+1] = data[j]; data[j] = temp; } } } } @Override public void sortSelect() { for (int i = 0; i < size - 1; i++) { int newIndex = i; for (int j = i + 1; j < size; j++) { if (data[j].compareTo(data[newIndex]) < 0) { newIndex = j; } } E temp = data[newIndex]; data[newIndex] = data[i]; data[i] = temp; } } @Override public void sortInsert() { for (int i = 1; i < size; i++) { E temp = data[i]; int j = i; while (j > 0 && data[j - 1].compareTo(temp) >= 0) { data[j] = data[--j]; } data[j] = temp; } } @Override public String toString() { StringBuilder sb = new StringBuilder("["); for (int i = 0; i < size -1; i++) { sb.append(data[i]); sb.append(", "); } if (size > 0) { sb.append(data[size - 1]); } sb.append("]"); return sb.toString(); } }
/* * This file is part of gplugins, licensed under the MIT License (MIT). * * Copyright (c) 2017, Jamie Mansfield <https://www.jamierocks.uk/> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package uk.jamierocks.canary.gplugins.processor; import static javax.tools.StandardLocation.CLASS_OUTPUT; import uk.jamierocks.canary.gplugins.Plugin; import java.io.BufferedWriter; import java.io.IOException; import java.util.Properties; import java.util.Set; import javax.annotation.processing.AbstractProcessor; import javax.annotation.processing.RoundEnvironment; import javax.annotation.processing.SupportedAnnotationTypes; import javax.annotation.processing.SupportedSourceVersion; import javax.lang.model.SourceVersion; import javax.lang.model.element.Element; import javax.lang.model.element.ElementKind; import javax.lang.model.element.TypeElement; import javax.tools.Diagnostic; @SupportedAnnotationTypes("uk.jamierocks.canary.gplugins.Plugin") @SupportedSourceVersion(SourceVersion.RELEASE_8) public class PluginProcessor extends AbstractProcessor { @Override public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) { for (Element annotatedElement : roundEnv.getElementsAnnotatedWith(Plugin.class)) { if (annotatedElement.getKind() != ElementKind.CLASS) { this.error("Only classes can be annotated with @Plugin", annotatedElement); return false; } final TypeElement pluginElement = (TypeElement) annotatedElement; final Plugin plugin = pluginElement.getAnnotation(Plugin.class); // Check plugin name if (plugin.name().isEmpty()) { this.error("The plugin name cannot be empty!", annotatedElement); return false; } // Lets create the Canary.inf final Properties props = new Properties(); props.setProperty("main-class", pluginElement.getQualifiedName().toString()); props.setProperty("name", plugin.name()); if (!plugin.version().isEmpty()) { props.setProperty("version", plugin.version()); } if (!plugin.author().isEmpty()) { props.setProperty("author", plugin.author()); } props.setProperty("language", "gplugin"); if (plugin.enableEarly()) { props.setProperty("enable-early", "true"); } if (plugin.dependencies().length != 0) { props.setProperty("dependencies", this.getDependencies(plugin.dependencies())); } try (BufferedWriter writer = new BufferedWriter(this.processingEnv.getFiler().createResource(CLASS_OUTPUT, "", "Canary.inf").openWriter())) { props.store(writer, "Generated by gplugins"); } catch (IOException e) { e.printStackTrace(); return false; } // There should only ever be one Plugin return true; } return false; } /** * Gets the dependency string for an array of dependencies. * * @param dependencies The dependency array * @return The dependency string */ private String getDependencies(String[] dependencies) { final StringBuilder builder = new StringBuilder(); for (int i = 0; i <= dependencies.length; i++) { builder.append(dependencies[i]); if (i != dependencies.length) { builder.append(","); } } return builder.toString(); } /** * Convenience method for printing an error message. * * @param message The message * @param element The element */ private void error(String message, Element element) { this.processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, message, element); } }
public enum STATUS { AVAILABLE,NOT_AVAILABLE }
/* * Copyright 2002-2022 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.core.testfixture.net; import java.net.InetAddress; import java.net.ServerSocket; import java.util.Random; import javax.net.ServerSocketFactory; /** * Simple utility for finding available TCP ports on {@code localhost} for use in * integration testing scenarios. * * <p>{@code SocketUtils} was removed from the public API in {@code spring-core} * in Spring Framework 6.0 and reintroduced as {@code TestSocketUtils}, which is * made available to all tests in Spring Framework's test suite as a Gradle * <em>test fixture</em>. * * <p>{@code SocketUtils} was introduced in Spring Framework 4.0, primarily to * assist in writing integration tests which start an external server on an * available random port. However, these utilities make no guarantee about the * subsequent availability of a given port and are therefore unreliable. Instead * of using {@code TestSocketUtils} to find an available local port for a server, * it is recommended that you rely on a server's ability to start on a random port * that it selects or is assigned by the operating system. To interact with that * server, you should query the server for the port it is currently using. * * @author Sam Brannen * @author Ben Hale * @author Arjen Poutsma * @author Gunnar Hillert * @author Gary Russell * @since 6.0 */ public abstract class TestSocketUtils { /** * The minimum value for port ranges used when finding an available TCP port. */ private static final int PORT_RANGE_MIN = 1024; /** * The maximum value for port ranges used when finding an available TCP port. */ private static final int PORT_RANGE_MAX = 65535; private static final int PORT_RANGE = PORT_RANGE_MAX - PORT_RANGE_MIN; private static final int MAX_ATTEMPTS = 1_000; private static final Random random = new Random(System.nanoTime()); /** * Find an available TCP port randomly selected from the range [1024, 65535]. * @return an available TCP port number * @throws IllegalStateException if no available port could be found */ public static int findAvailableTcpPort() { int candidatePort; int searchCounter = 0; do { if (searchCounter > MAX_ATTEMPTS) { throw new IllegalStateException(String.format( "Could not find an available TCP port in the range [%d, %d] after %d attempts", PORT_RANGE_MIN, PORT_RANGE_MAX, MAX_ATTEMPTS)); } candidatePort = PORT_RANGE_MIN + random.nextInt(PORT_RANGE + 1); searchCounter++; } while (!isPortAvailable(candidatePort)); return candidatePort; } /** * Determine if the specified TCP port is currently available on {@code localhost}. */ private static boolean isPortAvailable(int port) { try { ServerSocket serverSocket = ServerSocketFactory.getDefault().createServerSocket( port, 1, InetAddress.getByName("localhost")); serverSocket.close(); return true; } catch (Exception ex) { return false; } } }