text stringlengths 10 2.72M |
|---|
package adcar.com.model;
import com.google.android.gms.maps.model.LatLng;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Created by aditya on 02/02/16.
*/
public class AreaCoordinates {
private static AreaCoordinates areaCoordinates = new AreaCoordinates();
Map<String ,List<LatLng>> areas = new HashMap<String, List<LatLng>>();
public static AreaCoordinates getAreaCoordinates(){
return areaCoordinates;
}
}
|
package com.document.feed.controller;
import static org.springframework.http.MediaType.ALL;
import static org.springframework.http.MediaType.APPLICATION_JSON;
import static org.springframework.web.reactive.function.server.RequestPredicates.GET;
import static org.springframework.web.reactive.function.server.RequestPredicates.OPTIONS;
import static org.springframework.web.reactive.function.server.RequestPredicates.POST;
import static org.springframework.web.reactive.function.server.RequestPredicates.accept;
import com.document.feed.service.FeedService;
import com.document.feed.service.NewsService;
import com.document.feed.util.IdUtils;
import com.kwabenaberko.newsapilib.models.response.ArticleResponse;
import java.util.List;
import java.util.concurrent.TimeUnit;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.http.CacheControl;
import org.springframework.http.MediaType;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.web.reactive.function.client.ExchangeFilterFunction;
import org.springframework.web.reactive.function.server.RouterFunction;
import org.springframework.web.reactive.function.server.RouterFunctions;
import org.springframework.web.reactive.function.server.ServerRequest;
import org.springframework.web.reactive.function.server.ServerResponse;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
@Component
@Configuration
@RequiredArgsConstructor
@Slf4j
public class FeedHandler {
private final FeedService feedService;
private final NewsService newsService;
private Mono<ServerResponse> defaultReadResponse(
Flux<com.kwabenaberko.newsapilib.models.Article> articlePublisher) {
return ServerResponse.ok()
.contentType(APPLICATION_JSON)
.header("Access-Control-Allow-Origin", "*")
.body(articlePublisher, com.kwabenaberko.newsapilib.models.Article.class);
}
private ExchangeFilterFunction perResponse() {
return ExchangeFilterFunction.ofResponseProcessor(
clientResponse -> {
clientResponse.headers().asHttpHeaders().forEach((h, g) -> log.info(h + " g: " + g));
return Mono.just(clientResponse);
});
}
@Bean
public RouterFunction<ServerResponse> routeVanillaList() {
return RouterFunctions.route(OPTIONS("/**").and(accept(ALL)), this::HandleOptionsCall)
.andRoute(GET("/vanillalist").and(accept(APPLICATION_JSON)), this::vanillaList)
.andRoute(GET("/list").and(accept(APPLICATION_JSON)), this::list)
.andRoute(GET("/liked").and(accept(APPLICATION_JSON)), this::getPreference)
.andRoute(POST("/like").and(accept(APPLICATION_JSON)), this::savePreference)
.andRoute(POST("/dislike").and(accept(APPLICATION_JSON)), this::deletePreference)
.andRoute(GET("/newsapi/**").and(accept(APPLICATION_JSON)), this::newsAPI);
}
Mono<ServerResponse> newsAPI(ServerRequest r) {
var cacheControl = CacheControl.maxAge(30, TimeUnit.MINUTES);
System.out.println("r.uri(): " + r.uri() + "-" + r.path());
// /newsapi/v2/top-headlines?page=1&pageSize=30&language=en =>
// v2/top-headlines?page=1&pageSize=30&language=en
String path = r.path().substring(9);
return ServerResponse.ok()
.contentType(MediaType.APPLICATION_JSON)
.header("Access-Control-Allow-Origin", "*")
.cacheControl(cacheControl)
.body(
newsService.mimicNewsAPIOrg(path, r.queryParams().toSingleValueMap()),
ArticleResponse.class);
}
Mono<ServerResponse> HandleOptionsCall(ServerRequest r) {
return ServerResponse.ok().bodyValue("OK");
}
Mono<ServerResponse> vanillaList(ServerRequest r) {
PageRequest pageRequest = createPageRequest(r);
return defaultReadResponse(this.feedService.vanillaList(pageRequest));
}
Mono<ServerResponse> list(ServerRequest r) {
PageRequest pageRequest = createPageRequest(r);
return defaultReadResponse(this.feedService.list(pageRequest));
}
public Mono<ServerResponse> deletePreference(ServerRequest request) {
System.out.println("Start deletePreference()");
// Authentication authentication =
// SecurityContextHolder.getContext().getAuthentication();
// String username = (String) authentication.getPrincipal();
Mono<String> item = request.bodyToMono(String.class);
return item.flatMap(
url -> {
var id = IdUtils.id(url);
log.info("objectId: " + id);
return this.feedService
.deletePreference(id)
.then(ServerResponse.ok().contentType(APPLICATION_JSON).bodyValue(id));
});
}
Mono<ServerResponse> getPreference(ServerRequest r) {
r.session()
.subscribe(webSession -> System.out.println("webSession:" + webSession.getCreationTime()));
return defaultReadResponse(this.feedService.getPreference());
}
public Mono<ServerResponse> savePreference(ServerRequest request) {
System.out.println("Start savePreference()");
var authentication = SecurityContextHolder.getContext().getAuthentication();
String username = (String) authentication.getPrincipal();
var item = request.bodyToMono(com.kwabenaberko.newsapilib.models.Article.class);
item.cache();
return item.flatMap(
article -> {
return this.feedService
.savePreference(article, username)
.doOnSuccess(
preference -> {
System.out.println("serverResponse: " + preference);
});
})
.flatMap(x -> ServerResponse.ok().contentType(APPLICATION_JSON).bodyValue(x))
.switchIfEmpty(ServerResponse.notFound().build());
}
private PageRequest createPageRequest(ServerRequest r) {
MultiValueMap<String, String> params = r.queryParams();
System.out.println("headers " + r.queryParams());
int pageSize = 60; // default
Pageable p;
List<String> pageSizeOpt = params.get("limit");
if (null != pageSizeOpt && !pageSizeOpt.isEmpty() && !pageSizeOpt.isEmpty()) {
pageSize = Integer.parseInt(pageSizeOpt.get(0));
}
int pageIndex = 0; // default
List<String> skipOpt = params.get("skip");
if (null != skipOpt && !skipOpt.isEmpty() && !skipOpt.get(0).isEmpty()) {
// TODO(devansh): client can't request page starting from offset 10 of pagesize
// 500. Please handle that.
pageIndex = Integer.parseInt(skipOpt.get(0)) / pageSize;
}
return PageRequest.of(pageIndex, pageSize);
}
}
|
package com.capraro.sinistre.repository;
import com.capraro.sinistre.model.Sinistre;
import io.github.benas.jpopulator.api.Populator;
import io.github.benas.jpopulator.impl.PopulatorBuilder;
import io.github.benas.jpopulator.randomizers.DateStringRandomizer;
import org.springframework.stereotype.Repository;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
/**
* Fake Sinistre Repository.
* Created by Richard Capraro on 07/08/2015.
*/
@Repository
public class SinistreRepositoryImpl implements SinistreRepository {
final static DateFormat DF = new SimpleDateFormat("dd/mm/YYYY");
static Populator POPULATOR;
static {
try {
POPULATOR = new PopulatorBuilder()
.registerRandomizer(Sinistre.class, String.class, "dateSurvenance",
new DateStringRandomizer("dd/mm/YYYY", DF.parse("01/01/2000"), DF.parse("01/01/2016")))
.build();
} catch (ParseException e) {
e.printStackTrace();
}
}
@Override
public List<Sinistre> getSinistres() {
List<Sinistre> sinistres = new ArrayList<>();
for (int i = 0; i < 10; i++) {
sinistres.add(generateRandomSinistre());
}
return sinistres;
}
@Override
public Sinistre getSinistre() {
return generateRandomSinistre();
}
private Sinistre generateRandomSinistre() {
Sinistre contrat = POPULATOR.populateBean(Sinistre.class);
return contrat;
}
}
|
package com.almondtools.stringbench.incubation;
import static com.almondtools.stringbenchanalyzer.Family.PREFIX;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import org.ahocorasick.trie.Emit;
import org.ahocorasick.trie.Trie;
import org.ahocorasick.trie.Trie.TrieBuilder;
import com.almondtools.stringbench.MultiPatternMatcherBenchmark;
import com.almondtools.stringbenchanalyzer.Family;
public class ACAhoCorasickBenchmark extends MultiPatternMatcherBenchmark {
private static final String ID = "AhoCorasick.org Aho-Corasick";
private Trie trie;
@Override
public String getId() {
return ID;
}
@Override
public Family getFamily() {
return PREFIX;
}
@Override
public void prepare(Set<String> patterns) {
TrieBuilder builder = Trie.builder().removeOverlaps();
for (String pattern : patterns) {
builder.addKeyword(pattern);
}
trie = builder.build();
}
@Override
public List<Integer> find(String text) {
List<Integer> result = new ArrayList<>();
for (Emit emit : trie.parseText(text)) {
result.add(emit.getStart());
}
return result;
}
}
|
package de.cm.osm2po.snapp;
import static android.view.View.INVISIBLE;
import static android.view.View.VISIBLE;
import static de.cm.osm2po.sd.guide.SdMessageResource.MSG_ERR_POINT_FIND;
import static de.cm.osm2po.sd.guide.SdMessageResource.MSG_ERR_ROUTE_CALC;
import static de.cm.osm2po.snapp.Marker.ALERT_MARKER;
import static de.cm.osm2po.snapp.Marker.GPS_MARKER;
import static de.cm.osm2po.snapp.Marker.HOME_MARKER;
import static de.cm.osm2po.snapp.Marker.POS_MARKER;
import static de.cm.osm2po.snapp.Marker.SOURCE_MARKER;
import static de.cm.osm2po.snapp.Marker.TARGET_MARKER;
import static de.cm.osm2po.snapp.Marker.TOUCH_MARKER;
import org.mapsforge.android.maps.MapActivity;
import org.mapsforge.android.maps.MapView;
import org.mapsforge.core.GeoPoint;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.res.Configuration;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;
import android.widget.Toast;
import android.widget.ToggleButton;
import de.cm.osm2po.sd.routing.SdPath;
import de.cm.osm2po.sd.routing.SdTouchPoint;
public class MainActivity extends MapActivity
implements MarkerEditListener, AppListener {
private final static int CONTACT_SELECTED = 4711;
private final static int ACTION_MOVE = 1;
private final static int ACTION_GOTO = 2;
private MainApplication app;
private AppState appState;
private MapView mapView;
private RoutesLayer routesLayer;
private MarkersLayer markersLayer;
private ToggleButton tglCarOrBike;
private ToggleButton tglNaviOrEdit;
private ToggleButton tglPanOrHold;
private ToggleButton tglToneOrQuiet;
private TextView lblSpeed;
private EditText txtAddress;
private long nGpsCalls;
private ProgressDialog progressDialog;
private MarkerSelectDialog markerSelectDialog;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// toast("Starting Activity");
progressDialog = new ProgressDialog(this, R.style.StyledDialog) {
@Override
public void onBackPressed() {
app.cancelRouteCalculation();
progressDialog.dismiss();
toast("Calculation cancelled");
}
};
progressDialog.setMessage("Calculating Route...");
progressDialog.setCancelable(false);
markerSelectDialog = new MarkerSelectDialog();
app = (MainApplication) this.getApplication();
appState = app.getAppState();
if (app.isRouterBusy()) progressDialog.show();
tglCarOrBike = (ToggleButton) findViewById(R.id.tglCarOrBike);
tglCarOrBike.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
appState.setBikeMode(!tglCarOrBike.isChecked());
route();
}
});
tglNaviOrEdit = (ToggleButton) findViewById(R.id.tglNaviOrEdit);
tglNaviOrEdit.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
boolean navMode = tglNaviOrEdit.isChecked();
appState.setNavMode(navMode);
tglPanOrHold.setChecked(navMode);
appState.setPanMode(navMode);
txtAddress.setVisibility(navMode ? INVISIBLE : VISIBLE);
app.startNavi();
}
});
tglToneOrQuiet = (ToggleButton) findViewById(R.id.tglToneOrQuiet);
tglToneOrQuiet.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
app.setQuietMode(!tglToneOrQuiet.isChecked());
}
});
tglPanOrHold = (ToggleButton) findViewById(R.id.tglPanOrHold);
tglPanOrHold.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
appState.setPanMode(tglPanOrHold.isChecked());
}
});
txtAddress = (EditText) findViewById(R.id.txtAddress);
txtAddress.setImeActionLabel("Find", EditorInfo.IME_ACTION_SEARCH);
txtAddress.setOnEditorActionListener(new OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if (actionId == EditorInfo.IME_ACTION_SEARCH) {
findAddress(txtAddress.getText().toString());
}
return false;
}
});
mapView = (MapView) findViewById(R.id.mapView);
mapView.setClickable(true);
mapView.setBuiltInZoomControls(true);
mapView.setMapFile(app.getMapFile());
mapView.getController().setZoom(15);
lblSpeed = (TextView) findViewById(R.id.lblSpeed);
routesLayer = new RoutesLayer();
mapView.getOverlays().add(routesLayer);
markersLayer = new MarkersLayer(this, this);
mapView.getOverlays().add(markersLayer);
app.setAppListener(this);
Bundle extras = getIntent().getExtras();
if (extras != null) {
String msg = (String) extras.get("sms_msg");
String num = (String) extras.get("sms_num");
Double lat = (Double) extras.get("sms_lat");
Double lon = (Double) extras.get("sms_lon");
if (msg != null && num != null && lat != null && lon != null) {
toast("Position received from " + num + ": " + lat + "," + lon);
markersLayer.moveMarker(TOUCH_MARKER, new GeoPoint(lat, lon));
markersLayer.moveMarker(ALERT_MARKER, new GeoPoint(lat, lon));
appState.setMapZoom(15);
appState.setPanMode(false);
appState.setMapPos(new GeoPoint(lat, lon));
markerSelectDialog.show(ACTION_MOVE, getFragmentManager());
}
}
restoreViewState();
}
@Override
protected void onDestroy() {
super.onDestroy();
saveViewState();
app.setAppListener(null); // Important! Decouple from App!
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
// Empty for portrait-mode
}
@Override
public void onModeChanged() {
tglCarOrBike.setChecked(!appState.isBikeMode());
tglToneOrQuiet.setChecked(!appState.isQuietMode());
tglNaviOrEdit.setChecked(appState.isNavMode());
tglPanOrHold.setChecked(appState.isPanMode());
txtAddress.setVisibility(appState.isNavMode() ? INVISIBLE : VISIBLE);
}
@Override
protected void onResume() {
super.onResume();
onModeChanged();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onMenuItemSelected(int featureId, MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_nav_home:
GeoPoint gp1 = appState.getGpsPos();
GeoPoint gp2 = markersLayer.getMarkerPosition(HOME_MARKER);
if (gp1 != null && gp2 != null) {
appState.setTarget(null);
markersLayer.moveMarker(Marker.TOUCH_MARKER, gp1);
onMarkerAction(SOURCE_MARKER, ACTION_MOVE); // fake
markersLayer.moveMarker(Marker.TOUCH_MARKER, gp2);
onMarkerAction(TARGET_MARKER, ACTION_MOVE); // fake
}
break;
case R.id.menu_goto_marker:
markerSelectDialog.show(ACTION_GOTO, getFragmentManager());
break;
case R.id.menu_sms_pos:
// TODO this code is not optimal
// this syntax has been taken from my book but doesnt work in callback
// Intent intent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
// startActivityForResult(intent, CONTACT_SELECTED);
// this syntax is from the net
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType(ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE);
startActivityForResult(intent, CONTACT_SELECTED);
break;
}
return true;
}
@Override
public void onGpsSignal(double lat, double lon, float bearing) {
GeoPoint geoPoint = new GeoPoint(lat, lon);
markersLayer.moveMarker(GPS_MARKER, geoPoint, bearing);
appState.setGpsPos(geoPoint);
if (appState.isPanMode()) {
if (nGpsCalls == 0) mapView.setCenter(geoPoint);
if (++nGpsCalls > 10) nGpsCalls = 0;
}
}
@Override
public void onPathPositionChanged(double lat, double lon, float bearing) {
GeoPoint geoPoint = new GeoPoint(lat, lon);
lblSpeed.setText(app.getKmh() + " km/h");
markersLayer.moveMarker(POS_MARKER, geoPoint, bearing);
}
@Override
public void onPositionRequest(GeoPoint geoPoint) {
if (!appState.isNavMode()) {
markerSelectDialog.show(ACTION_MOVE, getFragmentManager());
}
}
@Override
public void onMarkerAction(Marker marker, int action) {
switch (action) {
case ACTION_MOVE:
moveMarker(marker);
break;
default:
gotoMarker(marker);
break;
}
}
public void gotoMarker(Marker marker) {
GeoPoint geoPoint = markersLayer.getMarkerPosition(marker);
if (geoPoint != null) {
mapView.setCenter(geoPoint);
} else {
toast("Marker not yet set");
}
}
public void moveMarker(Marker marker) {
GeoPoint geoPoint = markersLayer.getLastTouchPosition();
double lat = geoPoint.getLatitude();
double lon = geoPoint.getLongitude();
if (GPS_MARKER == marker) {
markersLayer.moveMarker(GPS_MARKER, geoPoint);
appState.setGpsPos(geoPoint);
app.navigate(lat, lon); // Simulation
return;
}
if (HOME_MARKER == marker) {
markersLayer.moveMarker(marker, geoPoint);
return;
}
SdTouchPoint tp = SdTouchPoint.create(
app.getGraph(), (float)lat, (float)lon, !appState.isBikeMode());
if (marker == SOURCE_MARKER) {
appState.setSource(tp);
} else if (marker == TARGET_MARKER) {
appState.setTarget(tp);
}
if (tp != null) {
geoPoint = new GeoPoint(tp.getLat(), tp.getLon());
markersLayer.moveMarker(marker, geoPoint);
} else {
app.speak(toast(MSG_ERR_POINT_FIND.getMessage()));
}
route();
}
private void route() {
if (app.runRouteCalculation()) {
progressDialog.show();
lblSpeed.setText(null);
}
}
@Override
public void onRouteLost() {
markersLayer.moveMarker(TOUCH_MARKER, appState.getGpsPos()); // fake
onMarkerAction(SOURCE_MARKER, ACTION_MOVE); // Fake
}
private String toast(String msg) {
Toast.makeText(this, msg, Toast.LENGTH_LONG).show();
return msg;
}
@Override
public void onRouteChanged() {
runOnUiThread(new Runnable() {
@Override
public void run() {
progressDialog.dismiss();
SdPath path = appState.getPath();
if (null == path) {
app.speak(toast(MSG_ERR_ROUTE_CALC.getMessage()));
}
routesLayer.drawPath(app.getGraph(), path);
}
});
}
private void saveViewState() {
GeoPoint gpMap = mapView.getMapPosition().getMapCenter();
appState.setMapPos(gpMap);
GeoPoint gpHome = markersLayer.getMarkerPosition(HOME_MARKER);
appState.setHomePos(gpHome);
GeoPoint gpGps = markersLayer.getMarkerPosition(GPS_MARKER);
appState.setGpsPos(gpGps);
appState.setMapZoom(mapView.getMapPosition().getZoomLevel());
app.saveAppState();
}
private void restoreViewState() {
int zoom = appState.getMapZoom();
if (zoom > 0) mapView.getController().setZoom(zoom);
GeoPoint gpMap = appState.getMapPos();
if (gpMap != null) mapView.setCenter(gpMap);
GeoPoint gpHome = appState.getHomePos();
if (gpHome != null) markersLayer.moveMarker(HOME_MARKER, gpHome);
GeoPoint gpGps = appState.getGpsPos();
if (gpGps != null) markersLayer.moveMarker(GPS_MARKER, gpGps);
tglCarOrBike.setChecked(!appState.isBikeMode());
tglToneOrQuiet.setChecked(!appState.isQuietMode());
tglPanOrHold.setChecked(appState.isPanMode());
tglNaviOrEdit.setChecked(appState.isNavMode());
SdTouchPoint source = appState.getSource();
if (source != null) {
GeoPoint geoPoint = new GeoPoint(source.getLat(), source.getLon());
markersLayer.moveMarker(SOURCE_MARKER, geoPoint);
}
SdTouchPoint target = appState.getTarget();
if (target != null) {
GeoPoint geoPoint = new GeoPoint(target.getLat(), target.getLon());
markersLayer.moveMarker(TARGET_MARKER, geoPoint);
}
routesLayer.drawPath(app.getGraph(), appState.getPath());
}
private boolean findAddress (String address) {
try {
GeoPoint gpAddress = app.findAddress(address);
if (gpAddress != null) {
mapView.setCenter(gpAddress);
mapView.getController().setZoom(14);
markersLayer.moveMarker(TOUCH_MARKER, gpAddress);
markerSelectDialog.show(ACTION_MOVE, getFragmentManager());
return true;
} else {
toast("Address not found");
}
} catch (Exception e) {
toast(e.getMessage());
}
return false;
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO this code is not optimal
if (CONTACT_SELECTED == requestCode && resultCode != 0) {
if (data != null) {
Uri uri = data.getData();
if (uri != null) {
Cursor c = null;
try {
c = getContentResolver().query(uri, new String[]{
ContactsContract.CommonDataKinds.Phone.NUMBER,
ContactsContract.CommonDataKinds.Phone.TYPE },
null, null, null);
if (c != null && c.moveToFirst()) {
String number = c.getString(0);
//int type = c.getInt(1);
toast("Position sent to " + number);
app.smsGeoPosition(number);
}
} finally {
if (c != null) {
c.close();
}
}
}
}
}
}
}
|
package com.amazonaws.entity;
public class MaintenanceTaskDetails {
private String maintenance_percentage;
private int sum;
public String getMaintenance_percentage() {
return maintenance_percentage;
}
public void setMaintenance_percentage(String maintenance_percentage) {
this.maintenance_percentage = maintenance_percentage;
}
public int getSum() {
return sum;
}
public void setSum(int sum) {
this.sum = sum;
}
}
|
package crescendo.lesson;
import java.util.List;
/**
* Represents a lesson book.
* @author forana
*/
public class LessonBook
{
// metadata
private String title;
private String author;
private String license;
private String licenseURL;
private String website;
private List<BookItem> items;
private LessonData data;
/**
* @param title
* @param author
* @param license
* @param licenseURL
* @param website
* @param items
* @param data
*/
public LessonBook(String title,String author,String license,String licenseURL,String website,List<BookItem> items,LessonData data)
{
this.title=title;
this.author=author;
this.license=license;
this.licenseURL=licenseURL;
this.website=website;
this.items=items;
this.data=data;
}
/**
* @return The lessons and chapters in the top level of this book.
*/
public List<BookItem> getContents()
{
return this.items;
}
public String getTitle()
{
return this.title;
}
public String getAuthor()
{
return this.author;
}
public String getLicense()
{
return this.license;
}
public String getLicenseURL()
{
return this.licenseURL;
}
public String getWebsite()
{
return this.website;
}
public LessonData getData()
{
return this.data;
}
}
|
package repositories;
import java.util.Collection;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;
import domain.PeriodRecord;
@Repository
public interface PeriodRecordRepository extends JpaRepository<PeriodRecord, Integer> {
@Query("select r from PeriodRecord r join r.brotherhood b where b.id=?1")
Collection<PeriodRecord> getPeriodRecordByBrotherhood(final int brotherhoodId);
}
|
package com.trump.auction.order.service.impl;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import com.trump.auction.account.api.AccountInfoStubService;
import com.trump.auction.goods.model.ProductInventoryLogModel;
import com.trump.auction.order.domain.Logistics;
import com.trump.auction.order.enums.EnumLogisticsStatus;
import com.trump.auction.order.enums.EnumOrderType;
import com.trump.auction.order.model.LogisticsModel;
import com.trump.auction.order.service.LogisticsService;
import com.trump.auction.trade.api.AuctionBidStubService;
import com.trump.auction.trade.api.AuctionOrderStubService;
import com.trump.auction.trade.model.BidResult;
import com.trump.auction.trade.vo.AuctionProductRecordVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import com.cf.common.id.IdGenerator;
import com.cf.common.util.mapping.BeanMapper;
import com.cf.common.util.page.PageUtils;
import com.cf.common.util.page.Paging;
import com.cf.common.utils.ServiceResult;
import com.github.pagehelper.PageHelper;
import com.trump.auction.cust.api.UserShippingAddressStuService;
import com.trump.auction.cust.model.UserShippingAddressModel;
import com.trump.auction.goods.api.ProductInventoryLogSubService;
import com.trump.auction.order.dao.OrderInfoDao;
import com.trump.auction.order.domain.OrderInfo;
import com.trump.auction.order.enums.EnumOrderStatus;
import com.trump.auction.order.enums.ResultEnum;
import com.trump.auction.order.model.OrderInfoModel;
import com.trump.auction.order.model.OrderInfoQuery;
import com.trump.auction.order.service.OrderInfoService;
import lombok.extern.slf4j.Slf4j;
/**
* 订单管理
* @author Created by wangjian on 2017/12/20.
*/
@Slf4j
@Service("orderInfoService")
public class OrderInfoServiceImpl implements OrderInfoService {
@Autowired
private OrderInfoDao orderInfoDao;
@Autowired
private BeanMapper beanMapper;
@Autowired
private UserShippingAddressStuService addressStuService;
@Autowired
private AccountInfoStubService accountInfoStubService;
@Autowired
private ProductInventoryLogSubService inventoryLogSubService;
@Autowired
private AuctionOrderStubService auctionOrderStubService;
@Autowired
private IdGenerator snowflakeOrderId;
@Autowired
private LogisticsService logisticsService;
/**
* 保存订单信息
* @param orderInfo {"订单总金额","用戶id","收货地址id","商品数量","实付金额","出价次数","拍品期数ID","拍币数量","购物币ID"}
* @return {code:"",msg:"",ext:"订单号"}
*/
@Override
@Transactional
public ServiceResult saveOrder(OrderInfoModel orderInfo){
long startTime = System.currentTimeMillis();
log.info("saveOrder invoke,StartTime:{},params:{}", startTime, orderInfo);
ServiceResult jsonResult = new ServiceResult(ServiceResult.FAILED,ResultEnum.SAVE_FAIL.getDesc());
//调用参数验证方法
ServiceResult checkResult = createOrderCheck(orderInfo);
//验证不通过则return
if (!ServiceResult.SUCCESS.equals(checkResult.getCode())) {
return checkResult;
}
//收货地址ID不可为空
if (null == orderInfo.getUserShippingId()) {
return new ServiceResult(ServiceResult.WAITING, ResultEnum.ADDRESS_ID_NOTNULL.getDesc());
}
//调用雪花算法生成订单ID
String orderId = String.valueOf(snowflakeOrderId.next());
orderInfo.setOrderId(orderId);
Integer productId = null;
Integer productNum = orderInfo.getProductNum();
Integer userShippingId = orderInfo.getUserShippingId();
boolean stackFlag = false;
boolean buyCoinFlag = false;
try {
//获取拍品信息
AuctionProductRecordVo productRecordVo = null;
try {
productRecordVo = auctionOrderStubService.getRecordByAuctionId(orderInfo.getAuctionNo());
log.info("auctionProductRecordVo:{}", productRecordVo);
if (null == productRecordVo) {
return new ServiceResult(ServiceResult.WAITING,ResultEnum.NULL_PRODUCT.getDesc());
}
} catch (Exception e) {
log.error("saveOrder...getRecordByAuctionId error:", e);
jsonResult.setMsg("call auctionOrderStubService error");
return jsonResult;
}
productId = productRecordVo.getProductId();
//验证库存
try {
boolean bo = inventoryLogSubService.validateStock(productId, productNum);
if (!bo) {
return new ServiceResult(ServiceResult.WAITING,ResultEnum.STOCK_NOTENOUGH.getDesc());
}
} catch (Exception e) {
log.error("saveOrder...validateStock error:", e);
jsonResult.setMsg("call inventoryLogSubService error");
return jsonResult;
}
//验证收货地址
UserShippingAddressModel userAddressModel = null;
try {
userAddressModel = addressStuService.findUserAddressItemByAddressId(userShippingId);
log.info("UserShippingAddressModel:{}", userAddressModel);
if (null == userAddressModel) {
return new ServiceResult(ServiceResult.WAITING,ResultEnum.NULL_ADDRESS.getDesc());
}
} catch (Exception e) {
log.error("saveOrder...findUserAddressItemByAddressId error:", e);
jsonResult.setMsg("call addressStuService error");
return jsonResult;
}
//创建订单前先减库存
try {
ProductInventoryLogModel model = new ProductInventoryLogModel();
model.setProductId(productId);
model.setProductNum(productNum);
int subStock = inventoryLogSubService.subtractStock(model);
if (subStock > 0) {
stackFlag = true;
log.info("subtractStock {}", "success");
} else {
throw new Exception();
}
} catch (Exception e) {
log.error("saveOrder...inventoryLogSubService error:", e);
jsonResult.setMsg(ResultEnum.REDUCE_STOCK_FAIL.getDesc());
}
//如果订单使用了购物币则冻结相应的用户购物币
ServiceResult accountResult = null;
if (null != orderInfo.getBuyCoinMoney() && orderInfo.getBuyCoinMoney().doubleValue() > 0) {
try {
accountResult = accountInfoStubService.reduceBuyCoin(Integer.valueOf(orderInfo.getBuyId()),
null, orderInfo.getBuyCoinMoney(),
orderInfo.getAuctionNo().toString(), 1);
if (ServiceResult.SUCCESS.equals(accountResult.getCode())) {
buyCoinFlag = true;
log.info("frozen buyCoin, result:success");
} else {
//冻结用户购物币失败则还原库存并return
if (stackFlag) {
ProductInventoryLogModel model = new ProductInventoryLogModel();
model.setProductId(productId);
model.setProductNum(productNum);
int subStock = inventoryLogSubService.addStock(model);
log.info("reduction {}", subStock > 0 ? "success" : "failed");
}
throw new Exception();
}
} catch (Exception e) {
log.error("saveOrder...accountInfoStubService error:", e);
jsonResult.setMsg(ResultEnum.REDUCE_BUY_COIN_FAILED.getDesc());
return jsonResult;
}
}
//封装订单信息
orderInfo.setOrderStatus(EnumOrderStatus.UNPAID.getValue());
orderInfo.setOrderType(EnumOrderType.DIFFERENTIAL.getValue());
getOrderInfo(orderInfo, productRecordVo, userAddressModel);
//保存订单信息
log.info("begin save order... orderInfo:{}", orderInfo);
int result = orderInfoDao.insert(beanMapper.map(orderInfo, OrderInfo.class));
log.info("save order end...orderId:{}, result:{}", orderId, result <= 0 ? "failed" : "success");
if (result > 0) {
jsonResult.setCode(ServiceResult.SUCCESS);
jsonResult.setMsg(ResultEnum.SAVE_SUCCESS.getDesc());
jsonResult.setExt(orderId);
}
} catch (Exception e) {
log.error("save order error orderId:{},error:{}", orderId, e);
//事务手动回滚
TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
//创建订单失败则还原库存
if (stackFlag) {
try {
ProductInventoryLogModel model = new ProductInventoryLogModel();
model.setProductId(productId);
model.setProductNum(productNum);
int subStock = inventoryLogSubService.addStock(model);
log.info("reduction {}", subStock > 0 ? "success" : "failed");
} catch (Exception e2) {
log.error("saveOrder...inventoryLogSubService error:", e2);
}
}
//创建订单失败则解冻用户购物币
if (buyCoinFlag) {
try {
ServiceResult accountResult = accountInfoStubService.reduceBuyCoin(Integer.valueOf(orderInfo.getBuyId()), null, orderInfo.getBuyCoinMoney(), orderInfo.getAuctionNo().toString(), 3);
log.info("thaw buyCoin, result:{}", ServiceResult.SUCCESS.equals(accountResult.getCode()) ? "success" : "failed");
} catch (Exception e2) {
log.error("saveOrder...accountInfoStubService error:", e2);
}
}
}
long endTime = System.currentTimeMillis();
log.info("saveOrder end,duration:{}", endTime - startTime);
return jsonResult;
}
/**
* 保存拍卖订单信息
* @param orderInfo {"订单总金额","用戶id","商品数量","实付金额","出价次数","拍品期数ID","拍币数量",""流拍标志位}
* @return {code:"",msg:"",ext:"订单号"}
*/
@Override
@Transactional
public ServiceResult saveAuctionOrder(OrderInfoModel orderInfo){
long startTime = System.currentTimeMillis();
log.info("saveAuctionOrder invoke,StartTime:{},params:{}", startTime, orderInfo);
ServiceResult jsonResult = new ServiceResult(ServiceResult.FAILED,ResultEnum.SAVE_FAIL.getDesc());
//调用参数验证方法
ServiceResult checkResult = createOrderCheck(orderInfo);
//验证不通过则return
if (!ServiceResult.SUCCESS.equals(checkResult.getCode())) {
return checkResult;
}
//调用雪花算法生成订单ID
String orderId = String.valueOf(snowflakeOrderId.next());
orderInfo.setOrderId(orderId);
Integer productNum = orderInfo.getProductNum();
try {
//获取拍品信息
AuctionProductRecordVo productRecordVo = null;
try {
productRecordVo = auctionOrderStubService.getRecordByAuctionId(orderInfo.getAuctionNo());
log.info("auctionProductRecordVo:{}", productRecordVo);
if (null == productRecordVo) {
return new ServiceResult(ServiceResult.WAITING,ResultEnum.NULL_PRODUCT.getDesc());
}
} catch (Exception e) {
log.error("saveAuctionOrder...getRecordByAuctionId error:", e);
jsonResult.setMsg("call auctionOrderStubService error");
return jsonResult;
}
UserShippingAddressModel userAddressModel = null;
//如果是机器人拍中的订单则将订单状态改为:已流拍
if (orderInfo.getIsLiuPai()) {
orderInfo.setOrderStatus(EnumOrderStatus.LIUPAI.getValue());
} else {
//如果是用户拍中的订单则绑定收货地址
try {
orderInfo.setOrderStatus(EnumOrderStatus.UNPAID.getValue());
userAddressModel = addressStuService.findDefaultUserAddressItemByUserId(Integer.valueOf(orderInfo.getBuyId()));
log.info("UserShippingAddressModel:{}", userAddressModel);
} catch (Exception e) {
log.error("saveAuctionOrder...findDefaultUserAddressItemByUserId error:", e);
}
}
//封装订单信息
orderInfo.setAddress(null);
orderInfo.setOrderType(EnumOrderType.AUCTION.getValue());
getOrderInfo(orderInfo, productRecordVo, userAddressModel);
//保存订单信息
log.info("begin saveAuctionOrder... orderInfo:{}", orderInfo);
int result = orderInfoDao.insert(beanMapper.map(orderInfo, OrderInfo.class));
log.info("saveAuctionOrder end...orderId:{}, result:{}", orderId, result <= 0 ? "failed" : "success");
if (result > 0) {
jsonResult.setCode(ServiceResult.SUCCESS);
jsonResult.setMsg(ResultEnum.SAVE_SUCCESS.getDesc());
jsonResult.setExt(orderId);
}
} catch (Exception e) {
log.error("saveAuctionOrder error orderId:{},error:{}", orderId, e);
//事务手动回滚
TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
}
long endTime = System.currentTimeMillis();
log.info("saveAuctionOrder end,duration:{}", endTime - startTime);
return jsonResult;
}
/**
* 根据条件分页查询订单列表数据
* @return
*/
@Override
public Paging<OrderInfoModel> findAllOrder(OrderInfoQuery orderInfo, Integer pageNum, Integer pageSize){
long startTime = System.currentTimeMillis();
log.info("findAllOrder invoke,StartTime:{},params:{},{},{}", startTime, orderInfo, pageNum, pageSize);
if (null == orderInfo || null == orderInfo.getBuyId()) {
throw new IllegalArgumentException("findAllOrder param buyId is null!");
}
PageHelper.startPage(pageNum, pageSize);
Paging<OrderInfoModel> orderInfos = null;
try {
orderInfos = PageUtils.page(
orderInfoDao.findAllOrder(beanMapper.map(orderInfo, OrderInfo.class)),
OrderInfoModel.class, beanMapper);
} catch (Exception e) {
log.error("findAllOrder error:", e);
}
long endTime = System.currentTimeMillis();
log.info("findAllOrder end,duration:{}", endTime - startTime);
return orderInfos;
}
/**
* 查询一条订单信息
* @param orderInfo
* @return
*/
@Override
public OrderInfoModel findOneOrder(OrderInfoQuery orderInfo){
long startTime = System.currentTimeMillis();
log.info("findOneOrder invoke,StartTime:{},params:{}", startTime, orderInfo);
if (null == orderInfo || StringUtils.isBlank(orderInfo.getOrderId())) {
throw new IllegalArgumentException("findOneOrder param orderInfo is null!");
}
OrderInfoModel orderInfoModel = null;
try {
orderInfoModel = beanMapper.map(orderInfoDao.selectByPrimaryKey(orderInfo.getOrderId()), OrderInfoModel.class);
orderInfoModel.setLogisticsModel(beanMapper.map(logisticsService.selectByPrimaryKey(orderInfo.getOrderId()), LogisticsModel.class));
} catch (Exception e) {
log.error("findOneOrder error:", e);
}
long endTime = System.currentTimeMillis();
log.info("findOneOrder end,duration:{}", endTime - startTime);
return orderInfoModel;
}
/**
* 根据订单id更新订单状态
* @param orderInfo
* @return
*/
@Override
@Transactional(propagation = Propagation.REQUIRED)
public ServiceResult updateOrderStatus(OrderInfoModel orderInfo){
long startTime = System.currentTimeMillis();
log.info("updateOrderStatus invoke,StartTime:{},params:{}", startTime, orderInfo);
ServiceResult jsonResult = new ServiceResult(ServiceResult.FAILED, ResultEnum.UPDATE_ORDER_FAIL.getDesc());
if (null == orderInfo) {
return new ServiceResult(ServiceResult.WAITING, ResultEnum.PARAM_EXCEPTION.getDesc());
}
if (null == orderInfo.getOrderId() || StringUtils.isBlank(orderInfo.getOrderId())) {
return new ServiceResult(ServiceResult.WAITING, ResultEnum.ORDER_ID_NOTNULL.getDesc());
}
if (null == orderInfo.getOrderStatus() || 0 == orderInfo.getOrderStatus()) {
return new ServiceResult(ServiceResult.WAITING, ResultEnum.ORDER_STATUS_NOTNULL.getDesc());
}
String orderId = orderInfo.getOrderId();
Integer orderStatus = orderInfo.getOrderStatus();
log.info("update order status. params:orderId:{},orderStatus:{}", orderId,orderStatus);
if(EnumOrderStatus.SHIPPED.getValue().equals(orderStatus)){
log.info("order delivery status:{}",orderStatus);
orderInfo.setOrderDeliveryTime(new Date());
}
if(EnumOrderStatus.RECEIVED.getValue().equals(orderStatus)){
log.info("order receive status:{}", orderStatus);
orderInfo.setOrderReceiveTime(new Date());
}
if(EnumOrderStatus.PAID.getValue().equals(orderStatus)){
log.info("order pay status:{}", orderStatus);
orderInfo.setBuyerPayTime(new Date());
orderInfo.setOrderDispatchTime(new Date());
}
if(EnumOrderStatus.CLOSE.getValue().equals(orderStatus)){
log.info("order canceled status:{}",orderStatus);
orderInfo.setCancelTime(new Date());
}
try {
int executeCount = orderInfoDao.updateOrderStatus(beanMapper.map(orderInfo, OrderInfo.class));
if (executeCount > 0) {
//已付款>>创建待发货的物流信息
if (EnumOrderStatus.PAID.getValue().equals(orderInfo.getOrderStatus())) {
log.info("create logistics information after payment...orderId:{}", orderId);
//获取订单信息
OrderInfo info = orderInfoDao.selectByPrimaryKey(orderId);
Logistics logistics = new Logistics();
//封装物流信息
getLogisticsInfo(info, logistics);
logistics.setBackUserId(orderInfo.getUserId());
int executeCounts = logisticsService.insert(logistics);
log.info("create logisticsInfo,execute size:{}", executeCounts);
//修改失败则回滚
if (executeCounts <= 0) {
throw new RuntimeException();
}
//如果订单使用了购物币则扣除相应的购物币
if (null != info.getBuyCoinMoney() && info.getBuyCoinMoney().doubleValue() > 0) {
try {
ServiceResult accountResult = accountInfoStubService.reduceBuyCoin(Integer.valueOf(info.getBuyId()), null, info.getBuyCoinMoney(), info.getAuctionNo().toString(), 2);
log.info("deduction buyCoin, result:{}", ServiceResult.SUCCESS.equals(accountResult.getCode()) ? "success" : "failed");
} catch (Exception e) {
log.error("orderPaid...accountInfoStubService error:", e);
}
}
}
//确认收货>>同步更新物流状态为已签收
if (EnumOrderStatus.RECEIVED.getValue().equals(orderInfo.getOrderStatus())) {
log.info("confirm receipt and update logistics information...orderId:{}", orderId);
Logistics logistics = new Logistics();
logistics.setOrderId(orderId);
logistics.setLogisticsStatus(EnumLogisticsStatus.DISPATCH_FALSE.getValue());
int executeCounts = logisticsService.updateByPrimaryKeySelective(logistics);
log.info("update logisticsStatus to received,execute size:{}", executeCounts);
//修改失败则回滚
if (executeCounts <= 0) {
throw new RuntimeException();
}
}
jsonResult.setCode(ServiceResult.SUCCESS);
jsonResult.setMsg(ResultEnum.UPDATE_ORDER_SUCCESS.getDesc());
OrderInfo orderInfos = orderInfoDao.selectByPrimaryKey(orderId);
//如果是取消订单则还原商品库存和购物币
if (EnumOrderStatus.CLOSE.getValue().equals(orderStatus)) {
try {
log.info("cancel order...restore inventory,orderId:{}", orderId);
ProductInventoryLogModel pilModel = new ProductInventoryLogModel();
pilModel.setProductId(orderInfos.getProductId());
pilModel.setProductNum(orderInfos.getProductNum());
int addStock = inventoryLogSubService.addStock(pilModel);
log.info("restore inventory {}", addStock > 0 ? "success" : "failed");
} catch (Exception e) {
log.error("cancelOrder...inventoryLogSubService error:", e);
}
//如果订单使用了购物币则冻结相应的用户购物币
if (null != orderInfos.getBuyCoinMoney() && orderInfos.getBuyCoinMoney().doubleValue() > 0) {
try {
ServiceResult accountResult = accountInfoStubService.reduceBuyCoin(Integer.valueOf(orderInfos.getBuyId()), null, orderInfos.getBuyCoinMoney(), orderInfos.getAuctionNo().toString(), 3);
log.info("thaw buyCoin, result:{}", ServiceResult.SUCCESS.equals(accountResult.getCode()) ? "success" : "failed");
} catch (Exception e) {
log.error("cancelOrder...accountInfoStubService error:", e);
}
}
}
}
} catch (Exception e) {
log.error("updateOrderStatus error:", e);
throw new RuntimeException(e);
}
long endTime = System.currentTimeMillis();
log.info("updateOrderStatus end,duration:{}", endTime - startTime);
return jsonResult;
}
/**
* 查询超时未支付订单
* @param date 当前时间前xx小时时间
* @param startTime 查询开始时间段
* @param endTime 查询结束时间段
* @return
*/
@Override
public List<String> queryUnpaidOrders(Date date, Date startTime, Date endTime){
long startTimes = System.currentTimeMillis();
log.info("queryUnpaidOrders invoke,StartTime:{},params:{},{},{}", startTime, date, startTime, endTime);
List<String> list = null;
try {
list = orderInfoDao.findOvertimeOrderInfo(date, startTime, endTime);
} catch (Exception e) {
log.error("queryUnpaidOrders error:", e);
}
long endTimes = System.currentTimeMillis();
log.info("queryUnpaidOrders end,duration:{}", endTimes - startTimes);
return list;
}
/**
* 根据订单号更新地址信息
* @param orderInfoModel
* @return
*/
@Override
public ServiceResult updateAddressByOrderId(OrderInfoModel orderInfoModel){
long startTime = System.currentTimeMillis();
log.info("updateAddressByOrderId invoke,StartTime:{},params:{}", startTime, orderInfoModel);
ServiceResult jsonResult = new ServiceResult(ServiceResult.FAILED,ResultEnum.UPDATE_ADDRESS_FAIL.getDesc());
int result = 0;
if (null == orderInfoModel||null==orderInfoModel.getOrderId()){
log.error("updateAddressByOrderId param orderId is null");
return new ServiceResult(ServiceResult.WAITING,ResultEnum.ORDER_ID_NOTNULL.getDesc());
}
try {
orderInfoModel.setUpdateTime(new Date());
result = orderInfoDao.updateAddressByOrderId(beanMapper.map(orderInfoModel, OrderInfo.class));
log.info("updateAddressByOrderId update result:{}",result);
if (result > 0) {
jsonResult.setCode(ServiceResult.SUCCESS);
jsonResult.setMsg(ResultEnum.UPDATE_ADDRESS_SUCCESS.getDesc());
}
} catch (Exception e) {
log.error("updateAddressByOrderId error:{}",e);
}
long endTime = System.currentTimeMillis();
log.info("updateAddressByOrderId end,duration:{}", endTime - startTime);
return jsonResult;
}
/**
* 根据用户ID、拍品期数ID批量查询订单信息集合
* @param userId
* @param auctionNos
* @return
*/
public List<OrderInfoModel> findOrderListByAcNo(Integer userId, List<Integer> auctionNos){
long startTime = System.currentTimeMillis();
log.info("findOrderListByAcNo invoke,StartTime:{},params:{},{}", startTime, userId, auctionNos);
if (null == userId || null == auctionNos) {
throw new IllegalArgumentException("findOrderListByAcNum param is null!");
}
List<OrderInfoModel> orderInfos = null;
try {
orderInfos = beanMapper.mapAsList(orderInfoDao.findOrderListByAcNo(userId, auctionNos), OrderInfoModel.class);
} catch (Exception e) {
log.error("findOrderListByAcNo error:", e);
}
long endTime = System.currentTimeMillis();
log.info("findOrderListByAcNo end,duration:{}", endTime - startTime);
return orderInfos;
}
/**
* 根据用户ID、拍品期数ID查询单条订单信息
* @param userId
* @param auctionNo
* @return
*/
public OrderInfoModel findOneOrderByAcNo(Integer userId, Integer auctionNo){
long startTime = System.currentTimeMillis();
log.info("findOneOrderByAcNo invoke,StartTime:{},params:{},{}", startTime, userId, auctionNo);
if (null == userId || null == auctionNo) {
throw new IllegalArgumentException("findOneOrderByAcNum param is null!");
}
OrderInfoModel orderInfo = null;
try {
orderInfo = beanMapper.map(orderInfoDao.findOneOrderByAcNo(userId, auctionNo), OrderInfoModel.class);
} catch (Exception e) {
log.error("findOneOrderByAcNo error:", e);
}
long endTime = System.currentTimeMillis();
log.info("findOneOrderByAcNo end,duration:{}", endTime - startTime);
return orderInfo;
}
/**
* 封装订单信息
* @param orderInfo
* @param productRecordVo
* @param userAddressModel
*/
private void getOrderInfo(OrderInfoModel orderInfo, AuctionProductRecordVo productRecordVo,
UserShippingAddressModel userAddressModel){
orderInfo.setProductPrice(productRecordVo.getProductPrice());
orderInfo.setProductName(productRecordVo.getProductName());
orderInfo.setProductPic(productRecordVo.getPreviewPic());
orderInfo.setMerchantId(String.valueOf(productRecordVo.getMerchantId()));
orderInfo.setProductId(productRecordVo.getProductId());
if (null != userAddressModel) {
orderInfo.setProvinceCode(userAddressModel.getProvinceCode());
orderInfo.setCityCode(userAddressModel.getPostCode());
orderInfo.setDistrictCode(userAddressModel.getDistrictCode() == null ? null : userAddressModel.getDistrictCode().toString());
orderInfo.setTownCode(userAddressModel.getTownCode() == null ? null : userAddressModel.getTownCode().toString());
orderInfo.setAddress(userAddressModel.getAddress());
orderInfo.setProvinceName(userAddressModel.getProvinceName());
orderInfo.setDistrictName(userAddressModel.getDistrictName());
orderInfo.setTownName(userAddressModel.getTownName());
orderInfo.setCityName(userAddressModel.getCityName());
orderInfo.setUserName(userAddressModel.getUserName());
orderInfo.setUserPhone(userAddressModel.getUserPhone());
}
orderInfo.setCreateTime(new Date());
orderInfo.setOrderCreateTime(new Date());
}
/**
* 创建订单参数验证
* @param orderInfo
* @return
*/
private ServiceResult createOrderCheck(OrderInfoModel orderInfo) {
if (null == orderInfo) {
return new ServiceResult(ServiceResult.WAITING, ResultEnum.PARAM_EXCEPTION.getDesc());
}
if (null == orderInfo.getBuyId()) {
return new ServiceResult(ServiceResult.WAITING, ResultEnum.USER_ID_NOTNULL.getDesc());
}
if (null == orderInfo.getProductNum()) {
return new ServiceResult(ServiceResult.WAITING, ResultEnum.PRODUCT_NUM_NOTNULL.getDesc());
}
if (null == orderInfo.getOrderAmount()) {
return new ServiceResult(ServiceResult.WAITING, ResultEnum.ORDER_AMOUNT_NOTNULL.getDesc());
}
if (null == orderInfo.getPaidMoney()) {
return new ServiceResult(ServiceResult.WAITING, ResultEnum.PAID_MONEY_NOTNULL.getDesc());
}
if (null == orderInfo.getBidTimes()) {
return new ServiceResult(ServiceResult.WAITING, ResultEnum.BID_TIMES_NOTNULL.getDesc());
}
if (null == orderInfo.getAuctionNo()) {
return new ServiceResult(ServiceResult.WAITING, ResultEnum.AUCTION_NO_NOTNULL.getDesc());
}
return new ServiceResult(ServiceResult.SUCCESS);
}
/**
* 封装物流信息
* @param info
* @param logistics
*/
private void getLogisticsInfo(OrderInfo info, Logistics logistics){
logistics.setOrderId(info.getOrderId());
logistics.setTotalOrder(info.getOrderAmount().longValue());
logistics.setCityCode(info.getCityCode() == null ? null : Integer.valueOf(info.getCityCode()));
logistics.setCityName(info.getCityName());
logistics.setDistrictCode(info.getDistrictCode() == null ? null : Integer.valueOf(info.getDistrictCode()));
logistics.setDistrictName(info.getDistrictName());
logistics.setProvinceCode(info.getProvinceCode());
logistics.setProvinceName(info.getProvinceName());
logistics.setTransName(info.getUserName());
logistics.setTransPhone(info.getUserPhone());
logistics.setAddress(info.getAddress());
logistics.setTownCode(info.getTownCode() == null ? null : Integer.valueOf(info.getTownCode()));
logistics.setTownName(info.getTownName());
}
} |
package collection_framework;
import java.util.Comparator;
public class Product
{
String name;
int cost;
int s_no;
public Product(String name, int cost, int s_no) {
super();
this.name = name;
this.cost = cost;
this.s_no = s_no;
}
@Override
public String toString() {
return "Product [name=" + name + ", cost=" + cost + ", s_no=" + s_no + "]";
}
}
class nameProduct implements Comparator<Product>
{
@Override
public int compare(Product o1, Product o2) {
return o1.name.compareToIgnoreCase(o2.name);
}
}
class SerialProduct implements Comparator<Product>
{
@Override
public int compare(Product o1, Product o2) {
if(o1.s_no>o2.s_no)
return 1;
else
return -1;
}
}
class CostProduct implements Comparator<Product>
{
@Override
public int compare(Product o1, Product o2) {
if(o1.cost>o2.cost)
return 1;
else
return -1;
}
} |
package com.logzc.compass.property;
import com.logzc.webzic.reflection.ClassPaths;
import com.logzc.common.util.PropertyUtil;
import com.logzc.webzic.web.controller.WebzicPath;
import org.junit.Assume;
import org.junit.Test;
import java.net.URL;
import java.util.Collection;
import java.util.HashSet;
/**
* Created by lishuang on 2016/9/28.
*/
public class PropertyTest {
@Test
public void testOverrideProperty(){
String url = PropertyUtil.getProperty("/config.properties","jdbc.url");
System.out.println(url);
}
@Test
public void testCollections(){
Collection<URL> urls1= ClassPaths.forPackage("com.logzc");
Collection<URL> urls2= ClassPaths.forPackage("com.logzc.webzic");
Collection<URL> urls=new HashSet<>();
urls.addAll(urls2);
urls.addAll(urls1);
Assume.assumeTrue(urls.size()==3);
Assume.assumeTrue(WebzicPath.class.getPackage().getName().equals("com.logzc.webzic.web.controller"));
}
}
|
package com.facade.common.example.two;
/**
* 写信过程实现
*/
public class LetterProcessImpl implements ILetterProcess {
//写信
public void writeContext(String context) {
System.out.println("填写信的内容...." + context);
}
//在信封上填写必要的信息
public void fillEnvelope(String address) {
System.out.println("填写收件人地址及姓名...." + address);
}
//把信放到信封中,并封好
public void letterInoteEnvelope() {
System.out.println("把信放到信封中....");
}
//塞到邮箱中,投递
public void sendLetter() {
System.out.println("邮递信封");
}
}
|
/**
*
*/
/**
* @author deeprk
*
*/
package com.itinerary.guest.itinerary.model.entity;
|
package org.typhon.client.model;
import java.util.*;
import java.sql.Timestamp;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.typhon.client.service.*;
public class PurchaseDetails {
private static final Logger logger = LoggerFactory.getLogger(PurchaseDetails.class);
private List<Customer> custormerObj;
private List<Integer
> custormer;
private List<Inventory> inventoriesObj;
private List<Integer
> inventories;
public List<Integer
> getCustormer(){
return custormer;
}
public void setCustormer(List<Integer
> custormer){
this.custormer = custormer;
}
public List<Integer
> getInventories(){
return inventories;
}
public void setInventories(List<Integer
> inventories){
this.inventories = inventories;
}
public List<Customer> getCustomerObj() {
CustomerService customerService = new CustomerService("http://localhost:8092");
List<Customer> result = new ArrayList<Customer>();
for (Integer
typeObj : custormer) {
try {
result.add(customerService.findById(typeObj));
}
catch (Exception e) {
logger.error(e.getMessage());
}
}
return result;
}
public List<Inventory> getInventoryObj() {
InventoryService inventoryService = new InventoryService("http://localhost:8094");
List<Inventory> result = new ArrayList<Inventory>();
for (Integer
typeObj : inventories) {
try {
result.add(inventoryService.findById(typeObj));
}
catch (Exception e) {
logger.error(e.getMessage());
}
}
return result;
}
}
|
package cit360concurrencySimple;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
public class TeamThread implements Runnable {
private final static AtomicInteger mvp = new AtomicInteger(0);
private final static AtomicBoolean win = new AtomicBoolean(false);
private static String mvpName;
private String teamName;
private int teamSize;
private int poolSize;
public TeamThread(int size, int pool, String name) {
teamName = name;
teamSize = size;
poolSize = pool;
}
@Override
public void run() {
List<Future<?>> Futures = new ArrayList<Future<?>>();
ExecutorService executor = Executors.newFixedThreadPool(poolSize);
for (int i = 0; i < teamSize; i++) {
PlayerThread player = new PlayerThread(i+1, teamName);
Future<?> f = executor.submit(player);
Futures.add(f);
if (player.getSpeed() > mvp.get()) {
mvp.getAndSet(player.getSpeed());
mvpName = player.getName();
}
}
executor.shutdown();
boolean allDone = false;
while(!allDone) {
allDone = true;
for(Future<?> future : Futures) {
allDone &= future.isDone();
}
}
System.out.println("\n" + teamName + " has finished the race!");
if (!win.get()) {
win.set(true);
System.out.println("Their MVP was " + mvpName + " with a speed of " + mvp + "\n");
}
else {
System.out.println("Sadly they lost - therefore their MVP was just not up to snuff");
}
}
}
|
package com.shi.androidstudio.permission;
import android.Manifest;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
public class CameraActivity extends AppCompatActivity {
int MY_PERMISSIONS_REQUEST_READ_CONTACTS = 1;
private Button btn_openCamera;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_camera);
btn_openCamera = (Button) findViewById(R.id.btn_openCamera);
btn_openCamera.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (ContextCompat.checkSelfPermission(CameraActivity.this,
Manifest.permission.CAMERA)
!= PackageManager.PERMISSION_GRANTED) {
//正常申请权限
ActivityCompat.requestPermissions(CameraActivity.this,
new String[]{Manifest.permission.CAMERA},
MY_PERMISSIONS_REQUEST_READ_CONTACTS);
}else{
ToastUtil.show(CameraActivity.this, "已经授予权限");
openCamera();
}
}
});
}
private void showMessageOKCancel(String message, DialogInterface.OnClickListener okListener) {
new AlertDialog.Builder(CameraActivity.this)
.setMessage(message)
.setPositiveButton("OK", okListener)
.setNegativeButton("Cancel", null)
.create()
.show();
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
openCamera();
}
if(requestCode == MY_PERMISSIONS_REQUEST_READ_CONTACTS){
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
openCamera();
}else{
//如果app之前请求过该权限,被用户拒绝, 这个方法就会返回true.
//如果用户之前拒绝权限的时候勾选了对话框中”Don’t ask again”的选项,那么这个方法会返回false.
//如果设备策略禁止应用拥有这条权限, 这个方法也返回false.
//默认的,第一次打开APP,这个方法也返回false
boolean flag = ActivityCompat.shouldShowRequestPermissionRationale(CameraActivity.this,
Manifest.permission.CAMERA);
if (!flag) {
showMessageOKCancel("请授权", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// 用户拒绝授权并选择了不再提示
ToastUtil.show(CameraActivity.this,"请进行手动授权");
// 帮跳转到该应用的设置界面,让用户手动授权
Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
Uri uri = Uri.fromParts("package", getPackageName(), null);
intent.setData(uri);
startActivity(intent);
}
});
}else{
SnackBarUtil.show(btn_openCamera, "授权失败");
}
}
}
}
/**
* 打开照相机
*/
void openCamera() {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivity(intent);
}
}
|
package com.gxtc.huchuan.im.provide;
import android.net.Uri;
import android.os.Parcel;
import android.text.TextUtils;
import android.util.Log;
import org.json.JSONException;
import org.json.JSONObject;
import io.rong.common.ParcelUtils;
import io.rong.imlib.MessageTag;
import io.rong.imlib.model.MessageContent;
import io.rong.imlib.model.UserInfo;
import io.rong.message.VoiceMessage;
import io.rong.message.VoiceMessageHandler;
/**
* Created by Gubr on 2017/4/9.
* 融云voiceMessage的适配器
* 因为 融云的voicemessage json不符合要求 所以需要写此类来适配
*/
@MessageTag(
value = "RC:VcMsg",
flag = 3,
messageHandler = VoiceMessageHandler.class
)
public class VoiceMessageAdapter extends MessageContent {
private Uri mUri;
private int mDuration;
private String mBase64;
protected String extra;
public static final Creator<VoiceMessage> CREATOR = new Creator<VoiceMessage>() {
public VoiceMessage createFromParcel(Parcel source) {
return new VoiceMessage(source);
}
public VoiceMessage[] newArray(int size) {
return new VoiceMessage[size];
}
};
public String getExtra() {
return this.extra;
}
public void setExtra(String extra) {
this.extra = extra;
}
public VoiceMessageAdapter(Parcel in) {
this.setExtra(ParcelUtils.readFromParcel(in));
this.mUri = (Uri)ParcelUtils.readFromParcel(in, Uri.class);
this.mDuration = ParcelUtils.readIntFromParcel(in).intValue();
this.setUserInfo((UserInfo)ParcelUtils.readFromParcel(in, UserInfo.class));
}
public VoiceMessageAdapter(VoiceMessage message,String uri){
setUri(uri==null?message.getUri():Uri.parse(uri));
setDuration(message.getDuration());
setExtra(message.getExtra());
setMentionedInfo(message.getMentionedInfo());
setUserInfo(message.getUserInfo());
setBase64(message.getBase64());
}
public VoiceMessageAdapter(String data){
try {
JSONObject e = new JSONObject(data);
if(e.has("duration")) {
this.setDuration(e.optInt("duration"));
}
if(e.has("content")) {
this.setBase64(e.optString("content"));
}
if (e.has("uri")){
this.setUri(Uri.parse(e.optString("uri")));
}
if(e.has("extra")) {
this.setExtra(e.optString("extra"));
}
if(e.has("user")) {
this.setUserInfo(this.parseJsonToUserInfo(e.getJSONObject("user")));
}
} catch (JSONException var4) {
Log.e("JSONException", var4.getMessage());
}
}
public VoiceMessageAdapter(byte[] data) {
this(new String(data));
// String jsonStr = new String(data);
//
// try {
// JSONObject e = new JSONObject(jsonStr);
// if(e.has("duration")) {
// this.setDuration(e.optInt("duration"));
// }
//
// if(e.has("content")) {
// this.setBase64(e.optString("content"));
// }
// if (e.has("uri")){
// this.setUri(Uri.parse(e.optString("uri")));
// }
//
// if(e.has("extra")) {
// this.setExtra(e.optString("extra"));
// }
//
// if(e.has("user")) {
// this.setUserInfo(this.parseJsonToUserInfo(e.getJSONObject("user")));
// }
// } catch (JSONException var4) {
// Log.e("JSONException", var4.getMessage());
// }
}
private VoiceMessageAdapter(Uri uri, int duration) {
this.mUri = uri;
this.mDuration = duration;
}
public static VoiceMessageAdapter obtain(Uri uri, int duration) {
return new VoiceMessageAdapter(uri, duration);
}
public Uri getUri() {
return this.mUri;
}
public void setUri(Uri uri) {
this.mUri = uri;
}
public int getDuration() {
return this.mDuration;
}
public void setDuration(int duration) {
this.mDuration = duration;
}
public String getBase64() {
return this.mBase64;
}
public void setBase64(String base64) {
this.mBase64 = base64;
}
public byte[] encode() {
JSONObject jsonObj = new JSONObject();
try {
jsonObj.put("content", this.mBase64);
jsonObj.put("duration", this.mDuration);
jsonObj.put("uri",this.getUri().toString());
if(!TextUtils.isEmpty(this.getExtra())) {
jsonObj.put("extra", this.extra);
}
if(this.getJSONUserInfo() != null) {
jsonObj.putOpt("user", this.getJSONUserInfo());
}
} catch (JSONException var3) {
Log.e("JSONException", var3.getMessage());
}
// this.mBase64 = null;
return jsonObj.toString().getBytes();
}
public int describeContents() {
return 0;
}
public void writeToParcel(Parcel dest, int flags) {
ParcelUtils.writeToParcel(dest, this.extra);
ParcelUtils.writeToParcel(dest, this.mUri);
ParcelUtils.writeToParcel(dest, Integer.valueOf(this.mDuration));
ParcelUtils.writeToParcel(dest, this.getUserInfo());
}
public VoiceMessage getVoicMessage(){
VoiceMessage voiceMessage = new VoiceMessage(new byte[]{});
voiceMessage.setExtra(getExtra());
voiceMessage.setDuration(getDuration());
voiceMessage.setUri(getUri());
voiceMessage.setUserInfo(getUserInfo());
voiceMessage.setBase64(getBase64());
return voiceMessage;
}
}
|
package webDriverMethods;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class NavigationMethods {
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver", "./src/test/resources/chromedriver.exe");
WebDriver driver = new ChromeDriver();
// Navigation methods - Navigate to specific url
driver.navigate().to("http://automationpractice.com/index.php?controller=authentication&back=my-account");
// Navigation methods - Refresh the existing page
driver.navigate().refresh();
// Go back to previous page
driver.navigate().back();
// Select the next page
driver.navigate().forward();
}
}
|
package com.mobilcom.mypicolo.repositories;
import android.app.Application;
import android.os.AsyncTask;
import androidx.lifecycle.LiveData;
import com.mobilcom.mypicolo.daos.TaskCategoryDao;
import com.mobilcom.mypicolo.databases.MyPicoloDatabase;
import com.mobilcom.mypicolo.entities.TaskCategory;
import java.util.List;
public class TaskCategoryRepository {
private TaskCategoryDao taskCategoryDao;
private LiveData<List<TaskCategory>> allTaskCategories;
public TaskCategoryRepository(Application application) {
MyPicoloDatabase database = MyPicoloDatabase.getInstance(application);
taskCategoryDao = database.taskCategoryDao();
allTaskCategories = taskCategoryDao.getAllTaskCategories();
}
public void insert(TaskCategory taskCategory) {
new InsertTaskCategoryAsyncTask(taskCategoryDao).execute(taskCategory);
}
public void update(TaskCategory taskCategory) {
new UpdateTaskCategoryAsyncTask(taskCategoryDao).execute(taskCategory);
}
public void delete(TaskCategory taskCategory) {
new DeleteTaskCategoryAsyncTask(taskCategoryDao).execute(taskCategory);
}
public LiveData<List<TaskCategory>> getAllTaskCategories() {
return allTaskCategories;
}
private static class InsertTaskCategoryAsyncTask extends AsyncTask<TaskCategory, Void, Void> {
private TaskCategoryDao taskCategoryDao;
private InsertTaskCategoryAsyncTask(TaskCategoryDao taskCategoryDao) {
this.taskCategoryDao = taskCategoryDao;
}
@Override
protected Void doInBackground(TaskCategory... taskCategories) {
taskCategoryDao.insert(taskCategories[0]);
return null;
}
}
private static class UpdateTaskCategoryAsyncTask extends AsyncTask<TaskCategory, Void, Void> {
private TaskCategoryDao taskCategoryDao;
private UpdateTaskCategoryAsyncTask(TaskCategoryDao taskCategoryDao) {
this.taskCategoryDao = taskCategoryDao;
}
@Override
protected Void doInBackground(TaskCategory... taskCategories) {
taskCategoryDao.update(taskCategories[0]);
return null;
}
}
private static class DeleteTaskCategoryAsyncTask extends AsyncTask<TaskCategory, Void, Void> {
private TaskCategoryDao taskCategoryDao;
private DeleteTaskCategoryAsyncTask(TaskCategoryDao taskCategoryDao) {
this.taskCategoryDao = taskCategoryDao;
}
@Override
protected Void doInBackground(TaskCategory... taskCategories) {
taskCategoryDao.delete(taskCategories[0]);
return null;
}
}
}
|
package me.asyc.jchat.network.pipeline;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import io.netty.util.AttributeKey;
import me.asyc.jchat.network.buffer.ByteArray;
import me.asyc.jchat.network.encryption.CryptoKey;
import me.asyc.jchat.network.encryption.CryptoManager;
import java.util.List;
/**
* Turns byte sequences/fragments into full packet payload. Also handles decryption.
* <p>
* Packet Format
* <pre>
* | Size | Payload Header | Payload |
* |---------|--------------------------|-------------|
* | integer | packet identifier(short) | packet data |
* </pre>
*/
public final class PacketFrameDecryptor extends ByteToMessageDecoder {
private static final AttributeKey<CryptoKey> KEY_ATTRIBUTE = AttributeKey.valueOf("jchat:key");
private final CryptoManager manager;
private final CryptoKey key;
private final ByteArray header;
private ByteArray packetBuffer;
public PacketFrameDecryptor(CryptoManager manager, CryptoKey key) {
this.manager = manager;
this.key = key;
this.header = new ByteArray(4);
this.packetBuffer = null;
}
/**
* Loops until all bytes are read, decodes as many frames as possible, then passes
* it on to the next handler in the netty pipeline.
*
* @param ctx The channel context
* @param in The rcv buffer
* @param out The output list
* @throws Exception If the packet data could not be parsed
*/
@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
while (in.readableBytes() > 0) {
byte[] decoded = this.decodeFrame(ctx, in);
if (decoded != null) out.add(decoded);
}
}
/**
* This method reads the size header of the frame, and reads all the payload bytes.
*
* @param ctx The channel context
* @param in The rcv buffer
* @return Returns a non-encrypted byte array of the packet payload. This value can be null, when there is not enough information to read whole frame.
* @throws Exception If the packet data could not be parsed
*/
private byte[] decodeFrame(ChannelHandlerContext ctx, ByteBuf in) throws Exception {
CryptoKey key = ctx.channel().attr(PacketFrameDecryptor.KEY_ATTRIBUTE).get();
if (!this.header.isFull()) {
int toRead = Math.min(this.header.getRemaining(), in.readableBytes());
in.readBytes(this.header, toRead);
if (!this.header.isFull()) return null;
byte[] sizeBuffer = this.header.getByteArray();
if (key != null) {
sizeBuffer = this.manager.decrypt(key, sizeBuffer);
}
this.packetBuffer = new ByteArray(((sizeBuffer[0] << 24) + (sizeBuffer[1] << 16) + (sizeBuffer[2] << 8) + (sizeBuffer[3])));
}
if (!this.packetBuffer.isFull()) return null;
int toRead = Math.min(this.packetBuffer.getRemaining(), in.readableBytes());
in.readBytes(this.packetBuffer, toRead);
if (!this.packetBuffer.isFull()) return null;
byte[] packetBuffer = this.packetBuffer.getByteArray();
if (key != null) {
packetBuffer = this.manager.decrypt(this.key, this.header.getByteArray(), packetBuffer);
}
this.header.reset();
this.packetBuffer = null;
return packetBuffer;
}
}
|
package be.dpms.medwan.common.model.vo.occupationalmedicine;
import java.io.Serializable;
/**
* Created by IntelliJ IDEA.
* User: MichaŽl
* Date: 02-juil.-2003
* Time: 13:38:23
*/
public class FunctionGroupExaminationVO implements Serializable {
public int tolerance;
public int frequency;
public Integer functionGroupExaminationId;
public ExaminationVO examination;
public FunctionGroupExaminationVO(int tolerance, int frequency, Integer functionGroupExaminationId, ExaminationVO examination) {
this.tolerance = tolerance;
this.frequency = frequency;
this.functionGroupExaminationId = functionGroupExaminationId;
this.examination = examination;
}
public int getTolerance() {
return tolerance;
}
public int getFrequency() {
return frequency;
}
public Integer getFunctionGroupExaminationId() {
return functionGroupExaminationId;
}
public ExaminationVO getExamination() {
return examination;
}
public void setTolerance(int tolerance) {
this.tolerance = tolerance;
}
public void setFrequency(int frequency) {
this.frequency = frequency;
}
public void setFunctionGroupExaminationId(Integer functionGroupExaminationId) {
this.functionGroupExaminationId = functionGroupExaminationId;
}
public void setExamination(ExaminationVO examination) {
this.examination = examination;
}
}
|
package coreJava_programs.Java_Programs;
public class PatternProgram8_25 {
/**
1
1 2 1
1 2 3 2 1
1 2 3 4 3 2 1
1 2 3 4 5 4 3 2 1
1 2 3 4 5 6 5 4 3 2 1
1 2 3 4 5 6 7 6 5 4 3 2 1
**/
public static void main(String[] args) {
for(int i = 1; i<=7; i++)
{
for(int j = 1; j<=i; j++)
{
System.out.print(j+" ");
}
for(int k = i-1; k>=1; k-- )
{
System.out.print(k+" ");
}
System.out.println();
}
}
}
|
/**
* Contains (un)marshallers optimized to store binary data in MIME attachments.
*/
@NonNullApi
@NonNullFields
package org.springframework.oxm.mime;
import org.springframework.lang.NonNullApi;
import org.springframework.lang.NonNullFields;
|
package com.vitaltech.bioink;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
public class BitOps {
public BitOps() {
// TODO Auto-generated constructor stub
}
/**
* @param args
*/
public static void main(String[] args) {
System.out.println("HELLO.");
Set<Byte> bytes = new LinkedHashSet<Byte>();
bytes.add((byte) 1); // 0000 0001 => 00000 00001 = 1 1
bytes.add((byte) 4); // 0000 0100 => 00000 00001 = 1 2
bytes.add((byte) 16); // 0001 0000 => 00000 00001 = 1 3
bytes.add((byte) 64); // 0100 0000 => 00000 00001 = 1 4
bytes.add((byte) 0); // 0000 0000 ^
bytes.add((byte) 3); // 0000 0011 => 11000 00011 = 771 5
bytes.add((byte) 31); // 0001 1111 => 11100 00111 = 903 6
bytes.add((byte)238); // 1110 1110 => 01110 01110 = 462 7
bytes.add((byte) 28); // 0001 1100 => 00111 11100 = 252 8
bytes.add((byte) 63); // 0011 1111 ^
bytes.add((byte) 48); // 0011 0000 => 10001 10000 = 560 9
bytes.add((byte) 2); // 0000 0010 => 10000 00000 = 512 10
bytes.add((byte) 8); // 0000 1000 => 10000 00000 = 512 11
bytes.add((byte) 32); // 0010 0000 => 10000 00000 = 512 12
bytes.add((byte)128); // 1000 0000 ^
bytes.add((byte)255); // 1111 1111 => 11111 11111 = 1023 13
bytes.add((byte)195); // 1100 0011 => 00001 10000 = 48 14
bytes.add((byte)240); // 1111 0000 => 11111 01111 = 1007 15
bytes.add((byte) 62); // 0011 1110 => 00111 10100 = 244 16
bytes.add((byte) 61); // 0011 1101 ^
bytes.add((byte) 85); // 0101 0101 => 01010 10101 = 341 17
bytes.add((byte)169); // 1010 1001 => 10101 01010 = 682 18 samples in 22.5 bytes
bytes.add((byte)106); // 0110 1010 ^ (junk 0110)
// for(int i=0; i<8; ++i){
// System.out.println("\ni=" + i + " => " + (0x1 << i) + "\t 2^ => " +
// BigInteger.valueOf( 1 << i ).toString(2) );
// System.out.print( "& 1 => " + BigInteger.valueOf((1 << i) & 1).toString(2) );
// System.out.print( "\t| 1 => " + BigInteger.valueOf((1 << i) | 1).toString(10));
// System.out.println("\t| 1 => " + BigInteger.valueOf((1 << i) | 1).toString(2) );
// }
Iterator<Byte> itr = bytes.iterator();
int i=1;
while(itr.hasNext()){
int it = (itr.next() & 255);
System.out.print((i++) + "> " + it + "\t: " + it );
// System.out.print("\t" + BigInteger.valueOf( (it & 2047) & 1023 ).toString(10) );
System.out.print("\t" + BigInteger.valueOf( it ).toString(10) );
String lead = "00000000".substring(0, (8-BigInteger.valueOf(it).toString(2).length()));
System.out.println("\t" + lead + BigInteger.valueOf(it).toString(2) );
// System.out.print("\t" + BigInteger.valueOf( (it & 2047) & 1023 ).toString(2) );
// System.out.println("\t" + BigInteger.valueOf( it ).toString(2) );
}
List<Long> list = zephyParse(bytes);
for(int j=0; j<list.size(); ++j){
System.out.print((j+1) + "\t");
System.out.print(
BigInteger.valueOf(
list.get(j)
).toString(10) +
"\t"
);
System.out.print(
"0000000000".substring(0, (10-BigInteger.valueOf(list.get(j)).toString(2).length())) +
BigInteger.valueOf(
list.get(j)
).toString(2)
);
System.out.print("\n");
}
for(int x = 0; x < 256; x++){
for(int y = 0; y < 256; y++){
System.out.println(String.valueOf(ZBTS((byte) y, (byte) x)));
if((ZBTS((byte) y, (byte) x) > Float.MAX_VALUE)){
System.out.println("OMG");
return;
}
}
}
}
// Turn a Set of 8-bit Bytes into a List of 10-bit Longs
public static List<Long> zephyParse(Set<Byte> samples) {
List<Long> decoded = new ArrayList<Long>();
Byte[] array = (Byte[])samples.toArray(new Byte[samples.size()]);
int shifter = 1;
for(int i=1; i<samples.size(); ++i){
if(shifter != 5){
long rightMask = ((long)255 << ((shifter-1) * 2)) & 255;
long right = (((long)array[i-1]) & rightMask) >> ((shifter-1)*2);
long leftMask = ((long)1 << (shifter * 2)) - 1;
long left = ((((long)array[i]) & leftMask) << (8-((shifter-1)*2)));
decoded.add(
(left | right) & 1023
);
}
shifter++;
if(shifter > 5){
shifter = 1;
}
}
return decoded;
}
public static float ZBTS(byte b1, byte b2) {
//Zephyr states that the first byte is LS
//Next one is MS
long MS = b2;
long LS = b1;
long number = (0xFFFF & ((MS & 0xFF) << 8) | (LS & 0xFF));
return Float.parseFloat(String.valueOf(number));
//return (short) ((b2 << 8) | (b1 & 0xFF));
}
}
|
package com.site.ui;
import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.Map;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BaiduMap.OnMapClickListener;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.MapPoi;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.model.LatLng;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;
import com.site.BaseActivity;
import com.site.R;
import com.site.tools.Bimp;
import com.site.tools.Constant;
import com.site.tools.ImageItem;
import com.site.tools.PublicWay;
import com.site.tools.Res;
import com.site.tools.SiteUtil;
import com.site.upload.FileUploadAsyncTask;
import com.site.upload.FormFile;
/**
* 首页面activity
*
* @version 2014年10月18日 下午11:48:34
*/
public class MainActivity extends BaseActivity {
private GridView noScrollgridview;
private GridAdapter adapter;
private View parentView;
private PopupWindow pop = null;
private LinearLayout ll_popup;
public static Bitmap bimap;
private ProgressBar mPgBar;
private TextView mTvProgress;
private Map<String,String>paramMap;
private FormFile[] formFiles;
private File[] files;
private View upView;
private String mPicName;
/* 定位相关 */
LocationClient mLocClient;
public MyLocationListenner myListener = new MyLocationListenner();
private BitmapDescriptor mCurrentMarker;
private MapView mMapView;
private BaiduMap baiduMap;
boolean isFirstLoc = true;// 是否首次定位
private String lineIds;
private ProgressDialog pd;
@ViewInject(R.id.title)
private TextView title;
@ViewInject(R.id.editUser)
private TextView editUser;
@ViewInject(R.id.site)
private TextView site;
@OnClick(R.id.site)
public void site(View v) {
finish();
}
@OnClick(R.id.cancel)
public void cancel(View v) {
finish();
}
private String showMsg="";
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Res.init(this);
bimap = BitmapFactory.decodeResource(getResources(),
R.drawable.icon_addpic_unfocused);
PublicWay.activityList.add(this);
parentView = getLayoutInflater().inflate(R.layout.activity_selectimg,
null);
setContentView(parentView);
Init();
addActivity(this);
ViewUtils.inject(this);
initView();
initValue();
}
@Override
protected void initView() {
// TODO Auto-generated method stub
title.setText("上报站点信息");
site.setText("线路列表");
editUser.setText("");
// 地图初始化
mMapView = (MapView) findViewById(R.id.bmapView);
baiduMap = mMapView.getMap();
// 开启定位图层
// baiduMap.setMyLocationEnabled(true);
// 定位初始化
mLocClient = new LocationClient(this);
mLocClient.registerLocationListener(myListener);
LocationClientOption option = new LocationClientOption();
option.setOpenGps(true);// 打开gps
option.setCoorType("bd09ll"); // 设置坐标类型
option.setScanSpan(72000);
mLocClient.setLocOption(option);
String l=SiteUtil.getLongitude();
String ln=SiteUtil.getLatitude();
double lng = Double.parseDouble(l);
double lan =Double.parseDouble(SiteUtil.getLatitude());
LatLng cenpt = new LatLng(lan, lng);
// 普通地图
baiduMap.setMapType(BaiduMap.MAP_TYPE_NORMAL);
// 开启交通图线
// baiduMap.setTrafficEnabled(true);
// 设置比例尺
baiduMap.setOnMapClickListener(listener);
mLocClient.start();
baiduMap.setOnMapStatusChangeListener( new BaiduMap.OnMapStatusChangeListener() {
/**
* 手势操作地图,设置地图状态等操作导致地图状态开始改变。
* @param status 地图状态改变开始时的地图状态
*/
public void onMapStatusChangeStart(MapStatus status){
}
/**
* 地图状态变化中
* @param status 当前地图状态
*/
public void onMapStatusChange(MapStatus status){
}
/**
* 地图状态改变结束
* @param status 地图状态改变结束后的地图状态
*/
public void onMapStatusChangeFinish(MapStatus status)
{
LatLng ll=status.target;
SiteUtil.writeLongitude(ll.longitude+"");
SiteUtil.writeLatitude(ll.latitude+"");
Log.d("map change","sts ch fs:"+ll.latitude+","+ll.longitude+"");
}
});
}
@Override
protected void initValue() {
// TODO Auto-generated method stub
}
@OnClick(R.id.input_img)
public void submit(View v)
{
pd = new ProgressDialog(this);
pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
pd.setMessage("上传中....");
pd.setCancelable(false);
pd.show();
ArrayList<ImageItem> imageItems = Bimp.tempSelectBitmap;
formFiles = new FormFile[imageItems.size()];
files=new File[imageItems.size()];
for (int i=0;i<imageItems.size();i++)
{
ImageItem item=imageItems.get(i);
Bitmap bitmap = item.getBitmap();
String path = item.getImagePath();
SiteUtil.compressBitmap(bitmap, path);
File imageFile = new File(path);
files[i]=imageFile;
}
FileUploadAsyncTask task = new FileUploadAsyncTask(this,pd);
task.execute(files);
}
private String getPicName() {
return new Date().getTime() + ".jpg";
}
public void submitResult(String json)
{
JsonParser jsonParser = new JsonParser();
JsonElement jsonElement = jsonParser.parse(json);
JsonObject jsonObject = jsonElement.getAsJsonObject();
String status = jsonObject.get("status").getAsString();
if ("00".equals(status))
{
showMsg="上传成功";
} else
{
showMsg="上传失败,请重试";
}
showDialog();
}
public void showDialog()
{
AlertDialog alertDialog = new AlertDialog.Builder(this).setPositiveButton("确定", new android.content.DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which)
{
// TODO Auto-generated method stub
for (int i = 0; i < PublicWay.activityList.size(); i++)
{
if (null != PublicWay.activityList.get(i))
{
PublicWay.activityList.get(i).finish();
}
}
System.exit(0);
}
}).setTitle("提示").setMessage(showMsg).create();
alertDialog.setCanceledOnTouchOutside(false);
alertDialog.show();
}
public void Init() {
pop = new PopupWindow(MainActivity.this);
View view = getLayoutInflater().inflate(R.layout.item_popupwindows,
null);
ll_popup = (LinearLayout) view.findViewById(R.id.ll_popup);
pop.setWidth(LayoutParams.MATCH_PARENT);
pop.setHeight(LayoutParams.WRAP_CONTENT);
pop.setBackgroundDrawable(new BitmapDrawable());
pop.setFocusable(true);
pop.setOutsideTouchable(true);
pop.setContentView(view);
RelativeLayout parent = (RelativeLayout) view.findViewById(R.id.parent);
Button bt1 = (Button) view.findViewById(R.id.item_popupwindows_camera);
Button bt2 = (Button) view.findViewById(R.id.item_popupwindows_Photo);
Button bt3 = (Button) view.findViewById(R.id.item_popupwindows_cancel);
parent.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
pop.dismiss();
ll_popup.clearAnimation();
}
});
bt1.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
photo();
pop.dismiss();
ll_popup.clearAnimation();
}
});
bt2.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this,AlbumActivity.class);
startActivity(intent);
overridePendingTransition(R.anim.activity_translate_in,
R.anim.activity_translate_out);
pop.dismiss();
ll_popup.clearAnimation();
finish();
}
});
bt3.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
pop.dismiss();
ll_popup.clearAnimation();
}
});
noScrollgridview = (GridView) findViewById(R.id.noScrollgridview);
noScrollgridview.setSelector(new ColorDrawable(Color.TRANSPARENT));
adapter = new GridAdapter(this);
adapter.update();
noScrollgridview.setAdapter(adapter);
noScrollgridview.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
if (arg2 == Bimp.tempSelectBitmap.size()) {
Log.i("ddddddd", "----------");
ll_popup.startAnimation(AnimationUtils.loadAnimation(
MainActivity.this, R.anim.activity_translate_in));
pop.showAtLocation(parentView, Gravity.BOTTOM, 0, 0);
} else {
Intent intent = new Intent(MainActivity.this,
GalleryActivity.class);
intent.putExtra("position", "1");
intent.putExtra("ID", arg2);
startActivity(intent);
}
}
});
}
@SuppressLint("HandlerLeak")
public class GridAdapter extends BaseAdapter {
private LayoutInflater inflater;
private int selectedPosition = -1;
private boolean shape;
public boolean isShape() {
return shape;
}
public void setShape(boolean shape) {
this.shape = shape;
}
public GridAdapter(Context context) {
inflater = LayoutInflater.from(context);
}
public void update() {
loading();
}
public int getCount() {
if (Bimp.tempSelectBitmap.size() == 6) {
return 6;
}
return (Bimp.tempSelectBitmap.size() + 1);
}
public Object getItem(int arg0) {
return null;
}
public long getItemId(int arg0) {
return 0;
}
public void setSelectedPosition(int position) {
selectedPosition = position;
}
public int getSelectedPosition() {
return selectedPosition;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
if (convertView == null) {
convertView = inflater.inflate(R.layout.item_published_grida,
parent, false);
holder = new ViewHolder();
holder.image = (ImageView) convertView
.findViewById(R.id.item_grida_image);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
if (position == Bimp.tempSelectBitmap.size()) {
holder.image.setImageBitmap(BitmapFactory.decodeResource(
getResources(), R.drawable.icon_addpic_unfocused));
if (position == 6) {
holder.image.setVisibility(View.GONE);
}
} else {
holder.image.setImageBitmap(Bimp.tempSelectBitmap.get(position)
.getBitmap());
}
return convertView;
}
public class ViewHolder {
public ImageView image;
}
Handler handler = new Handler() {
public void handleMessage(Message msg) {
switch (msg.what) {
case 1:
adapter.notifyDataSetChanged();
break;
}
super.handleMessage(msg);
}
};
public void loading() {
new Thread(new Runnable() {
public void run() {
while (true) {
if (Bimp.max == Bimp.tempSelectBitmap.size()) {
Message message = new Message();
message.what = 1;
handler.sendMessage(message);
break;
} else {
Bimp.max += 1;
Message message = new Message();
message.what = 1;
handler.sendMessage(message);
}
}
}
}).start();
}
}
public String getString(String s) {
String path = null;
if (s == null)
return "";
for (int i = s.length() - 1; i > 0; i++) {
s.charAt(i);
}
return path;
}
protected void onRestart() {
adapter.update();
super.onRestart();
}
// 完成
private static final int TAKE_PICTURE = 0x000001;
public void photo() {
mPicName=getPicName();
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT,Uri.fromFile(new File(Constant.IMG_PATH+mPicName)));
startActivityForResult(intent, TAKE_PICTURE);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case TAKE_PICTURE:
if (Bimp.tempSelectBitmap.size() < 6 && resultCode == RESULT_OK) {
String fileName = String.valueOf(System.currentTimeMillis());
// Bitmap bm = (Bitmap) data.getExtras().get("data");
// FileUtils.saveBitmap(bm, fileName);
File imageFile = new File(Constant.IMG_PATH, mPicName);
File file = new File(imageFile.getAbsolutePath());
// SiteUtil.compressBitmapT(imageFile.getAbsolutePath(), mPicName);
if (file.exists())
{
Bitmap bitmap = BitmapFactory.decodeFile(file.getPath());
ImageItem takePhoto = new ImageItem();
takePhoto.setBitmap(bitmap);
takePhoto.setImagePath(imageFile.getAbsolutePath());
Bimp.tempSelectBitmap.add(takePhoto);
}
}
break;
}
}
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
for (int i = 0; i < PublicWay.activityList.size(); i++) {
if (null != PublicWay.activityList.get(i)) {
PublicWay.activityList.get(i).finish();
}
}
System.exit(0);
}
return true;
}
/**
* 定位SDK监听函数
*/
public class MyLocationListenner implements BDLocationListener {
@Override
public void onReceiveLocation(BDLocation location) {
// map view 销毁后不在处理新接收的位置
if (location == null || mMapView == null)
return;
MyLocationData locData = new MyLocationData.Builder()
.accuracy(location.getRadius())
// 此处设置开发者获取到的方向信息,顺时针0-360
.direction(100).latitude(location.getLatitude())
.longitude(location.getLongitude()).build();
baiduMap.setMyLocationData(locData);
if (isFirstLoc) {
isFirstLoc = false;
LatLng ll = new LatLng(location.getLatitude(),
location.getLongitude());
// MapStatusUpdate u = MapStatusUpdateFactory.newLatLng(ll);
// baiduMap.animateMapStatus(u);
baiduMap.setMapStatus(MapStatusUpdateFactory.newMapStatus(new MapStatus.Builder().target(ll).zoom(16).build()));
}
}
public void onReceivePoi(BDLocation poiLocation) {
}
}
OnMapClickListener listener = new OnMapClickListener() {
@Override
public void onMapClick(LatLng arg0)
{
// TODO Auto-generated method stub
System.out.println(arg0.latitude);
System.out.println(arg0.longitude);
// mLocClient.setLocOption(LatLng);
}
@Override
public boolean onMapPoiClick(MapPoi arg0) {
// TODO Auto-generated method stub
return false;
}
};
}
|
package com.train.amm;
import android.app.job.JobScheduler;
import android.app.job.JobService;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
public class MyBroadCastActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my_broad_cast);
}
public void openMyBroadCast(View view){
//开启自定义广播
Intent intent = new Intent();
intent.setAction("com.train.action");
sendBroadcast(intent);
}
//发送有序广播
public void orderCast(View view){
//有序广播可以层层拦截,层层剥夺,修改广播至下级,甚至拦截广播
Intent intent = new Intent();
intent.setAction("com.train.order");
sendOrderedBroadcast(intent,null,null,null,0,"有序广播",null);
}
public void resultCast(View view){
Intent intent = new Intent();
intent.setAction("com.train.order");
sendOrderedBroadcast(intent,null,new MyResultReceiver(),null,0,"有序广播",null);
}
//最终接收者不需要再清单文件中配置,这个广播接收者只接收该有序广播,且是最后一个收到该广播的
class MyResultReceiver extends BroadcastReceiver{
@Override
public void onReceive(Context context, Intent intent) {
String resultData = getResultData();
System.out.println("最终接收者: " + resultData);
}
}
}
|
package nuc.bsd.util;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.itextpdf.io.codec.Base64;
import nuc.bsd.report.Impl.PdfReport;
public class EChartsUtil {
private static String url = "http://localhost:9090";
private static final Logger logger = LoggerFactory.getLogger(EChartsUtil.class);
public static boolean generateEChartsImage(String optJson, String outFile) {
boolean isSuccess = true;
try {
Map<String, String> map = new HashMap<String, String>();
map.put("opt", optJson);
String post = post(url, map, "utf-8");
JSONObject myJsonObject = new JSONObject(post);
if(myJsonObject.getInt("code")==1) {
logger.info("图表服务器生成成功");
isSuccess = GenerateImage(myJsonObject.getString("data"), outFile);
}else {
isSuccess = false;
logger.error("图表服务器生成失败"+myJsonObject.getString("msg"));
}
} catch (ParseException e) {
isSuccess = false;
logger.error("上传的json字符串解析失败:"+optJson);
} catch (IOException e) {
isSuccess = false;
logger.error("图表服务器连接失败:"+e.getMessage());
}
return isSuccess;
}
private static String post(String url, Map<String, String> map, String encoding)
throws ParseException, IOException {
String body = "";
CloseableHttpClient client = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(url);
List<NameValuePair> nvps = new ArrayList<NameValuePair>();
if (map != null) {
for (Entry<String, String> entry : map.entrySet()) {
nvps.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
}
}
httpPost.setEntity(new UrlEncodedFormEntity(nvps, encoding));
CloseableHttpResponse response = client.execute(httpPost);
HttpEntity entity = response.getEntity();
if (entity != null) {
body = EntityUtils.toString(entity, encoding);
}
EntityUtils.consume(entity);
response.close();
return body;
}
private static boolean GenerateImage(String imgStr, String imgFilePath) {
if (imgStr == null)
return false;
try {
byte[] b = Base64.decode(imgStr);
for (int i = 0; i < b.length; ++i) {
if (b[i] < 0) {
b[i] += 256;
}
}
OutputStream out = new FileOutputStream(imgFilePath);
out.write(b);
out.flush();
out.close();
ImageUtil.trimBlank(imgFilePath);
return true;
} catch (Exception e) {
return false;
}
}
}
|
package com.design.patterns.structurals.bridge;
// De cierto modo este es el bridge, quita lo acoplado en las jerarquías
// Segundo nivel de jerarquía
public interface MessageSender {
void sendMessage();
}
|
package de.varylab.discreteconformal.convergence;
import static de.varylab.discreteconformal.convergence.ConvergenceUtility.getMaxMeanSumCrossRatio;
import static de.varylab.discreteconformal.convergence.ConvergenceUtility.getMaxMeanSumMultiRatio;
import static de.varylab.discreteconformal.convergence.ConvergenceUtility.getMaxMeanSumScaleInvariantCircumRadius;
import static de.varylab.discreteconformal.util.DiscreteEllipticUtility.calculateHalfPeriodRatio;
import static de.varylab.discreteconformal.util.DiscreteEllipticUtility.generateEllipticImage;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.logging.Logger;
import joptsimple.OptionParser;
import joptsimple.OptionSet;
import joptsimple.OptionSpec;
import de.jreality.math.Pn;
import de.jtem.mfc.field.Complex;
import de.varylab.discreteconformal.heds.CoEdge;
import de.varylab.discreteconformal.heds.CoFace;
import de.varylab.discreteconformal.heds.CoHDS;
import de.varylab.discreteconformal.heds.CoVertex;
import de.varylab.discreteconformal.unwrapper.SphereUtility;
import de.varylab.discreteconformal.util.CuttingUtility.CuttingInfo;
public class ConvergenceNumberOfPoints extends ConvergenceSeries {
private Logger
log = Logger.getLogger(ConvergenceNumberOfPoints.class.getName());
private int
minExtraPoints = 0,
maxExtraPoints = 0,
iterations = 1,
numOptSteps = 0,
numJobs = 4;
@Override
protected OptionSet configureAndParseOptions(OptionParser p, String... args) {
OptionSpec<Integer> minPointsSpec = p.accepts("min", "Minimum number of extra points").withRequiredArg().ofType(Integer.class).defaultsTo(0);
OptionSpec<Integer> maxPointsSpec = p.accepts("max", "Maximum number of extra points").withRequiredArg().ofType(Integer.class).defaultsTo(50);
OptionSpec<Integer> iterationsPointsSpec = p.accepts("iter", "Iterations").withRequiredArg().ofType(Integer.class).defaultsTo(1000);
OptionSpec<Integer> optStepsSpec = p.accepts("nopt", "Number of triangulation optimization steps").withRequiredArg().ofType(Integer.class).defaultsTo(0);
OptionSpec<Integer> jobsSpec = p.accepts("jobs", "Number of Jobs").withRequiredArg().ofType(Integer.class).defaultsTo(4);
OptionSet opts = p.parse(args);
minExtraPoints = minPointsSpec.value(opts);
maxExtraPoints = maxPointsSpec.value(opts);
iterations = iterationsPointsSpec.value(opts);
numOptSteps = opts.valueOf(optStepsSpec);
numJobs = opts.valueOf(jobsSpec);
return opts;
}
@Override
protected void perform() throws Exception {
String description = "vertexNum[1]\tdistErr[2]\tabsErr[3]\targErr[4]\treErr[5]\timErr[6]\tre[7]\tim[8]\t";
description += "MaxCrossRatio\t";
description += "MeanCrossRatio\t";
description += "SumCrossRatio\t";
description += "MaxMultiRatio\t";
description += "MeanMultiRatio\t";
description += "SumMultiRatio\t";
description += "MaxCircleRadius\t";
description += "MeanCircleRadius\t";
description += "SumCircleRadius";
writeComment(description);
ExecutorService executor = Executors.newFixedThreadPool(numJobs);
for (int i = 0; i < iterations; i++) {
executor.submit(new Runnable() {
@Override
public void run() {
CoHDS hds = new CoHDS();
// predefined vertices
for (int vi = 0; vi < vertices.length; vi++) {
CoVertex v = hds.addNewVertex();
v.P = new double[] {vertices[vi][0], vertices[vi][1], vertices[vi][2], 1.0};
Pn.setToLength(v.P, v.P, 1, Pn.EUCLIDEAN);
}
// additional points
int numVertices = rnd.nextInt(maxExtraPoints - minExtraPoints) + minExtraPoints;
for (int j = 0; j < numVertices; j++) {
CoVertex v = hds.addNewVertex();
v.P = new double[] {rnd.nextGaussian(), rnd.nextGaussian(), rnd.nextGaussian(), 1.0};
Pn.setToLength(v.P, v.P, 1, Pn.EUCLIDEAN);
}
// optimize triangulation
if (numOptSteps > 0) {
Set<CoVertex> fixedVertices = new HashSet<CoVertex>();
fixedVertices.add(hds.getVertex(branchIndices[0]));
fixedVertices.add(hds.getVertex(branchIndices[1]));
fixedVertices.add(hds.getVertex(branchIndices[2]));
fixedVertices.add(hds.getVertex(branchIndices[3]));
SphereUtility.equalizeSphereVertices(hds, fixedVertices, numOptSteps, 1E-6);
}
Complex tau = null;
double[] crossRatioQuality = null;
double[] multiRatioQuality = null;
double[] circleRadiusQuality = null;
CoVertex cutRoot = hds.getVertex(branchIndices[0]);
CuttingInfo<CoVertex, CoEdge, CoFace> cutInfo = new CuttingInfo<>();
try {
Set<CoEdge> glueSet = new HashSet<CoEdge>();
Map<CoVertex, CoVertex> involution = generateEllipticImage(hds, 0, glueSet, branchIndices);
if (!cutRoot.isValid()) cutRoot = involution.get(cutRoot);
crossRatioQuality = getMaxMeanSumCrossRatio(hds, 1);
multiRatioQuality = getMaxMeanSumMultiRatio(hds, 1);
tau = calculateHalfPeriodRatio(hds, cutRoot, 1E-9, cutInfo);
circleRadiusQuality = getMaxMeanSumScaleInvariantCircumRadius(hds);
} catch (Exception e) {
log.warning(e.getMessage());
return;
}
double absErr = tau.abs() - getExpectedTau().abs();
double argErr = tau.arg() - getExpectedTau().arg();
double reErr = tau.re - getExpectedTau().re;
double imErr = tau.im - getExpectedTau().im;
double distErr = getExpectedTau().minus(tau).abs();
String logString = numVertices + "\t" + distErr + "\t" + absErr + "\t" + argErr + "\t" + reErr + "\t" + imErr + "\t" + tau.re + "\t" + tau.im + "\t";
logString += crossRatioQuality[0] + "\t";
logString += crossRatioQuality[1] + "\t";
logString += crossRatioQuality[2] + "\t";
logString += multiRatioQuality[0] + "\t";
logString += multiRatioQuality[1] + "\t";
logString += multiRatioQuality[2] + "\t";
logString += circleRadiusQuality[0] + "\t";
logString += circleRadiusQuality[1] + "\t";
logString += circleRadiusQuality[2] + "\t";
writeData(logString);
}
});
}
executor.awaitTermination(10, TimeUnit.DAYS);
}
}
|
package be.mxs.common.util.pdf.general.oc.examinations;
import be.mxs.common.util.pdf.general.PDFGeneralBasic;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfPCell;
import java.util.Vector;
/**
* User: ssm
* Date: 18-jul-2007
*/
public class PDFPostPartumMother extends PDFGeneralBasic {
//--- ADD CONTENT -----------------------------------------------------------------------------
protected void addContent(){
try{
if(transactionVO.getItems().size() >= minNumberOfItems){
Vector list = new Vector();
list.add(IConstants_PREFIX+"ITEM_TYPE_CARDIAL_CLINICAL_EXAMINATION_SYSTOLIC_PRESSURE_LEFT");
list.add(IConstants_PREFIX+"ITEM_TYPE_CARDIAL_CLINICAL_EXAMINATION_DIASTOLIC_PRESSURE_LEFT");
list.add(IConstants_PREFIX+"ITEM_TYPE_BIOMETRY_WEIGHT");
list.add(IConstants_PREFIX+"ITEM_TYPE_BIOMETRY_TEMPERATURE");
list.add(IConstants_PREFIX+"ITEM_TYPE_PPM_CONJUNCTIVA");
list.add(IConstants_PREFIX+"ITEM_TYPE_PPM_LOSS");
list.add(IConstants_PREFIX+"ITEM_TYPE_PPM_BREAST");
list.add(IConstants_PREFIX+"ITEM_TYPE_PPM_OBSERVATION");
list.add(IConstants_PREFIX+"ITEM_TYPE_PPM_TREATMENT");
list.add(IConstants_PREFIX+"ITEM_TYPE_PPM_ASPECT");
list.add(IConstants_PREFIX+"ITEM_TYPE_PPM_ODEUR");
list.add(IConstants_PREFIX+"ITEM_TYPE_PPM_CONCLUSION");
list.add(IConstants_PREFIX+"ITEM_TYPE_PPM_LOCHIES_CONCLUSION_REMARK");
if(verifyList(list)){
contentTable = new PdfPTable(1);
table = new PdfPTable(10);
int itemCount = 0;
//*** bloodpressure ***
String sysLeft = getItemValue(IConstants_PREFIX+"ITEM_TYPE_CARDIAL_CLINICAL_EXAMINATION_SYSTOLIC_PRESSURE_LEFT"),
diaLeft = getItemValue(IConstants_PREFIX+"ITEM_TYPE_CARDIAL_CLINICAL_EXAMINATION_DIASTOLIC_PRESSURE_LEFT");
String bloodpressure = sysLeft+" / "+diaLeft+" mmHg";
if(sysLeft.length() > 0 || diaLeft.length() > 0){
addItemRow(table,getTran("openclinic.chuk","bloodpressure"),bloodpressure);
itemCount++;
}
// weight
itemValue = getItemValue(IConstants_PREFIX+"ITEM_TYPE_BIOMETRY_WEIGHT");
if(itemValue.length() > 0){
addItemRow(table,getTran("openclinic.chuk","weight"),itemValue);
itemCount++;
}
// temperature
itemValue = getItemValue(IConstants_PREFIX+"ITEM_TYPE_BIOMETRY_TEMPERATURE");
if(itemValue.length() > 0){
addItemRow(table,getTran("openclinic.chuk","temperature"),itemValue);
itemCount++;
}
// paleness.conjunctiva
itemValue = getItemValue(IConstants_PREFIX+"ITEM_TYPE_PPM_CONJUNCTIVA");
if(itemValue.length() > 0){
addItemRow(table,getTran("openclinic.chuk","paleness.conjunctiva"),itemValue);
itemCount++;
}
// ppm loss
itemValue = getItemValue(IConstants_PREFIX+"ITEM_TYPE_PPM_LOSS");
if(itemValue.length() > 0){
addItemRow(table,getTran("openclinic.chuk","loss"),itemValue);
itemCount++;
}
// breast
itemValue = getItemValue(IConstants_PREFIX+"ITEM_TYPE_PPM_BREAST");
if(itemValue.length() > 0){
addItemRow(table,getTran("openclinic.chuk","breast"),itemValue);
itemCount++;
}
// observation
itemValue = getItemValue(IConstants_PREFIX+"ITEM_TYPE_PPM_OBSERVATION");
if(itemValue.length() > 0){
addItemRow(table,getTran("openclinic.chuk","observation"),itemValue);
itemCount++;
}
// treatment
itemValue = getItemValue(IConstants_PREFIX+"ITEM_TYPE_PPM_TREATMENT");
if(itemValue.length() > 0){
addItemRow(table,getTran("openclinic.chuk","treatment"),itemValue);
itemCount++;
}
// add cell to achieve an even number of displayed cells
if(itemCount%2==1){
cell = new PdfPCell();
cell.setColspan(5);
cell.setBorder(PdfPCell.NO_BORDER);
table.addCell(cell);
}
//*** LOCHIES *******************************************************
PdfPTable lochiesTable = new PdfPTable(4);
// aspect
itemValue = getItemValue(IConstants_PREFIX+"ITEM_TYPE_PPM_ASPECT");
if(itemValue.length() > 0){
lochiesTable.addCell(createItemNameCell(getTran("gynaeco","lochies.aspect"),1));
lochiesTable.addCell(createValueCell(getTran("web.occup",itemValue).toLowerCase(),3));
}
// odeur
itemValue = getItemValue(IConstants_PREFIX+"ITEM_TYPE_PPM_ODEUR");
if(itemValue.length() > 0){
lochiesTable.addCell(createItemNameCell(getTran("gynaeco","lochies.odeur"),1));
lochiesTable.addCell(createValueCell(getTran("web.occup",itemValue).toLowerCase(),3));
}
// conclusion
itemValue = getItemValue(IConstants_PREFIX+"ITEM_TYPE_PPM_CONCLUSION");
if(itemValue.length() > 0){
itemValue = itemValue.substring(itemValue.lastIndexOf(".")+1);
lochiesTable.addCell(createItemNameCell(getTran("gynaeco","lochies.conclusion"),1));
lochiesTable.addCell(createValueCell(getTran("gynaeco.conclusion",itemValue).toLowerCase(),3));
}
// remark
itemValue = getItemValue(IConstants_PREFIX+"ITEM_TYPE_PPM_LOCHIES_CONCLUSION_REMARK");
if(itemValue.length() > 0){
lochiesTable.addCell(createItemNameCell(getTran("gynaeco","lochies.remark"),1));
lochiesTable.addCell(createValueCell(itemValue,3));
}
// add lochies table
if(lochiesTable.size() > 0){
// title
cell = createItemNameCell(getTran("gynaeco","lochies"),2);
cell.setBackgroundColor(BGCOLOR_LIGHT);
table.addCell(cell);
table.addCell(createCell(new PdfPCell(lochiesTable),8,PdfPCell.ALIGN_CENTER,PdfPCell.BOX));
}
// add table
if(table.size() > 0){
if(contentTable.size() > 0) contentTable.addCell(emptyCell());
contentTable.addCell(createCell(new PdfPCell(table),1,PdfPCell.ALIGN_CENTER,PdfPCell.NO_BORDER));
tranTable.addCell(new PdfPCell(contentTable));
addTransactionToDoc();
}
// diagnoses
addDiagnosisEncoding();
addTransactionToDoc();
}
}
}
catch(Exception e){
e.printStackTrace();
}
}
//#############################################################################################
//### PRIVATE METHODS #########################################################################
//#############################################################################################
//--- ADD ITEM ROW ----------------------------------------------------------------------------
protected void addItemRow(PdfPTable table, String itemName, String itemValue){
cell = createItemNameCell(itemName);
cell.setBackgroundColor(BGCOLOR_LIGHT);
table.addCell(cell);
table.addCell(createValueCell(itemValue));
}
}
|
package net.codejava;
public class FoodItem {
public String Name;
public int price;
public int quantity;
/*
* public FoodItem(String FoodName, int FoodPrice, int FoodQuantity) { Name =
* FoodName; price = FoodPrice; quantity = FoodQuantity; }
*/
public FoodItem(String foodName, int foodPrice, int foodQuantity) {
// TODO Auto-generated constructor stub
Name = foodName;
price = foodPrice;
quantity = foodQuantity;
}
}
|
package com.example.chordnote.data.network;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
import javax.inject.Inject;
public class ApiHeader {
private ProtectedApiHeader mProtectedApiHeader;
@Inject
public ApiHeader(ProtectedApiHeader protectedApiHeader) {
mProtectedApiHeader = protectedApiHeader;
}
public ProtectedApiHeader getmProtectedApiHeader() {
return mProtectedApiHeader;
}
public static final class ProtectedApiHeader {
@Expose
@SerializedName("token")
private String mAccessToken;
public ProtectedApiHeader(String token) {
mAccessToken = token;
}
public String getmAccessToken() {
return mAccessToken;
}
public void setmAccessToken(String mAccessToken) {
this.mAccessToken = mAccessToken;
}
}
}
|
package com.ramonmr95.app.validators;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
import com.ramonmr95.app.parsers.JsonParser;
/**
*
* Class used to validate if an entity fulfill all of its validation beans.
*
* @author Ramón Moñino Rubio.
*
* @param <T> Class of the entity.
*/
public class EntityValidator<T> {
private JsonParser jsonParser = new JsonParser();
/**
*
* Gets a map with all of the validation errors.
*
* @param entity Entity to be validated.
* @return map with validation errors.
*/
public Map<String, Set<String>> getEntityValidationErrors(T entity) {
ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
Validator validator = factory.getValidator();
Set<ConstraintViolation<T>> validationErrors = validator.validate(entity);
Set<String> errorsSet = new HashSet<>();
for (ConstraintViolation<T> constraintViolation : validationErrors) {
errorsSet.add(constraintViolation.getMessage());
}
Map<String, Set<String>> errors = new HashMap<>();
errors.put("errors", errorsSet);
return errors;
}
/**
*
* Gets all of the validation errors as string.
*
* @param entity Entity to be validated.
* @return json format string with the errors.
*/
public String getEntityValidationErrorsString(T entity) {
return jsonParser.getMapAsJsonFormat(getEntityValidationErrors(entity));
}
/**
*
* Checks if an entity contains any validation error.
*
* @param entity Entity to be validated.
* @return true if contains any error, false if not.
*/
public boolean isEntityValid(T entity) {
return this.getEntityValidationErrors(entity).get("errors").isEmpty();
}
}
|
package com.example.certificate_demo;
import java.util.List;
import java.util.Map;
/**
* web response to keep status, response body, headers and related exceptions
*
* @author omercan
*/
public class HttpWebResponse {
private int mStatusCode;
private byte[] mResponseBody;
private Map<String, List<String>> mResponseHeaders;
private Exception responseException = null;
public HttpWebResponse() {
mStatusCode = 200;
mResponseBody = null;
}
public HttpWebResponse(int statusCode, byte[] responseBody,
Map<String, List<String>> responseHeaders) {
mStatusCode = statusCode;
mResponseBody = responseBody;
mResponseHeaders = responseHeaders;
}
public Exception getResponseException() {
return responseException;
}
public void setResponseException(Exception responseException) {
this.responseException = responseException;
}
HttpWebResponse(int statusCode) {
mStatusCode = statusCode;
}
public int getStatusCode() {
return mStatusCode;
}
public void setStatusCode(int status) {
mStatusCode = status;
}
public Map<String, List<String>> getResponseHeaders() {
return mResponseHeaders;
}
public void setResponseHeaders(Map<String, List<String>> headers) {
mResponseHeaders = headers;
}
public byte[] getBody() {
return mResponseBody;
}
public void setBody(byte[] body) {
mResponseBody = body;
}
}
|
package yzk.user.formEntity;
public class PwdEntity {
private String xh;
public String getXh() {
return xh;
}
public void setXh(String xh) {
this.xh = xh;
}
}
|
package pak3;
import java.io.IOException;
import java.io.PrintWriter;
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.Cookie;
@WebServlet(urlPatterns = {"/get_cookies"})
public class get_cookies extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setContentType("text/html");
PrintWriter pw = resp.getWriter();
Cookie cookie=null;
Cookie[] cookies = req.getCookies();
if (cookies != null) {
pw.println("Found Cookies Name and Value: ");
for (int i = 0; i < cookies.length; i++) {
cookie = cookies[i];
pw.print(" " + cookie.getName() + "--");
pw.print("..." + cookie.getValue());
}
} else {
pw.println("No cookies founds");
}
}
}
|
package com.brichri.howTiredAmI.provider;
import android.net.Uri;
import android.provider.BaseColumns;
public final class TestResultsContract {
public static final String AUTHORITY = "com.brichri.howTiredAmI.provider";
public static final String TESTS = "tests";
public static final String RESULTS = "results";
private TestResultsContract (){} // this class cannot be instantiated
public static final class Tests implements BaseColumns {
private Tests (){} // this class cannot be instantiated
public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/tests");
public static final String CONTENT_TYPE = "vnd.android.cursor.dir/vnd.brichri.howTiredAmI.tests";
public static final String DURATION = "duration";
public static final String START_TIME_SECONDS = "unix_start_time";
public static final String NOTES = "notes";
public static final String REACTION_SCORE = "reaction_score";
public static final String LAPSE_TIME = "lapse_time";
public static final String LAPSE_COUNT = "lapse_count";
public static final String SORT_BY_NEWEST = START_TIME_SECONDS + " DESC";
public static final String SORT_BY_OLDEST = START_TIME_SECONDS + " ASC";
public static final String SORT_BY_FASTEST = REACTION_SCORE + " ASC, " + LAPSE_COUNT + " ASC, " + START_TIME_SECONDS + " DESC";
public static final String SORT_BY_SLOWEST = REACTION_SCORE + " DESC, " + LAPSE_COUNT + " DESC, " + START_TIME_SECONDS + " DESC";
public static final String SORT_BY_MOST_FAILS = LAPSE_COUNT + " DESC, " + REACTION_SCORE + " DESC, " + START_TIME_SECONDS + " DESC";
public static final String SORT_BY_LEAST_FAILS = LAPSE_COUNT + " ASC, " + REACTION_SCORE + " ASC, " + START_TIME_SECONDS + " DESC";
}
public static final class Results implements BaseColumns {
private Results (){} // this class cannot be instantiated
public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/results");
public static final String CONTENT_TYPE = "vnd.android.cursor.dir/vnd.brichri.howTiredAmI.results";
public static final String TIME = "result_time";
public static final String VALUE = "result_value";
public static final String TEST_ID = "test_id";
public static final String DEFAULT_SORT_ORDER = "result_time ASC";
}
} |
package com.amhable.persistencia.implementacion;
import java.util.List;
import org.apache.log4j.Logger;
import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import com.amhable.dominio.CategoriaDto;
import com.amhable.exception.MyException;
import com.amhable.persistencia.CategoriaDao;
/**
* Clase encargada de implementar los metodos definidos
* en la interface CategoriaDao
*
* @author Jorge Atehortua
*
*/
public class CategoriaDaoImp extends HibernateDaoSupport implements CategoriaDao{
Logger log = Logger.getLogger(this.getClass());
/**
* metodo obtenerCategoria(Integer idcategoria) encargado de obtener una categoria
* de la base de datos buscado por idCategoria
*
* @param idCategoria que se va obtener
* @return Categoria que coincide con el parametro de busqueda
* @throws MyException
*/
public CategoriaDto obtenerCategoria(Integer idCategoria) throws MyException {
try {
Session session=null;
CategoriaDto categoria = null;
session=getSession();
categoria = (CategoriaDto)session.get(CategoriaDto.class, idCategoria);
return categoria;
}catch(HibernateException e){
log.error("ERROR obteniendo categoria: ", e);
throw new MyException(e);
}finally{
}
}
/**
*Metodo guardarCategoria(CategoriaDto categoria) encargado de guardar la categoria enviada como
*parametro en la base de datos
*
* @param categoria que se va guardar
* @throws MyException
*/
public void guardar(CategoriaDto categoria) throws MyException {
Session session = null;
try {
session =getSession();
Transaction tx = session.beginTransaction();
session.save(categoria);
tx.commit();
} catch(HibernateException e){
e.printStackTrace();
log.error("ERROR guardando categoria: ", e);
throw new MyException(e);
}finally{
}
}
/**
* Metododo obtenerCategorias() encargado de obtener una lista con las categorias
* existentes en la base de datos
*
* @return Listado de las categorias en la base de datos
* @throws MyException
*/
@SuppressWarnings("unchecked")
public List<CategoriaDto> obtenerCategorias() throws MyException {
Session session=null;
List<CategoriaDto> categorias=null;
try{
session=getSession();
Criteria criteria=session.createCriteria(CategoriaDto.class);
categorias=criteria.list();
}catch(HibernateException e){
e.printStackTrace();
log.error("ERROR obteniendo lista de categorias: ", e);
throw new MyException(e);
}finally{
}
return categorias;
}
/**
* ActualizarCategoria(categoriaDto categoria) actualiza la categoria que se
* pasa como parametro
*
* @param categoria que se va actualizar
* @throws MyException
*/
public void actualizar(CategoriaDto categoria) throws MyException {
Session session = null;
try {
session = getSession();
Transaction tx = session.beginTransaction();
session.update(categoria);
tx.commit();
} catch(HibernateException e){
e.printStackTrace();
log.error("ERROR actualizando categoria: ", e);
throw new MyException(e);
}finally{
}
}
/**
* Metodo eliminar sera el encargado de eliminar una
* categoria de la base de datos.
*
* @param la categoria que se va a eliminar.
* @throws MyException
*/
public void eliminar(CategoriaDto categoria) throws MyException {
Session session = null;
try {
session = getSession();
Transaction tx = session.beginTransaction();
session.delete(categoria);
tx.commit();
} catch(HibernateException e){
e.printStackTrace();
log.error("ERROR eliminando categoria: ", e);
throw new MyException(e);
}finally{
}
}
}
|
package com.lti.Algorithms.Codility.SieveOfEratosthenes;
import java.util.Arrays;
import java.util.Map;
import java.util.TreeMap;
/**
* Created by busis on 2020-12-14.
*/
public class CountNonDivisible {
public static void main(String[] args) {
int[] a={3,1,2,3,6};
System.out.println(Arrays.toString(solution(a)));
}
public static int[] solution(int[] a){
int n=a.length;
int[] ans=new int[n];
//HashMap replaces the old with new one in case of collisions
Map<Integer,Integer> frequencyMap=new TreeMap<Integer, Integer>();
int maxValue=Integer.MIN_VALUE;
for(int i=0;i<n;i++){
if(a[i]>maxValue)
maxValue=a[i];
int v=frequencyMap.containsKey(a[i])?frequencyMap.get(a[i]):0;
v+=1;
frequencyMap.put(a[i],v);
}
for(int i=0;i<n;i++){
int num=a[i];
int freq=0;
int sqrtNum=(int)Math.sqrt(num);
for(int j=1;j<=sqrtNum;j++){
if(num%j==0){
freq+=frequencyMap.containsKey(j)?frequencyMap.get(j):0;
freq+=frequencyMap.containsKey(num/j)?frequencyMap.get(num/j):0;
}
}
if(sqrtNum*sqrtNum==num)
freq-=frequencyMap.containsKey(sqrtNum)?frequencyMap.get(sqrtNum):0;
ans[i]=n-freq;
}
return ans;
}
}
|
package com.example.federation.Participants;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.RatingBar;
import android.widget.TextView;
import android.widget.Toast;
import com.example.federation.Events.EventInformationActivity;
import com.example.federation.R;
import com.example.federation.SQLite.DatabaseLRHandler;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.SortedSet;
import java.util.TreeSet;
public class Feedback extends AppCompatActivity {
TextView eventName,participantName,participantEmail;
ListView feedbackCriteriaListView;
Button submitButton;
EditText remarks;
DatabaseLRHandler db;
List<String> feedbackCriteriaLinkedList=new ArrayList<>();
Map<Integer,Float> mapOfFeedBack=new LinkedHashMap<>();
float [] ratings;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_feedback);
db=new DatabaseLRHandler(this);
eventName=(TextView)findViewById(R.id.eventName);
participantEmail=(TextView)findViewById(R.id.participantEmail);
participantName=(TextView)findViewById(R.id.participantName);
remarks=(EditText)findViewById(R.id.remarks);
eventName.setText(getIntent().getStringExtra("eventName"));
participantEmail.setText(getIntent().getStringExtra("participantEmail"));
participantName.setText(getIntent().getStringExtra("participantName"));
feedbackCriteriaListView=(ListView)findViewById(R.id.feedbackCriteriaListView);
submitButton=(Button)findViewById(R.id.submitButton);
feedbackCriteriaLinkedList.add("Did the programme create an awakening for outdoor Activities?");
feedbackCriteriaLinkedList.add("Did the programme provide the stretch for discovering the potential in you?");
feedbackCriteriaLinkedList.add("Did the Water Sports activity Increase your confidence level in water ?");
feedbackCriteriaLinkedList.add("Did the Ice Breaker game help in bringing you closer to one another to form a good team Ice Brea er game?");
feedbackCriteriaLinkedList.add("Did the Adventures activities create awareness of achieving goals through Team Performance ?");
feedbackCriteriaLinkedList.add("Did the adventure activities focus on Leadership Development ?");
feedbackCriteriaLinkedList.add("Keeping in view the overall programme, how do you grade your group Instructor?");
for(int i=0;i<feedbackCriteriaLinkedList.size();i++){
mapOfFeedBack.put(i,(float)0);
populateFeedBackList();
}
ratings=new float[feedbackCriteriaLinkedList.size()+1];
submitButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
JSONArray jsonArray=new JSONArray();
JSONObject jsonObject=new JSONObject();
SortedSet<Integer> keys=new TreeSet<Integer>(mapOfFeedBack.keySet());
for(Integer key:keys){
try {
jsonObject.put(String.valueOf(key),String.valueOf(mapOfFeedBack.get(key)));
} catch (JSONException e) {
e.printStackTrace();
}
}
jsonArray.put(jsonObject);
db.submitFeedback(getIntent().getIntExtra("participantId",0),getIntent().getIntExtra("eventId",0),jsonArray.toString(),remarks.getText().toString().trim());
Toast.makeText(getApplicationContext(), "Feedback submitted!", Toast.LENGTH_SHORT).show();
Intent iF=new Intent(getApplicationContext(), EventInformationActivity.class);
iF.putExtra("eventCode",getIntent().getStringExtra("eventCode"));
iF.putExtra("eventName",getIntent().getStringExtra("eventName"));
iF.putExtra("eventId",getIntent().getIntExtra("eventId",0));
startActivity(iF);
finish();
}
});
}
private void populateFeedBackList(){
ArrayAdapter<String> adapter=new PopulateFeedbackListAdapter();
feedbackCriteriaListView.setAdapter(adapter);
}
class PopulateFeedbackListAdapter extends ArrayAdapter<String>{
public PopulateFeedbackListAdapter(){
super(getApplicationContext(),R.layout.activity_feedback_list_item_layout,feedbackCriteriaLinkedList);
}
@NonNull
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
View row = convertView;
if(row==null){
row= getLayoutInflater().inflate(R.layout.activity_feedback_list_item_layout,parent,false);
}
TextView feedbackCriteria=(TextView)row.findViewById(R.id.feedbackCriteria);
feedbackCriteria.setText(feedbackCriteriaLinkedList.get(position));
RatingBar rating=(RatingBar)row.findViewById(R.id.ratingBar);
rating.setRating(ratings[position]);
rating.setTag(position);
rating.setOnRatingBarChangeListener(new RatingBar.OnRatingBarChangeListener() {
@Override
public void onRatingChanged(RatingBar ratingBar, float rating, boolean b) {
if(!b)return;
int index = (Integer)(ratingBar.getTag());
ratings[index] = rating;
mapOfFeedBack.remove(position);
mapOfFeedBack.put(position,rating);
}
});
return row;
}
}
}
|
package com.marijannovak.littletanks;
/**
* Created by marij on 17.5.2017..
*/
public class ScoreItem {
private String playerName;
private int score, playTime, killed;
public ScoreItem()
{
}
public ScoreItem(String name, int scr, int time, int klld)
{
this.playerName = name;
this.score = scr;
this.playTime = time;
this.killed = klld;
}
public String getPlayerName() {
return playerName;
}
public int getScore() {
return score;
}
public int getPlayTime() {
return playTime;
}
public int getKilled() {
return killed;
}
public void setPlayerName(String playerName) {
this.playerName = playerName;
}
public void setScore(int score) {
this.score = score;
}
public void setPlayTime(int playTime) {
this.playTime = playTime;
}
public void setKilled(int killed) {
this.killed = killed;
}
}
|
package com.example.demo;
import java.util.HashMap;
import java.util.Map;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class ProductController {
private static final Logger logger = LogManager.getLogger(DemoApplication.class);
private static Map<String, Product> productRepo = new HashMap<>();
static {
Product honey = new Product();
honey.setId("1");
honey.setName("Honey");
productRepo.put(honey.getId(), honey);
Product almond = new Product();
almond.setId("2");
almond.setName("Almond");
productRepo.put(almond.getId(), almond);
}
@RequestMapping(value = "/products")
public ResponseEntity<Object> getProducts() {
logger.info("Products method");
return new ResponseEntity<>(productRepo.values(), HttpStatus.OK);
}
@RequestMapping(value = "/products/{id}")
public ResponseEntity<Object> getProduct(@PathVariable("id") String id) {
logger.info("Product methoda");
System.out.println(id);
productRepo.get(id);
return new ResponseEntity<>(productRepo.values(), HttpStatus.OK);
}
}
|
/*
* 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.beans.factory.support;
import java.lang.annotation.Annotation;
import java.lang.reflect.Executable;
import java.util.List;
import java.util.Locale;
import java.util.concurrent.Executor;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.testfixture.beans.factory.generator.factory.NumberHolder;
import org.springframework.beans.testfixture.beans.factory.generator.factory.NumberHolderFactoryBean;
import org.springframework.beans.testfixture.beans.factory.generator.factory.SampleFactory;
import org.springframework.core.ResolvableType;
import org.springframework.core.annotation.MergedAnnotations.SearchStrategy;
import org.springframework.lang.Nullable;
import org.springframework.util.ReflectionUtils;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalStateException;
/**
* Tests for {@link ConstructorResolver} focused on AOT constructor and factory
* method resolution.
*
* @author Stephane Nicoll
* @author Phillip Webb
*/
class ConstructorResolverAotTests {
@Test
void detectBeanInstanceExecutableWithBeanClassAndFactoryMethodName() {
DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory();
beanFactory.registerSingleton("testBean", "test");
BeanDefinition beanDefinition = BeanDefinitionBuilder
.rootBeanDefinition(SampleFactory.class).setFactoryMethod("create")
.addConstructorArgReference("testBean").getBeanDefinition();
Executable executable = resolve(beanFactory, beanDefinition);
assertThat(executable).isNotNull().isEqualTo(
ReflectionUtils.findMethod(SampleFactory.class, "create", String.class));
}
@Test
void detectBeanInstanceExecutableWithBeanClassNameAndFactoryMethodName() {
DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory();
beanFactory.registerSingleton("testBean", "test");
BeanDefinition beanDefinition = BeanDefinitionBuilder
.rootBeanDefinition(SampleFactory.class.getName())
.setFactoryMethod("create").addConstructorArgReference("testBean")
.getBeanDefinition();
Executable executable = resolve(beanFactory, beanDefinition);
assertThat(executable).isNotNull().isEqualTo(
ReflectionUtils.findMethod(SampleFactory.class, "create", String.class));
}
@Test
void beanDefinitionWithFactoryMethodNameAndAssignableConstructorArg() {
DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory();
beanFactory.registerSingleton("testNumber", 1L);
beanFactory.registerSingleton("testBean", "test");
BeanDefinition beanDefinition = BeanDefinitionBuilder
.rootBeanDefinition(SampleFactory.class).setFactoryMethod("create")
.addConstructorArgReference("testNumber")
.addConstructorArgReference("testBean").getBeanDefinition();
Executable executable = resolve(beanFactory, beanDefinition);
assertThat(executable).isNotNull().isEqualTo(ReflectionUtils
.findMethod(SampleFactory.class, "create", Number.class, String.class));
}
@Test
void beanDefinitionWithFactoryMethodNameAndMatchingMethodNames() {
DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory();
BeanDefinition beanDefinition = BeanDefinitionBuilder
.rootBeanDefinition(DummySampleFactory.class).setFactoryMethod("of")
.addConstructorArgValue(42).getBeanDefinition();
Executable executable = resolve(beanFactory, beanDefinition);
assertThat(executable).isNotNull().isEqualTo(ReflectionUtils
.findMethod(DummySampleFactory.class, "of", Integer.class));
}
@Test
void beanDefinitionWithFactoryMethodNameAndOverriddenMethod() {
DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory();
beanFactory.registerBeanDefinition("config", new RootBeanDefinition(ExtendedSampleFactory.class));
BeanDefinition beanDefinition = BeanDefinitionBuilder
.rootBeanDefinition(String.class).setFactoryMethodOnBean("resolve", "config")
.addConstructorArgValue("test").getBeanDefinition();
Executable executable = resolve(beanFactory, beanDefinition);
assertThat(executable).isNotNull().isEqualTo(ReflectionUtils
.findMethod(ExtendedSampleFactory.class, "resolve", String.class));
}
@Test
void detectBeanInstanceExecutableWithBeanClassAndFactoryMethodNameIgnoreTargetType() {
DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory();
beanFactory.registerSingleton("testBean", "test");
RootBeanDefinition beanDefinition = (RootBeanDefinition) BeanDefinitionBuilder
.rootBeanDefinition(SampleFactory.class).setFactoryMethod("create")
.addConstructorArgReference("testBean").getBeanDefinition();
beanDefinition.setTargetType(String.class);
Executable executable = resolve(beanFactory, beanDefinition);
assertThat(executable).isNotNull().isEqualTo(
ReflectionUtils.findMethod(SampleFactory.class, "create", String.class));
}
@Test
void beanDefinitionWithConstructorArgsForMultipleConstructors() throws Exception {
DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory();
beanFactory.registerSingleton("testNumber", 1L);
beanFactory.registerSingleton("testBean", "test");
BeanDefinition beanDefinition = BeanDefinitionBuilder
.rootBeanDefinition(SampleBeanWithConstructors.class)
.addConstructorArgReference("testNumber")
.addConstructorArgReference("testBean").getBeanDefinition();
Executable executable = resolve(beanFactory, beanDefinition);
assertThat(executable).isNotNull().isEqualTo(SampleBeanWithConstructors.class
.getDeclaredConstructor(Number.class, String.class));
}
@Test
void beanDefinitionWithMultiArgConstructorAndMatchingValue() throws NoSuchMethodException {
BeanDefinition beanDefinition = BeanDefinitionBuilder
.rootBeanDefinition(MultiConstructorSample.class)
.addConstructorArgValue(42).getBeanDefinition();
Executable executable = resolve(new DefaultListableBeanFactory(), beanDefinition);
assertThat(executable).isNotNull().isEqualTo(
MultiConstructorSample.class.getDeclaredConstructor(Integer.class));
}
@Test
void beanDefinitionWithMultiArgConstructorAndMatchingArrayValue() throws NoSuchMethodException {
BeanDefinition beanDefinition = BeanDefinitionBuilder
.rootBeanDefinition(MultiConstructorArraySample.class)
.addConstructorArgValue(42).getBeanDefinition();
Executable executable = resolve(new DefaultListableBeanFactory(), beanDefinition);
assertThat(executable).isNotNull().isEqualTo(MultiConstructorArraySample.class
.getDeclaredConstructor(Integer[].class));
}
@Test
void beanDefinitionWithMultiArgConstructorAndMatchingListValue() throws NoSuchMethodException {
BeanDefinition beanDefinition = BeanDefinitionBuilder
.rootBeanDefinition(MultiConstructorListSample.class)
.addConstructorArgValue(42).getBeanDefinition();
Executable executable = resolve(new DefaultListableBeanFactory(), beanDefinition);
assertThat(executable).isNotNull().isEqualTo(
MultiConstructorListSample.class.getDeclaredConstructor(List.class));
}
@Test
void beanDefinitionWithMultiArgConstructorAndMatchingValueAsInnerBean() throws NoSuchMethodException {
BeanDefinition beanDefinition = BeanDefinitionBuilder
.rootBeanDefinition(MultiConstructorSample.class)
.addConstructorArgValue(
BeanDefinitionBuilder.rootBeanDefinition(Integer.class, "valueOf")
.addConstructorArgValue("42").getBeanDefinition())
.getBeanDefinition();
Executable executable = resolve(new DefaultListableBeanFactory(), beanDefinition);
assertThat(executable).isNotNull().isEqualTo(
MultiConstructorSample.class.getDeclaredConstructor(Integer.class));
}
@Test
void beanDefinitionWithMultiArgConstructorAndMatchingValueAsInnerBeanFactory() throws NoSuchMethodException {
BeanDefinition beanDefinition = BeanDefinitionBuilder
.rootBeanDefinition(MultiConstructorSample.class)
.addConstructorArgValue(BeanDefinitionBuilder
.rootBeanDefinition(IntegerFactoryBean.class).getBeanDefinition())
.getBeanDefinition();
Executable executable = resolve(new DefaultListableBeanFactory(), beanDefinition);
assertThat(executable).isNotNull().isEqualTo(
MultiConstructorSample.class.getDeclaredConstructor(Integer.class));
}
@Test
void beanDefinitionWithMultiArgConstructorAndNonMatchingValue() {
BeanDefinition beanDefinition = BeanDefinitionBuilder
.rootBeanDefinition(MultiConstructorSample.class)
.addConstructorArgValue(Locale.ENGLISH).getBeanDefinition();
assertThatIllegalStateException().isThrownBy(() -> resolve(new DefaultListableBeanFactory(), beanDefinition))
.withMessageContaining(MultiConstructorSample.class.getName())
.withMessageContaining("and argument types [java.util.Locale]");
}
@Test
void beanDefinitionWithMultiArgConstructorAndNonMatchingValueAsInnerBean() {
BeanDefinition beanDefinition = BeanDefinitionBuilder
.rootBeanDefinition(MultiConstructorSample.class)
.addConstructorArgValue(BeanDefinitionBuilder
.rootBeanDefinition(Locale.class, "getDefault")
.getBeanDefinition())
.getBeanDefinition();
assertThatIllegalStateException().isThrownBy(() -> resolve(new DefaultListableBeanFactory(), beanDefinition))
.withMessageContaining(MultiConstructorSample.class.getName())
.withMessageContaining("and argument types [java.util.Locale]");
}
@Test
void detectBeanInstanceExecutableWithFactoryBeanSetInBeanClass() {
DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory();
RootBeanDefinition beanDefinition = new RootBeanDefinition();
beanDefinition.setTargetType(
ResolvableType.forClassWithGenerics(NumberHolder.class, Integer.class));
beanDefinition.setBeanClass(NumberHolderFactoryBean.class);
Executable executable = resolve(beanFactory, beanDefinition);
assertThat(executable).isNotNull()
.isEqualTo(NumberHolderFactoryBean.class.getDeclaredConstructors()[0]);
}
@Test
void detectBeanInstanceExecutableWithFactoryBeanSetInBeanClassAndNoResolvableType() {
DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory();
RootBeanDefinition beanDefinition = new RootBeanDefinition();
beanDefinition.setBeanClass(NumberHolderFactoryBean.class);
Executable executable = resolve(beanFactory, beanDefinition);
assertThat(executable).isNotNull()
.isEqualTo(NumberHolderFactoryBean.class.getDeclaredConstructors()[0]);
}
@Test
void detectBeanInstanceExecutableWithFactoryBeanSetInBeanClassThatDoesNotMatchTargetType() {
DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory();
RootBeanDefinition beanDefinition = new RootBeanDefinition();
beanDefinition.setTargetType(
ResolvableType.forClassWithGenerics(NumberHolder.class, String.class));
beanDefinition.setBeanClass(NumberHolderFactoryBean.class);
assertThatIllegalStateException()
.isThrownBy(() -> resolve(beanFactory, beanDefinition))
.withMessageContaining("Incompatible target type")
.withMessageContaining(NumberHolder.class.getName())
.withMessageContaining(NumberHolderFactoryBean.class.getName());
}
@Test
void beanDefinitionWithClassArrayConstructorArgAndStringArrayValueType() throws NoSuchMethodException {
DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory();
BeanDefinition beanDefinition = BeanDefinitionBuilder
.rootBeanDefinition(ConstructorClassArraySample.class.getName())
.addConstructorArgValue(new String[] { "test1, test2" })
.getBeanDefinition();
Executable executable = resolve(beanFactory, beanDefinition);
assertThat(executable).isNotNull().isEqualTo(
ConstructorClassArraySample.class.getDeclaredConstructor(Class[].class));
}
@Test
void beanDefinitionWithClassArrayConstructorArgAndStringValueType() {
DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory();
BeanDefinition beanDefinition = BeanDefinitionBuilder
.rootBeanDefinition(ConstructorClassArraySample.class.getName())
.addConstructorArgValue("test1").getBeanDefinition();
Executable executable = resolve(beanFactory, beanDefinition);
assertThat(executable).isNotNull().isEqualTo(
ConstructorClassArraySample.class.getDeclaredConstructors()[0]);
}
@Test
void beanDefinitionWithClassArrayConstructorArgAndAnotherMatchingConstructor() throws NoSuchMethodException {
DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory();
BeanDefinition beanDefinition = BeanDefinitionBuilder
.rootBeanDefinition(MultiConstructorClassArraySample.class.getName())
.addConstructorArgValue(new String[] { "test1, test2" })
.getBeanDefinition();
Executable executable = resolve(beanFactory, beanDefinition);
assertThat(executable).isNotNull()
.isEqualTo(MultiConstructorClassArraySample.class
.getDeclaredConstructor(String[].class));
}
@Test
void beanDefinitionWithClassArrayFactoryMethodArgAndStringArrayValueType() {
DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory();
BeanDefinition beanDefinition = BeanDefinitionBuilder
.rootBeanDefinition(ClassArrayFactoryMethodSample.class.getName())
.setFactoryMethod("of")
.addConstructorArgValue(new String[] { "test1, test2" })
.getBeanDefinition();
Executable executable = resolve(beanFactory, beanDefinition);
assertThat(executable).isNotNull().isEqualTo(ReflectionUtils
.findMethod(ClassArrayFactoryMethodSample.class, "of", Class[].class));
}
@Test
void beanDefinitionWithClassArrayFactoryMethodArgAndAnotherMatchingConstructor() {
DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory();
BeanDefinition beanDefinition = BeanDefinitionBuilder.rootBeanDefinition(
ClassArrayFactoryMethodSampleWithAnotherFactoryMethod.class.getName())
.setFactoryMethod("of").addConstructorArgValue("test1")
.getBeanDefinition();
Executable executable = resolve(beanFactory, beanDefinition);
assertThat(executable).isNotNull()
.isEqualTo(ReflectionUtils.findMethod(
ClassArrayFactoryMethodSampleWithAnotherFactoryMethod.class, "of",
String[].class));
}
@Test
void beanDefinitionWithMultiArgConstructorAndPrimitiveConversion() throws NoSuchMethodException {
BeanDefinition beanDefinition = BeanDefinitionBuilder
.rootBeanDefinition(ConstructorPrimitiveFallback.class)
.addConstructorArgValue("true").getBeanDefinition();
Executable executable = resolve(new DefaultListableBeanFactory(), beanDefinition);
assertThat(executable).isEqualTo(
ConstructorPrimitiveFallback.class.getDeclaredConstructor(boolean.class));
}
@Test
void beanDefinitionWithFactoryWithOverloadedClassMethodsOnInterface() {
BeanDefinition beanDefinition = BeanDefinitionBuilder
.rootBeanDefinition(FactoryWithOverloadedClassMethodsOnInterface.class)
.setFactoryMethod("byAnnotation").addConstructorArgValue(Nullable.class)
.getBeanDefinition();
Executable executable = resolve(new DefaultListableBeanFactory(), beanDefinition);
assertThat(executable).isEqualTo(ReflectionUtils.findMethod(
FactoryWithOverloadedClassMethodsOnInterface.class, "byAnnotation",
Class.class));
}
private Executable resolve(DefaultListableBeanFactory beanFactory, BeanDefinition beanDefinition) {
return new ConstructorResolver(beanFactory).resolveConstructorOrFactoryMethod(
"testBean", (RootBeanDefinition) beanDefinition);
}
static class IntegerFactoryBean implements FactoryBean<Integer> {
@Override
public Integer getObject() {
return 42;
}
@Override
public Class<?> getObjectType() {
return Integer.class;
}
}
@SuppressWarnings("unused")
static class MultiConstructorSample {
MultiConstructorSample(String name) {
}
MultiConstructorSample(Integer value) {
}
}
@SuppressWarnings("unused")
static class MultiConstructorArraySample {
public MultiConstructorArraySample(String... names) {
}
public MultiConstructorArraySample(Integer... values) {
}
}
@SuppressWarnings("unused")
static class MultiConstructorListSample {
public MultiConstructorListSample(String name) {
}
public MultiConstructorListSample(List<Integer> values) {
}
}
interface DummyInterface {
static String of(Object o) {
return o.toString();
}
}
@SuppressWarnings("unused")
static class DummySampleFactory implements DummyInterface {
static String of(Integer value) {
return value.toString();
}
protected String resolve(String value) {
return value;
}
}
@SuppressWarnings("unused")
static class ExtendedSampleFactory extends DummySampleFactory {
@Override
protected String resolve(String value) {
return super.resolve(value);
}
}
@SuppressWarnings("unused")
static class ConstructorClassArraySample {
ConstructorClassArraySample(Class<?>... classArrayArg) {
}
ConstructorClassArraySample(Executor somethingElse) {
}
}
@SuppressWarnings("unused")
static class MultiConstructorClassArraySample {
MultiConstructorClassArraySample(Class<?>... classArrayArg) {
}
MultiConstructorClassArraySample(String... stringArrayArg) {
}
}
@SuppressWarnings("unused")
static class ClassArrayFactoryMethodSample {
static String of(Class<?>[] classArrayArg) {
return "test";
}
}
@SuppressWarnings("unused")
static class ClassArrayFactoryMethodSampleWithAnotherFactoryMethod {
static String of(Class<?>[] classArrayArg) {
return "test";
}
static String of(String[] classArrayArg) {
return "test";
}
}
@SuppressWarnings("unnused")
static class ConstructorPrimitiveFallback {
public ConstructorPrimitiveFallback(boolean useDefaultExecutor) {
}
public ConstructorPrimitiveFallback(Executor executor) {
}
}
static class SampleBeanWithConstructors {
public SampleBeanWithConstructors() {
}
public SampleBeanWithConstructors(String name) {
}
public SampleBeanWithConstructors(Number number, String name) {
}
}
interface FactoryWithOverloadedClassMethodsOnInterface {
static FactoryWithOverloadedClassMethodsOnInterface byAnnotation(
Class<? extends Annotation> annotationType) {
return byAnnotation(annotationType, SearchStrategy.INHERITED_ANNOTATIONS);
}
static FactoryWithOverloadedClassMethodsOnInterface byAnnotation(
Class<? extends Annotation> annotationType,
SearchStrategy searchStrategy) {
return null;
}
}
}
|
package com.zc.pivas.docteradvice.syndatasz.message.resp;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
/**
* soap获取消息类
* <一句话功能简述>
*
* @author cacabin
* @version 1.0
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlRootElement(name = "Envelope", namespace = "http://schemas.xmlsoap.org/soap/envelope/")
public class SoapEnvelope
{
/**
* soap 中 envelope namespace
*/
public static final String NAMESPACE_OF_ENVELOPE = "http://schemas.xmlsoap.org/soap/envelope/";
@XmlElement(name = "Body", namespace = NAMESPACE_OF_ENVELOPE)
private SoapBody body;
public SoapBody getBody()
{
return body;
}
public void setBody(SoapBody body)
{
this.body = body;
}
}
|
package com.z.zz.zzz.utils;
import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Build;
import android.text.TextUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.File;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.List;
public class U {
private static final String TAG = "U";
public static boolean fileExist(String filePath) {
boolean result = false;
File file = new File(filePath);
if (file.exists()) {
result = true;
}
return result;
}
public static String getSystemProperties(String key) {
String value = null;
try {
Class<?> c = Class.forName("android.os.SystemProperties");
Method get = c.getMethod("get", String.class, String.class);
value = (String) get.invoke(c, key, Build.UNKNOWN);
L.v(TAG, "getSystemProperties(" + key + "): " + value);
} catch (Exception e) {
L.e(TAG, "getSystemProperties error: ", e);
}
return value;
}
public static String tempToStr(float temp, int tempSetting) {
if (temp <= 0.0f) {
return "";
}
if (tempSetting == 2) {
return String.format("%.1f°F",
new Object[]{Float.valueOf(((9.0f * temp) + 160.0f) / 5.0f)});
}
return String.format("%.1f°C", new Object[]{Float.valueOf(temp)});
}
public static JSONObject putJsonSafed(JSONObject json, String name, Object value) {
try {
return json.put(name, value);
} catch (JSONException e) {
}
return json;
}
public static <O> O getJsonSafed(JSONObject json, String name) {
try {
if (json.has(name) && !json.isNull(name)) {
return (O) json.get(name);
}
} catch (JSONException e) {
}
return null;
}
public static JSONArray putJsonSafed(JSONArray json, int index, Object value) {
try {
return json.put(index, value);
} catch (JSONException e) {
}
return json;
}
public static <O> O getJsonSafed(JSONArray json, int index) {
try {
return (O) json.get(index);
} catch (JSONException e) {
}
return null;
}
public static String formatJson(Object source) {
StringBuilder builder = new StringBuilder();
builder.append("\n");
builder.append(getSplitter(100));
builder.append("\n");
builder.append(formatJsonBody(source));
builder.append("\n");
builder.append(getSplitter(100));
return builder.toString();
}
private static String getSplitter(int length) {
StringBuilder builder = new StringBuilder();
for (int i = 0; i < length; i++) {
builder.append("-");
}
return builder.toString();
}
private static String formatJsonBody(Object source) {
Object o = getJsonObjFromStr(source);
if (o != null) {
try {
if (o instanceof JSONObject) {
return ((JSONObject) o).toString(2);
} else if (o instanceof JSONArray) {
return ((JSONArray) o).toString(2);
} else {
return source.toString();
}
} catch (JSONException e) {
return source.toString();
}
} else {
return source.toString();
}
}
private static Object getJsonObjFromStr(Object test) {
Object o = null;
try {
o = new JSONObject(test.toString());
} catch (JSONException ex) {
try {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
o = new JSONArray(test);
}
} catch (JSONException ex1) {
return null;
}
}
return o;
}
@SuppressLint("MissingPermission")
public static String getBuildSerial(Context context) {
String serial = Build.UNKNOWN;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {//9.0+
try {
serial = Build.getSerial();
} catch (Throwable th) {
th.printStackTrace();
}
} else if (Build.VERSION.SDK_INT > Build.VERSION_CODES.N) {//8.0+
serial = Build.SERIAL;
} else {//8.0-
serial = getSystemProperties("ro.serialno");
}
return TextUtils.isEmpty(serial) ? Build.UNKNOWN : serial;
}
public static List<String> executeCommand(String[] shellCmd) {
long start = System.currentTimeMillis();
SystemCommandExecutor executor = new SystemCommandExecutor(shellCmd);
try {
int result = executor.executeCommand();
L.v(TAG, "call executeCommand " + Arrays.asList(shellCmd) + ": " + result
+ ", cost: " + (System.currentTimeMillis() - start) + "ms");
} catch (Exception e) {
L.e(TAG, "call SystemCommandExecutor error: ", e);
}
return executor.getStandardOutputStream();
}
/**
* str 原字符串
* strLength 字符串总长
*/
public static String addZeroToNum(String str, int strLength) {
int strLen = str.length();
if (strLen < strLength) {
while (strLen < strLength) {
StringBuffer sb = new StringBuffer();
sb.append("0").append(str);// 左补0
// sb.append(str).append("0");//右补0
str = sb.toString();
strLen = str.length();
}
}
return str;
}
}
|
package com.regentzu.untitledgame.character;
/**
* Created on 12/16/13.
*/
public enum CharacterEquipment {
WEAPON,
ARMOR;
}
|
package com.iks.education.calculator.gui.buttons;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import com.iks.education.calculator.controller.CalculatorController;
@SuppressWarnings("serial")
public class CEButton extends JButton {
public CEButton() {
super();
setText("CE");
addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
CalculatorController.getInstance().cleanInput();
}
});
}
}
|
package prodcloud;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.Test;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.AfterClass;
public class Header {
private WebDriver driver;
private String baseUrl;
@BeforeClass
public void beforeClass() {
driver = new FirefoxDriver();
baseUrl = "http://www.cloudphone.com/";
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
}
@Test
public void C62165() {
driver.get(baseUrl);
driver.findElement(By.cssSelector("img[alt=\"Voxox\"]")).click();
String exp1;
String exp1a;
exp1a = driver.findElement(By.xpath("//*[@id='reset-one']/h5")).getText();
exp1 = driver.getCurrentUrl();
System.out.println("Expected Result: " +exp1a);
System.out.println("Expected Result: " +exp1);
}
@Test
public void C62166() {
driver.get(baseUrl);
driver.findElement(By.linkText("Menu")).click();
driver.findElement(By.linkText("Home")).click();
String exp2;
String exp2a;
exp2a = driver.findElement(By.xpath("//*[@id='reset-one']/h5")).getText();
exp2 = driver.getCurrentUrl();
driver.findElement(By.linkText("Menu")).click();
System.out.println("Expected Result: " + exp2);
System.out.println("Expected Result: " +exp2a);
}
@Test
public void C62167() {
driver.get(baseUrl);
driver.findElement(By.linkText("Menu")).click();
driver.findElement(By.linkText("Features")).click();
String exp3;
String exp2a;
exp2a = driver.findElement(By.xpath("//*[@id='reset-one']/h5")).getText();
exp3 = driver.getCurrentUrl();
System.out.println("Expected Result: " + exp3);
System.out.println("Expected Result: " + exp2a);
}
@Test
public void C62168() {
driver.get(baseUrl);
driver.findElement(By.linkText("Menu")).click();
driver.findElement(By.linkText("Pricing & Signup")).click();
driver.findElement(By.linkText("Get a 30 Day Free Trial")).click();
String exp4;
exp4 = driver.getCurrentUrl();
System.out.println("Expected Result: " + exp4);
}
@Test
public void C62170() {
driver.get(baseUrl);
driver.findElement(By.linkText("Menu")).click();
driver.findElement(By.linkText("Sign in")).click();
String exp6;
String exp6a;
exp6a = driver.findElement(By.xpath("//*[@id='Form-Login']/h2")).getText();
exp6 = driver.getCurrentUrl();
System.out.println("Expected Result: " + exp6);
System.out.println("Expected Result: " + exp6a);
}
@AfterClass
public void afterClass() {
driver.quit();
}
}
|
package com.ascendaz.roster.util;
import org.hibernate.proxy.HibernateProxy;
import org.hibernate.proxy.LazyInitializer;
import org.joda.time.DateTimeZone;
import org.joda.time.LocalDate;
public class Util {
public static final DateTimeZone jodaTzUTC = DateTimeZone.forID("UTC");
public static <T> T deproxy (T obj) {
if (obj == null)
return obj;
if (obj instanceof HibernateProxy) {
// Unwrap Proxy;
// -- loading, if necessary.
HibernateProxy proxy = (HibernateProxy) obj;
LazyInitializer li = proxy.getHibernateLazyInitializer();
return (T) li.getImplementation();
}
return obj;
}
public static boolean isProxy (Object obj) {
if (obj instanceof HibernateProxy)
return true;
return false;
}
// from java.sql.Date to LocalDate:
public static LocalDate dateToLocalDate(java.sql.Date d) {
if(d==null) return null;
return new LocalDate(d.getTime(), jodaTzUTC);
}
// from LocalDate to java.sql.Date:
public static java.sql.Date localdateToDate(LocalDate ld) {
if(ld==null) return null;
return new java.sql.Date(
ld.toDateTimeAtStartOfDay(jodaTzUTC).getMillis());
}
}
|
package com.mingrisoft;
import java.util.LinkedHashMap;
import java.util.Map;
public class CityMap {
/**
* 全国(省,直辖市,自治区)映射集合
*/
public static Map<String,String[]> model=new LinkedHashMap<String, String[]>();
static{
model.put("北京", new String[]{"北京"});
model.put("上海", new String[]{"上海"});
model.put("天津", new String[]{"天津"});
model.put("重庆", new String[]{"重庆"});
model.put("黑龙江", new String[]{"哈尔滨","齐齐哈尔","牡丹江","大庆","伊春","双鸭山","鹤岗","鸡西","佳木斯","七台河","黑河","绥化","大兴安岭"});
model.put("吉林", new String[]{"长春","延边","吉林","白山","白城","四平","松原","辽源","大安","通化"});
model.put("辽宁", new String[]{"沈阳","大连","葫芦岛","旅顺","本溪","抚顺","铁岭","辽阳","营口","阜新","朝阳","锦州","丹东","鞍山"});
model.put("内蒙古", new String[]{"呼和浩特","呼伦贝尔","锡林浩特","包头","赤峰","海拉尔","乌海","鄂尔多斯","通辽"});
model.put("河北", new String[]{"石家庄","唐山","张家口","廊坊","邢台","邯郸","沧州","衡水","承德","保定","秦皇岛"});
model.put("河南", new String[]{"郑州","开封","洛阳","平顶山","焦作","鹤壁","新乡","安阳","濮阳","许昌","漯河","三门峡","南阳","商丘","信阳","周口","驻马店"});
model.put("山东", new String[]{"济南","青岛","淄博","威海","曲阜","临沂","烟台","枣庄","聊城","济宁","菏泽","泰安","日照","东营","德州","滨州","莱芜","潍坊"});
model.put("山西", new String[]{"太原","阳泉","晋城","晋中","临汾","运城","长治","朔州","忻州","大同","吕梁"});
model.put("江苏", new String[]{"南京","苏州","昆山","南通","太仓","吴县","徐州","宜兴","镇江","淮安","常熟","盐城","泰州","无锡","连云港","扬州","常州","宿迁"});
model.put("安徽", new String[]{"合肥","巢湖","蚌埠","安庆","六安","滁州","马鞍山","阜阳","宣城","铜陵","淮北","芜湖","毫州","宿州","淮南","池州"});
model.put("陕西", new String[]{"西安","韩城","安康","汉中","宝鸡","咸阳","榆林","渭南","商洛","铜川","延安"});
model.put("宁夏", new String[]{"银川","固原","中卫","石嘴山","吴忠"});
model.put("甘肃", new String[]{"兰州","白银","庆阳","酒泉","天水","武威","张掖","甘南","临夏","平凉","定西","金昌"});
model.put("青海", new String[]{"西宁","海北","海西","黄南","果洛","玉树","海东","海南"});
model.put("湖北", new String[]{"武汉","宜昌","黄冈","恩施","荆州","神农架","十堰","咸宁","襄樊","孝感","随州","黄石","荆门","鄂州"});
model.put("湖南", new String[]{"长沙","邵阳","常德","郴州","吉首","株洲","娄底","湘潭","益阳","永州","岳阳","衡阳","怀化","韶山","张家界"});
model.put("浙江", new String[]{"杭州","湖州","金华","宁波","丽水","绍兴","雁荡山","衢州","嘉兴","台州","舟山","温州"});
model.put("江西", new String[]{"南昌","萍乡","九江","上饶","抚州","吉安","鹰潭","宜春","新余","景德镇","赣州"});
model.put("福建", new String[]{"福州","厦门","龙岩","南平","宁德","莆田","泉州","三明","漳州"});
model.put("贵州", new String[]{"贵阳","安顺","赤水","遵义","铜仁","六盘水","毕节","凯里","都匀"});
model.put("四川", new String[]{"成都","泸州","内江","凉山","阿坝","巴中","广元","乐山","绵阳","德阳","攀枝花","雅安","宜宾","自贡","甘孜州","达州","资阳","广安","遂宁","眉山","南充"});
model.put("广东", new String[]{"广州","深圳","潮州","韶关","湛江","惠州","清远","东莞","江门","茂名","肇庆","汕尾","河源","揭阳","梅州","中山","德庆","阳江","云浮","珠海","汕头","佛山"});
model.put("广西", new String[]{"南宁","桂林","阳朔","柳州","梧州","玉林","桂平","贺州","钦州","贵港","防城港","百色","北海","河池","来宾","崇左"});
model.put("云南", new String[]{"昆明","保山","楚雄","德宏","红河","临沧","怒江","曲靖","思茅","文山","玉溪","昭通","丽江","大理"});
model.put("海南", new String[]{"海口","三亚","儋州","琼山","通什","文昌"});
model.put("新疆", new String[]{"乌鲁木齐","阿勒泰","阿克苏","昌吉","哈密","和田","喀什","克拉玛依","石河子","塔城","库尔勒","吐鲁番","伊宁"});
}
}
|
package com.minhvu.proandroid.sqlite.database.services;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Environment;
import android.support.v4.content.LocalBroadcastManager;
import android.text.TextUtils;
import android.util.Log;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.database.ChildEventListener;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import com.minhvu.proandroid.sqlite.database.R;
import com.minhvu.proandroid.sqlite.database.Utils.NoteUtils;
import com.minhvu.proandroid.sqlite.database.models.DAO.ImageDAO;
import com.minhvu.proandroid.sqlite.database.models.DAO.LastSyncDAO;
import com.minhvu.proandroid.sqlite.database.models.DAO.NoteDAO;
import com.minhvu.proandroid.sqlite.database.models.entity.Image;
import com.minhvu.proandroid.sqlite.database.models.entity.Note;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import rx.Observable;
/**
* Created by vomin on 1/9/2018.
*/
public class SignInService extends ALongRunningNonStickyBroadcastService {
private String mUser;
private ValueEventListener mValueEventListener;
private StorageReference mStorage;
private DatabaseReference mDb;
private NoteDAO mNoteDAO;
private ImageDAO mImageDAO;
public SignInService() {
super(SignInService.class.getSimpleName());
}
@Override
public void onDestroy() {
/*if(mValueEventListener != null){
mDb.child(getString(R.string.users_list_firebase)).removeEventListener(mValueEventListener);
Intent intent = new Intent(getString(R.string.broadcast_sign_out));
intent.putExtra(getString(R.string.sign_in_flag), "yes");
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
}*/
super.onDestroy();
}
@Override
public void handIntentBroadcast(Intent intentBroadcast) {
mUser = intentBroadcast.getStringExtra(getString(R.string.user_token));
if (TextUtils.isEmpty(mUser)) {
return;
}
mNoteDAO = new NoteDAO(this);
mImageDAO = new ImageDAO(this);
mainHandle();
GetLastSyncFromServer();
}
private void mainHandle() {
mStorage = FirebaseStorage.getInstance().getReference();
mDb = FirebaseDatabase.getInstance().getReference();
DatabaseReference mRef = mDb.child(getString(R.string.users_list_firebase));
mValueEventListener = new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.hasChild(mUser)) {
for (DataSnapshot ds : dataSnapshot.child(mUser).getChildren()) {
handleNote(ds);
}
}
completeTask();
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
};
mRef.addValueEventListener(mValueEventListener);
}
private void completeTask(){
mNoteDAO = null;
mDb.child(getString(R.string.users_list_firebase)).removeEventListener(mValueEventListener);
//active notification to MainFragment
Intent intent = new Intent(getString(R.string.broadcast_sign_out));
intent.putExtra(getString(R.string.sign_in_flag), "yes");
LocalBroadcastManager.getInstance(SignInService.this).sendBroadcast(intent);
//close Sign In Window
Intent closeWindowIntent = new Intent(getString(R.string.close_sign_in_when_complete_task));
LocalBroadcastManager.getInstance(this).sendBroadcast(closeWindowIntent);
}
private void GetLastSyncFromServer(){
final DatabaseReference mRef = mDb.child(getString(R.string.users_list_firebase));
mRef.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(dataSnapshot.hasChild(mUser)){
if (dataSnapshot.child(mUser).hasChild(getString(R.string.last_update_ones_account))){
Long time = dataSnapshot.child(mUser)
.child(getString(R.string.last_update_ones_account))
.getValue(Long.class);
LastSyncDAO dao = new LastSyncDAO(SignInService.this);
dao.InsertLastSyncTime(time);
}
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
//[start handle a note]
private void handleNote(DataSnapshot mDataSnapshot) {
if (!mDataSnapshot.hasChild(getString(R.string.note_directory))) {
return;
}
String mKey = mDataSnapshot.getKey();
DataSnapshot dataSnapshot = mDataSnapshot.child(getString(R.string.note_directory));
Note mNote = dataSnapshot.getValue(Note.class);
if (!mNoteDAO.isSyncChecksExist(mKey)) {
mNote.setKeySync(mKey);
long noteID = mNoteDAO.insertNote(mNote);
handleDocument(mDataSnapshot, noteID);
}
}
//[end note]
//[start handle a document]
private void handleDocument(DataSnapshot mDataSnapshot, long noteID) {
if (!mDataSnapshot.hasChild(getString(R.string.document_directory))) {
return;
}
List<String> imageList = new ArrayList<>();
for (DataSnapshot ds : mDataSnapshot.child(getString(R.string.document_directory)).getChildren()) {
imageList.add(ds.getValue(String.class));
}
/*new Thread() {
@Override
public void run() {
super.run();
getImageFromServer(imageList, noteID);
}
}.start();*/
getImageFromServer(imageList, noteID);
}
private void getImageFromServer(List<String> imageList, final long noteID) {
if (imageList == null || imageList.size() == 0)
return;
StorageReference ref = mStorage.child(mUser);
for (String path : imageList) {
ref.child(path).getDownloadUrl().addOnSuccessListener(uri -> {
saveImage(uri, path, noteID);
});
/*.getFile(file)
.addOnSuccessListener(taskSnapshot -> {
insertImageIntoDatabase("file:" + file.getAbsolutePath(), noteID);
})
.addOnFailureListener(e -> {
});*/
}
}
private Bitmap imageStream(Uri uri) {
HttpURLConnection connection = null;
final String methodGET = "GET";
try {
URL url = new URL(uri.toString());
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod(methodGET);
connection.setDoInput(true);
int responseCode = connection.getResponseCode();
if (responseCode != HttpURLConnection.HTTP_OK) {
return null;
}
connection.connect();
InputStream is = new BufferedInputStream(connection.getInputStream());
return BitmapFactory.decodeStream(is);
} catch (Exception e) {
String error = e.getMessage();
return null;
}
}
private void saveImage(Uri uri, final String fileName, final long noteID) {
new AsyncTask<Uri, Void, String>() {
@Override
protected String doInBackground(Uri... uris) {
if (uris.length == 0)
return null;
Bitmap bitmap = imageStream(uris[0]);
if (bitmap == null)
return null;
File file = getOutputMediaFile(fileName);
try {
FileOutputStream fos = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
return file.getPath();
} catch (FileNotFoundException e) {
return null;
}
}
@Override
protected void onPostExecute(String path) {
super.onPostExecute(path);
if (TextUtils.isEmpty(path)) return;
insertImageIntoDatabase("file:" + path, noteID);
}
}.execute(uri);
}
private void insertImageIntoDatabase(String path, long noteID) {
mImageDAO.insertItem(new Image(path, 1, noteID));
}
private File getOutputMediaFile(String fileName) {
File root = new File(getExternalFilesDir(Environment.DIRECTORY_PICTURES), getString(R.string.my_storage));
if(!root.exists()){
root.mkdirs();
}
return new File(root.getPath() + File.separator + fileName);
}
//[end document]
}
|
package com.wizinno.shuhao.user.domain;
import com.wizinno.shuhao.condition.LogCondition;
import com.wizinno.shuhao.user.domain.model.Log;
import java.util.List;
public interface LogMapper {
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table log
*
* @mbggenerated Wed Nov 08 14:24:12 CST 2017
*/
int deleteByPrimaryKey(Long id);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table log
*
* @mbggenerated Wed Nov 08 14:24:12 CST 2017
*/
int insert(Log record);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table log
*
* @mbggenerated Wed Nov 08 14:24:12 CST 2017
*/
Log selectByPrimaryKey(Long id);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table log
*
* @mbggenerated Wed Nov 08 14:24:12 CST 2017
*/
List<Log> selectAll(LogCondition logCondition);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table log
*
* @mbggenerated Wed Nov 08 14:24:12 CST 2017
*/
int updateByPrimaryKey(Log record);
List<Log> queryByCondition(LogCondition logCondition);
} |
package planetsw;
import java.util.Scanner;
public class Brandcontroller {
public Brand AddBrand(PlanetDB s )
{
Brand p=new Brand();
System.out.println("Enter the name of the Brand: ");
Scanner in=new Scanner(System.in);
p.setName(in.nextLine());
System.out.println("Enter the Owner ID: ");
Scanner inn=new Scanner(System.in);
p.setOwnerID(inn.nextInt());
boolean f=true;
for (int i=0;i< s.registered.size(); i++)
{
if (s.registered.get(i).getType()=="owner" )
{
Owner o= (Owner)s.registered.get(i);
if (o.getID()== p.getOwnerID())
{
o.getArrayofbrand().add(p);
f=false;
s.brands.add(p);
break;
}
}
}
if (f==true)
{
System.out.println("Wrong ID!!");
}
return null;
}
}
|
package com.dengzhili.bookStore.init;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Random;
import ch.qos.logback.classic.net.SyslogAppender;
//随机初始化书排序数据(热门,推荐,最新)
public class BookSortInit {
public static void main(String[] args) throws Exception {
Class.forName("com.mysql.jdbc.Driver");
Connection connect = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/python","root","123456");
String sql="update book set hot=?,vote=?,new=? where book_id=?";
PreparedStatement pstm=connect.prepareStatement(sql);
//生产随机数
Random random=new Random();
//获得最小ID值
int min=getMinId(connect);
//获得最大ID值
int max=getMaxId(connect);
//(ID自增) 可循环插入
int randomNew=0;
int hot=0;
int vote=0;
long startTime=System.currentTimeMillis();
for(;min<=max;min++) {
randomNew=random.nextInt(max);
hot=random.nextInt(max);
vote=random.nextInt(max);
pstm.setInt(1, hot);
pstm.setInt(2, vote);
pstm.setInt(3, randomNew);
pstm.setInt(4, min);
pstm.addBatch();
}
pstm.executeBatch();
long endTime=System.currentTimeMillis();
System.out.println("cost Time:"+(endTime-startTime));
}
public static Integer getMinId(Connection conn) {
String sql="select min(book_id) from book";
try {
Statement stmt=conn.createStatement();
ResultSet rs=stmt.executeQuery(sql);
if(rs.next())
{
return rs.getInt(1);
}else {
return -1;
}
} catch (SQLException e) {
e.printStackTrace();
return -1;
}
}
public static Integer getMaxId(Connection conn) {
String sql="select max(book_id) from book";
try {
Statement stmt=conn.createStatement();
ResultSet rs=stmt.executeQuery(sql);
if(rs.next())
{
return rs.getInt(1);
}else {
return -1;
}
} catch (SQLException e) {
e.printStackTrace();
return -1;
}
}
}
|
public class TestC {
static void overloadedFunc(Object obj) {
System.out.println("3");
}
static void overloadedFunc(Two b) {
System.out.println("2");
}
static void overloadedFunc(One a) {
System.out.println("1");
}
public static class One {
}
public static class Two extends One {
}
public static class Three extends Two{
}
public static void main(String[] args) {
Three a = new Three();
overloadedFunc(a);
}
}
|
import java.applet.Applet;
import java.awt.Graphics;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.Arrays;
import java.util.Random;
class Box
{
private int properties;
public Box()
{
properties = 0;
}
public int getProperties()
{
return properties;
}
public void setProperties(int properties)
{
if (!((properties >= 0 && properties <= 15) || properties == 31))
throw new IllegalArgumentException("propety value not valid!");
else
this.properties = properties;
}
public char getTopBit()
{
String s = Integer.toBinaryString(properties);
int l = s.length();
return (s.charAt(l - 1));
}
public char getBottomBit()
{
String s = Integer.toBinaryString(properties);
int l = s.length() - 3;
if (l < 0)
return '0';
else
return s.charAt(l);
}
public char getLeftBit()
{
String s = Integer.toBinaryString(properties);
int l = s.length() - 4;
if (l < 0)
return '0';
else
return s.charAt(l);
}
public char getRightBit()
{
String s = Integer.toBinaryString(properties);
int l = s.length() - 2;
if (l < 0)
return '0';
else
return s.charAt(l);
}
public char allSidesSet()
{
if (getLeftBit() == '1' && getRightBit() == '1'
&& getBottomBit() == '1' && getTopBit() == '1')
return '1';
else
return '0';
}
public char getPlayerBit()
{
String s = Integer.toBinaryString(properties);
int l = s.length() - 5;
if (l < 0)
return '0';
else
return s.charAt(l);
}
public int getSidesSet()
{
int c = getTopBit() + getBottomBit() + getLeftBit() + getRightBit() - 4
* '0';
return c;
}
public void SetPlayerOwned()
{
StackTraceElement[] stacktrace = Thread.currentThread().getStackTrace();
StackTraceElement e = stacktrace[3];
String methodName = e.getMethodName();
// System.out.println(methodName);
if (allSidesSet() == '1' && methodName != "BotThink")
{
setProperties(properties + 16);
}
}
}
public class DotsnBoxes extends Applet implements MouseListener
{
public static final int GRID = 6;
public static final int TOP = 1;
public static final int RIGHT = 2;
public static final int BOTTOM = 4;
public static final int LEFT = 8;
public static final int PLAYER_OWNED = 16;
Box[][] b = new Box[GRID][GRID];
@Override
public void init()
{
for (int i = 0; i < GRID; i++)
for (int j = 0; j < GRID; j++)
b[i][j] = new Box();
addMouseListener(this);
}
@Override
public void paint(Graphics g)
{
this.setSize(80 * GRID, 80 * GRID);
int player_points = 0;
int bot_points = 0;
for (int i = 0; i <= GRID; i++)
{
for (int j = 0; j <= GRID; j++)
{
g.fillRect(i * 50 + 5, j * 50 + 5, 5, 5);
if (i != GRID && j != GRID)
{
// System.out.println(i + ", " + j + " : "
// + Integer.toBinaryString(b[i][j].getProperties())
// + " Sides : " + b[i][j].getSidesSet());
if (b[i][j].getTopBit() == '1')
g.drawLine(i * 50 + 5, j * 50 + 5, i * 50 + 55,
j * 50 + 5);
if (j == GRID - 1 && b[i][j].getBottomBit() == '1')
g.drawLine(i * 50 + 5, j * 50 + 55, i * 50 + 55,
j * 50 + 55);
if (b[i][j].getLeftBit() == '1')
g.drawLine(i * 50 + 5, j * 50 + 5, i * 50 + 5,
j * 50 + 55);
if (i == GRID - 1 && b[i][j].getRightBit() == '1')
g.drawLine(i * 50 + 55, j * 50 + 5, i * 50 + 55,
j * 50 + 55);
if (b[i][j].getPlayerBit() == '1')
{
player_points++;
g.drawString("P", i * 50 + 25, j * 50 + 25);
}
if (b[i][j].getPlayerBit() == '0'
&& b[i][j].allSidesSet() == '1')
{
bot_points++;
g.drawString("B", i * 50 + 25, j * 50 + 25);
}
}
}
}
g.drawString("Player : " + player_points,10 ,70*GRID );
g.drawString("Bot : " + bot_points,10 ,70*GRID -20 );
}
@Override
public void mouseClicked(MouseEvent me)
{
int x = me.getX();
int y = me.getY();
// System.out.println("Pos1 : " + x + ", " + y);
if (y > 40)
y = y + 10;
if (x > 40)
x = x + 10;
int xbox = (x - 5) / 50;
int ybox = (y - 5) / 50;
x = (x - 5) % 50;
y = (y - 5) % 50;
int ret = 0;
ret = gameplay(x, y, xbox, ybox);
repaint();
if (ret == 1)
{
BotPlay();
repaint();
}
}
@Override
public void mouseEntered(MouseEvent arg0)
{
// TODO Auto-generated method stub
}
@Override
public void mouseExited(MouseEvent arg0)
{
// TODO Auto-generated method stub
}
@Override
public void mousePressed(MouseEvent arg0)
{
// TODO Auto-generated method stub
}
@Override
public void mouseReleased(MouseEvent arg0)
{
// TODO Auto-generated method stub
}
public int gameplay(int x, int y, int xbox, int ybox)
{
// System.out.println("Pos2 : " + x + ", " + y);
// System.out.println("Box : " + xbox + ", " + ybox);
if (xbox <= GRID && ybox <= GRID)
{
if (y >= 0 && y <= 20)
// horizontal line
{
if (ybox == 0 && b[xbox][ybox].getTopBit() != '1')
{
b[xbox][ybox].setProperties(b[xbox][ybox].getProperties()
+ TOP);
b[xbox][ybox].SetPlayerOwned();
return 1;
}
else if (ybox == GRID
&& b[xbox][ybox - 1].getBottomBit() != '1')
{
b[xbox][ybox - 1].setProperties(b[xbox][ybox - 1]
.getProperties() + BOTTOM);
b[xbox][ybox - 1].SetPlayerOwned();
return 1;
}
else if (ybox > 0 && ybox < GRID)
{
if (b[xbox][ybox].getTopBit() != '1'
&& b[xbox][ybox - 1].getBottomBit() != '1')
{
b[xbox][ybox].setProperties(b[xbox][ybox]
.getProperties() + TOP);
b[xbox][ybox - 1].setProperties(b[xbox][ybox - 1]
.getProperties() + BOTTOM);
b[xbox][ybox - 1].SetPlayerOwned();
b[xbox][ybox].SetPlayerOwned();
return 1;
}
else
return 0;
}
else
return 0;
}
else if (x >= 0 && x <= 20)
// vertical line
{
if (xbox == 0 && b[xbox][ybox].getLeftBit() != '1')
{
b[xbox][ybox].setProperties(b[xbox][ybox].getProperties()
+ LEFT);
b[xbox][ybox].SetPlayerOwned();
return 1;
}
else if (xbox == GRID && b[xbox - 1][ybox].getRightBit() != '1')
{
b[xbox - 1][ybox].setProperties(b[xbox - 1][ybox]
.getProperties() + RIGHT);
b[xbox - 1][ybox].SetPlayerOwned();
return 1;
}
else if (xbox > 0 && xbox < GRID)
{
if (b[xbox][ybox].getLeftBit() != '1'
&& b[xbox - 1][ybox].getRightBit() != '1')
{
b[xbox][ybox].setProperties(b[xbox][ybox]
.getProperties() + LEFT);
b[xbox - 1][ybox].setProperties(b[xbox - 1][ybox]
.getProperties() + RIGHT);
b[xbox - 1][ybox].SetPlayerOwned();
b[xbox][ybox].SetPlayerOwned();
return 1;
}
else
return 0;
}
else
return 0;
}
else
return 0;
}
else
return 0;
}
public void BotPlay()
{
int ret = 0;
int sides[] = { 3, 0, 1, 2 };
for (int i = 0; i < 4; i++)
if (ret == 1)
return;
else
ret = BotThink(sides[i]);
}
public static int[] generateRandomNumber(int[][] availableCollection)
{
Random rand = new Random();
return availableCollection[rand.nextInt(availableCollection.length)];
}
int BotThink(int sides)
{
for (int i = 0; i < GRID; i++)
{
for (int j = 0; j < GRID; j++)
{
if (b[i][j].allSidesSet() != '1')
{
int[] left = { b[i][j].getLeftBit(), 8, 33 };
int[] right = { b[i][j].getRightBit(), 8, 33 };
int[] top = { b[i][j].getTopBit(), 47, 3 };
int[] bottom = { b[i][j].getBottomBit(), 47, 3 };
if (b[i][j].getSidesSet() == sides)
{
int[][] collection = { top, bottom, left, right };
int[] random;
do
{
random = generateRandomNumber(collection);
// System.out.println(random[0] - '0' + " : " + sides);
}
while (random[0] == '1');
if (Arrays.equals(random, left)
|| Arrays.equals(random, top))
gameplay(random[1], random[2], i, j);
else if (Arrays.equals(random, right))
gameplay(random[1], random[2], i + 1, j);
else if (Arrays.equals(random, bottom))
gameplay(random[1], random[2], i, j + 1);
return 1;
}
}
}
}
return 0;
}
}
|
package com.example.route;
import androidx.appcompat.app.AppCompatActivity;
import android.animation.ObjectAnimator;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import com.bumptech.glide.Glide;
import java.util.Timer;
import java.util.TimerTask;
import butterknife.BindView;
import butterknife.ButterKnife;
public class Route extends AppCompatActivity {
MediaPlayer sonDemarrage;
MediaPlayer sonPointMort;
MediaPlayer sonAcceleration;
MediaPlayer sonAccelerationTurbo;
Timer timer = new Timer();
private int newPosition = 0;
private boolean voitureSon = true;
@BindView(R.id.retour)
public ImageButton retour;
@BindView(R.id.ligne1)
public View ligne1;
@BindView(R.id.ligne2)
public View ligne2;
@BindView(R.id.ligne3)
public View ligne3;
@BindView(R.id.ligne4)
public View ligne4;
@BindView(R.id.ligne5)
public View ligne5;
@BindView(R.id.ligne6)
public View ligne6;
@BindView(R.id.boite_de_vitesse)
public ImageView boiteDeVitesse;
@BindView(R.id.turbo)
public Button turbo;
@BindView(R.id.superTurbo)
public Button superTurbo;
@BindView(R.id.voiture)
public ImageButton voiture;
@BindView(R.id.feu_turbo)
public ImageView feuTurbo;
@BindView(R.id.vitesse_sup)
public ImageButton vitesseSup;
@BindView(R.id.vitesse_inf)
public ImageButton vitesseInf;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.route);
ButterKnife.bind(this);
ligne1.setY(0);
ligne2.setY(800);
ligne3.setY(1600);
ligne4.setY(2400);
ligne5.setY(3200);
ligne6.setY(4000);
sonDemarrage = MediaPlayer.create(Route.this, R.raw.demarrage);
sonPointMort = MediaPlayer.create(Route.this,R.raw.ferrari_point_mort);
sonAcceleration = MediaPlayer.create(Route.this, R.raw.deppart);
sonAccelerationTurbo = MediaPlayer.create(Route.this, R.raw.deppart2);
sonDemarrage.start();
sonPointMort.start();
sonPointMort.setLooping(true);
this.elementsGraphiques();
}
@Override
protected void onResume() {
timer.scheduleAtFixedRate( new TimerTask() {
@Override
public void run() {
ligne1.setY(Lignes.Ligne(ligne1.getY(), newPosition));
ligne2.setY(Lignes.Ligne(ligne2.getY(), newPosition));
ligne3.setY(Lignes.Ligne(ligne3.getY(), newPosition));
ligne4.setY(Lignes.Ligne(ligne4.getY(), newPosition));
ligne5.setY(Lignes.Ligne(ligne5.getY(), newPosition));
ligne6.setY(Lignes.Ligne(ligne6.getY(), newPosition));
}
}, 0, 1);
super.onResume();
}
@Override
protected void onPause() {
timer.cancel();
sonDemarrage.stop();
sonPointMort.stop();
sonAcceleration.stop();
sonAccelerationTurbo.stop();
super.onPause();
}
// ----------------------- Les éléments graphiques -------------------------------
private void elementsGraphiques (){
boiteDeVitesse.setOnClickListener(v -> {
if ( vitesseSup.getVisibility() == View.VISIBLE){
vitesseSup.setVisibility(View.INVISIBLE);
vitesseInf.setVisibility(View.INVISIBLE);
}
else {
vitesseSup.setVisibility(View.VISIBLE);
vitesseInf.setVisibility(View.VISIBLE);
}
});
vitesseSup.setOnClickListener(v -> {
departVoiture(1);
if( newPosition < 6){
newPosition++;
}
boiteDeVitesseImage();
});
vitesseInf.setOnClickListener(v -> {
departVoiture(1);
if( newPosition > -2){
newPosition--;
}
boiteDeVitesseImage();
});
vitesseSup.setOnLongClickListener(v -> {
departVoiture(2);
while (newPosition < 6){
newPosition++;
}
sonPointMort.pause();
boiteDeVitesseImage();
return false;
});
vitesseInf.setOnLongClickListener(v -> {
departVoiture(1);
while (newPosition != 0){
if( newPosition < 0 ){
newPosition++;
}
else{
newPosition--;
}
}
boiteDeVitesseImage();
return false;
});
turbo.setOnClickListener(v -> {
departVoiture(2);
newPosition = 8;
Glide.with(boiteDeVitesse)
.load(R.drawable.vitesse_turbo)
.into(boiteDeVitesse);
});
superTurbo.setOnClickListener(v -> {
departVoiture(2);
newPosition = 10;
Glide.with(boiteDeVitesse)
.load(R.drawable.vitesse_super_turbo)
.into(boiteDeVitesse);
});
voiture.setOnClickListener(v -> departVoiture(1) );
retour.setOnClickListener(v -> finish());
}
// ----------------------- Image de la boite de vitesse -------------------------------
private void boiteDeVitesseImage (){
if ( newPosition > 6){
newPosition = 6;
}
switch (newPosition)
{
case -1:
Glide.with(boiteDeVitesse)
.load(R.drawable.vitesse_arriere)
.into(boiteDeVitesse);
break;
case 0:
Glide.with(boiteDeVitesse)
.load(R.drawable.vitesse_nul)
.into(boiteDeVitesse);
break;
case 1:
Glide.with(boiteDeVitesse)
.load(R.drawable.vitesse1)
.into(boiteDeVitesse);
break;
case 2:
Glide.with(boiteDeVitesse)
.load(R.drawable.vitesse2)
.into(boiteDeVitesse);
break;
case 3:
Glide.with(boiteDeVitesse)
.load(R.drawable.vitesse3)
.into(boiteDeVitesse);
break;
case 4:
Glide.with(boiteDeVitesse)
.load(R.drawable.vitesse4)
.into(boiteDeVitesse);
break;
case 5:
Glide.with(boiteDeVitesse)
.load(R.drawable.vitesse5)
.into(boiteDeVitesse);
break;
case 6 :
Glide.with(boiteDeVitesse)
.load(R.drawable.vitesse6)
.into(boiteDeVitesse);
break;
}
}
private void departVoiture (int numero){
if ( voitureSon ){
sonPointMort.pause();
if( numero == 1){
sonAcceleration.start();
ObjectAnimator.ofFloat(voiture,"translationY", 0, -2000).setDuration(3000).start();
}
else if ( numero == 2){
sonAccelerationTurbo.start();
ObjectAnimator.ofFloat(voiture,"translationY", 0, 2000,-2000).setDuration(5000).start();
}
voitureSon = false;
}
}
} |
package org.juxtasoftware.diff;
import eu.interedition.text.Range;
import eu.interedition.text.Text;
/**
* An entity to be collated against another of its kind.
* <p/>
* Defines a minimal contract whereby a comparand is comprised of some text and the (sub-)range of its characters
* to be compared.
*
* @see DiffCollator#collate(DiffCollatorConfiguration, Comparand, Comparand)
* @author <a href="http://gregor.middell.net/" title="Homepage">Gregor Middell</a>
*/
public interface Comparand {
/**
* Text to be collated.
* <p/>
* The collator accesses the content of the text by using it as a handle against a {@link TokenSource token source}.
*
* @return the text of the comparand to be collated
*/
Text getText();
/**
* Specifies the range of characters contained in the text, which the collator will include in the comparison.
* <p/>
* This may be a fragment of the whole textual content or its entirety from <code>0</code> to the
* {@link eu.interedition.text.Text#getLength() text's length}.
*
* @return the text range of the comparand to be collated
*/
Range getTextRange();
}
|
package edu.mit.cci.wikipedia.articlenetwork;
public class Result {
private String data;
private int count;
private String nextId;
private boolean archive;
public Result() {
data = new String();
count = 0;
nextId = "0";
archive = false;
}
public void setResult(String _data) {
data = _data;
}
public void append(String _data) {
data += _data;
count++;
}
public String getResult() {
return data;
}
public int getCount() {
return count;
}
public void clear() {
data = "";
count = 0;
nextId = "0";
archive = false;
}
public void setNextId(String _nextId) {
nextId = _nextId;
}
public String getNextId() {
return nextId;
}
public boolean hasNextId() {
if (nextId.equals("0"))
return false;
else
return true;
}
public boolean getArchive() {
return archive;
}
public void setArchive(boolean flag) {
archive = flag;
}
}
|
package racingcar.domain;
import org.junit.Test;
import racingcar.random.CarMoveThresholdGenerator;
import racingcar.random.IntMoreThanCarMoveThresholdGenerator;
import racingcar.random.RandomIntGenerator;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import static org.assertj.core.api.Assertions.assertThat;
public class RacingCarGroupTest {
private List<String> carNames = Arrays.asList("pobi", "crong", "honux");
@Test
public void 항상_전진하는_자동차_그룹() {
// given
RandomIntGenerator randomIntGenerator = new IntMoreThanCarMoveThresholdGenerator();
List<Car> cars = carNames.stream()
.map(Car::new)
.collect(Collectors.toList());
RacingCarGroup racingCarGroup = new RacingCarGroup(cars, randomIntGenerator);
// when
racingCarGroup.go();
// then
List<Car> carsOfGroup = racingCarGroup.getCars();
carsOfGroup.forEach(car ->
assertThat(car.getMovedDistance()).isEqualTo(1)
);
}
@Test
public void 전진하지_않는_자동차_그룹() {
// given
RandomIntGenerator randomIntGenerator = new CarMoveThresholdGenerator();
List<Car> cars = carNames.stream()
.map(Car::new)
.collect(Collectors.toList());
RacingCarGroup racingCarGroup = new RacingCarGroup(cars, randomIntGenerator);
// when
racingCarGroup.go();
// then
List<Car> carsOfGroup = racingCarGroup.getCars();
carsOfGroup.forEach(car ->
assertThat(car.getMovedDistance()).isEqualTo(0)
);
}
@Test
public void 초기화() {
// given
List<Car> cars = carNames.stream()
.map(name -> new Car(name, 3))
.collect(Collectors.toList());
RacingCarGroup racingCarGroup = new RacingCarGroup(cars);
// when
racingCarGroup.initialize();
// then
racingCarGroup.getCars().forEach(car ->
assertThat(car.getMovedDistance()).isEqualTo(0)
);
}
}
|
package com.company.screen;
import com.company.Main;
import com.company.graphics.Sprite;
import java.awt.*;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.awt.image.BufferStrategy;
/**
* Created by Ilya Malinovskiy on 26.04.2016.
*/
public class GeneralMenu extends Canvas implements Runnable,Scene, MouseListener, MouseMotionListener {
public static boolean running = false;
private Sprite[] button = new Sprite[7];
public static boolean isStartButton=false;
public static boolean isScoreButton=false;
public static boolean isExitButton=false;
private Sprite background;
Thread thread;
public GeneralMenu() {
background= new Sprite("menu.jpg");
for (int i=1;i<7;i++)
button[i]=new Sprite("button"+i+".png");
}
@Override
public void run() {
Display.setMouseListener(this,this);
while (running) {
render(Display.bs);
}
}
@Override
public synchronized void start() {
running=true;
thread=new Thread(this);
thread.start();
}
@Override
public synchronized void stop() {
running=false;
thread.stop();
}
@Override
public void render(BufferStrategy bs) {
Graphics g = bs.getDrawGraphics();
background.drawImage(g,0,0);
drawButton(g);
g.dispose();
bs.show();
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
@Override
public void update(long delta){
}
public void startGame(){
Game game = new Game();
game.start();
Display.delMouseListener(this,this);
stop();
}
private void drawButton(Graphics g){
if(!isStartButton)
button[1].drawImage(g,96,90);
else
button[4].drawImage(g,96,90);
if(!isScoreButton)
button[2].drawImage(g,96,224);
else
button[5].drawImage(g,96,224);
if(!isExitButton)
button[3].drawImage(g,96,367);
else
button[6].drawImage(g,96,367);
}
@Override
public void mouseClicked(MouseEvent e) {
if ((e.getX() >= 96 && e.getX() <= 96 + button[1].getwidth()) && (e.getY() >= 90 && e.getY() <= 90 + button[1].getheight()))
Main.menu.startGame();
if ((e.getX() >= 96 && e.getX() <= 96 + button[3].getwidth()) && (e.getY() >= 367 && e.getY() <= 367 + button[3].getheight()))
System.exit(0);
}
@Override
public void mouseMoved(MouseEvent e) {
if ((e.getX() >= 96 && e.getX() <= 96 + button[1].getwidth()) && (e.getY() >= 90 && e.getY() <= 90 + button[1].getheight()))
isStartButton=true;
else
isStartButton=false;
if ((e.getX() >= 96 && e.getX() <= 96 + button[2].getwidth()) && (e.getY() >= 224 && e.getY() <= 224 + button[2].getheight()))
isScoreButton=true;
else
isScoreButton=false;
if ((e.getX() >= 96 && e.getX() <= 96 + button[3].getwidth()) && (e.getY() >= 367 && e.getY() <= 367 + button[3].getheight()))
isExitButton=true;
else
isExitButton=false;
}
@Override
public void mousePressed(MouseEvent e) {
}
@Override
public void mouseReleased(MouseEvent e) {
}
@Override
public void mouseEntered(MouseEvent e) {
}
@Override
public void mouseExited(MouseEvent e) {
}
@Override
public void mouseDragged(MouseEvent e) {
}
}
|
package control.servicos;
import java.io.File;
public class DeletaDat {
public static void deletaDat(String tipoUsuario){
if(tipoUsuario.equals("root")) {
new File("arquivos\\" + tipoUsuario + ".dat").delete();
new File("arquivos\\listas\\lista_alunos.dat").delete();
new File("arquivos\\listas\\lista_prof.dat").delete();
new File("arquivos\\listas\\lista_turmas.dat").delete();
new File("arquivos\\listas\\lista_matricul_aluno.dat").delete();
new File("arquivos\\listas\\lista_matricul_prof.dat").delete();
}else if(tipoUsuario.equals("prof")){
new File("arquivos\\" + tipoUsuario + ".dat").delete();
new File("arquivos\\listas\\lista_prof.dat").delete();
new File("arquivos\\listas\\lista_matricul_aluno.dat").delete();
new File("arquivos\\listas\\lista_matricul_prof.dat").delete();
}else {
new File("arquivos\\" + tipoUsuario + ".dat").delete();
new File("arquivos\\listas\\lista_matricul_aluno.dat").delete();
new File("arquivos\\listas\\lista_matricul_prof.dat").delete();
}
}
public static void deletaDatOnExit(){
new File("arquivos\\root.dat").deleteOnExit();
new File("arquivos\\prof.dat").deleteOnExit();
new File("arquivos\\aluno.dat").deleteOnExit();
new File("arquivos\\listas\\lista_alunos.dat").deleteOnExit();
new File("arquivos\\listas\\lista_prof.dat").deleteOnExit();
new File("arquivos\\listas\\lista_turmas.dat").deleteOnExit();
new File("arquivos\\listas\\lista_matricul_aluno.dat").deleteOnExit();
new File("arquivos\\listas\\lista_matricul_prof.dat").deleteOnExit();
}
}
|
package com.epam.TrafficLights;
class TrafficLights {
String changeLight(int trafficTime) {
if (trafficTime < 0) {
return "Invalid number";
}
if (trafficTime >= 10) {
trafficTime = trafficTime % 10;
}
if (trafficTime <= 2) {
return "red";
} else {
if (trafficTime <= 5) {
return "yellow";
} else {
return "green";
}
}
}
} |
package org.bots.sources;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.bots.model.datebase.Movie;
import org.bots.model.datebase.MovieFile;
import org.bots.model.items.MovieSearchResponse;
import org.bots.model.sources.FilmixDataResponse;
import org.bots.model.sources.FilmixFilesMessage;
import org.bots.model.sources.FilmixPlaylist;
import org.bots.model.sources.FilmixSearchResponse;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import java.io.IOException;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import static org.bots.common.Constants.FILMIX_SUCCESS;
@Component
@Slf4j
public class FilmixSource implements MovieSources {
private static final String SOURCE = "filmix";
private static final String PLAYLIST_TRUE = "yes";
private static final Pattern p = Pattern.compile(".+(\\[.*?]).*");
private ObjectMapper mapper = new ObjectMapper();
@Autowired
private RestTemplate restTemplate;
@Value("${sources.filmix.search2}")
private String searchUrl;
@Value("${sources.filmix.data}")
private String dataUrl;
@Value("${sources.filmix.info}")
private String infoUrl;
private static String decoder(String data)
{
String[] a = new String[] {"0", "1", "2", "3", "4", "5", "6", "7", "=", "B", "D", "H", "I", "J", "L", "M", "N", "U", "V", "Z", "c", "f", "i", "k", "n", "p"};
String[] b = new String[] {"d", "9", "b", "e", "R", "X", "8", "T", "r", "Y", "G", "W", "s", "u", "Q", "y", "a", "w", "o", "g", "z", "v", "m", "l", "x", "t"};
for (int i=0; i < a.length; i++)
{
data = data.replace(b[i], "__");
data = data.replace(a[i], b[i]);
data = data.replace("__", a[i]);
}
return new String(Base64.getDecoder().decode(data));
}
public Movie getMovieById(Integer id) {
String token = null;
Movie movie = getMovie(id, token);
List<MovieFile> movieFiles = fillMovieFiles(movie, "60kl9voiena7uqsog0gpel8l55");
movie.setMovieFiles( movieFiles);
return movie;
}
private Movie getMovie(Integer id, String token) {
Movie resultMovie = new Movie();
resultMovie.setId(id);
try {
Document doc = Jsoup.connect(String.format(infoUrl, id)).get();
Elements content = doc.getElementsByClass("titles-left");
Element element = content.get(0);
Elements href = element.select(" div > a");
String infoLink = href.get(0).attr("href");
doc = Jsoup.connect(infoLink).get();
Element elementInfo = doc.getElementById("dle-content");
Elements imgTag = elementInfo.select("article > div > span > a");
resultMovie.setPoster(imgTag.attr("href"));
Elements name = elementInfo.select("div > div > h1.name");
resultMovie.setTitle(name.get(0).childNode(0).outerHtml());
Elements originName = elementInfo.select("div > div > div.origin-name");
resultMovie.setOriginalTitle(originName.get(0).childNode(0).outerHtml());
Elements directors = doc.select("div.directors > span > span > a > span[itemprop=\"name\"]");
resultMovie.setDirectors(directors.stream().map(elem -> elem.childNode(0).outerHtml()).collect(Collectors.toList()));
Elements actors = doc.select("div.actors > span > span > a > span[itemprop=\"name\"]");
resultMovie.setCasts(actors.stream().map(elem -> elem.childNode(0).outerHtml()).collect(Collectors.toList()));
Elements category = doc.select("div.category > span > span > a[itemprop=\"genre\"]");
resultMovie.setCategories(category.stream().map(elem -> elem.childNode(0).outerHtml()).collect(Collectors.toList()));
Elements year = doc.select("div.year > span > a[itemprop=\"copyrightYear\"]");
resultMovie.setDate(year.stream().map(elem -> elem.childNode(0).outerHtml()).reduce((s, s2) -> s + " - " + s2).orElse(""));
Elements ratio = doc.select("div > div > footer > span.imdb > p");
resultMovie.setRatio(ratio.get(0).childNode(0).outerHtml());
} catch (IOException e) {
log.error("Error parsing movie description", e);
}
return resultMovie;
}
private List<MovieFile> fillMovieFiles(Movie movie, String filmixToken) {
MultiValueMap<String, String> requestParams = new LinkedMultiValueMap<>();
requestParams.add("post_id", String.valueOf(movie.getId()));
Map<String, String> headers = new HashMap<>();
headers.put("Cookie", "FILMIXNET=" + filmixToken);
FilmixDataResponse response = null;
try {
response = sendRestRequest(dataUrl, requestParams, headers, FilmixDataResponse.class);
} catch (Exception e) {
log.error("Error getting movie file list", e);
}
List<MovieFile> movieFiles = new ArrayList<>();
if (response != null && FILMIX_SUCCESS.equalsIgnoreCase(response.getType())) {
if (response.getMessage() != null && response.getMessage().getTranslations() != null) {
FilmixFilesMessage.Translation translation = response.getMessage().getTranslations();
if (PLAYLIST_TRUE.equalsIgnoreCase(translation.getPlaylist())) {
movie.setWithPlaylist(true);
translation.getFlash().forEach((key, value) -> {
movieFiles.addAll(createPlaylist(key, decoder(value)));
});
} else {
translation.getFlash().forEach((key, value) -> {
MovieFile movieFile = new MovieFile();
movieFile.setName(key);
movieFile.setSource(SOURCE);
movieFile.setUrls(generateFileLinkMap(decoder(value)));
movieFiles.add(movieFile);
});
}
}
}
return movieFiles;
}
private List<MovieFile> createPlaylist(String translation, String url){
List<MovieFile> result = new ArrayList<>();
FilmixPlaylist filmixPlaylist = null;
try {
HttpHeaders headers = new HttpHeaders();
headers.set("Cookie", "FILMIXNET=6o53jodaeddcie9i5kca1qk9j7");
HttpEntity<String> request = new HttpEntity<>(null, headers);
ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.GET, request, String.class);
String decoded = decoder(response.getBody());
filmixPlaylist = mapper.readValue(decoded, FilmixPlaylist.class);
} catch (Exception e) {
log.error("Error creating playlist", e);
}
if(filmixPlaylist != null) {
List<FilmixPlaylist> grouped = filmixPlaylist.getPlaylist()
.stream()
.map(FilmixPlaylist::getPlaylist)
.flatMap(Collection::stream)
.collect(Collectors.toList());
grouped.forEach(fpl -> result.add(createMovieFiles(translation, fpl)));
}
return result;
}
private MovieFile createMovieFiles(String translation, FilmixPlaylist filmixFile){
MovieFile movieFile = new MovieFile();
movieFile.setSource(SOURCE);
movieFile.setName(filmixFile.getComment());
movieFile.setSeason(Integer.valueOf(filmixFile.getSeason()));
movieFile.setSeries(Integer.valueOf(filmixFile.getSerieId()));
movieFile.setUrls(generateFileLinkMap(filmixFile.getFile()));
movieFile.setTranslation(translation);
return movieFile;
}
private Map<String, String> generateFileLinkMap(final String url){
Map<String,String> result = new LinkedHashMap<>();
Matcher m = p.matcher( url);
if(m.matches()){
String qualityStr = m.group(1);
List<String> qualityList = makeQualityList(qualityStr);
qualityList.forEach(s -> {
result.put(s, url.replace(qualityStr, s));
});
}
return result;
}
private List<String> makeQualityList(String qualityList) {
String str = qualityList.substring(1, qualityList.length()-1);
return Arrays.stream(str.split(",")).filter(s -> !s.isEmpty()).collect(Collectors.toList());
}
@Override
public List<MovieSearchResponse> searchMovie(String searchText) {
MultiValueMap<String, String> requestParams = new LinkedMultiValueMap<>();
requestParams.add("search_word", searchText);
FilmixSearchResponse response = null;
try {
response = sendRestRequest(searchUrl, requestParams, null, FilmixSearchResponse.class);
} catch (Exception e) {
e.printStackTrace();
}
List<MovieSearchResponse> result = new ArrayList<>();
if(response != null && FILMIX_SUCCESS.equalsIgnoreCase(response.getType())){
response.getMessage().forEach(msg -> {
MovieSearchResponse searchResult = new MovieSearchResponse();
searchResult.setId(msg.getId());
searchResult.setOriginalName(msg.getOriginalName());
searchResult.setTitle(msg.getTitle());
searchResult.setYear(msg.getYear());
searchResult.setPoster(msg.getPoster());
result.add(searchResult);
});
}
return result;
}
private <T> T sendRestRequest(String url, MultiValueMap<String, String> map, Map<String,String> headMap, Class<T> responseType) throws Exception {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
headers.set("X-Requested-With", "XMLHttpRequest");
if(headMap != null){
headMap.forEach(headers::set);
}
headers.setAccept(Collections.singletonList(MediaType.APPLICATION_FORM_URLENCODED));
HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(map, headers);
ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.POST, request, String.class);
if (response.getStatusCode().is2xxSuccessful()) {
return mapper.readValue(response.getBody(), responseType);
} else {
throw new Exception("Response error");
}
}
}
|
package it.contrader.sprint3.model;
import it.contrader.sprint3.service.GommaService;
import javax.persistence.*;
import java.io.Serializable;
@Entity
@Table(name = "gomme")
public class GommaEntity implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;
@Column
private String model;
@Column
private String manufacturer;
@Column
private double price;
public GommaEntity () {}
public GommaEntity(String model, String manufacturer, double price) {
this.model = model;
this.manufacturer = manufacturer;
this.price = price;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getModel() {
return model;
}
public void setModel(String model) {
this.model = model;
}
public String getManufacturer() {
return manufacturer;
}
public void setManufacturer(String manufacturer) {
this.manufacturer = manufacturer;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
GommaEntity gommaEntity = (GommaEntity) o;
if (Double.compare(gommaEntity.price, price) != 0) return false;
if (model != null ? !model.equals(gommaEntity.model) : gommaEntity.model != null) return false;
return manufacturer != null ? manufacturer.equals(gommaEntity.manufacturer) : gommaEntity.manufacturer == null;
}
@Override
public int hashCode() {
int result;
long temp;
result = model != null ? model.hashCode() : 0;
result = 31 * result + (manufacturer != null ? manufacturer.hashCode() : 0);
temp = Double.doubleToLongBits(price);
result = 31 * result + (int) (temp ^ (temp >>> 32));
return result;
}
@Override
public String toString() {
return "Model: " + model + "\nManufacturer: " +manufacturer + "\nPrice: "+price+"\n";
}
}
|
package ir.ac.kntu.weapon.rifle;
public class MP5 extends Rifle {
public MP5(){
super("MP5", 1500, 13, 120, 3.1, 30, ACCESSIBILITY.BOTH);
}
}
|
package com.majkl.kitereg;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
public class MainActivity extends AppCompatActivity {
//views
private FloatingActionButton addRecordbtn;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//initialize views
addRecordbtn = findViewById(R.id.addRecordBtn);
//on click start AddUpdate activity
addRecordbtn.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v){
//starting AddUpdate activity
startActivity(new Intent(MainActivity.this,AddUpdateActivity.class));
}
});
}
}
|
// https://leetcode.com/problems/online-stock-span/
// #stack
class StockSpanner {
/* User array to store consecutive days at i-th => LOOP TO CHECK
[100, 65, 60, 70, 60, 75, 85],
1. 1. 1. 3. 1. 5 6
*/
/*
optimize: use stack instead of list, and only store the greater item than current.
65 60 70 60 => not need anymore after current 75
*/
private ArrayList<Integer> stockSpanList;
private ArrayList<Integer> stockPriceList;
public StockSpanner() {
stockSpanList = new ArrayList<>();
stockPriceList = new ArrayList<>();
}
public int next(int price) {
if (stockPriceList.isEmpty()) {
stockPriceList.add(price);
stockSpanList.add(1);
return 1;
}
int idx = stockPriceList.size() - 1;
int ret = 1;
while (idx >= 0) {
if (stockPriceList.get(idx) <= price) {
ret += stockSpanList.get(idx);
idx -= stockSpanList.get(idx);
} else {
break;
}
}
stockPriceList.add(price);
stockSpanList.add(ret);
return ret;
}
}
/**
* Your StockSpanner object will be instantiated and called as such: StockSpanner obj = new
* StockSpanner(); int param_1 = obj.next(price);
*/
|
/*
Given an array of distinct integers arr, find all pairs of elements with the minimum absolute difference of any two elements.
Return a list of pairs in ascending order(with respect to pairs), each pair [a, b] follows
a, b are from arr
a < b
b - a equals to the minimum absolute difference of any two elements in arr
Example 1:
Input: arr = [4,2,1,3]
Output: [[1,2],[2,3],[3,4]]
Explanation: The minimum absolute difference is 1. List all pairs with difference equal to 1 in ascending order.
Example 2:
Input: arr = [1,3,6,10,15]
Output: [[1,3]]
Example 3:
Input: arr = [3,8,-10,23,19,-4,-14,27]
Output: [[-14,-10],[19,23],[23,27]] */
class Solution {
public List<List<Integer>> minimumAbsDifference(int[] arr) {
Arrays.sort(arr);
int mindiff = Integer.MAX_VALUE;
for(int i = 1; i < arr.length; i++){
if(arr[i] - arr[i-1] < mindiff)
mindiff = arr[i] - arr[i-1];
}
List<List<Integer>> res = new ArrayList<>();
for(int i = 1; i < arr.length; i++){
if(arr[i] - arr[i-1] == mindiff){
List<Integer> list = new ArrayList<>();
list.add(arr[i-1]);
list.add(arr[i]);
res.add(list);
}
}
return res;
}
}
//same idea using hashmap(not necessary, slower)
class Solution {
public List<List<Integer>> minimumAbsDifference(int[] arr) {
Arrays.sort(arr);
HashMap<Integer, Integer> map = new HashMap<>();
map.put(arr[0], 0);
int mindiff = Integer.MAX_VALUE;
for(int i = 1; i < arr.length; i++){
map.put(arr[i], i);
if(arr[i] - arr[i-1] < mindiff)
mindiff = arr[i] - arr[i-1];
}
List<List<Integer>> res = new ArrayList<>();
for(int key : map.keySet()){
List<Integer> list = new ArrayList<>();
if(map.containsKey(key - mindiff) && map.get(key) != map.get(key - mindiff)){
list.add(key - mindiff);
list.add(key);
res.add(list);
}
}
Collections.sort(res, (a, b) -> a.get(0) - b.get(0));
return res;
}
}
// 1 2 3 4 |
package com.beike.dao.trx;
import java.util.Date;
import java.util.List;
import java.util.Map;
import com.beike.common.entity.trx.TrxorderGoods;
import com.beike.common.enums.trx.AuthStatus;
import com.beike.common.enums.trx.CreditStatus;
import com.beike.common.enums.trx.ReqChannel;
import com.beike.common.enums.trx.TrxStatus;
import com.beike.common.exception.StaleObjectStateException;
import com.beike.dao.GenericDao;
/**
* @Title: TrxorderGoodsDao.java
* @Package com.beike.dao.trx
* @Description: 订单商品明细DAO
* @date May 16, 2011 6:53:25 PM
* @author wh.cheng
* @version v1.0
*/
public interface TrxorderGoodsDao extends GenericDao<TrxorderGoods, Long> {
public void addTrxGoods(TrxorderGoods trxGoods);
public void updateTrxStatusBySn(String sn, TrxStatus trxStatus, Long version)throws StaleObjectStateException;
public void updateTrxStatusById(Long id, TrxStatus trxStatus, Long version)throws StaleObjectStateException;
public void updateTrxAndAauthStatusById(Long id, TrxStatus trxStatus,AuthStatus authStatus, Long voucherId, Long version)throws StaleObjectStateException;
public void updateTrxGoods(TrxorderGoods trxGoods)throws StaleObjectStateException;
public TrxorderGoods findBySn(String trxSn);
public TrxorderGoods findById(Long id);
// 增加乐观锁后取消for update
/* public TrxorderGoods findByIdForUpdate(Long id); */
public TrxorderGoods findById(Long id, Long userId);
public TrxorderGoods findByVoucherId(Long voucherId);
public List<TrxorderGoods> findByTrxId(Long trxId);
public List<Map<String, Object>> findTrxIdByUserIdAndType(Long userId,
int startRow, int pageSize, String viewType);
public List<TrxorderGoods> findInTrxId(String trxIdStr, String goodsIdStr);
public int findCountByUserId(String idStr, String viewType);
/**
* 取分组求和后的分页总数
*/
public int findPageCountByUserId(Long userId, String viewType);
public List<TrxorderGoods> findListInId(String inIdStr);
/**
* 根据时间和状态查询订单
*/
public List<TrxorderGoods> findByStatusAndDate(TrxStatus trxStatus,Date date,boolean isRefund,int start,int daemonLength,ReqChannel channel);
/**
* 根据状态,是否发送商家验证码、是否支持退款查询
*
* @param trxStatus
* @param isSendMerVou
* @param isRefund
* @return
*/
public List<TrxorderGoods> findByStatusAndIsMerIsRefund(TrxStatus trxStatus, Long isSendMerVou, Long isRefund);
/**
* 查询本次购买数量(以商品ID分组)
*
* @param trxId
* @return
*/
public List<Map<String, Long>> findCountByTrxId(Long trxId);
/**
* 查询该交易限制下单个用户对应的抽奖活动的订单数量(该SQL执行次数极少,故联表)
*
* @param UId
* @param extendInfo
* @param trxRuleId
* @return
*/
public Long findCountByUIdAndLottery(Long UId, String extendInfo,Long trxRuleId);
/**
* 根据表后缀随机匹配查询订单号
*
* @return
*/
public Map<String, String> findTrxGoodsSn(String snTbNameInt);
/**
* 根据表后缀随机匹配查询订单号(带偏移量)
* @param snTbNameInt
* @param ofset
* @return
*/
public List<Map<String, Object>> findTrxGoodsSnForOfset(String snTbNameInt,int ofset);
/**
* 根据表后缀及订单号进行删除
*
* @return
*/
public void delTrxGoodsSn(String snTbNameInt, int trxGoodsId);
public List<Map<String, Object>> findTrxOrderIdByUserID(Long userId);
/**
* 查询消费未返现记录
*
* @return
*/
public List<TrxorderGoods> findByDis(int isDis);
/**
* 根据tgId更新tg TRX_STATUS状态
* @param idStrs
* 8:02:03 PM
* janwen
*
*/
public int updateTrxStatusByIds(String idStr,String trxStatusFinal,String trxStatusPro,Long evaluationid);
/**
* 0元抽奖2.0获取订单号
* @Title: findSnByTrxId
* @Description: TODO
* @param @param trxId
* @param @return
* @return List<Map<String,Long>>
* @throws
*/
@SuppressWarnings("unchecked")
public List findSnByTrxId(Long trxId);
/**
* 短信提醒: 订单过期提醒
*
* @param loseToNow10DateStr
* @param loseToNow3Date
* @return
*/
List<Map<String, Object>> findLoseDate(Date loseToNow10Date,Date loseToNow3Date);
/**
* 手机端的分页数据总数量
* @param userId
* @param status
* @param sendMerVou
* @return
*/
public int findPageCountByUserIdStatus(Long userId,String status);
/**
* 手机端的分页后数据
* @param userId
* @param startRow
* @param pageSize
* @param trxStatus
* @return
*/
public List<Map<String, Object>> findTrxorderGoodsByUserIdStatus(Long userId,int startRow,int pageSize, String trxStatus);
/**
* 手机端我的订单查询
* @return
*/
public List<Map<String,Object>> findTrxorderGoodsByGoodsIdTrxorderId(String trxIdStr,String goodsIdStr);
/**
* 根据订单ID查询58需求信息
* @param trxOrderId
* @return
*/
public List<Map<String,Object>> findByTrxOrderId(Long trxOrderId);
/**
* 根据订单号查询订单状态
* @param trxorderId
* @param trxGoodsSn
* @return
*/
public Map<String,Object> findByTrxorderIdAndSn(Long trxorderId, String trxGoodsSn);
/**
* 根据voucherId查询订单状态
* @param trxorderId
* @param voucherId
* @return
*/
public Map<String,Object> findByTrxorderIdAndVouId(Long trxorderId, Long voucherId);
/**
* 按照更新时间和订单状态查询凭证信息
* @param startTime
* @param endTime
* @param userIdStr
* @return
*/
public List<Map<String, Object>> findByLastUpdateDateAndStatus(Date startTime, Date endTime,String userIdStr,String trxStatusStr);
/**
* 查询出过期订单
* @param loseToNow3Date
* @return
*/
public List<Map<String, Object>> findLoseNowDate(Date loseToNowDate,int startCount,int endCount);
/**
* 查询出过期订单 总数量
* @param loseToNowDate
* @return
*/
public int findLoseCountDate(Date loseToNowDate) ;
public List<TrxorderGoods> findTgByVoucherId(String voucherId);
/**
* 查询商品订单结算信息
*/
public List<Map<String, Object>> querySettleDetailByIds(String idStr);
/**
* 查询出过期是否支持退款的总数量
* @param trxStatus
* @param date
* @param isRefund
* @return
*/
public int findByStatusAndDateCount(TrxStatus trxStatus,Date date,boolean isRefund,ReqChannel channel) ;
/**
* 批量删除已经预取的订单号
* @param snTbNameInt
* @param idS
*/
public void delTrxGoodsSnByIds(String snTbNameInt, String idS) ;
/**
* 根据更新时间和状态查询商品订单
* @param startTime
* @param endTime
* @param trxStatus
* @return
*/
public List<TrxorderGoods> findTrxGoodsByUpDateTimeAndStatus(String date, TrxStatus trxStatus);
/**
* 根据trxOrderId查询券有关信息
* @param trxOrderId
* @return
*/
public List<Map<String,Object>> findVoucherInfoByTrxOrderId(Long trxOrderId);
/**
* 查询商品订单信息
* map参数名称:
* guestId商家编号
* subGuestId分店编号
* trxGoodsSn商品订单号
* goodsId商品编号
* voucherCode服务密码凭证号
* trxStatus订单状态
* 购买时间createDateBegin - createDateEnd
* 消费时间 confirmDateBegin - confirmDateEnd
* 分页参数 startRow offSet
*/
public List<Map<String,Object>> queryTrxOrderGoodsForGuest(Map<String, String> map,int startRow,int offSet);
/**
* 查询商品订单信息数量
* map参数名称:
* guestId商家编号
* subGuestId分店编号
* trxGoodsSn商品订单号
* goodsId商品编号
* voucherCode服务密码凭证号
* 购买时间createDateBegin - createDateEnd
* 消费时间 confirmDateBegin - confirmDateEnd
*/
public Map<String,Long> queryTrxOrderGoodsForGuestCountGroupByTrxStatus(Map<String, String> condition);
/**
* 查询未入账的商品订单
* @return
*/
public List<TrxorderGoods> getTrxOrderGoodsByCreditStatus(String startDate,String endDate,CreditStatus creditStatus);
/**
* 查询商家购买数量
* @param map
* @return Map<String,Object>
*/
public List<Map<String, Object>> queryTrxGoodsBuyCountForGuest(Map<String, String> map);
/**
* 查询商家消费数量
* @param map
* @return Map<String,Object>
*/
public List<Map<String, Object>> queryTrxGoodsUsedCountForGuest(Map<String, String> map);
}
|
package com.fanfte.designPattern.build;
import javafx.util.Builder;
import sun.reflect.generics.tree.Tree;
public class ConcreteBuilder implements Builder<Tree> {
@Override
public Tree build() {
return null;
}
}
|
package com.CaseySinglehurst.facilities;
import java.util.Timer;
import java.util.TimerTask;
public class CrystalResource {
private final int baseLevel = 1, baseIncrease = 50, baseStorage = 10000;
private int level = 1, crystal = 0, storageLevel = 0, storage = 0;
CrystalResource(){
Timer timer = new Timer();
TimerTask task = new TimerTask(){
public void run(){
addCrystal(1);
}
};
timer.scheduleAtFixedRate(task,1000,1000);
}
public CrystalResource(int newLevel, int newCrystal, int newStorageLevel, int newStorage){
level = newLevel;
crystal = newCrystal;
storageLevel = newStorageLevel;
storage = newStorage;
Timer timer = new Timer();
TimerTask task = new TimerTask(){
public void run(){
addCrystal(1);
}
};
timer.scheduleAtFixedRate(task,1000,1000);
}
public void addCrystal(int times){
//crystal += (int)Math.round((50 + Math.exp(level)));
int incrementValue = ((int)Math.round((baseIncrease + Math.exp(level)))*times);
if ((crystal+incrementValue)<=storage){
crystal+=incrementValue;
} else if ((crystal+incrementValue) > storage){
crystal = storage;
}
}
public void update(){
if (storage < baseStorage){
storage = baseStorage;
}
//For development only
if (storage > baseStorage){
storage = baseStorage;
}
}
public int getLevel(){
return level;
}
public int getCrystal(){
return crystal;
}
public int getStorageLevel(){
return storageLevel;
}
public int getStorage(){
return storage;
}
public void setLevel(int newLevel){
level = newLevel;
}
public void setMetal(int newCrystal){
crystal = newCrystal;
}
public void setStorageLevel(int newStorageLevel){
storageLevel = newStorageLevel;
}
public void setStorage(int newStorage){
storage = newStorage;
}
}
|
package sop.filegen;
/**
* @Author: LCF
* @Date: 2020/1/9 9:37
* @Package: sop.filegen
*/
public class FileGeneratorConstant {
public static final String SUCCESS = "200";
public static final String FAILED = "500";
public static final String REPORT_TYPE_ONLINE = "ONLINE";
public static final String REPORT_TYPE_BATCH = "BATCH";
// Output types:
public static final String OUTPUT_TYPE_PDF = "PDF";
public static final String OUTPUT_TYPE_ITEXT_PDF = "ITEXT_PDF";
public static final String OUTPUT_TYPE_ITEXT_CSV = "ITEXT_CSV";
public static final String OUTPUT_TYPE_XLS = "XLS";
public static final String OUTPUT_TYPE_XLSX = "XLSX";
public static final String OUTPUT_TYPE_DOC = "DOC";
public static final String OUTPUT_TYPE_DOCX = "DOCX";
public static final String OUTPUT_TYPE_CSV = "CSV";
// Report processing status
public static final String REPORT_STATUS_PROCESSING = "PROCESSING";
public static final String REPORT_STATUS_COMPLETED = "COMPLETED";
// A constant request user id for batch job-report generating request to
// avoid validation error
public static final String REQ_USER_ID_FOR_BATCH = "BATCH";
public static final Integer NON_EXISTED_ID = -1;
}
|
package com.pibs.form;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionMapping;
import com.pibs.constant.ActionConstant;
import com.pibs.constant.MapConstant;
import com.pibs.constant.ModuleConstant;
import com.pibs.constant.ParamConstant;
import com.pibs.model.MonitorRoomTransfer;
import com.pibs.model.Room;
import com.pibs.service.ServiceManager;
import com.pibs.service.ServiceManagerImpl;
import com.pibs.util.DateUtils;
public class MonitorRoomTransferFormBean extends PIBSFormBean {
private static final long serialVersionUID = 1L;
private int id;
private int patientCaseSystemId;
private int roomIdTransfer;
private String dateTransferred;
//name fields
private String roomNoTransfer;
private List<Room> modelList;
private List<MonitorRoomTransfer> entityList;
private String criteria;
private String category;
private int noOfPages;
private int currentPage;
private boolean transactionStatus;
private String transactionMessage;
public MonitorRoomTransferFormBean() {}
public String getCriteria() {
return criteria;
}
public void setCriteria(String criteria) {
this.criteria = criteria;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public int getNoOfPages() {
return noOfPages;
}
public void setNoOfPages(int noOfPages) {
this.noOfPages = noOfPages;
}
public int getCurrentPage() {
return currentPage;
}
public void setCurrentPage(int currentPage) {
this.currentPage = currentPage;
}
public boolean isTransactionStatus() {
return transactionStatus;
}
public void setTransactionStatus(boolean transactionStatus) {
this.transactionStatus = transactionStatus;
}
public String getTransactionMessage() {
return transactionMessage;
}
public void setTransactionMessage(String transactionMessage) {
this.transactionMessage = transactionMessage;
}
public int getPatientCaseSystemId() {
return patientCaseSystemId;
}
public void setPatientCaseSystemId(int patientCaseSystemId) {
this.patientCaseSystemId = patientCaseSystemId;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public List<Room> getModelList() {
return modelList;
}
public void setModelList(List<Room> modelList) {
this.modelList = modelList;
}
public String getDateTransferred() {
return dateTransferred;
}
public void setDateTransferred(String dateTransferred) {
this.dateTransferred = dateTransferred;
}
public String getRoomNoTransfer() {
return roomNoTransfer;
}
public void setRoomNoTransfer(String roomNoTransfer) {
this.roomNoTransfer = roomNoTransfer;
}
public List<MonitorRoomTransfer> getEntityList() {
return entityList;
}
public void setEntityList(List<MonitorRoomTransfer> entityList) {
this.entityList = entityList;
}
public int getRoomIdTransfer() {
return roomIdTransfer;
}
public void setRoomIdTransfer(int roomIdTransfer) {
this.roomIdTransfer = roomIdTransfer;
}
public void populateFormBean(MonitorRoomTransfer model) throws Exception {
setPatientCaseSystemId(model.getPatientCaseSystemId());
setRoomIdTransfer(model.getRoomIdTransfer());
if (model.getDateTransferred()!=null) {
setDateTransferred(DateUtils.sqlDateToString(model.getDateTransferred()));
}
}
public void populateEntityList(List<MonitorRoomTransfer> rsList) throws Exception {
setEntityList(rsList);
}
public MonitorRoomTransfer populateModel (MonitorRoomTransferFormBean formbean) throws Exception {
MonitorRoomTransfer model = new MonitorRoomTransfer();
model.setPatientCaseSystemId(formbean.getPatientCaseSystemId());
model.setRoomIdTransfer(formbean.getRoomIdTransfer());
if (formbean.getDateTransferred()!=null && formbean.getDateTransferred().trim().length() > 0) {
model.setDateTransferred(DateUtils.strToSQLDate(formbean.getDateTransferred()));;
}
return model;
}
@Override
public ActionErrors validate(ActionMapping mapping,
HttpServletRequest request) {
// TODO Auto-generated method stub
ActionErrors errors = new ActionErrors();
String command = (String) request.getParameter("command");
if (command!=null && (command.equalsIgnoreCase(ParamConstant.AJAX_SAVE) || command.equalsIgnoreCase(ParamConstant.AJAX_UPDATE))) {
}
return errors;
}
public void getRoomDetails(HttpServletRequest request) throws Exception {
//fetch the room details
int id = Integer.parseInt(request.getParameter("roomTransferId"));
Room model = new Room();
model.setId(id);
HashMap<String,Object> dataMap = new HashMap<String, Object>();
dataMap.put(MapConstant.MODULE, ModuleConstant.ROOM);
dataMap.put(MapConstant.CLASS_DATA, model);
dataMap.put(MapConstant.ACTION, ActionConstant.GET_DATA);
ServiceManager service = new ServiceManagerImpl();
Map<String, Object> resultMap = service.executeRequest(dataMap);
if (resultMap!=null && !resultMap.isEmpty()) {
model = (Room) resultMap.get(MapConstant.CLASS_DATA);
setRoomIdTransfer(model.getId());
setRoomNoTransfer(model.getRoomNo());
}
}
}
|
/*
* Copyright (c) 2016 ICM Uniwersytet Warszawski All rights reserved.
* See LICENCE.txt file for licensing information.
*/
package pl.edu.icm.unity.db.generic.bulk;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import pl.edu.icm.unity.db.DBGeneric;
import pl.edu.icm.unity.db.generic.DependencyNotificationManager;
import pl.edu.icm.unity.db.generic.GenericObjectsDB;
import pl.edu.icm.unity.server.bulkops.ScheduledProcessingRule;
/**
* Easy to use interface to {@link AbstractTranslationProfile} storage.
* @author K. Benedyczak
*/
@Component
public class ProcessingRuleDB extends GenericObjectsDB<ScheduledProcessingRule>
{
@Autowired
public ProcessingRuleDB(ProcessingRuleHandler handler,
DBGeneric dbGeneric, DependencyNotificationManager notificationManager)
{
super(handler, dbGeneric, notificationManager, ScheduledProcessingRule.class, "processing rule");
}
}
|
package com.gome.manager.controler;
import java.io.UnsupportedEncodingException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang.StringUtils;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSON;
import com.gome.manager.common.Constant;
import com.gome.manager.common.Page;
import com.gome.manager.common.util.ResponsesDTO;
import com.gome.manager.constants.ReturnCode;
import com.gome.manager.controler.base.BaseController;
import com.gome.manager.domain.Meeting;
import com.gome.manager.service.MeetingService;
@Controller
@RequestMapping(value = "/meeting")
public class MeetingController extends BaseController{
@Resource
private MeetingService meetingService;
/**
* 跳转到新增会议页.
*
* @param request
* @param response
* @return
*
* <pre>
* 修改日期 修改人 修改原因
* 2015年11月09日 liuhaikun 新建
* </pre>
*/
@RequestMapping(value="/toAddMeetingView", method={RequestMethod.GET, RequestMethod.POST})
public ModelAndView toAddMeetingView(HttpServletRequest request, HttpServletResponse response, ModelAndView model){
model.setViewName("/meeting/addMeeting");
String userName = getUserInfo(request, "userName");
String code = meetingService.queryMeetCode();
model.addObject("operateUser", userName);
model.addObject("code", code);
return model;
}
/**
*
* 新增会议.
*
* @param content
* 会议信息
* @param request
* @param response
* @return
*
* <pre>
* 修改日期 修改人 修改原因
* 2015年11月09日 liuhaikun 新建
* </pre>
*/
@RequestMapping(value="/addMeeting", method={RequestMethod.GET, RequestMethod.POST}, produces="application/json;charset=utf-8")
@ResponseBody
public ResponsesDTO addMeeting(@Param(value="content")String content, HttpServletRequest request, HttpServletResponse response){
ResponsesDTO responses = new ResponsesDTO(ReturnCode.ACTIVE_FAILURE);
try{
if(StringUtils.isNotEmpty(content)){
Meeting meeting = JSON.parseObject(content, Meeting.class);
if(meeting != null){
DateFormat df = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss");
String format = df.format(new Date());
meeting.setCreateTime(format);
meeting.setCreatePer(meeting.getOperateUser());
int record = meetingService.addMeeting(meeting);
if(record > 0){
responses.setReturnCode(ReturnCode.ACTIVE_SUCCESS);
meetingService.updateMeetCode(meeting.getCode());
} else {
responses.setReturnCode(ReturnCode.ACTIVE_FAILURE);
}
}
}
} catch(Exception e) {
e.printStackTrace();
responses.setReturnCode(ReturnCode.ACTIVE_EXCEPTION);
}
return responses;
}
/**
*
* 跳转到会议列表页.
*
* @param content
* 搜索条件
* @param request
* @param response
* @param model
* @return
*
* <pre>
* 修改日期 修改人 修改原因
* 2015年11月09日 liuhaikun 新建
* </pre>
* @throws UnsupportedEncodingException
*/
@RequestMapping(value="/queryMeetListView", method={RequestMethod.GET,RequestMethod.POST})
public ModelAndView queryMeetListView(@Param(value="content")String content, @Param(value="page")String page, @Param(value="size")String size, HttpServletRequest request, HttpServletResponse response, ModelAndView model) throws UnsupportedEncodingException{
if(StringUtils.isEmpty(content)){
model.setViewName("/meeting/meetingList");
} else {
model.setViewName("/meeting/meetingTable");
}
int pageNo = 1;
if(StringUtils.isNotEmpty(page)){
pageNo = Integer.parseInt(page);
}
int pageSize = Constant.PAGE_SIZE;
if(StringUtils.isNotEmpty(size)){
pageSize = Integer.parseInt(size);
}
Page<Meeting> p = new Page<Meeting>(pageNo, pageSize);
Meeting meeting = null;
if(StringUtils.isNotEmpty(content)){
meeting = JSON.parseObject(content, Meeting.class);
} else {
meeting = new Meeting();
}
p.setConditions(meeting);
Page<Meeting> pageMeeting = meetingService.findMeetingListByPage(p);
model.addObject("page", pageMeeting);
return model;
}
/**
*
* 跳转到编辑会议页.
*
* @param id
* 会议ID
* @param request
* @param response
* @param model
* @return
*
* <pre>
* 修改日期 修改人 修改原因
* 2015年11月09日 liuhaikun 新建
* </pre>
*/
@RequestMapping(value="/toEditMeetingView", method={RequestMethod.GET,RequestMethod.POST})
public ModelAndView toEditMeetingView(@Param(value="id")String id, HttpServletRequest request, HttpServletResponse response, ModelAndView model){
model.setViewName("/meeting/editMeeting");
if(StringUtils.isNotEmpty(id)){
Meeting meeting = meetingService.findMeetingById(Long.parseLong(id));
if(meeting != null){
model.addObject("meeting", meeting);
String userName = getUserInfo(request, "userName");
model.addObject("operateUser", userName);
}
}
return model;
}
/**
*
* 编辑会议.
*
* @param content
* 会议信息
* @param request
* @param response
* @return
*
* <pre>
* 修改日期 修改人 修改原因
* 2015年11月09日 liuhaikun 新建
* </pre>
*/
@RequestMapping(value="/editMeeting", method={RequestMethod.GET, RequestMethod.POST}, produces="application/json;charset=utf-8")
@ResponseBody
public ResponsesDTO editMeeting(@Param(value="content")String content, HttpServletRequest request, HttpServletResponse response){
ResponsesDTO responses = new ResponsesDTO(ReturnCode.ACTIVE_FAILURE);
try{
Meeting meeting = JSON.parseObject(content, Meeting.class);
if(meeting != null){
int record = meetingService.updateMeeting(meeting);
if(record > 0){
responses.setReturnCode(ReturnCode.ACTIVE_SUCCESS);
} else {
responses.setReturnCode(ReturnCode.ACTIVE_FAILURE);
}
}
} catch(Exception e) {
e.printStackTrace();
responses.setReturnCode(ReturnCode.ACTIVE_EXCEPTION);
}
return responses;
}
/**
*
* 删除会议.
*
* @param id
* 会议ID
* @param request
* @param response
* @return
*
* <pre>
* 修改日期 修改人 修改原因
* 2015年11月09日 liuhaikun 新建
* </pre>
*/
@RequestMapping(value="/deleteMeeting", method={RequestMethod.GET, RequestMethod.POST}, produces="application/json;charset=utf-8")
@ResponseBody
public ResponsesDTO deleteMeeting(@Param(value="id")String id, HttpServletRequest request, HttpServletResponse response){
ResponsesDTO responses = new ResponsesDTO(ReturnCode.ACTIVE_FAILURE);
try{
if(StringUtils.isNotEmpty(id)){
Long MeetingId = Long.parseLong(id);
int record = meetingService.deleteMeetingById(MeetingId);
if(record > 0){
responses.setReturnCode(ReturnCode.ACTIVE_SUCCESS);
} else {
responses.setReturnCode(ReturnCode.ACTIVE_FAILURE);
}
}
} catch(Exception e) {
e.printStackTrace();
responses.setReturnCode(ReturnCode.ACTIVE_EXCEPTION);
}
return responses;
}
/**
*
* 会议码校验.
*
* @param code
* 会议code
* @param request
* @param response
* @return
*
* <pre>
* 修改日期 修改人 修改原因
* 2015年11月09日 liuhaikun 新建
* </pre>
*/
@RequestMapping(value="/validateMeetCode", method={RequestMethod.GET, RequestMethod.POST}, produces="application/json;charset=utf-8")
@ResponseBody
public ResponsesDTO validateMeetCode(@Param(value="code")String code, HttpServletRequest request, HttpServletResponse response){
ResponsesDTO responses = new ResponsesDTO(ReturnCode.ACTIVE_FAILURE);
try{
if(StringUtils.isNotEmpty(code)){
Meeting meeting = meetingService.validateMeetCode(code);
if(meeting != null){
responses.setReturnCode(ReturnCode.ACTIVE_SUCCESS);
responses.setAttach(meeting);
} else {
responses.setReturnCode(ReturnCode.ACTIVE_FAILURE);
}
}else{
responses.setReturnCode(ReturnCode.ACTIVE_FAILURE);
}
} catch(Exception e) {
e.printStackTrace();
responses.setReturnCode(ReturnCode.ACTIVE_EXCEPTION);
}
return responses;
}
/**
*
* 会议码校验.
*
* @param code
* 会议code
* @param request
* @param response
* @return
*
* <pre>
* 修改日期 修改人 修改原因
* 2015年11月09日 liuhaikun 新建
* </pre>
*/
@RequestMapping(value="/queryMeetInfo", method={RequestMethod.GET, RequestMethod.POST}, produces="application/json;charset=utf-8")
@ResponseBody
public ResponsesDTO queryMeetInfo(@Param(value="meetId")String meetId, HttpServletRequest request, HttpServletResponse response){
ResponsesDTO responses = new ResponsesDTO(ReturnCode.ACTIVE_FAILURE);
try{
if(StringUtils.isNotEmpty(meetId)){
Meeting meeting = meetingService.findMeetingById(Long.parseLong(meetId));
if(meeting != null){
responses.setReturnCode(ReturnCode.ACTIVE_SUCCESS);
responses.setAttach(meeting);
} else {
responses.setReturnCode(ReturnCode.ACTIVE_FAILURE);
}
}else{
responses.setReturnCode(ReturnCode.ACTIVE_FAILURE);
}
} catch(Exception e) {
e.printStackTrace();
responses.setReturnCode(ReturnCode.ACTIVE_EXCEPTION);
}
return responses;
}
}
|
package com.somecompany.customermatches.repository;
import com.somecompany.customermatches.model.Match;
import java.util.Set;
import java.util.UUID;
public interface MatchRepository {
Set<Match> getMatchesFor(Set<UUID> matchIds);
}
|
package service;
import dao.AuthTokenDao;
import dao.DataAccessException;
import dao.Database;
import dao.EventDao;
import model.AuthToken;
import model.Event;
import response.ErrorResponse;
import response.EventResponse;
import response.Response;
import java.util.ArrayList;
/**
* Event Service will call the DAOs to get event data from the database and pass it to the handler
*/
public class EventService {
public EventService() {
}
/**
* getEvent returns the data for a single event
* @param event_id is the primary key used to retrieve the data
* @return
*/
public Response getEvent(String authTokenStr, String event_id) throws DataAccessException{
EventResponse response = new EventResponse();
Database db = new Database();
try {
db.openConnection();
db.createTables();
AuthTokenDao atd = new AuthTokenDao(db.getConn());
AuthToken token = atd.find(authTokenStr);
EventDao eventDao = new EventDao(db.getConn());
Event event = eventDao.find(event_id);
db.closeConnection(true);
if (token == null){
ErrorResponse error = new ErrorResponse("Invalid auth token");
return error;
}
if (!event.getAssociatedUsername().equals(token.getUserName())){
ErrorResponse error = new ErrorResponse("Event does not belong to user");
return error;
}
db.openConnection();
eventDao = new EventDao(db.getConn());
Event result = eventDao.find(event_id);
if (result == null) {
ErrorResponse error = new ErrorResponse("No data matched the query");
db.closeConnection(false);
db = null;
return error;
}
else {
response.setAssociatedUsername(result.getAssociatedUsername());
response.setEventID(result.getEventID());
response.setPersonID(result.getPersonID());
response.setLatitude(result.getLatitude());
response.setLongitude(result.getLongitude());
response.setCountry(result.getCountry());
response.setCity(result.getCity());
response.setEventType(result.getEventType());
response.setYear(result.getYear());
db.closeConnection(true);
db = null;
}
}
catch (DataAccessException e) {
db.closeConnection(false);
ErrorResponse error = new ErrorResponse(e.getMessage());
return error;
}
catch (NullPointerException e){
ErrorResponse error = new ErrorResponse("Invalid data");
return error;
}
return response;
}
/**
* getAllEvents will return all the events associated with a username, which will be found using the authtoken
* @param authTokenStr is the identifier that will be used to retrieve the data
* @return
*/
public Response[] getAllEvents(String authTokenStr) {
ArrayList<EventResponse> familyAL = new ArrayList<>();
ArrayList<Event> famEvents = new ArrayList<>();
Database db = new Database();
try {
db.openConnection();
db.createTables();
AuthTokenDao atd = new AuthTokenDao(db.getConn());
AuthToken token = atd.find(authTokenStr);
db.closeConnection(true);
if (token == null){
ErrorResponse error = new ErrorResponse("Invalid auth token");
Response[] errorResp = {error};
return errorResp;
}
String username = token.getUserName();
db.openConnection();
EventDao eventDao = new EventDao(db.getConn());
famEvents = eventDao.findMany(username);
db.closeConnection(true);
for (Event event : famEvents) {
EventResponse response = new EventResponse();
response.setAssociatedUsername(event.getAssociatedUsername());
response.setEventID(event.getEventID());
response.setPersonID(event.getPersonID());
response.setLatitude(event.getLatitude());
response.setLongitude(event.getLongitude());
response.setCountry(event.getCountry());
response.setCity(event.getCity());
response.setEventType(event.getEventType());
response.setYear(event.getYear());
familyAL.add(response);
}
}
catch (DataAccessException e) {
ErrorResponse error = new ErrorResponse(e.getMessage());
Response[] errorResp= {error};
return errorResp;
}
EventResponse[] family = new EventResponse[familyAL.size()];
for (int i = 0; i < family.length; ++i) {
family[i] = familyAL.get(i);
}
return family;
}
}
|
package by.avdeev.test;
public enum E {
A(1), B(2) , C(3);
private int a;
E(int a) {
this.a = a;
}
}
|
package controller;
import java.net.URL;
import java.util.ArrayList;
import java.util.ResourceBundle;
import db.create;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.TreeCell;
import javafx.scene.control.TreeItem;
import javafx.scene.control.TreeView;
import javafx.scene.control.cell.PropertyValueFactory;
import jsoup.PobLigi;
import model.Mecz;
public class MainController implements Initializable {
@FXML TreeView<String> treeView;
@FXML TableView<Mecz> table;
@FXML TableColumn<Mecz,String> dr1;
@FXML TableColumn<Mecz,Integer> wyn1;
@FXML TableColumn<Mecz,Integer> wyn2;
@FXML TableColumn<Mecz,String> dr2;
int tab[] = {0,0,0,0,0,0,0,0,0,0,0};
PobLigi l = new PobLigi();
@Override
public void initialize(URL arg0, ResourceBundle arg1) {
// TODO Auto-generated method stub
l.getListaLig().get(1).wczytajMecze();
TreeItem<String> Listalig = new TreeItem<String>("2018");
Listalig.setExpanded(true);
for(int i = 0; i < l.getListaLig().size(); i++) {
TreeItem<String> xd = new TreeItem<String>(l.getListaLig().get(i).getNazwa());
Listalig.getChildren().add(xd);
}
treeView.setRoot(Listalig);
table.setVisible(false);
treeView.setCellFactory(tree -> {
TreeCell<String> cell = new TreeCell<String>() {
@Override
public void updateItem(String item, boolean empty) {
super.updateItem(item, empty) ;
if (empty) {
setText(null);
} else {
setText(item);
}
}
};
cell.setOnMouseClicked(event -> {
if (! cell.isEmpty()) {
TreeItem<String> Item = cell.getTreeItem();
int i = 0;
while(Item.getValue()!= l.getListaLig().get(i).getNazwa()) {
i++;
}
ArrayList<Mecz> mecz;
ObservableList<Mecz> lista = FXCollections.observableArrayList(
mecz=l.getListaLig().get(i).wczytajMecze()
);
if(tab[i]==0) {
create cr = new create(l.getListaLig().get(i).getNazwa(), mecz);
tab[i]=1;
}
table.setItems(lista);
table.setVisible(true);
}
});
return cell ;
});
dr1.setCellValueFactory(new PropertyValueFactory<Mecz, String>("dr1"));
dr2.setCellValueFactory(new PropertyValueFactory<Mecz, String>("dr2"));
wyn1.setCellValueFactory(new PropertyValueFactory<Mecz, Integer>("wynik1"));
wyn2.setCellValueFactory(new PropertyValueFactory<Mecz, Integer>("wynik2"));
}
}
|
package old.sys;
public class PaperWordPoint implements Comparable<PaperWordPoint>{
private String paperId;
private int points;
public PaperWordPoint(String paperId) {
this.paperId = paperId;
this.points = 0;
}
public int getPoints() {
return points;
}
public void addPoints(int points) {
this.points += points;
}
public String getPaperId() {
return paperId;
}
@Override
public int compareTo(PaperWordPoint o) {
if(this.getPoints() < o.getPoints()){
return -1;
}else if(this.getPoints() > o.getPoints()){
return 1;
}else{
return 0;
}
}
} |
package com.fr3ddy.mods.autotext;
import net.minecraft.client.Minecraft;
/**
* Fr3ddy's AutoText for Forge 1.8.9 <https://github.com/ThatFr3ddy/AutoText>
* Copyright(c) 2018 ThatFr3ddy
*/
public class Macro
{
/** The unique ID of the macro */
private int id;
/** The name of the macro */
private String name;
/** The command executed when the macro's key is pressed */
private String command;
/** The key id bound the macro */
private int keyCode;
/** Reference to Minecraft Object */
private static final Minecraft mc = Minecraft.getMinecraft();
/**
* Sets private fields to its Args
*
* @param id
* @param name
* @param command
* @param keyCode
*/
public Macro(int id, String name, String command, int keyCode)
{
this.id = id;
this.name = name;
this.command = command;
this.keyCode = keyCode;
}
/** Executes the command */
public void executeCommand()
{
this.mc.thePlayer.sendChatMessage(this.command);
}
/**
* Getters & setters
*/
public int getId()
{
return id;
}
public void setId(int id)
{
this.id = id;
}
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public String getCommand()
{
return command;
}
public void setCommand(String command)
{
this.command = command;
}
public int getKeyCode()
{
return keyCode;
}
public void setKeyCode(int keyCode)
{
this.keyCode = keyCode;
}
}
|
package homework3.calcs.simple;
import homework3.calcs.additional.CalculatorWithCounterAutoCompositeInterface;
import homework3.calcs.additional.CalculatorWithCounterAutoDecorator;
import homework3.calcs.api.ICalculator;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
import java.util.stream.Stream;
import static org.junit.jupiter.params.provider.Arguments.arguments;
public class CalculatorTest {
@ParameterizedTest(name = "{argumentsWithNames}")
@MethodSource("calcProvider")
public void multyCalculatorTest(ICalculator calculator){
Assertions.assertEquals(140.45999999999998,
calculator.plus(4.1, calculator.plus(calculator.mult(15, 7),
calculator.pow(calculator.div(28, 5), 2))));
}
public static Stream<Arguments> calcProvider(){
return Stream.of(
arguments(new CalculatorWithMathCopy()),
arguments(new CalculatorWithOperator()),
arguments(new CalculatorWithMathExtends()),
arguments(new CalculatorWithCounterAutoCompositeInterface(new CalculatorWithMathCopy())),
arguments(new CalculatorWithCounterAutoDecorator(new CalculatorWithOperator()))
);
}
}
|
package br.com.wasys.gfin.cheqfast.cliente.fragment;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.Snackbar;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v7.app.AlertDialog;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.github.clans.fab.FloatingActionButton;
import com.github.clans.fab.FloatingActionMenu;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.BooleanUtils;
import java.util.ArrayList;
import br.com.wasys.gfin.cheqfast.cliente.R;
import br.com.wasys.gfin.cheqfast.cliente.dataset.DataSet;
import br.com.wasys.gfin.cheqfast.cliente.dialog.DigitalizacaoDialog;
import br.com.wasys.gfin.cheqfast.cliente.model.CampoGrupoModel;
import br.com.wasys.gfin.cheqfast.cliente.model.ChequeModel;
import br.com.wasys.gfin.cheqfast.cliente.model.DigitalizacaoModel;
import br.com.wasys.gfin.cheqfast.cliente.model.DocumentoModel;
import br.com.wasys.gfin.cheqfast.cliente.model.ProcessoModel;
import br.com.wasys.gfin.cheqfast.cliente.model.ProcessoRegraModel;
import br.com.wasys.gfin.cheqfast.cliente.service.DigitalizacaoService;
import br.com.wasys.gfin.cheqfast.cliente.service.ProcessoService;
import br.com.wasys.gfin.cheqfast.cliente.widget.AppGroupReadonlyInputLayout;
import br.com.wasys.library.utils.FieldUtils;
import br.com.wasys.library.utils.FragmentUtils;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import rx.Observable;
import rx.Subscriber;
import static br.com.wasys.gfin.cheqfast.cliente.background.DigitalizacaoService.startDigitalizacaoService;
/**
* A simple {@link Fragment} subclass.
*/
public class ProcessoDetalheFragment extends CheqFastFragment implements View.OnClickListener, TransferenciaFragment.OnTransferenciaListener {
@BindView(R.id.view_root) View mViewRoot;
@BindView(R.id.text_id) TextView mIdTextView;
@BindView(R.id.text_taxa) TextView mTaxaTextView;
@BindView(R.id.text_data) TextView mDataTextView;
@BindView(R.id.text_status) TextView mStatusTextView;
@BindView(R.id.text_coleta) TextView mColetaTextView;
@BindView(R.id.image_status) ImageView mStatusImageView;
@BindView(R.id.layout_fields) LinearLayout mLayoutFields;
@BindView(R.id.layout_documentos) LinearLayout mLayoutDocumentos;
@BindView(R.id.text_valor_liberado) TextView mValorLiberadoTextView;
@BindView(R.id.button_info) ImageButton mInfoButton;
@BindView(R.id.fab_menu) FloatingActionMenu mFloatingActionMenu;
@BindView(R.id.button_aprovar) FloatingActionButton mAprovarFloatingActionButton;
@BindView(R.id.button_cancelar) FloatingActionButton mCancelarFloatingActionButton;
private Long mId;
private ProcessoModel mProcesso;
private ProcessoRegraModel mRegra;
private DigitalizacaoModel mDigitalizacao;
private static final String KEY_ID = ProcessoPesquisaFragment.class.getSimpleName() + ".mId";
public static ProcessoDetalheFragment newInstance(Long id) {
ProcessoDetalheFragment fragment = new ProcessoDetalheFragment();
if (id != null) {
Bundle bundle = new Bundle();
bundle.putLong(KEY_ID, id);
fragment.setArguments(bundle);
}
return fragment;
}
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle bundle = getArguments();
if (bundle != null) {
if (bundle.containsKey(KEY_ID)) {
mId = bundle.getLong(KEY_ID);
}
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_processo_detalhe, container, false);
}
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
ButterKnife.bind(this, view);
prepare();
}
@Override
public void onResume() {
super.onResume();
if (mId != null) {
startAsyncEditarById(mId);
}
}
@Override
public void onClick(View view) {
Object object = view.getTag();
if (object instanceof DocumentoModel) {
DocumentoModel documento = (DocumentoModel) object;
DocumentoDetalheFragment fragment = DocumentoDetalheFragment.newInstance(documento.id);
FragmentUtils.replace(getActivity(), R.id.content_main, fragment, fragment.getBackStackName());
}
}
@OnClick(R.id.button_info)
public void onInfoClick() {
if (mId != null) {
startAsyncDigitalizacaoBy(mId);
}
}
@OnClick(R.id.button_aprovar)
public void onAprovarClick() {
mFloatingActionMenu.close(true);
aprovar();
}
@OnClick(R.id.button_cancelar)
public void onCancelarClick() {
mFloatingActionMenu.close(true);
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity())
.setTitle(R.string.cancelar)
.setMessage(R.string.msg_cancelar_processo)
.setPositiveButton(R.string.sim, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
cancelar();
}
})
.setNegativeButton(R.string.nao, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
});
AlertDialog dialog = builder.create();
dialog.show();
}
private void prepare() {
setTitle(R.string.detalhe);
setRootViewVisibility(View.GONE);
mFloatingActionMenu.setClosedOnTouchOutside(true);
}
private void aprovar() {
if (mId != null) {
TransferenciaFragment fragment = TransferenciaFragment.newInstance(mId);
fragment.setOnTransferenciaListener(this);
FragmentUtils.replace(getActivity(), R.id.content_main, fragment, fragment.getBackStackName());
}
}
private void cancelar() {
if (mId != null) {
startAsyncCancelar(mId);
}
}
private void setRootViewVisibility(int visibility) {
mViewRoot.setVisibility(visibility);
}
private void populate() {
mLayoutFields.removeAllViews();
mLayoutDocumentos.removeAllViews();
mFloatingActionMenu.setVisibility(View.GONE);
mAprovarFloatingActionButton.setEnabled(false);
mCancelarFloatingActionButton.setEnabled(false);
if (mProcesso != null) {
Context context = getContext();
mStatusImageView.setImageResource(mProcesso.status.drawableRes);
FieldUtils.setText(mIdTextView, mProcesso.id);
FieldUtils.setText(mStatusTextView, getString(mProcesso.status.stringRes));
FieldUtils.setText(mDataTextView, mProcesso.dataCriacao, "dd/MM/yyyy HH:mm");
if (mProcesso.coleta != null) {
FieldUtils.setText(mColetaTextView, getString(mProcesso.coleta.stringRes));
}
FieldUtils.setText(mTaxaTextView, mProcesso.taxa);
FieldUtils.setText(mValorLiberadoTextView, mProcesso.valorLiberado);
ArrayList<CampoGrupoModel> gruposCampos = mProcesso.gruposCampos;
if (CollectionUtils.isNotEmpty(gruposCampos)) {
for (CampoGrupoModel grupo : gruposCampos) {
AppGroupReadonlyInputLayout campoGrupoLayout = new AppGroupReadonlyInputLayout(context);
campoGrupoLayout.setOrientation(LinearLayout.VERTICAL);
campoGrupoLayout.setGrupo(grupo);
mLayoutFields.addView(campoGrupoLayout);
}
}
ArrayList<DocumentoModel> documentos = mProcesso.documentos;
if (CollectionUtils.isNotEmpty(documentos)) {
LayoutInflater inflater = LayoutInflater.from(context);
for (DocumentoModel documento : documentos) {
View view = inflater.inflate(R.layout.list_item_documento, null);
DocumentoModel.Status status = documento.status;
ImageView statusImageView = ButterKnife.findById(view, R.id.image_status);
TextView dataTextView = ButterKnife.findById(view, R.id.text_data);
TextView nomeTextView = ButterKnife.findById(view, R.id.text_nome);
TextView statusTextView = ButterKnife.findById(view, R.id.text_status);
TextView documentoTextView = ButterKnife.findById(view, R.id.text_documento);
statusImageView.setImageResource(status.drawableRes);
FieldUtils.setText(dataTextView, documento.dataDigitalizacao);
FieldUtils.setText(nomeTextView, documento.nome);
FieldUtils.setText(statusTextView, getString(status.stringRes));
ChequeModel cheque = documento.cheque;
if (cheque != null) {
FieldUtils.setText(documentoTextView, cheque.cpfCnpj);
}
if (DocumentoModel.Status.PENDENTE.equals(status)) {
View viewPendencia = ButterKnife.findById(view, R.id.view_pendencia);
TextView observacaoTextView = ButterKnife.findById(view, R.id.text_observacao);
TextView irregularidadeTextView = ButterKnife.findById(view, R.id.text_irregularidade);
FieldUtils.setText(observacaoTextView, documento.pendenciaObservacao);
FieldUtils.setText(irregularidadeTextView, documento.irregularidadeNome);
viewPendencia.setVisibility(View.VISIBLE);
}
view.setTag(documento);
view.setOnClickListener(this);
mLayoutDocumentos.addView(view);
}
}
setRootViewVisibility(View.VISIBLE);
mInfoButton.setVisibility(View.GONE);
ProcessoModel.Status status = mProcesso.status;
if (!ProcessoModel.Status.CANCELADO.equals(status)) {
mInfoButton.setVisibility(View.VISIBLE);
startAsyncCheckErrorById(mProcesso.id);
}
if (mRegra != null) {
mAprovarFloatingActionButton.setEnabled(mRegra.podeAprovar);
mCancelarFloatingActionButton.setEnabled(mRegra.podeCancelar);
if (mRegra.podeAprovar || mRegra.podeCancelar) {
mFloatingActionMenu.setVisibility(View.VISIBLE);
}
}
}
}
private void digitalizar() {
String referencia = String.valueOf(mId);
DigitalizacaoModel.Tipo tipo = DigitalizacaoModel.Tipo.TIPIFICACAO;
startDigitalizacaoService(getContext(), tipo, referencia);
Toast.makeText(getContext(), R.string.msg_processo_enviado, Toast.LENGTH_LONG).show();
}
/**
*
* COMPLETED METHODS ASYNCHRONOUS HANDLERS
*
*/
private void onAsyncEditarCompleted(DataSet<ProcessoModel, ProcessoRegraModel> dataSet) {
mRegra = dataSet.meta;
mProcesso = dataSet.data;
populate();
}
private void onAsyncCheckErrorCompleted(Boolean exists) {
if (BooleanUtils.isTrue(exists)) {
String text = getString(R.string.msg_erro_digitalizacao);
Snackbar snackbar = makeSnackbar(text, Snackbar.LENGTH_INDEFINITE);
snackbar.setAction(R.string.abrir, new View.OnClickListener() {
@Override
public void onClick(View v) {
startAsyncDigitalizacaoBy(mId);
}
});
snackbar.show();
}
}
private void onAsyncDigitalizacaoCompleted(DigitalizacaoModel model) {
mDigitalizacao = model;
if (mDigitalizacao == null) {
Toast.makeText(getContext(), R.string.msg_sem_info_digitalizacao, Toast.LENGTH_SHORT).show();
} else {
DigitalizacaoDialog dialog = DigitalizacaoDialog.newInstance(mDigitalizacao, new DigitalizacaoDialog.OnUplodErrorListener() {
@Override
public void onReenviar(boolean answer) {
if (answer) {
digitalizar();
}
}
});
FragmentManager fragmentManager = getFragmentManager();
dialog.show(fragmentManager, dialog.getClass().getSimpleName());
}
}
/**
*
* ASYNCHRONOUS METHODS
*
*/
private void startAsyncEditarById(Long id) {
showProgress();
setRootViewVisibility(View.GONE);
Observable<DataSet<ProcessoModel, ProcessoRegraModel>> observable = ProcessoService.Async.editar(id);
prepare(observable).subscribe(new Subscriber<DataSet<ProcessoModel, ProcessoRegraModel>>() {
@Override
public void onCompleted() {
hideProgress();
}
@Override
public void onError(Throwable e) {
hideProgress();
handle(e);
}
@Override
public void onNext(DataSet<ProcessoModel, ProcessoRegraModel> dataSet) {
hideProgress();
onAsyncEditarCompleted(dataSet);
}
});
}
private void startAsyncCheckErrorById(Long id) {
String referencia = String.valueOf(id);
Observable<Boolean> observable = DigitalizacaoService.Async.existsBy(referencia, DigitalizacaoModel.Tipo.TIPIFICACAO, DigitalizacaoModel.Status.ERRO);
prepare(observable).subscribe(new Subscriber<Boolean>() {
@Override
public void onCompleted() {
}
@Override
public void onError(Throwable e) {
handle(e);
}
@Override
public void onNext(Boolean exists) {
onAsyncCheckErrorCompleted(exists);
}
});
}
private void startAsyncDigitalizacaoBy(Long id) {
String referencia = String.valueOf(id);
Observable<DigitalizacaoModel> observable = DigitalizacaoService.Async.getBy(referencia, DigitalizacaoModel.Tipo.TIPIFICACAO);
prepare(observable).subscribe(new Subscriber<DigitalizacaoModel>() {
@Override
public void onCompleted() {
}
@Override
public void onError(Throwable e) {
handle(e);
}
@Override
public void onNext(DigitalizacaoModel model) {
onAsyncDigitalizacaoCompleted(model);
}
});
}
private void startAsyncCancelar(Long id) {
showProgress();
setRootViewVisibility(View.GONE);
Observable<DataSet<ProcessoModel, ProcessoRegraModel>> observable = ProcessoService.Async.cancelar(id);
prepare(observable).subscribe(new Subscriber<DataSet<ProcessoModel, ProcessoRegraModel>>() {
@Override
public void onCompleted() {
hideProgress();
}
@Override
public void onError(Throwable e) {
hideProgress();
handle(e);
}
@Override
public void onNext(DataSet<ProcessoModel, ProcessoRegraModel> dataSet) {
hideProgress();
onAsyncEditarCompleted(dataSet);
}
});
}
@Override
public void onAprovar(DataSet<ProcessoModel, ProcessoRegraModel> dataSet) {
onAsyncEditarCompleted(dataSet);
}
}
|
package com.wang.aop.common;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
/**
* 序列化工具
* @author wxe
* @since 1.0.0
*/
public abstract class JsonUtils {
public static String toJson(Object o) {
return JSON.toJSONString(o);
}
public static <T> T fromJson(String json, Class<T> clazz) {
return JSON.parseObject(json, clazz);
}
public static <T> T fromJson(String text, TypeReference<T> type) {
return JSON.parseObject(text, type);
}
}
|
package com.zzc2422.push_stones_to_go;
import com.zzc2422.push_stones_to_go.data.Behavior;
public final class TouchEvent {
private final static int MIN_DXY = 10;
public final static TouchEvent INSTANCE = new TouchEvent();
private int downX, downY;
private TouchEvent() {
downX = downY = 0;
}
public void down(int x, int y) {
downX = x;
downY = y;
}
public int up(int upX, int upY) {
int dx = upX - downX, dy = upY - downY,
dxAbs = (dx >= 0 ? dx : -dx), dyAbs = (dy >= 0 ? dy : -dy);
if (dxAbs >= dyAbs && dxAbs >= MIN_DXY) {
return (dx > 0 ? Behavior.RIGHT : Behavior.LEFT);
} else if (dxAbs < dyAbs && dyAbs >= MIN_DXY) {
return (dy > 0 ? Behavior.DOWN : Behavior.UP);
} else {
return Behavior.NO_BEHAVIOR;
}
}
} |
package com.sirma.itt.javacourse.chat.common;
/**
* An message interpreter interface.
*
* @author siliev
*
*/
public interface MessageInterpreter {
public Message generateMessage(MessageType type, long id, String content,
String author);
/**
* Interprets a message by using the {@link TYPE} parameter in
* {@link Message}.
*
* @param message
* the message that is to be interpreted.
* @param user
* the user who sent the message.
*/
void interpretMessage(Message message, ChatUser user);
}
|
package org.webtop.module.polarization;
import org.webtop.x3d.*;
import org.web3d.x3d.sai.*;
public abstract class Filter extends X3DObject {
protected String id;
// Jones-Matrix:
// [ 0 1 ]
// [ 2 3 ]
//
// Ma = amplitude
// Mp = phase
protected final float Ma[]={1,0,0,1},Mp[]={1,0,0,1};
protected float z,angle;
protected NamedNode nodes[];
protected SFInt32 StateEIn;
protected SFFloat AngleEIn,ZEIn;
protected SFBool EnabledEIn;
protected SFBool ZHighlightedEIn;
protected SFBool AngleHighlightedEIn;
protected static final float PI = (float) (Math.PI);
protected static final float PI_2 = (float) (PI * 2.0f);
protected static final float PI_1_2 = (float) (PI/2.0f);
protected static final float PI_3_2 = (float) (PI*3.0f/2.0f);
//private Engine engine;
//private FilterPanel filterPanel;
//public Filter() {
// super(sai, sai.getNode())
//}
public Filter(SAI sai, float z_, float angle_) {
super(sai, sai.getNode("FilterHolder"));
z = z_;
setAngle(angle_, false);
}
public Filter(SAI sai, float z_, float angle_, Filter prev_, Filter next_) {
super(sai, sai.getNode("FilerHolder"));
z = z_;
setAngle(angle_, false);
}
public void setID(String s) {id = s;}
public String getID() {return id;}
//public void setEngine(Engine e) {engine = e;}
//public void setFilterPanel(FilterPanel f) {filterPanel = f;}
public float getZ() {return z;}
public void setZ(float z_, boolean setVRML) {
z = z_;
if(setVRML) ZEIn.setValue(z_);
}
public void setAngle(float angle_) {setAngle(angle_, false);}
public void setAngle(float angle_, boolean setVRML) {
angle = angle_;
if(setVRML) AngleEIn.setValue(angle);
}
public float getAngle() {return angle;}
public void setActive(boolean active) {
if(active) StateEIn.setValue(1);
else StateEIn.setValue(0);
}
public void setEnabled(boolean enabled) {
EnabledEIn.setValue(enabled);
}
public void setAngleHighlighted(boolean highlighted) {
AngleHighlightedEIn.setValue(highlighted);
}
public void setZHighlighted(boolean highlighted) {
ZHighlightedEIn.setValue(highlighted);
}
protected float[] getMatrix() {return (float[])Ma.clone();}
// Transform the electric field vector using the Jones-Matrix.
// The argument 'polarized' may be useful to subclasses.
public void transform(Engine.EVector E, boolean polarized) {
double A1, A2, B1, B2;
double r1, x1, r2, x2;
double sr, sx;
double Ex, Ey, Ax, Ay; // we'll need the old values until the end
// X Component
A1 = E.x * Ma[0];
B1 = E.xphase + Mp[0];
A2 = E.y * Ma[1];
B2 = E.yphase + Mp[1];
r1 = A1 * Math.cos(B1);
x1 = A1 * Math.sin(B1);
r2 = A2 * Math.cos(B2);
x2 = A2 * Math.sin(B2);
sr = r1 + r2;
sx = x1 + x2;
Ex = Math.sqrt(sr*sr + sx*sx);
Ax = Math.atan2(sx, sr);
// Y Component
A1 = E.x * Ma[2];
B1 = E.xphase + Mp[2];
A2 = E.y * Ma[3];
B2 = E.yphase + Mp[3];
r1 = A1 * Math.cos(B1);
x1 = A1 * Math.sin(B1);
r2 = A2 * Math.cos(B2);
x2 = A2 * Math.sin(B2);
sr = r1 + r2;
sx = x1 + x2;
Ey = Math.sqrt(sr*sr + sx*sx);
Ay = Math.atan2(sx, sr);
E.x = (float) Ex;
E.y = (float) Ey;
E.xphase = (float) Ax;
E.yphase = (float) Ay;
}
public NamedNode[] getNodes() {return nodes;}
public NamedNode getNode() {return nodes[0];}
public abstract String getType();
}
|
package sr.hakrinbank.intranet.api.model;
import org.hibernate.envers.Audited;
import javax.persistence.*;
import java.util.Date;
/**
* Created by clint on 8/4/17.
*/
@Entity
@Audited
public class CbvsRates {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@Temporal(TemporalType.TIMESTAMP)
private Date date;
@ManyToOne
private Currency currency;
private Double bankPapierBid;
private Double bankPapierAsk;
private Double resterendBid;
private Double resterendAsk;
@Column(nullable = false, columnDefinition = "TINYINT", length = 1)
private boolean deleted;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
public Double getBankPapierBid() {
return bankPapierBid;
}
public void setBankPapierBid(Double bankPapierBid) {
this.bankPapierBid = bankPapierBid;
}
public Double getBankPapierAsk() {
return bankPapierAsk;
}
public void setBankPapierAsk(Double bankPapierAsk) {
this.bankPapierAsk = bankPapierAsk;
}
public Double getResterendBid() {
return resterendBid;
}
public void setResterendBid(Double resterendBid) {
this.resterendBid = resterendBid;
}
public Double getResterendAsk() {
return resterendAsk;
}
public void setResterendAsk(Double resterendAsk) {
this.resterendAsk = resterendAsk;
}
public boolean isDeleted() {
return deleted;
}
public void setDeleted(boolean deleted) {
this.deleted = deleted;
}
public Currency getCurrency() {
return currency;
}
public void setCurrency(Currency currency) {
this.currency = currency;
}
}
|
package homework3.calcs.simple;
import homework3.calcs.api.ICalculator;
/**
* Создать класс CalculatorWithMathCopy.
* 3.1 Все методы объявленные в данном классе НЕ статические (не имеют модификатор static).
* 3.2 В классе должны присутствовать математические методы:
* 3.2.1 4 базовых математических метода (деление, умножение, вычитание, сложение). Скопировать базовые
* математические операции из CalculatorWithOperator.
* 3.2.2 3 метода (Возведение в целую степень дробного положительного числа, Модуль числа, Корень из числа).
* Данные методы должны содержать в своём теле вызов библиотеки Math и возврат полученного результата.
*
*/
public class CalculatorWithMathCopy implements ICalculator {
// Скопировать базовые математические операции из CalculatorWithOperator.
public double div(double a , double b){
if(b != 0){
return a / b;
}
return -1.0; // деление но ноль невозможно
}
public double mult(double a, double b){
return a * b;
}
public double minus(double a, double b){
return a - b;
}
public double plus(double a , double b){
return a + b;
}
public double pow(double a, int b){
return Math.pow(a, b);
}
public double abs(double a){
return Math.abs(a);
}
public double sqrt(double a){
return Math.sqrt(a);
}
}
|
package org.example.business.user;
import org.example.business.BaseService;
import org.example.common.captcha.CaptchaResponse;
import org.example.common.rest.user.UserLogin;
import org.example.data.model.user.User;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public interface UserService extends BaseService<User> {
CaptchaResponse captcha();
User login(UserLogin request, HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse);
void logout(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse);
}
|
package com.zzh.cloud.controller;
import com.zzh.cloud.entity.User;
import com.zzh.cloud.feign.UserFeignCustomAuthClient;
import com.zzh.cloud.feign.UserFeignCustomClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
/**
* @author zzh
* @version 1.0
* @date 2017/12/11 17:18
*/
@RestController
public class MovieFeignCustomController {
@Autowired
private UserFeignCustomClient userFeignCustomClient;
@Autowired
private UserFeignCustomAuthClient userFeignCustomAuthClient;
@GetMapping("/movie/{id}")
public User findById(@PathVariable Long id) {
return userFeignCustomClient.findById(id);
}
@GetMapping("/{serviceName}")
public String findEurekaInfo(@PathVariable String serviceName){
return userFeignCustomAuthClient.findEurekaInfo(serviceName);
}
}
|
//вывод самой длинной последовательности повторяющихся чисел (из введеных 10)
package Tasks;
import java.io.*;
import java.util.*;
public class Task6 {
public static void main(String[] args) throws IOException{
// BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
Scanner scanner = new Scanner(System.in);
ArrayList<Integer> list = new ArrayList<Integer>();
int num = 1;
int b = 0;
int a = scanner.nextInt();
list.add(a);
for(int i = 0, n = 1; i < 9; i++){
b = scanner.nextInt();
list.add(b);
if(a == b){
++n;
}
else{
n = 1;
}
a = b;
if(n > num) {
num = n;
}
}
System.out.println(num);
}
}
|
package models;
import javax.swing.table.AbstractTableModel;
import java.util.Arrays;
import java.util.Vector;
public class NPVTableModel extends AbstractTableModel {
public static final int PERIOD_COLUMN = 0;
public static final int NPV_COLUMN = 6;
private Vector<String> columnNames = new Vector<>(Arrays.asList(
"Период",
"Доходы, тыс. руб.",
"Затраты, тыс. руб.",
"Инвестиции, тыс. руб.",
"Денежные потоки, тыс. руб.",
"Дисконтированные денежные потоки, тыс. руб.",
"Дисконтированные денежные потоки нарастающим итогом, тыс. руб."
));
private Vector<Object []> data;
private double discountRate;
private int period;
public NPVTableModel(double discount, double investments) {
discountRate = discount;
period = 0;
data = new Vector<>();
data.add(new Object[] {period, 0, 0, investments, investments, investments, investments});
}
public void addRow(double incomes, double expenses) {
double lastCumulativeCashFlows = (double) data.get(period)[columnNames.size() - 1];
period++;
double cashFlows = incomes - expenses;
double discountedCashFlows = cashFlows / Math.pow(1 + discountRate, period);
double cumulativeCashFlows = lastCumulativeCashFlows + discountedCashFlows;
data.add(new Object[] {
period,
incomes,
expenses,
0,
cashFlows,
discountedCashFlows,
cumulativeCashFlows
});
fireTableDataChanged();
}
public double getNPV() {
return (double) data.get(period)[columnNames.size() - 1];
}
public Vector<Double> getColumn(int index) {
Vector<Double> values = new Vector<>();
for (Object[] row : data) {
Double value = Double.valueOf(row[index].toString());
values.add(value);
}
return values;
}
@Override
public int getRowCount() {
return data.size();
}
@Override
public int getColumnCount() {
return columnNames.size();
}
@Override
public String getColumnName(int column) {
return columnNames.get(column);
}
@Override
public Object getValueAt(int rowIndex, int columnIndex) {
return data.get(rowIndex)[columnIndex];
}
@Override
public boolean isCellEditable(int rowIndex, int columnIndex) {
return false;
}
@Override
public Class<?> getColumnClass(int columnIndex) {
return getValueAt(0, columnIndex).getClass();
}
}
|
package com.gy.service.impl;
import com.gy.entity.Mylog;
import com.gy.entity.WorkOrder;
import com.gy.mapper.MylogMapper;
import com.gy.mapper.TyreMapper;
import com.gy.mapper.WorkOrderMapper;
import com.gy.service.WorkOrderService;
import com.gy.util.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import java.util.Date;
import java.util.List;
/**
* @Author: liumin
* @Description:
* @Date: Created in 2018/4/9 9:48
*/
@Service
public class WorkOrderServiceImpl implements WorkOrderService{
@Autowired
private RedisUtil redisUtil;
@Autowired
private WorkOrderMapper workOrderMapper;
@Autowired
private TyreMapper tyreMapper;
@Autowired
private MylogMapper mylogMapper;
@Override
@Transactional
public ResultObject workOrder(String tyreId, String installPlace, String carNo, String problem, String token) {
ResultObject ro = new ResultObject();
//根据token获取缓存中的用户id(id字段)
String operator=redisUtil.getRedisUserId(token);
if(EmptyUtils.isEmpty(operator)){//查看该token对应的用户是否存在,不存在则return,且提示500
ro.setCode(Constant.RESULT_CODE_LOGIN);
ro.setMessage(Constant.RESULT_MESSAGE_LOGIN);
return ro;
}
try {
if(workOrderMapper.insertWorkOrder(new Date().getTime()+"",operator,tyreId,installPlace,carNo,problem)>0){
if(tyreMapper.updateStatus(tyreId,Constant.TYRE_STATUS_YES)>0){
ro.setCode(Constant.RESULT_CODE_SUCCESS);
ro.setMessage(Constant.RESULT_MESSAGE_SUCCESS);
//记录日记
mylogMapper.addMyLog(MylogUtil.getMylog(new Date().getTime() + "", operator, Constant.MYLOG_MESSAGE_CHECK_WORKORDER,
Constant.MYLOG_TYPE_CHECK_WORKORDER, tyreId));
}else {
ro.setCode(Constant.RESULT_CODE_ERROR);
ro.setMessage(Constant.RESULT_MESSAGE_ERROR);
TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
}
}else{
ro.setCode(Constant.RESULT_CODE_ERROR);
ro.setMessage(Constant.RESULT_MESSAGE_ERROR);
}
}catch (Exception e){
e.printStackTrace();
TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
ro.setMessage(Constant.RESULT_MESSAGE_ERROR);
ro.setCode(Constant.RESULT_CODE_ERROR);
}
return ro;
}
@Override
public ResultObject list(String tyreId, String carNo) {
ResultObject ro = new ResultObject();
WorkOrder wo = new WorkOrder();
if(EmptyUtils.isNotEmpty(tyreId)){
wo.setTyreId(tyreId);
}
if(EmptyUtils.isNotEmpty(carNo)) {
wo.setCarNo(carNo);
}
List<WorkOrder> workOrderList = workOrderMapper.findList(wo);
ro.setCode(Constant.RESULT_CODE_SUCCESS);
ro.setMessage(Constant.RESULT_MESSAGE_SUCCESS);
ro.setData(workOrderList);
return ro;
}
@Override//记得还要修改轮胎的状态
public ResultObject deal(String id, String result,String token) {
ResultObject ro = new ResultObject();
//根据token获取缓存中的用户id(id字段)
String operator=redisUtil.getRedisUserId(token);
if(EmptyUtils.isEmpty(operator)){//查看该token对应的用户是否存在,不存在则return,且提示500
ro.setCode(Constant.RESULT_CODE_LOGIN);
ro.setMessage(Constant.RESULT_MESSAGE_LOGIN);
return ro;
}
if(workOrderMapper.updateResult(id,result)>0){
ro.setCode(Constant.RESULT_CODE_SUCCESS);
ro.setMessage(Constant.RESULT_MESSAGE_SUCCESS);
//记录日记
mylogMapper.addMyLog(MylogUtil.getMylog(new Date().getTime() + "", operator, Constant.MYLOG_MESSAGE_DEAL_WORKORDER,
Constant.MYLOG_TYPE_DEAL_WORKORDER, id));
}else{
ro.setCode(Constant.RESULT_CODE_ERROR);
ro.setMessage(Constant.RESULT_MESSAGE_ERROR);
}
return ro;
}
}
|
package selenium;
import selenium.helpers.SeleniumHelpersAnswers;
import org.junit.*;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import selenium.pages.*;
public class Iteration3Exercises {
private WebDriver driver;
private SeleniumHelpersAnswers selenium = new SeleniumHelpersAnswers();
@Before
public void startBrowser() {
System.setProperty("webdriver.chrome.driver", "src/test/resources/drivers/chromedriver.exe");
driver = new ChromeDriver();
driver.manage().window().maximize();
}
@Test
public void DoLoanRequest_UsingAmountsBeyondLimits_ShouldBeDenied() {
new ParabankLoginPage(driver).
load().
loginAs("john", "demo");
new ParabankAccountsOverviewPageAnswers(driver).
selectMenuItem("Request Loan");
// Fill in form to request loan
// TODO: Complete exercises 1-5 in pages.ParabankLoanApplicationPageExercises
// TODO: Refactor the methods below so that the applyForLoan() method in the Page Object is used
selenium.sendKeys(driver, By.id("amount"), "1000");
selenium.sendKeys(driver, By.id("downPayment"), "100");
selenium.select(driver, By.id("fromAccountId"), "54321");
selenium.click(driver, By.xpath("//input[@value='Apply Now']"));
// Verify feedback
// TODO: Complete exercise 6 in pages.ParabankLoanApplicationPageExercises
// TODO: Refactor the methods below so that the getApplicationResult() method in the Page Object is used
String actualStatus = selenium.getElementText(driver, By.id("loanStatus"));
Assert.assertEquals("Denied", actualStatus);
}
@After
public void closeBrowser() {
driver.quit();
}
}
|
/*
* Created on Nov 9, 2004 by Ming Chow
*
* RCX code for telerobotics sample: starts and stops motor
*/
import josx.platform.rcx.*;
import josx.rcxcomm.*;
import java.io.*;
public class MotorControl1RCX
{
// Constant for the power level of the motor
// 7 is the maximum power level, and most powerful/fastest
private static final int powerLevel=2;
public static void main(String[] args)
{
rcxReceive();
}
private static void rcxReceive()
{
RCXPort port;
InputStream in;
int cmd;
try
{
// Opens communication to IR tower
port=new RCXPort();
in=port.getInputStream();
while (true)
{
// The RCX listens to inputs (0/1 sent from PC)
cmd=in.read();
setMotorAction(cmd);
}
}
catch (IOException ioe) {};
}
private static void setMotorAction(int actionFlag)
{
// If the signal sent from the PC is the number 1, then turn on the motor
if (actionFlag==1)
{
Motor.C.setPower(powerLevel);
Motor.C.forward();
}
else
// The signal sent from the PC is the number 0
Motor.C.stop();
}
}
|
package kr.co.magiclms.domain;
import java.util.Date;
public class Review {
// 리뷰번호
private int reviewNo;
// 상품목록번호
private int goodsNo;
// 리뷰생성날짜
private Date reviewRegDate;
// 회원아이디
private String memberId;
// 리뷰평점
private String reviewPoint;
// 리뷰내용
private String reviewContent;
public int getReviewNo() {
return reviewNo;
}
public void setReviewNo(int reviewNo) {
this.reviewNo = reviewNo;
}
public int getGoodsNo() {
return goodsNo;
}
public void setGoodsNo(int goodsNo) {
this.goodsNo = goodsNo;
}
public Date getReviewRegDate() {
return reviewRegDate;
}
public void setReviewRegDate(Date reviewRegDate) {
this.reviewRegDate = reviewRegDate;
}
public String getMemberId() {
return memberId;
}
public void setMemberId(String memberId) {
this.memberId = memberId;
}
public String getReviewPoint() {
return reviewPoint;
}
public void setReviewPoint(String reviewPoint) {
this.reviewPoint = reviewPoint;
}
public String getReviewContent() {
return reviewContent;
}
public void setReviewContent(String reviewContent) {
this.reviewContent = reviewContent;
}
}
|
package com.vivek.sampleapp.modal;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.List;
/**
* Created by vivek-pc on 12/12/2015.
*/
@JsonIgnoreProperties(ignoreUnknown=true)
public class News {
Pagination Pagination;
List<NewsItem> NewsItem;
public com.vivek.sampleapp.modal.Pagination getPagination() {
return Pagination;
}
@JsonProperty("Pagination")
public void setPagination(com.vivek.sampleapp.modal.Pagination pagination) {
Pagination = pagination;
}
public List<com.vivek.sampleapp.modal.NewsItem> getNewsItem() {
return NewsItem;
}
@JsonProperty("NewsItem")
public void setNewsItem(List<com.vivek.sampleapp.modal.NewsItem> newsItem) {
NewsItem = newsItem;
}
}
|
package com.thomson.dp.principle.zen.lsp.domain;
/**
* 实现两数相加
*
* @author Thomson Tang
*/
public class Operation {
public int m1(int a, int b) {
return a + b;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.