text
stringlengths
10
2.72M
package com.ymhd.main; import android.content.Intent; import android.graphics.Color; import android.os.Bundle; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.RadioButton; import android.widget.RadioGroup; import android.widget.RadioGroup.OnCheckedChangeListener; import com.amap.api.location.AMapLocation; import com.amap.api.location.AMapLocationClient; import com.amap.api.location.AMapLocationClientOption; import com.amap.api.location.AMapLocationClientOption.AMapLocationMode; import com.amap.api.location.AMapLocationListener; import com.amap.api.maps2d.AMap; import com.amap.api.maps2d.AMap.OnMapLoadedListener; import com.amap.api.maps2d.AMap.OnMarkerClickListener; import com.amap.api.maps2d.CameraUpdateFactory; import com.amap.api.maps2d.LocationSource; import com.amap.api.maps2d.MapView; import com.amap.api.maps2d.model.BitmapDescriptorFactory; import com.amap.api.maps2d.model.LatLng; import com.amap.api.maps2d.model.Marker; import com.amap.api.maps2d.model.MarkerOptions; import com.amap.api.maps2d.model.MyLocationStyle; import com.example.mifen.R; import com.ymhd.mifei.listadapter.nearbylistadapter; import java.util.ArrayList; import java.util.List; //本页具体操作方法,详见高德地图api public class nearbypage extends baseActivity implements OnMapLoadedListener, OnMarkerClickListener, LocationSource, AMapLocationListener { private LinearLayout nearby_lin, nearby_line; private View view_list, view_map; private ListView nearbyforlistinfo; private nearbylistadapter nearbylistadapter; private List<String> list; private LayoutInflater minflater; private RadioButton rad_list, rad_map; private Button busline_btn, walkline_btn, driveline_btn; private AMap aMap; private MapView mapView; private OnLocationChangedListener mListener; private AMapLocationClient mlocationClient; private AMapLocationClientOption mLocationOption; private Marker marker; private AMapLocation amapLocation; private LatLng start; @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.nearby); minflater = LayoutInflater.from(this); init(); //初始化控件界面 initlist(); //初始化界面中列表 mapView = (MapView) view_map.findViewById(R.id.map); mapView.onCreate(savedInstanceState);// 此方法必须重写 initMapLoction(); //初始化地图定位 // mlocationClient = new AMapLocationClient(this.getApplicationContext()); // mLocationOption = new AMapLocationClientOption(); // // 设置定位监听 // mlocationClient.setLocationListener(this); // // 设置低精度定位 // mLocationOption.setLocationMode(AMapLocationMode.Battery_Saving); // // 设置定位参数 // mlocationClient.setLocationOption(mLocationOption); // // 启动定位 // mlocationClient.startLocation(); // addMarkersToMap(); } /* * 初始化地图显示 * */ public void initMap(){ } public void init() { view_list = minflater.inflate(R.layout.nearbyforlist, null); view_map = minflater.inflate(R.layout.nearbyformap, null); nearby_line = (LinearLayout) view_map.findViewById(R.id.near_line); nearby_line.setVisibility(View.GONE); // 隐藏导航方式 nearby_lin = (LinearLayout) findViewById(R.id.nearby_lin); nearbyforlistinfo = (ListView) view_list.findViewById(R.id.nearby_listinfo); busline_btn = (Button) view_map.findViewById(R.id.busline); driveline_btn = (Button) view_map.findViewById(R.id.driveline); walkline_btn = (Button) view_map.findViewById(R.id.walkline); busline_btn.setOnClickListener(itemsOnClick); driveline_btn.setOnClickListener(itemsOnClick); walkline_btn.setOnClickListener(itemsOnClick); nearby_lin.addView(view_list); rad_list = (RadioButton) findViewById(R.id.radio_list); rad_map = (RadioButton) findViewById(R.id.radio_map); RadioGroup group = (RadioGroup) this.findViewById(R.id.radioGroup1); group.setOnCheckedChangeListener(new OnCheckedChangeListener() { @Override public void onCheckedChanged(RadioGroup group, int checkedId) { // TODO Auto-generated method stub // 获取变更后的选中项的ID int radioButtonId = group.getCheckedRadioButtonId(); // 根据ID获取RadioButton的实例 RadioButton rb = (RadioButton) nearbypage.this.findViewById(radioButtonId); switch (radioButtonId) { case R.id.radio_list: nearby_lin.removeAllViews(); nearby_lin.addView(view_list); break; case R.id.radio_map: nearby_lin.removeAllViews(); nearby_lin.addView(view_map); break; default: break; } } }); } public void initlist() { list = new ArrayList<String>(); list.add("1"); list.add("1"); list.add("1"); list.add("1"); list.add("1"); list.add("1"); list.add("1"); nearbylistadapter = new nearbylistadapter(list, this, itemsOnClick); nearbyforlistinfo.setAdapter(nearbylistadapter); } public void initMapLoction() { if (aMap == null) { aMap = mapView.getMap(); setUpMap(); } } /** * 设置一些amap的属性 */ private void setUpMap() { // 自定义系统定位小蓝点 MyLocationStyle myLocationStyle = new MyLocationStyle(); myLocationStyle.myLocationIcon(BitmapDescriptorFactory.fromResource(R.drawable.location_marker));// 设置小蓝点的图标 myLocationStyle.strokeColor(Color.BLACK);// 设置圆形的边框颜色 myLocationStyle.radiusFillColor(Color.argb(100, 0, 0, 180));// 设置圆形的填充颜色 // myLocationStyle.anchor(int,int)//设置小蓝点的锚点 myLocationStyle.strokeWidth(1.0f);// 设置圆形的边框粗细 aMap.setMyLocationStyle(myLocationStyle); aMap.setLocationSource(this);// 设置定位监听 aMap.getUiSettings().setMyLocationButtonEnabled(true);// 设置默认定位按钮是否显示 aMap.setMyLocationEnabled(true);// 设置为true表示显示定位层并可触发定位,false表示隐藏定位层并不可触发定位,默认是false // aMap.setMyLocationType() aMap.setOnMarkerClickListener(this);// 设置点击marker事件监听器 // CameraUpdateFactory.zoomTo(15); aMap.moveCamera(CameraUpdateFactory.zoomTo(12)); } /** * 方法必须重写 */ @Override protected void onResume() { super.onResume(); mapView.onResume(); } /** * 方法必须重写 */ @Override protected void onPause() { super.onPause(); mapView.onPause(); deactivate(); } /** * 方法必须重写 */ @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); mapView.onSaveInstanceState(outState); } /** * 方法必须重写 */ @Override protected void onDestroy() { super.onDestroy(); mapView.onDestroy(); } /** * 定位成功后回调函数 */ @Override public void onLocationChanged(AMapLocation amapLocation) { if (mListener != null && amapLocation != null) { if (amapLocation != null && amapLocation.getErrorCode() == 0) { this.amapLocation = amapLocation; mListener.onLocationChanged(amapLocation);// 显示系统小蓝点 start = new LatLng(amapLocation.getLatitude(), amapLocation.getLongitude()); Log.e("onLocationChanged: ",amapLocation+""); // LatLng end = new LatLng(30.651865197817393, 104.18533690345772); // float x = AMapUtils.calculateLineDistance(start, end); // Log.e("Location", amapLocation.getProvince() + amapLocation.getAccuracy() + amapLocation.getLongitude() // + amapLocation.getLatitude() + "xxx" + x); } else { String errText = "定位失败," + amapLocation.getErrorCode() + ": " + amapLocation.getErrorInfo(); Log.e("AmapErr", errText); } } } /** * 激活定位 */ @Override public void activate(OnLocationChangedListener listener) { Log.d("tag", "activate: 1111111111111111"); mListener = listener; if (mlocationClient == null) { mlocationClient = new AMapLocationClient(this); mLocationOption = new AMapLocationClientOption(); // 设置定位监听 mlocationClient.setLocationListener(this); // 设置为高精度定位模式 mLocationOption.setLocationMode(AMapLocationMode.Hight_Accuracy); // 设置定位参数 mlocationClient.setLocationOption(mLocationOption); // 此方法为每隔固定时间会发起一次定位请求,为了减少电量消耗或网络流量消耗, // 注意设置合适的定位时间的间隔(最小间隔支持为2000ms),并且在合适时间调用stopLocation()方法来取消定位请求 // 在定位结束后,在合适的生命周期调用onDestroy()方法 // 在单次定位情况下,定位无论成功与否,都无需调用stopLocation()方法移除请求,定位sdk内部会移除 mlocationClient.startLocation(); } } /** * 停止定位 */ @Override public void deactivate() { mListener = null; if (mlocationClient != null) { mlocationClient.stopLocation(); mlocationClient.onDestroy(); } mlocationClient = null; } // 实现监听类 private OnClickListener itemsOnClick = new OnClickListener() { public void onClick(View v) { Log.d("tag", "onClick: 222222222222222"); Intent in; switch (v.getId()) { case R.id.btngohere: nearby_lin.removeAllViews(); nearby_lin.addView(view_map); rad_list.setChecked(false); rad_map.setChecked(true); break; case R.id.busline: in = new Intent(nearbypage.this, TwoDemisonAcitivity.class); in.putExtra("stype", "0"); in.putExtra("NaviLatLng", start.latitude + "," + start.longitude ); startActivity(in); break; case R.id.driveline: in = new Intent(nearbypage.this, TwoDemisonAcitivity.class); in.putExtra("stype", "1"); in.putExtra("NaviLatLng", start.latitude + "," + start.longitude ); startActivity(in); break; case R.id.walkline: in = new Intent(nearbypage.this, TwoDemisonAcitivity.class); in.putExtra("stype", "2"); in.putExtra("NaviLatLng", start.latitude + "," + start.longitude ); startActivity(in); break; // case R.id.btn_pick_photo: // break; default: break; } } }; LatLng end = new LatLng(30.651865197817393, 104.18533690345772); /** * 在地图上添加marker */ private void addMarkersToMap() { drawMarkers(end);// 添加n个带有系统默认icon的marker } /** * 绘制系统默认的1种marker背景图片 */ public void drawMarkers(LatLng end) { marker = aMap.addMarker(new MarkerOptions().position(end).snippet("") .icon(BitmapDescriptorFactory.defaultMarker(R.drawable.localtion)).draggable(false)); } /** * 对marker标注点点击响应事件 */ int temp = 0; @Override public boolean onMarkerClick(final Marker marker) { if (temp == 0) { marker.hideInfoWindow(); temp = 1; nearby_line.setVisibility(View.GONE); } else { temp = 0; marker.showInfoWindow(); nearby_line.setVisibility(View.VISIBLE); } return true; } /** * 监听amap地图加载成功事件回调 */ @Override public void onMapLoaded() { // 设置中心点和缩放比例 aMap.moveCamera(CameraUpdateFactory.changeLatLng(start)); } }
package io.pivotal.pcc.ri.mwld.repository; import io.pivotal.pcc.ri.mwld.model.gf.Item; import org.springframework.data.gemfire.repository.GemfireRepository; public interface ItemRepository extends GemfireRepository<Item, String> { }
package mw.wspolne.zdarzenia.publikacja; import mw.wspolne.zdarzenia.bazowe.ZdarzenieBazowe; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationEventPublisher; import org.springframework.context.ApplicationEventPublisherAware; import org.springframework.stereotype.Component; /** * Created by mw on 19.08.16. */ @Component public class PublikujacyZdarzeniaBean implements ApplicationEventPublisherAware { @Autowired public PublikujacyZdarzeniaBean(ApplicationEventPublisher publisher) { this.publisher = publisher; } private ApplicationEventPublisher publisher; @Override public void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) { this.publisher = publisher; } public void publikujZdarzenie(ZdarzenieBazowe aZdarzenie){ publisher.publishEvent(aZdarzenie); } }
package com.hhdb.csadmin.plugin.tree.ui; import javax.swing.JTextArea; import javax.swing.text.AttributeSet; import javax.swing.text.BadLocationException; import javax.swing.text.PlainDocument; public class BaseTextArea extends JTextArea { private static final long serialVersionUID = 1L; public BaseTextArea(int length) { setDocument(new LimitNumDocument(length)); init(); } public void setRowAsColumn(int rows, int columns) { setRows(rows); setColumns(columns); } private void init() { setLineWrap(true);// 激活自动换行功能 setWrapStyleWord(true);// 激活断行不断字功能 } private class LimitNumDocument extends PlainDocument { /** * */ private static final long serialVersionUID = 1L; private int fLength = -1; // 可任意输入 public LimitNumDocument(int length) { fLength = length; } public void insertString(int offs, String str, AttributeSet attr) throws BadLocationException { int originalLength = getLength(); if (originalLength <= 0) { super.insertString(offs, str, attr); return; } char[] input = str.toCharArray(); int inputLength = 0; for (int i = 0; i < input.length; i++) { if (originalLength + inputLength >= fLength) { break; } inputLength++; } super.insertString(offs, new String(input, 0, inputLength), attr); } } }
package se.eskilson.buildengine.filemonitor; import java.util.Date; public class FileEvent { static public enum Action { Appeared, // A file/directory is discovered Modified, Disappeared; }; private final Action action; private final IMonitoredFile file; private final Date timeStamp; public FileEvent(IMonitoredFile file, Action action) { this.action = action; this.file = file; this.timeStamp = new Date(); } public Action getAction() { return action; } public IMonitoredFile getMonitoredFile() { return file; } public Date getTimeStamp() { return timeStamp; } @Override public String toString() { return String.format("FileEvent<%s, %s, event-timestamp=%s>", action, file, timeStamp); } }
package com.zl.pojo; import com.fasterxml.jackson.annotation.JsonFormat; import org.springframework.format.annotation.DateTimeFormat; import java.util.Date; public class DealerDO { private String dealerId; private String dealerName; private String dealerPhone; private String dealerAddress; private Integer dealerStatus; @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") //将String转换成Date,一般前台给后台传值时用 @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8") //将Date转换成String,一般后台传值给前台时 private Date dealerTime; public String getDealerId() { return dealerId; } public void setDealerId(String dealerId) { this.dealerId = dealerId == null ? null : dealerId.trim(); } public String getDealerName() { return dealerName; } public void setDealerName(String dealerName) { this.dealerName = dealerName == null ? null : dealerName.trim(); } public String getDealerPhone() { return dealerPhone; } public void setDealerPhone(String dealerPhone) { this.dealerPhone = dealerPhone == null ? null : dealerPhone.trim(); } public String getDealerAddress() { return dealerAddress; } public void setDealerAddress(String dealerAddress) { this.dealerAddress = dealerAddress == null ? null : dealerAddress.trim(); } public Integer getDealerStatus() { return dealerStatus; } public void setDealerStatus(Integer dealerStatus) { this.dealerStatus = dealerStatus; } public Date getDealerTime() { return dealerTime; } public void setDealerTime(Date dealerTime) { this.dealerTime = dealerTime; } @Override public String toString() { return "DealerDO{" + "dealerId='" + dealerId + '\'' + ", dealerName='" + dealerName + '\'' + ", dealerPhone='" + dealerPhone + '\'' + ", dealerAddress='" + dealerAddress + '\'' + ", dealerStatus=" + dealerStatus + ", dealerTime=" + dealerTime + '}'; } }
package StaticProxy; import java.text.ParseException; import java.text.SimpleDateFormat; import java.time.LocalDate; import java.time.Period; import java.util.*; /** * @Auther: liuyi * @Date: 2019/6/21 16:09 * @Description: */ public class test { public static void main(String[] args) throws ParseException { int[] a = {2,4,1,3,5}; Arrays.sort(a); for(int i=0;i<a.length;i++) { System.out.println(a[i]); } ArrayList<Integer> arrayList = new ArrayList<Integer>(Arrays.asList()); arrayList.sort((o1, o2) -> { if(o1>o2){ return 1; }else if(o1<o2){ return -1; } return 0; }); String str="2"; int a3 = str.charAt(0)-'0'; CountProxy countProxy1 = new CountProxy(new CountImpl()); CountProxy countProxy2 = new CountProxy(new CountImpl2()); countProxy1.queryCount(); countProxy1.updateCount(); countProxy2.queryCount(); countProxy2.updateCount(); System.out.println(); LocalDate now = LocalDate.now(); LocalDate old = LocalDate.of(2019,6,1); Period p = Period.between(old,now); int diffYear = p.getYears(); int diffMonth = p.getMonths(); int diffDay = p.getDays(); System.out.println("年:"+diffYear+"月:"+diffMonth+"日:"+ diffDay); SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd"); Date oriDate = simpleDateFormat.parse("2019-06-01"); System.out.println(oriDate); Calendar calendar = Calendar.getInstance(); Date current = simpleDateFormat.parse("2019-07-09"); System.out.println(current); long diff = (current.getTime()-oriDate.getTime())/(24*3600*1000); System.out.println(diff); calendar.setTime(oriDate); int count=0; for(long i=0;i<=diff;i++){ count++; System.out.println("循环:"+count+"日期:"+ simpleDateFormat.format(calendar.getTime())); calendar.add(Calendar.DATE,1); } } }
package com.jgermaine.fyp.android_client.model; /** * Created by jason on 01/02/15. */ public class Employee extends User{ private String firstName; private String lastName; private String phoneNum; private Report report; private String reportId; public String getDeviceId() { return deviceId; } public void setDeviceId(String deviceId) { this.deviceId = deviceId; } private String deviceId; private double longitude, latitude; public Employee() { } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getReportId() { return reportId; } public void setReportId(String reportId) { this.reportId = reportId; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public String getPhoneNum() { return phoneNum; } public void setPhoneNum(String phoneNum) { this.phoneNum = phoneNum; } public Report getReport() { return report; } public void setReport(Report report) { this.report = report; } public double getLongitude() { return longitude; } public void setLongitude(double longitude) { this.longitude = longitude; } public double getLatitude() { return latitude; } public void setLatitude(double latitude) { this.latitude = latitude; } }
public class CampLunch { private long MOD = 1000000007; public int count(int N, int M, String[] a) { int[][] seating = new int[N][M]; for(int i = 0; i < seating.length; ++i) { for(int j = 0; j < seating[i].length; ++j) { seating[i][j] = a[i].charAt(j) - 'A'; } } long[][][] dp = new long[N + 1][M][1 << M]; dp[0][0][0] = 1; //seen = new boolean[1 << M][N][M]; for(int day = 0; day < N; ++day) { for(int seat = 0; seat < M; ++seat) { int current = seating[day][seat]; for(int mask = 0; mask < dp[day][seat].length; ++mask) { //allready filled if((mask & (1 << current)) != 0) { if(seat + 1 < M) { dp[day][seat + 1][mask ^ (1 << current)] += dp[day][seat][mask]; dp[day][seat + 1][mask ^ (1 << current)] %= MOD; } else { dp[day + 1][0][mask ^ (1 << current)] += dp[day][seat][mask]; dp[day + 1][0][mask ^ (1 << current)] %= MOD; } } else { //double lunch two people if(seat + 1 < M) { int next = seating[day][seat + 1]; if((mask & (1 << next)) == 0) { dp[day][seat + 1][mask | (1 << next)] += dp[day][seat][mask]; dp[day][seat + 1][mask | (1 << next)] %= MOD; } //double lunch single person if(day + 1 < N) { dp[day][seat + 1][mask | (1 << current)] += dp[day][seat][mask]; dp[day][seat + 1][mask | (1 << current)] %= MOD; } //single lunch dp[day][seat + 1][mask] += dp[day][seat][mask]; dp[day][seat + 1][mask] %= MOD; } else { //double lunch single person if(day + 1 < N) { dp[day + 1][0][mask | (1 << current)] += dp[day][seat][mask]; dp[day + 1][0][mask | (1 << current)] %= MOD; } //single lunch dp[day + 1][0][mask] += dp[day][seat][mask]; dp[day + 1][0][mask] %= MOD; } } } } } return (int)dp[N][0][0]; } }
package me.itzg.ghrelwatcher.model; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import org.junit.Test; import org.springframework.core.io.ClassPathResource; import java.io.IOException; import static org.junit.Assert.*; /** * @author Geoff Bourne * @since Jul 2018 */ public class GithubViewerLoginTest { @Test public void testParsing() throws IOException { final ObjectMapper objectMapper = new ObjectMapper(); final ClassPathResource resource = new ClassPathResource("from-github/viewer-login.json"); final JsonNode queryResult = objectMapper.readValue(resource.getFile(), JsonNode.class); final JsonNode loginNode = queryResult.path("data").path("viewer").path("login"); assertFalse(loginNode.isMissingNode()); final String login = loginNode.asText(); assertEquals("itzg", login); } }
/* * Created on Mar 2, 2007 * * * Window - Preferences - Java - Code Style - Code Templates */ package com.citibank.ods.modules.client.customerprvtcmpl.form; import javax.servlet.http.HttpServletRequest; import org.apache.struts.action.ActionErrors; import org.apache.struts.action.ActionMapping; import com.citibank.ods.common.util.ODSValidator; import com.citibank.ods.modules.client.customerprvtcmpl.functionality.valueobject.CustomerPrvtCmplHistoryDetailFncVO; /** * @author bruno.zanetti * * * Window - Preferences - Java - Code Style - Code Templates * @generated "UML to Java (com.ibm.xtools.transform.uml2.java.internal.UML2JavaTransform)" */ public class CustomerPrvtCmplHistoryDetailForm extends BaseCustomerPrvtCmplDetailForm implements CustomerPrvtCmplDetailable { private String m_custRefDate; /** * @return Returns custRefDate. */ public String getCustRefDate() { return m_custRefDate; } /** * @param custRefDate_ Field custRefDate to be setted. */ public void setCustRefDate( String custRefDate_ ) { m_custRefDate = custRefDate_; } /* * Realiza as validações de tipos e tamanhos */ public ActionErrors validate( ActionMapping actionMapping_, HttpServletRequest request_ ) { ActionErrors errors = super.validate (actionMapping_, request_ ); ODSValidator.validateDate( CustomerPrvtCmplHistoryDetailFncVO.C_CUST_REF_DATE_DESCRIPTION, m_custRefDate, errors ); return errors; } }
package api.valorevaluacion; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import java.util.List; @RestController @RequestMapping({"valorevaluacion"}) public class RestControladorValorEvaluacion { @Autowired private ServicioValorEvaluacion servicioValorEvaluacion; /** * Este método corresponde al RF20. Adicionar Año Docente. * * @param valorEvaluacion * @return {@link EntidadValorEvaluacion} */ @PostMapping public EntidadValorEvaluacion adicionarProvincia(@RequestBody EntidadValorEvaluacion valorEvaluacion) { return servicioValorEvaluacion.guardar(valorEvaluacion); } /** * Este método corresponde al RF21. Mostrar año docente. * * @param id * @return {@link EntidadValorEvaluacion} */ @GetMapping(path = {"{id}"}) public ResponseEntity<EntidadValorEvaluacion> mostrarValorEvaluacion(@PathVariable int id) { return servicioValorEvaluacion.obtenerPorId(id) .map(record -> ResponseEntity.ok(record)) .orElse(ResponseEntity.notFound().build()); } /** * Este método corresponde al RF22. Editar año docente * * @param * @param valorEvaluacion * @return {@link EntidadValorEvaluacion} */ @PutMapping(path = "{id}") public ResponseEntity<EntidadValorEvaluacion> editarNombreAnno(@PathVariable int id, @RequestBody EntidadValorEvaluacion valorEvaluacion) { return servicioValorEvaluacion.actualizar(id, valorEvaluacion) .map(record -> ResponseEntity.ok(record)) .orElse(ResponseEntity.notFound().build()); } /** * Este método corresponde al RF23. Eliminar año docente * * @param id * @return {@link EntidadValorEvaluacion} */ @DeleteMapping(path = "{id}") public ResponseEntity<EntidadValorEvaluacion> eliminarValorEvaluacion(@PathVariable int id) { return servicioValorEvaluacion.eliminar(id) .map(record -> ResponseEntity.ok(record)) .orElse(ResponseEntity.notFound().build()); } /** * Este método corresponde al RF24. Mostrar listado de años docentes * * @return */ @GetMapping public List<EntidadValorEvaluacion> mostrarValorEvaluacion() { return servicioValorEvaluacion.listarTodos(); } }
package hr.fer.aoc; import java.util.HashSet; import java.util.Scanner; import java.util.Set; public class Day3 { public static void main(String[] args) { Scanner sc = new Scanner(System.in); String[] first = sc.nextLine().split(","); String[] second = sc.nextLine().split(","); Set<Node> set1 = getNodes(first); Set<Node> set2 = getNodes(second); set1.retainAll(set2); int min = Integer.MAX_VALUE; for (Node n : set1) { int dis = Math.abs(n.a) + Math.abs(n.b); if (dis < min && dis != 0) { min = dis; } } System.out.println(min); int minSteps = Integer.MAX_VALUE; for (Node n : set1) { int res = calculateSteps(n, first) + calculateSteps(n, second); if (res < minSteps) minSteps = res; } System.out.println(minSteps); sc.close(); } private static int calculateSteps(Node node, String[] arr) { int steps = 0; Node last = new Node(0, 0); for (String n : arr) { int len = Integer.parseInt(n.substring(1)); if (n.startsWith("D") && last.a == node.a && node.b < last.b && node.b > last.b - len) { steps += Math.abs(last.b - node.b + 1); break; } else if (n.startsWith("R") && last.b == node.b && node.a > last.a && node.a < last.a + len) { steps += Math.abs(last.a - node.a + 1); break; } else if (n.startsWith("U") && last.a == node.a && node.b > last.b && node.b < last.b + len) { steps += Math.abs(node.b - last.b + 1); break; } else if (n.startsWith("L") && last.b == node.b && node.a > last.a && node.a < last.a - len) { steps += Math.abs(node.a - last.a + 1); break; } else steps += len; if (n.startsWith("D")) { last.b -= len; } if (n.startsWith("R")) { last.a += len; } if (n.startsWith("U")) { last.b += len; } if (n.startsWith("L")) { last.a -= len; } } return steps; } private static Set<Node> getNodes(String[] instr) { Set<Node> nodes = new HashSet<>(); Node last = new Node(0, 0); Node a = null; for (String n : instr) { for (int i = 0; i < Integer.parseInt(n.substring(1)); i++) { if (n.startsWith("D")) { a = new Node(last.a, last.b - 1); } if (n.startsWith("R")) { a = new Node(last.a + 1, last.b); } if (n.startsWith("U")) { a = new Node(last.a, last.b + 1); } if (n.startsWith("L")) { a = new Node(last.a - 1, last.b); } nodes.add(a); last = a; } } return nodes; } }
package edu.sjsu.rmarcelita.readingchallengeapp; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.Toolbar; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.widget.ImageView; import android.widget.RatingBar; import android.widget.TextView; import com.google.android.gms.nearby.messages.internal.Update; import com.squareup.picasso.Picasso; public class BookDetailsActivity extends AppCompatActivity { private SQLiteHelper db; private Books currentBook; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_book_details); db = new SQLiteHelper(this); Intent intent = getIntent(); String intent1 = intent.getStringExtra(ReadOnActivity.BOOK_TITLE_EXTRAMSG); String intent2 = intent.getStringExtra(YourChallengeActivity.BOOK_EXTRA_MSG); String intent3 = intent.getStringExtra(UpdateCurrentBookActivity.CURBOOK_EXTRA_MSG); if(intent1 != null || intent2 != null || intent3 != null) { if(intent1 != null) { readBookDetails(intent1, "booksInfo"); } else if(intent2 != null){ readBookDetails(intent2, "readBooks"); } else { readBookDetails(intent3, "currentBooks"); } } setHomeToolbar(); } public void setHomeToolbar() { final Intent intent_home = new Intent(this, HomeActivity.class); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); toolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() { @Override public boolean onMenuItemClick(MenuItem item) { startActivity(intent_home); return true; } }); } public void readBookDetails(String bookTitle, String tableName) { currentBook = db.getBookByTitle(tableName, bookTitle); if(currentBook == null && tableName.equals("readBooks")) { tableName = "booksInfo"; currentBook = db.getBookByTitle(tableName, bookTitle); } else if(currentBook == null && tableName.equals("booksInfo")) { tableName = "readBooks"; currentBook = db.getBookByTitle(tableName, bookTitle); } ImageView cover = (ImageView) findViewById(R.id.detailsCoverImageView); TextView title = (TextView) findViewById(R.id.detailsTitleTextView); TextView author = (TextView) findViewById(R.id.detailsAuthorTextView); TextView bookDetails = (TextView) findViewById(R.id.bookDetailsTextView); TextView synopsis = (TextView) findViewById(R.id.bookSynopsisTextView); StringBuffer synopsisSpaced = new StringBuffer(); String currentSynopsis = currentBook.getSynopsis(); title.setText(bookTitle); author.setText("by " + currentBook.getAuthor()); bookDetails.setText("Genre: " + currentBook.getGenre() + ", " + currentBook.getPages() + " pages"); RatingBar stars = findViewById(R.id.bookRatingBar); stars.setRating((float) currentBook.getStars()); synopsis.setText(currentSynopsis); Picasso.with(getApplicationContext()).load(currentBook.getCover()).into(cover); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_main, menu); return true; } }
package checkitems.dialog.org.activities; import android.os.CountDownTimer; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.ImageView; import android.widget.TextView; import androidx.annotation.Nullable; import androidx.appcompat.app.AppCompatActivity; import java.util.ArrayList; import checkitems.dialog.org.checklistdialog.R; import checkitems.dialog.org.dialogs.CheckListDialog; import checkitems.dialog.org.interfaces.DialogResponse; /** * Actividad para mostrar un cuadro de diálogo con lista de selección múltiple */ public class CheckListActivity extends AppCompatActivity implements DialogResponse { private Button btOnOff; private boolean startLight1, startLight2, startLight3, startLight4, startLight5, startLight6; private ImageView ivStart1, ivStart2, ivStart3, ivStart4, ivStart5, ivStart6; private TextView tvNavidad; private CountDownTimer cT; private ArrayList<CountDownTimer> timers; private boolean startLights; private CheckListDialog cld; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_check_list); cld = new CheckListDialog(); btOnOff = findViewById(R.id.btOnOff); btOnOff.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(!startLights) { timers.clear(); cld.show(getSupportFragmentManager(), null); }else{ startLights = false; btOnOff.setText(R.string.crear_ambiente); tvNavidad.setVisibility(View.INVISIBLE); for(CountDownTimer timer:timers){ timer.onFinish(); timer.cancel(); } } } }); ivStart1 = findViewById(R.id.ivStart1); ivStart2 = findViewById(R.id.ivStart2); ivStart3 = findViewById(R.id.ivStart3); ivStart4 = findViewById(R.id.ivStart4); ivStart5 = findViewById(R.id.ivStart5); ivStart6 = findViewById(R.id.ivStart6); tvNavidad = findViewById(R.id.tvNavidad); timers = new ArrayList<CountDownTimer>(); } /** * Método de interfaz para el callback entre el cuadro de diálogo y la actividad en la que se * aceptan los elementos seleccionados * @param checkedItems Elementos seleccionados de la lista */ @Override public void onResponse(boolean[] checkedItems) { btOnOff.setText(R.string.quitar_ambiente); for(int i=0;i<checkedItems.length;i++){ if(checkedItems[i]){ setTimer(i+1); } } startLights = true; tvNavidad.setVisibility(View.VISIBLE); } /** * Método de interfaz para el callback entre el cuadro de diálogo y la actividad, se cancelan los * elementos seleccionados */ @Override public void onCancel() { startLights = false; btOnOff.setText(R.string.crear_ambiente); } /** * Método para temporizar el encendido y apagado de las estrellas del árbol * @param checkItem Elemento seleccionado (nivel del árbol) */ private void setTimer(final int checkItem){ cT = new CountDownTimer(100000, 1000) { public void onTick(long millisUntilFinished) { String v = String.format("%02d",millisUntilFinished/60000); int va = (int)((millisUntilFinished%60000)/1000); if(checkItem==1){ ivStart1.setImageResource(startLight1?android.R.drawable.star_big_on:android.R.drawable.star_big_off); startLight1 = !startLight1; }else if(checkItem==2){ ivStart2.setImageResource(startLight2?android.R.drawable.star_big_on:android.R.drawable.star_big_off); startLight2 = !startLight2; ivStart3.setImageResource(startLight3?android.R.drawable.star_big_on:android.R.drawable.star_big_off); startLight3 = !startLight3; }else if(checkItem==3){ ivStart4.setImageResource(startLight4?android.R.drawable.star_big_on:android.R.drawable.star_big_off); startLight4 = !startLight4; ivStart5.setImageResource(startLight5?android.R.drawable.star_big_on:android.R.drawable.star_big_off); startLight5 = !startLight5; ivStart6.setImageResource(startLight6?android.R.drawable.star_big_on:android.R.drawable.star_big_off); startLight6 = !startLight6; } } public void onFinish() { ivStart1.setImageResource(android.R.drawable.star_big_off); ivStart2.setImageResource(android.R.drawable.star_big_off); ivStart3.setImageResource(android.R.drawable.star_big_off); ivStart4.setImageResource(android.R.drawable.star_big_off); ivStart5.setImageResource(android.R.drawable.star_big_off); ivStart6.setImageResource(android.R.drawable.star_big_off); } }; timers.add(cT); cT.start(); } }
package com.logicbig.example; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Profile; @Configuration public class AppConfig { @Bean @Profile("windows") public MyService myServiceA() { return new MyServiceA(); } @Bean @Profile("other") public MyService myServiceB() { return new MyServiceB(); } }
package Common; import java.util.Date; import org.junit.Test; public class DoWhile { @Test public void testDoWhile(){ int a=0; do{ a++; System.out.println("runing"+(new Date())); }while(a<10); } }
package machine; import java.util.Scanner; /** * <i>Singleton</i> class to assist with basic keyboard input operations. Only a single <i>Input</i> object will ever be created. The <i>Input</i> class clusters related input operations and will build one <i>Scanner</i> object to use with input. * <i>Scanner</i> objects are big and complex; thus, this approach reduces the overhead associated with the repeated creation of <i>Scanner</i> objects. * * @author Rex Woollard * @version Lab Assignment 1: <i>Lord of the Rings</i> */ public final class Input { /** Keyword <i>static</i> makes this a <i>class</i> oriented variable, rather than <i>object</i> oriented variable; only one instance of an <i>Input</i> object will ever exist, and the instance is tracked by this reference variable. */ private static Input referenceToSingleInputObject = null; /** Object-oriented instance variable, but since only one <i>Input</i> can ever be created, only one <i>Scanner</i> object will ever be created. */ private Scanner scannerKeyboard; /** A <i>private</i> constructor guarantees that no <i>Input</i> object can be created from outside the <i>Input</i> class; this is essential for the <i>singleton</i> design pattern. */ private Input() { scannerKeyboard = new Scanner(System.in); } /** The <i>static</i> modifier means this method can be called without the existence of an <i>Input</i> object; if no <i>Input</i> object exists one will be created; if one already exists, it will be re-used. */ public static Input getInstance() { if (referenceToSingleInputObject == null) referenceToSingleInputObject = new Input(); return referenceToSingleInputObject; } // end static Input getInstance() /** * Presents a prompt to the user and retrieves an <i>int</i> value. * @param sPrompt reference to a <i>String</i> object whose contents will be displayed to the user as a prompt. * @return <i>int</i> value input from keyboard */ public int getInt(String sPrompt) { System.out.print(sPrompt); while ( ! scannerKeyboard.hasNextInt()) { // peek into keyboard buffer to see if next token is a legitimate int System.out.println("Number is required input."); System.out.print(sPrompt); scannerKeyboard.nextLine(); // clear bad input data from the keyboard } return scannerKeyboard.nextInt(); } // end int getInt(String sPrompt) /** * Presents a prompt to the user and retrieves an <i>int</i> value which is within the range of <i>nLow</i> to <i>nHigh</i> (inclusive). * @param sPrompt reference to a <i>String</i> object whose contents will be displayed to the user as a prompt. * @param nLow lower boundary on the range of legitimate values * @param nHigh upper boundary on the range of legitimate values * @return <i>int</i> value input from keyboard */ public int getInt(String sPrompt, int nLow, int nHigh) { int nInput; do { System.out.printf("%s (%d-%d): ", sPrompt, nLow, nHigh); while ( ! scannerKeyboard.hasNextInt()) { // peek into keyboard buffer to see if next token is a legitimate int System.out.println("Number is required input."); System.out.print(sPrompt); scannerKeyboard.nextLine(); // retrieves input to the next \r\n (line separator) and we choose to ignore the String that is created and returned } nInput = scannerKeyboard.nextInt(); if (nInput >= nLow && nInput <= nHigh) // int value is within range, thus it is valid . . . time to break out of loop break; System.out.println("Value out of range. Try again."); } while (true); return nInput; } // end int getInt(String sPrompt, int nLow, int nHigh) /** * Presents a prompt to the user and retrieves a <i>reference-to-String</i>. * @param sPrompt reference to a <i>String</i> object whose contents will be displayed to the user as a prompt. * @return <i>reference-to-String</i> object created by keyboard input */ public String getString(String sPrompt) { System.out.print(sPrompt); scannerKeyboard.useDelimiter("\r\n"); // Setting this delimiter ensures that we capture everything up to the <Enter> key. Without this, input stops at the next whitespace (space, tab, newline etc.). StringBuffer sInput; // try { sInput = new StringBuffer(scannerKeyboard.nextLine()); // } catch (Exception e) { // sInput = scannerKeyboard.next(); // } /*finally { // System.out.println("sInput = scannerKeyboard.nextLine();"); // }*/ // String sInput = scannerKeyboard.next(); /*??? don`t work ???*/ scannerKeyboard.reset(); // The preceding use of useDelimiter() changed the state of the Scanner object. reset() re-establishes the original state. return sInput.toString(); } // end String getString(String sPrompt) public String getString() { return getString(""); } // end String getString(String sPrompt) /** * Presents a prompt to the user and retrieves a <i>boolean</i> value. * @param sPrompt reference to a <i>String</i> object whose contents will be displayed to the user as a prompt. * @return <i>boolean</i> value input from keyboard */ public boolean getBoolean(String sPrompt) { System.out.print(sPrompt); return scannerKeyboard.nextBoolean(); } // end boolean getBoolean(String sPrompt) } // end class Input()
package InheritancePrograms; class Mobile { void calling() { System.out.println("call"); } void sms() { System.out.println("sms from mobile"); } } public class SamsungS extends Mobile { public void sms() { System.out.println("sms"); super.sms(); } void internet() { System.out.println("2g"); } public static void main(String args[]) { SamsungS s=new SamsungS(); s.sms(); s.calling(); s.internet(); } }
package com.microservice.counthvip.controller; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.support.WebExchangeBindException; import java.net.URI; import java.util.Map; import javax.validation.Valid; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import com.microservice.counthvip.model.ClientPerson; import com.microservice.counthvip.model.CountHvip; import com.microservice.counthvip.services.CountHvipServiceImp; import com.microservice.counthvip.services.CountHvipServices; import ch.qos.logback.core.util.ContentTypeUtil; import lombok.Value; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; @RestController @RequestMapping("/counthvip") public class CountHvipController { private static Logger log = LoggerFactory.getLogger(CountHvipController.class); @Autowired private CountHvipServices service; @Autowired private CountHvipServiceImp serviceclient; @GetMapping public Mono<ResponseEntity<Flux<CountHvip>>> lista() { return Mono.just(ResponseEntity.ok().contentType(MediaType.APPLICATION_JSON_UTF8).body(service.findAll())); } // see the list of savings accounts for id @GetMapping("/{id}") public Mono<ResponseEntity<CountHvip>> ver(@PathVariable String id) { return service.findById(id).map(p -> ResponseEntity.ok().contentType(MediaType.APPLICATION_JSON_UTF8).body(p)) .defaultIfEmpty(ResponseEntity.notFound().build()); } // @PostMapping // public Mono<CountH> create(@RequestBody CountH monoCounth){ // String dni =monoCounth.getClientperson().getDni(); // Mono<CountH> mono = null; // if( service.findClientPersonByDni(dni)!= null) { // mono= service.save(monoCounth); // } // return mono; // // // } // creation of a savings account @PostMapping public Mono<CountHvip> create(@RequestBody CountHvip monoCounth) { ClientPerson client = new ClientPerson(); client = monoCounth.getClientperson(); client.setType("personal client vip"); serviceclient.saveMSClient(client).subscribe(); service.saveClientPerson(client).subscribe(); return service.save(monoCounth); } // @PostMapping // public Mono<ResponseEntity<Map<String, Object>>> crear(@RequestBody Mono<CountH> monoProducto){ // // Map<String, Object> respuesta = new HashMap<String, Object>(); // // return monoProducto.flatMap(counth->{ // return service.save(counth).map(c->{ // respuesta.put("saving account", c); // respuesta.put("mensaje", "cuenta de ahoro creada con exito"); // return ResponseEntity // .created(URI.create("/api/counth/".concat(c.getId()))) // .contentType(MediaType.APPLICATION_JSON_UTF8) // .body(respuesta); // }); // }).onErrorResume(t -> { // return Mono.just(t).cast(WebExchangeBindException.class) // .flatMap(e -> Mono.just(e.getFieldErrors())) // .flatMapMany(Flux::fromIterable) // .map(fieldError -> "El campo "+fieldError.getField() + " " + fieldError.getDefaultMessage()) // .collectList() // .flatMap(list -> { // respuesta.put("errors", list); // respuesta.put("status", HttpStatus.BAD_REQUEST.value()); // return Mono.just(ResponseEntity.badRequest().body(respuesta)); // }); // }); // } // public Mono<> create(@RequestBody Mono<CountH> monoProducto){ // // edit the savings account @PutMapping("/{id}") public Mono<ResponseEntity<CountHvip>> upadate(@RequestBody CountHvip counth, @PathVariable String id) { return service.findById(id).flatMap(c -> { c.setNum(counth.getNum()); c.setMonto(counth.getMonto()); c.setClientperson(counth.getClientperson()); return service.save(c); }).map(c -> ResponseEntity.created(URI.create("/counthvip/".concat(c.getId()))) .contentType(MediaType.APPLICATION_JSON_UTF8).body(c)) .defaultIfEmpty(ResponseEntity.notFound().build()); } // delete the savings account @DeleteMapping("/{id}") public Mono<ResponseEntity<Void>> delete(@PathVariable String id) { return service.findById(id).flatMap(p -> { return service.delete(p).then(Mono.just(new ResponseEntity<Void>(HttpStatus.NO_CONTENT))); }).defaultIfEmpty(new ResponseEntity<Void>(HttpStatus.NOT_FOUND)); } @GetMapping("/counthclient/{dni}") public Flux<CountHvip> getClientDni(@PathVariable String dni) { return service.findByDniClient(dni); } @GetMapping("/getmoney/{dni}") public Mono<Map<String, Object>> getMoney(@PathVariable String dni) { return service.getMoney(dni); } }
package com.forfinance.dto; import com.fasterxml.jackson.annotation.JsonAutoDetect; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonRootName; import com.fasterxml.jackson.databind.annotation.JsonSerialize; import org.apache.commons.lang3.builder.EqualsBuilder; import org.apache.commons.lang3.builder.HashCodeBuilder; import org.apache.commons.lang3.builder.ToStringBuilder; import org.hibernate.validator.constraints.NotEmpty; import java.io.Serializable; @JsonAutoDetect(fieldVisibility = JsonAutoDetect.Visibility.NONE, getterVisibility = JsonAutoDetect.Visibility.NONE, setterVisibility = JsonAutoDetect.Visibility.NONE) @JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL) @JsonIgnoreProperties(ignoreUnknown = true) @JsonRootName(value = "customer") @SuppressWarnings("unused") public class CustomerDTO implements Serializable { private static final long serialVersionUID = -792605859918207756L; @JsonProperty private Long id; @JsonProperty @NotEmpty private String firstName; @JsonProperty @NotEmpty private String lastName; @JsonProperty @NotEmpty private String code; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public String getCode() { return code; } public void setCode(String code) { this.code = code; } @Override public int hashCode() { HashCodeBuilder builder = new HashCodeBuilder(); builder.append(code).append(firstName).append(lastName); return builder.toHashCode(); } @Override public boolean equals(Object obj) { if (obj == null) return false; if (obj == this) return true; if (obj instanceof CustomerDTO) { CustomerDTO that = (CustomerDTO) obj; EqualsBuilder builder = new EqualsBuilder(); builder.append(this.code, that.code); builder.append(this.firstName, that.firstName); builder.append(this.lastName, that.lastName); return builder.isEquals(); } else { return false; } } @Override public String toString() { return ToStringBuilder.reflectionToString(this); } }
package com.beike.entity.catlog; import java.io.Serializable; import java.util.List; /** * <p> * Title:地域、属性分类 * </p> * <p> * Description: * </p> * <p> * Copyright: Copyright (c) 2011 * </p> * <p> * Company: Sinobo * </p> * * @date May 24, 2011 * @author ye.tian * @version 1.0 */ public class RegionCatlog implements Serializable { private static final long serialVersionUID = 1L; private Long catlogid; // 地域或者属性类别id private String catlogName;// 地域或者属性的名称 private String url;// 跳转url 伪静态准备 private List<RegionCatlog> childRegionCatlog;// 本类别下面的子类别 private String count;// 此标签显示的数量 private Long parentId; private String region_enname; private Long cityId; // 城市ID public Long getCityId() { return cityId; } public void setCityId(Long cityId) { this.cityId = cityId; } public String getRegion_enname() { return region_enname; } public void setRegion_enname(String region_enname) { this.region_enname = region_enname; } @Override public boolean equals(Object obj) { if (obj == null) return false; RegionCatlog regionCatlog = null; if (obj instanceof RegionCatlog) { regionCatlog = (RegionCatlog) obj; } if (regionCatlog.getCatlogid().equals(this.getCatlogid())) { return true; } return false; } @Override public int hashCode() { return this.getCatlogid().hashCode(); } public Long getCatlogid() { return catlogid; } public void setCatlogid(Long catlogid) { this.catlogid = catlogid; } public String getCatlogName() { return catlogName; } public void setCatlogName(String catlogName) { this.catlogName = catlogName; } public List<RegionCatlog> getChildRegionCatlog() { return childRegionCatlog; } public void setChildRegionCatlog(List<RegionCatlog> childRegionCatlog) { this.childRegionCatlog = childRegionCatlog; } public String getCount() { return count; } public void setCount(String count) { this.count = count; } public Long getParentId() { return parentId; } public void setParentId(Long parentId) { this.parentId = parentId; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } }
import java.awt.image.BufferedImage; /** * Created by Jack on 31/08/2016. */ public class TrumpCard extends CardDescription { public TrumpCard(String name, String economicValue, BufferedImage cardPicture){ super(name, economicValue, cardPicture); } //Defines how to print the cards public String toString() { return "Card Name: " + cardTitle + " " + "Category: " + cardEconomicValue + "\n" ; } }
package lab4; public class Hinh { public double rong; public double dai; public Hinh() { } public Hinh(double dai, double rong) { super(); this.rong=rong; this.dai =dai; } public double getChuvi() { double chuvi= (dai+rong)*2; return chuvi; } public double getDienTich() { double dientich= (dai*rong); return dientich; } public void xuat() { System.out.println(" chu vi hinh chu nhat:"+getChuvi()); System.out.println(" dien tich hinh chu nhat:"+getDienTich()); } }
package top.kwseeker.classLoader; import java.net.URL; import java.net.URLClassLoader; public class HotClassLoader implements IClassLoader { @Override public ClassLoader createClassLoader(ClassLoader parentClassLoader) { URL[] urls = new URL[]{}; //TODO: 从这里开始创建 类加载器 有问题,参考测试类重新创建类加载器,然后加载改变的类 return new URLClassLoader(urls, parentClassLoader); } }
/* * Copyright (C) 2012~2016 dinstone<dinstone@163.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.dinstone.beanstalkc; import java.util.concurrent.TimeUnit; /** * {@link JobProducer} is a kind of client beanstalk, that is responsible for * the production job. * * @author guojf * @version 1.0.0.2013-4-15 */ public interface JobProducer { /** * It inserts a job into the client's currently used tube. * * @param priority * an integer < 2**32. Jobs with smaller priority values will be * scheduled before jobs with larger priorities. The most urgent * priority is 0; the least urgent priority is 4,294,967,295. * @param delay * {@link TimeUnit.SECONDS} * @param ttr * {@link TimeUnit.SECONDS} time to run -- is an integer number of * seconds to allow a worker to run this job. This time is counted * from the moment a worker reserves this job. If the worker does not * delete, release, or bury the job within <ttr> seconds, the job * will time out and the server will release the job. The minimum ttr * is 1. If the client sends 0, the server will silently increase the * ttr to 1. * @param data * the job body,that length is an integer indicating the size of the * job body, not including the trailing "\r\n". This value must be * less than max-job-size (default: 2**16). * @return the integer id of the new job */ public long putJob(int priority, int delay, int ttr, byte[] data); /** * close the current connection and release resources. that's status is * closed, and is no longer available. */ public void close(); }
package ru.job4j.waitnotify; import java.io.File; import java.io.FileInputStream; import java.io.InputStreamReader; import java.io.IOException; import java.nio.file.Files; import java.util.Arrays; import java.util.ArrayList; import java.util.concurrent.ExecutionException; import java.util.concurrent.Executors; import java.util.concurrent.ExecutorService; import java.util.concurrent.Future; import java.util.LinkedList; import java.util.List; import java.util.HashSet; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * Класс ParallelSearch реализует параллельный поиск текста в файлах с указанными расширениями, начиная с указанной папки. Использован пул потоков, размер которого равен количеству доступных системе процессоров. * * @author Gureyev Ilya (mailto:ill-jah@yandex.ru) * @version 2 * @since 2017-08-03 */ class ParallelSearch { /** * Коллекция папок. */ private HashSet<File> dirs; /** * Коллекция файлов. */ private LinkedList<File> files; /** * Строка поиска. */ private String text; /** * Коллекция расширений файлов, в которых производится поиск. */ private List<String> exts; /** * Корневая папка поиска. */ private File rootDir; /** * Коллекция трэдов. */ private ArrayList<ThreadSearch> threads; /** * Пул трэдов. */ private ExecutorService pool; /** * Объект блокировки (монитора). */ private Object lock; /** * Конструктор. * @param root имя папки, в которой производится поиск. * @param text строка поиска. * @param exts список расширений файлов, в которых производится поиск. */ ParallelSearch(String root, String text, List<String> exts) { this.rootDir = new File(root); if (!this.rootDir.isDirectory()) { throw new PathIsNotDirException(root); } if (text.trim().isEmpty()) { throw new SearchStringIsEmptyException(); } this.dirs = new HashSet<>(); this.dirs.add(this.rootDir.getAbsoluteFile()); this.files = new LinkedList<>(); this.threads = new ArrayList<>(); this.pool = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors()); this.lock = this; this.text = text; this.exts = exts; } /** * Помещает в дерево все папки. */ private void findFiles() { File[] files = this.rootDir.listFiles(); ArrayList<File> filePaths = new ArrayList<>(Arrays.asList(files)); File file; String ext; for (int a = 0; a < filePaths.size(); a++) { file = filePaths.get(a); if (Files.isSymbolicLink(file.toPath())) { continue; } ext = file.getName().substring(file.getName().lastIndexOf(".") + 1); if (file.isDirectory()) { if (!this.dirs.contains(file)) { this.dirs.add(file); files = file.listFiles(); filePaths.addAll(Arrays.asList(files)); } } else if (file.isFile() && (this.exts.size() > 0 ? this.exts.contains(ext) : true)) { String path = file.getAbsolutePath(); File f = new File(path); this.files.add(f); this.threads.add(new ThreadSearch(f, this.text)); } } } /** * Ищет в файлах совпадения со строкой поиска. */ private void findMatches() { try { ArrayList<Future> futureList = new ArrayList<>(); for (ThreadSearch t : this.threads) { futureList.add(this.pool.submit(t)); } for (Future item : futureList) { item.get(); } } catch (InterruptedException ex) { ex.printStackTrace(); } catch (ExecutionException ex) { ex.printStackTrace(); } } /** * Удаляет файл из коллекции. * @param file объект удаляемого файла. */ private void remove(File file) { synchronized (this.lock) { this.files.remove(file); } } /** * Возвращает результаты поиска строки в файлах с указанным расширением. * @return список имён файлов, в которых есть совпаденияме со строкой поиска. */ public List<String> result() { this.findFiles(); this.findMatches(); LinkedList<String> list = new LinkedList<>(); for (File file : this.files) { list.add(file.toString()); } return (List) list; } /** * Класс ThreadSearch реализует сущность "Поиск строки в файле в отдельном потоке". * * @author Goureyev Ilya (mailto:ill-jah@yandex.ru) * @version 1 * @since 2017-07-31 */ class ThreadSearch extends Thread { /** * Файл, в котором производится поиск текста. */ private File file; /** * Строка поиска. */ private String text; /** * Конструктор. * @param file файл, в котором производится поиск текста. * @param text строка поиска. */ ThreadSearch(File file, String text) { this.file = file; this.text = text; } /** * Переопределёный метод. */ @Override public void run() { try { byte[] bytes = Files.readAllBytes(this.file.toPath()); InputStreamReader isr = new InputStreamReader(new FileInputStream(this.file.getAbsolutePath())); Pattern p = Pattern.compile(this.text); Matcher m = p.matcher(new String(bytes, isr.getEncoding())); if (!m.find()) { ParallelSearch.this.remove(this.file); } } catch (IOException ex) { ex.printStackTrace(); } finally { Thread.currentThread().interrupt(); } } } } /** * Класс PathIsNotDirException реализует исключение "Указанный путь не является папкой". * * @author Goureyev Ilya (mailto:ill-jah@yandex.ru) * @version 1 * @since 2017-07-31 */ class PathIsNotDirException extends RuntimeException { /** * Конструктор. * @param path путь до папки. */ PathIsNotDirException(String path) { super(String.format("Specified path: %s is not a directory.", path)); } } /** * Класс SearchStringIsEmptyException реализует исключение "Строка поиска пуста". * * @author Goureyev Ilya (mailto:ill-jah@yandex.ru) * @version 1 * @since 2017-07-31 */ class SearchStringIsEmptyException extends RuntimeException { /** * Конструктор. */ SearchStringIsEmptyException() { super(String.format("Search string is empty.")); } }
package listeners; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Dimension; import java.awt.FlowLayout; import java.awt.Font; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.GridLayout; import java.awt.Insets; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.File; import java.util.logging.Level; import javax.swing.BorderFactory; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JDialog; import javax.swing.JFileChooser; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.border.EmptyBorder; import javax.swing.filechooser.FileNameExtensionFilter; import authoring.GUI; import authoring.RecordAudio; import authoring.ThreadRunnable; import commands.CellCharCommand; import commands.CellLowerCommand; import commands.CellRaiseCommand; import commands.ClearAllCommand; import commands.ClearCellCommand; import commands.GoHereCommand; import commands.PauseCommand; import commands.RepeatButtonCommand; import commands.RepeatCommand; import commands.ResetButtonCommand; import commands.SetPinsCommand; import commands.SetStringCommand; import commands.SetVoiceCommand; import commands.SkipButtonCommand; import commands.SkipCommand; import commands.SoundCommand; import commands.TTSCommand; import commands.UserInputCommand; /** * This class is used as an action listener whenever the "New Item" button is * clicked. It enables the user to set items from dialog box with their value. * * @author Dilshad Khatri, Alvis Koshy, Drew Noel, Jonathan Tung * @version 1.0 * @since 4/3/2017 * */ public class NewButtonListener implements ActionListener { private GUI gui; ThreadRunnable thread = null; File file = null; private boolean isRecording = false; private boolean noRecording = true; private boolean recordFlag = false; private RecordAudio rc = new RecordAudio(); private static final String FONT_FACE = "Arial"; private static final int FONT_SIZE = 12; private JFrame frame; // /** * Create the NewButtonListener with a reference to the base GUI object * (required to access the left panel) * * @param gui * Instance of currently running GUI */ public NewButtonListener(GUI gui) { this.gui = gui; file = null; } @Override public void actionPerformed(ActionEvent e) { gui.logger.log(Level.INFO, "User has clicked New Item button."); // Show the Add Item dialog JPanel panel = new JPanel(); panel.setLayout(new GridLayout(6, 1, 5, 3)); panel.setBorder(BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(), "Items")); frame = new JFrame("Add New Item"); frame.setPreferredSize(new Dimension(200, 200)); frame.setMaximumSize(new Dimension(200, 200)); frame.setResizable(false); frame.add(panel, BorderLayout.CENTER); frame.pack(); frame.setVisible(true); JButton btnNewButton = new JButton("Text To Speech"); btnNewButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { frame.dispose(); processAnswer("Text-to-speech", "add"); } }); btnNewButton.setFont(new Font(FONT_FACE, Font.PLAIN, FONT_SIZE)); panel.add(btnNewButton); JButton btnRecordAudio = new JButton("Record Audio"); btnRecordAudio.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { frame.dispose(); processAnswer("Record Audio", "add"); } }); btnRecordAudio.setFont(new Font(FONT_FACE, Font.PLAIN, FONT_SIZE)); panel.add(btnRecordAudio); JButton btnPlaySound = new JButton("Play Sound"); btnPlaySound.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { frame.dispose(); processAnswer("Play Sound", "add"); } }); btnPlaySound.setFont(new Font(FONT_FACE, Font.PLAIN, FONT_SIZE)); panel.add(btnPlaySound); JButton btnPause = new JButton("Pause"); btnPause.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { frame.dispose(); processAnswer("Pause", "add"); } }); btnPause.setFont(new Font(FONT_FACE, Font.PLAIN, FONT_SIZE)); panel.add(btnPause); JButton btnDisplayOnBraille = new JButton("Display on Braille Cell"); btnDisplayOnBraille.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { frame.dispose(); processAnswer("Display on Braille Cell", "add"); } }); btnDisplayOnBraille.setFont(new Font(FONT_FACE, Font.PLAIN, FONT_SIZE)); panel.add(btnDisplayOnBraille); String[] array = { "Advance Options", "Repeat", "Button Repeat", "Button Location", "User Input", "Reset Buttons", "Go To Location", "Clear All", "Clear Cell", "Set Pins", "Set Character", "Raise Pin", "Lower Pin", "Set Voice", "Location Tag" }; JComboBox comboBox = new JComboBox<Object>(array); comboBox.setSelectedItem("Advance Options"); comboBox.setFont(new Font(FONT_FACE, Font.PLAIN, FONT_SIZE)); panel.add(comboBox); comboBox.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent event) { // // Get the source of the component, which is our combobox. Object selected = comboBox.getSelectedItem(); String answer = selected.toString(); frame.dispose(); processAnswer(answer, "add"); } }); } public void processAnswer(String answer, String ID) { Object value; if (answer != null) { switch (answer) { case "Pause": value = JOptionPane.showInputDialog(gui, "Length of time to wait", "Edit Item Details", JOptionPane.PLAIN_MESSAGE, null, null, ""); if (value != null && value != "") { if (ID == "add") gui.getLeftPanel().addItem(new PauseCommand((String) value)); else gui.getLeftPanel().addItemAt(new PauseCommand((String) value)); this.gui.counterMap.put("Pause", gui.counterMap.get("Pause") + 1); } break; case "Text-to-speech": value = JOptionPane.showInputDialog(gui, "Text to say", "Edit Item Details", JOptionPane.PLAIN_MESSAGE, null, null, ""); if (value != null && value != "") { if (ID == "add") gui.getLeftPanel().addItem(new TTSCommand((String) value)); else gui.getLeftPanel().addItemAt(new TTSCommand((String) value)); gui.counterMap.put("Text-to-speech", gui.counterMap.get("Text-to-speech") + 1); } break; case "Display on Braille Cell": value = JOptionPane.showInputDialog(gui, "String to display", "Edit Item Details", JOptionPane.PLAIN_MESSAGE, null, null, ""); if (value != null && value != "") { if (ID == "add") gui.getLeftPanel().addItem(new SetStringCommand((String) value)); else gui.getLeftPanel().addItemAt(new SetStringCommand((String) value)); gui.counterMap.put("Display on Braille Cell", gui.counterMap.get("Display on Braille Cell") + 1); } break; case "Repeat": value = JOptionPane.showInputDialog(gui, "Text to be repeated", "Edit Item Details", JOptionPane.PLAIN_MESSAGE, null, null, ""); if (value != null && value != "") { if (ID == "add") gui.getLeftPanel().addItem(new RepeatCommand((String) value)); else gui.getLeftPanel().addItemAt(new RepeatCommand((String) value)); gui.counterMap.put("Repeat", gui.counterMap.get("Repeat") + 1); } break; case "Button Repeat": value = JOptionPane.showInputDialog(gui, "Button to use for repeating", "Edit Item Details", JOptionPane.PLAIN_MESSAGE, null, null, ""); if (value != null && value != "") { if (ID == "add") gui.getLeftPanel().addItem(new RepeatButtonCommand((String) value)); else gui.getLeftPanel().addItemAt(new RepeatButtonCommand((String) value)); gui.counterMap.put("Button Repeat", gui.counterMap.get("Button Repeat") + 1); } break; case "Button Location": value = JOptionPane.showInputDialog(gui, "Button and identifier (space separated)", "Edit Item Details", JOptionPane.PLAIN_MESSAGE, null, null, ""); if (value != null && value != "") { if (ID == "add") gui.getLeftPanel().addItem(new SkipButtonCommand((String) value)); else gui.getLeftPanel().addItemAt(new SkipButtonCommand((String) value)); gui.counterMap.put("Button Location", gui.counterMap.get("Button Location") + 1); } break; case "User Input": System.out.println("here"); if (ID == "add") gui.getLeftPanel().addItem(new UserInputCommand()); else gui.getLeftPanel().addItemAt(new UserInputCommand()); gui.counterMap.put("User Input", gui.counterMap.get("User Input") + 1); break; case "Play Sound": JFileChooser load = new JFileChooser(); FileNameExtensionFilter wavFileFilter = new FileNameExtensionFilter("wav files (*.wav)", "wav"); load.addChoosableFileFilter(wavFileFilter); load.setFileFilter(wavFileFilter); load.showOpenDialog(null); file = load.getSelectedFile(); if (file != null) { if (ID == "add") gui.getLeftPanel().addItem(new SoundCommand(file.toString(), this.gui)); else gui.getLeftPanel().addItemAt(new SoundCommand(file.toString(), this.gui)); gui.counterMap.put("Play Sound", gui.counterMap.get("Play Sound") + 1); } break; case "Record Audio": rc.recordAudio(this.gui); // calls recordAudio method in // RecordAudio class if (rc.file != null && rc.recordFlag == true) { if (ID == "add") gui.getLeftPanel().addItem(new SoundCommand(rc.file.toString(), this.gui)); else gui.getLeftPanel().addItemAt(new SoundCommand(rc.file.toString(), this.gui)); gui.counterMap.put("Record Audio", gui.counterMap.get("Record Audio") + 1); } break; case "Reset Buttons": if (ID == "add") gui.getLeftPanel().addItem(new ResetButtonCommand("")); else gui.getLeftPanel().addItemAt(new ResetButtonCommand("")); gui.counterMap.put("Reset Buttons", gui.counterMap.get("Reset Buttons") + 1); break; case "Go To Location": value = JOptionPane.showInputDialog(gui, "Enter location to go to", "Edit Item Details", JOptionPane.PLAIN_MESSAGE, null, null, ""); if (value != null && value != "") { if (ID == "add") gui.getLeftPanel().addItem(new SkipCommand((String) value)); else gui.getLeftPanel().addItemAt(new SkipCommand((String) value)); gui.counterMap.put("Go To Location", gui.counterMap.get("Go To Location") + 1); } break; case "Clear All": if (ID == "add") gui.getLeftPanel().addItem(new ClearAllCommand("")); else gui.getLeftPanel().addItemAt(new ClearAllCommand("")); gui.counterMap.put("Clear All", gui.counterMap.get("Clear All") + 1); break; case "Clear Cell": value = JOptionPane.showInputDialog(gui, "Cell number", "Edit Item Details", JOptionPane.PLAIN_MESSAGE, null, null, ""); if (value != null && value != "") { if (ID == "add") gui.getLeftPanel().addItem(new ClearCellCommand((String) value)); else gui.getLeftPanel().addItemAt(new ClearCellCommand((String) value)); gui.counterMap.put("Clear Cell", gui.counterMap.get("Clear Cell") + 1); } break; case "Set Pins": value = JOptionPane.showInputDialog(gui, "Cell and pins (space separated)", "Edit Item Details", JOptionPane.PLAIN_MESSAGE, null, null, ""); if (value != null && value != "") { if(ID=="add") gui.getLeftPanel().addItem(new SetPinsCommand((String) value)); else gui.getLeftPanel().addItemAt(new SetPinsCommand((String) value)); gui.counterMap.put("Set Pins", gui.counterMap.get("Set Pins") + 1); } break; case "Set Character": value = JOptionPane.showInputDialog(gui, "Cell and character (space seperated)", "Edit Item Details", JOptionPane.PLAIN_MESSAGE, null, null, ""); if (value != null && value != "") { if(ID=="add") gui.getLeftPanel().addItem(new CellCharCommand((String) value)); else gui.getLeftPanel().addItemAt(new CellCharCommand((String) value)); gui.counterMap.put("Set Character", gui.counterMap.get("Set Character") + 1); } break; case "Raise Pin": value = JOptionPane.showInputDialog(gui, "Cell and Pin to raise (space separated)", "Edit Item Details", JOptionPane.PLAIN_MESSAGE, null, null, ""); if (value != null && value != "") { if(ID=="add") gui.getLeftPanel().addItem(new CellRaiseCommand((String) value)); else gui.getLeftPanel().addItemAt(new CellRaiseCommand((String) value)); gui.counterMap.put("Raise Pin", gui.counterMap.get("Raise Pin") + 1); } break; case "Lower Pin": value = JOptionPane.showInputDialog(gui, "Cell and Pin to lower (space separated)", "Edit Item Details", JOptionPane.PLAIN_MESSAGE, null, null, ""); if (value != null && value != "") { if(ID=="add") gui.getLeftPanel().addItem(new CellLowerCommand((String) value)); else gui.getLeftPanel().addItemAt(new CellLowerCommand((String) value)); gui.counterMap.put("Lower Pin", gui.counterMap.get("Lower Pin") + 1); } break; case "Set Voice": String[] voices = {"1. male","2. female","3. male","4. male"}; value = JOptionPane.showInputDialog(gui, "Select a voice", "Edit Item Details", JOptionPane.PLAIN_MESSAGE, null, voices, voices[0]); if (value != null && value != "") { gui.getLeftPanel().addItem(new SetVoiceCommand(value.toString().substring(0, 1))); gui.counterMap.put("Set Voice", gui.counterMap.get("Set Voice") + 1); } break; case "Location Tag": value = JOptionPane.showInputDialog(gui, "Enter name of location", "Edit Item Details", JOptionPane.PLAIN_MESSAGE, null, null, ""); if (value != null && value != "") { if(ID=="add") gui.getLeftPanel().addItem(new GoHereCommand((String) value)); else gui.getLeftPanel().addItemAt(new GoHereCommand((String) value)); gui.counterMap.put("Location Tag", gui.counterMap.get("Location Tag") + 1); } break; default: break; } } } }
package ru.avokin.filediff; import ru.avokin.uidiff.diff.filediff.model.FileDiffCodeBlock; import ru.avokin.uidiff.diff.folderdiff.model.DiffStatusEnum; import java.util.ArrayList; import java.util.Collections; import java.util.List; /** * User: Andrey Vokin * Date: 24.08.2010 */ public class LongestCommonSubsequenceSearcher { public static int[][] findLongestCommonSubsequence(List<String> l1, List<String> l2) { int[][] max = new int[l1.size()][l2.size()]; //noinspection ConditionalExpression max[0][0] = (l1.get(0).equals(l2.get(0))) ? 1 : 0; // First horizontal line. for (int i = 1; i < l1.size(); i++) { if (l1.get(i).equals(l2.get(0))) { max[i][0] = 1; } else { max[i][0] = max[i-1][0]; } } // First vertical line. for (int j = 1; j < l2.size(); j++) { if (l2.get(j).equals(l1.get(0))) { max[0][j] = 1; } else { max[0][j] = max[0][j - 1]; } } for (int i = 1; i < l1.size(); i++) { for (int j = 1; j < l2.size(); j++) { //noinspection ConditionalExpression int equals = l1.get(i).equals(l2.get(j)) ? 1 : 0; max[i][j] = Math.max(max[i][j - 1], max[i - 1][j]); max[i][j] = Math.max(max[i][j], max[i - 1][j - 1] + equals); } } return max; } public static Difference createDifference(int leftStartLine, int leftEndLine, int rightStartLine, int rightEndLine) { DiffStatusEnum status = DiffStatusEnum.changed; if (leftStartLine > leftEndLine) { status = DiffStatusEnum.added; } if (rightStartLine > rightEndLine) { status = DiffStatusEnum.deleted; } return new Difference(new FileDiffCodeBlock(leftStartLine, leftEndLine, status), new FileDiffCodeBlock(rightStartLine, rightEndLine, status)); } public static FileDifference diff(List<String> l1, List<String> l2) { int[][] maxSubsequincesLength = findLongestCommonSubsequence(l1, l2); // Looking for last common item. int maxI = 0; int maxJ = 0; for (int i = 0; i < maxSubsequincesLength.length; i++) { for (int j = 0; j < maxSubsequincesLength[0].length; j++) { if (l1.get(i).equals(l2.get(j)) && maxSubsequincesLength[maxI][maxJ] < maxSubsequincesLength[i][j]) { maxI = i; maxJ = j; } } } List<Difference> result = new ArrayList<Difference>(); if (maxI < maxSubsequincesLength.length - 1 || maxJ < maxSubsequincesLength[0].length - 1) { // Tail change or insert. int leftTop = maxI + 1; int leftBottom = maxSubsequincesLength.length - 1; int rightTop = maxJ + 1; int rightBottom = maxSubsequincesLength[0].length - 1; result.add(createDifference(leftTop, leftBottom, rightTop, rightBottom)); } boolean diffBlock = false; int bottomI = -1; int bottomJ = -1; int i = maxI; int j = maxJ; while (i >= 0 || j >= 0) { if (i >= 0 && j >= 0 && l1.get(i).equals(l2.get(j))) { if (diffBlock) { // Diff block finished. //noinspection SuspiciousNameCombination result.add(createDifference(i + 1, bottomI, j + 1, bottomJ)); } diffBlock = false; i--; j--; } else { if (!diffBlock) { bottomI = i; bottomJ = j; diffBlock = true; } if (i == -1) { j--; } else if (j == -1) { i--; } else if (i > 0 && j > 0) { if (maxSubsequincesLength[i - 1][j] > maxSubsequincesLength[i][j - 1]) { i--; } else { j--; } } else if (i == 0) { j--; } else { i--; } } } if (diffBlock) { // Leading change or insert. //noinspection SuspiciousNameCombination result.add(createDifference(0, bottomI, 0, bottomJ)); } Collections.reverse(result); return new FileDifference(result); } }
package itcast.mobilecounter; import java.util.Calendar; import java.util.Date; public class Rent { private int price;//分为单位 private RentUnit unit = RentUnit.MONTH; public Rent(int price,RentUnit unit){ this.price = price; this.unit = unit; } public int coputeRent(Date startTime,Date currentMonth){ //首先应该想到去找开源的日期运算类 if(unit == RentUnit.DAY){ Calendar start = Calendar.getInstance(); start.setTime(startTime); Calendar end = Calendar.getInstance(); end.setTime(currentMonth); //将日期设置为当月的最后一天 end.set(Calendar.DAY_OF_MONTH, 1); end.add(Calendar.MONTH, 1); end.add(Calendar.DAY_OF_MONTH, -1); int days = end.get(Calendar.DAY_OF_MONTH) ; //计费不到一个月 if(end.get(Calendar.MONTH) == start.get(Calendar.MONTH)){ days -= start.get(Calendar.DAY_OF_MONTH) + 1; } return price*days; } else{ return price; } } public static void main(String[] args) { Calendar calendar = Calendar.getInstance(); calendar.setTime(new Date()); calendar.set(calendar.DAY_OF_MONTH,1); calendar.add(Calendar.MONDAY, 1); calendar.add(Calendar.DAY_OF_MONTH, -1); System.out.println( calendar.get(Calendar.DAY_OF_MONTH)); } }
package com.itinerary.guest.profile.dao; import com.itinerary.guest.profile.model.entity.EntityGuestprofile; /** * IGuestProfileDAO. */ public interface IGuestProfileDAO { /** * @param newguest * newguest * @return Long */ Long createGuest(EntityGuestprofile newguest); /** * @param emailId * emailId * @return boolean */ boolean checkGuestExist(String emailId); /** * @param emailId * emailId * @param password * password * @return EntityGuestprofile */ EntityGuestprofile validateGuest(String emailId, String password); }
package com.capstone.kidinvest.repositories; import com.capstone.kidinvest.models.Lemonade; import org.springframework.data.jpa.repository.JpaRepository; public interface LemonadeRepo extends JpaRepository<Lemonade, Long> { }
package models; import io.ebean.*; import javax.inject.Inject; import javax.persistence.*; @Entity @Table(name="cart") public class Cart extends Model{ @Id public Long id; public String items; public static Finder<Long,Cart> find = new Finder<>(Cart.class); }
package com.self.modules.blog.entity; import java.io.Serializable; import java.util.Date; /** * Blog class * * @author SuYiyi * @date 2018/03/17 */ public class Blog implements Serializable { /** * */ private static final long serialVersionUID = 1L; /** * id */ private Integer id; /** * 标题 */ private String title; /** * 内容 */ private String content; private String htmlCode; /** * 创建日期 */ private Date createDate; /** * 逻辑删除(0;1) */ private Integer delFlag; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } public String getHtmlCode() { return htmlCode; } public void setHtmlCode(String htmlCode) { this.htmlCode = htmlCode; } public Date getCreateDate() { return createDate; } public void setCreateDate(Date createDate) { this.createDate = createDate; } public Integer getDelFlag() { return delFlag; } public void setDelFlag(Integer delFlag) { this.delFlag = delFlag; } @Override public String toString() { return "Blog [id=" + id + ", title=" + title + ", content=" + content + ", htmlCode=" + htmlCode + ", createDate=" + createDate + ", delFlag=" + delFlag + "]"; } }
package br.com.genericsfx.dao; import br.com.genericsfx.model.Carro; public class CarroDao extends GenericDao<Carro, Integer> { private static CarroDao instance; private CarroDao() { super(Carro.class); } public static CarroDao getInstance() { if (instance == null) { instance = new CarroDao(); } return instance; } }
package nl.axians.ocp.demo.backend.domain; import lombok.*; import javax.persistence.CascadeType; import javax.persistence.JoinColumn; import javax.persistence.OneToOne; import javax.validation.Valid; import javax.validation.constraints.NotEmpty; import javax.validation.constraints.NotNull; import java.time.Instant; @Getter @Setter @NoArgsConstructor @AllArgsConstructor public class Task { private Long id; @NotEmpty private String title; private String description; @Valid @NotNull private User user; @NotNull private Instant creationDate; private Instant dueDate; @NotNull private TaskStatus status; }
package jcomponentslecture; import java.awt.Graphics; import javax.swing.JButton; import javax.swing.JFrame; public class None extends JFrame { private JButton b1, b2, b3; int count = 0; public None() { super("None"); setSize(400,450); setDefaultCloseOperation(EXIT_ON_CLOSE); setLayout(null); b1 = new JButton("one"); add(b1); b2 = new JButton("two"); add(b2); b3 = new JButton("three"); add(b3); b1.setBounds(50, 5, 100, 20); b2.setBounds(70, 35, 100, 20); // b3.setBounds(130, 45, 100, 50); } public void paint(Graphics g) { super.paint(g); // Note that I can also do the setBounds in the paint method. b3.setBounds(130, 45, 100, 50); System.out.println("paint called, count = " + count++); } public static void main(String[] args) { None none = new None(); none.setVisible(true); } }
package com.iterlife.xspring.beans.factory.support; import java.io.IOException; import com.iterlife.xspring.beans.factory.ApplicationContext; import com.iterlife.xspring.beans.factory.BeanFactory; import com.iterlife.xspring.beans.factory.ConfigurableApplicationContext; import com.iterlife.xspring.beans.factory.DisposableBean; import com.iterlife.xspring.beans.factory.config.BeanFactoryPostProcessor; import com.iterlife.xspring.beans.factory.config.BeanPostProcessor; import com.iterlife.xspring.context.ApplicationEvent; import com.iterlife.xspring.context.ApplicationListener; import com.iterlife.xspring.core.io.DefaultResourceLoader; import com.iterlife.xspring.core.io.Resource; import com.iterlife.xspring.exception.BeanException; import com.iterlife.xspring.exception.NoSuchBeanDefinitionException; public abstract class AbstractApplicationContext extends DefaultResourceLoader implements ConfigurableApplicationContext, DisposableBean { private ApplicationContext parent; //配置文件地址,配置在web.xml中 private String[] configLocations; public AbstractApplicationContext() { } public AbstractApplicationContext(ApplicationContext parent) { this.parent = parent; } @Override public String getId() { // TODO Auto-generated method stub return null; } @Override public String getDisplayName() { // TODO Auto-generated method stub return null; } @Override public long getStartupDate() { // TODO Auto-generated method stub return 0; } @Override public ApplicationContext getParentApplicationContext() { // TODO Auto-generated method stub return null; } @Override public void setParentBeanFactory(BeanFactory beanFactory) { // TODO Auto-generated method stub } @Override public void setBeanClassLoader(ClassLoader classLoader) { // TODO Auto-generated method stub } @Override public ClassLoader getBeanClassLoader() { // TODO Auto-generated method stub return null; } @Override public void setCacheBeanMetadata(boolean cacheBeanMetadata) { // TODO Auto-generated method stub } @Override public boolean isCacheBeanMetadata() { // TODO Auto-generated method stub return false; } @Override public void addBeanPostProcessor(BeanPostProcessor beanPostProcessor) { // TODO Auto-generated method stub } @Override public int getBeanPostProcessorCount() { // TODO Auto-generated method stub return 0; } @Override public boolean isFactoryBean() throws NoSuchBeanDefinitionException { // TODO Auto-generated method stub return false; } @Override public void registerDependentBean(String beanName, String dependentBeanName) { // TODO Auto-generated method stub } @Override public String getDependentBeans(String beanName) { // TODO Auto-generated method stub return null; } @Override public String getDependenciesForBean(String beanName) { // TODO Auto-generated method stub return null; } @Override public void destroyBean(String beanName, Object beanInstance) { // TODO Auto-generated method stub } @Override public void destroyScopeBean(String beanName) { // TODO Auto-generated method stub } @Override public void destroySingleton() { // TODO Auto-generated method stub } @Override public BeanFactory getParentFactory() { // TODO Auto-generated method stub return null; } @Override public Object getBean(String beanKey) { // TODO Auto-generated method stub return null; } @Override public Object getBeanByName(String beanName) { // TODO Auto-generated method stub return null; } @Override public Object getBeanById(String beanId) { // TODO Auto-generated method stub return null; } @Override public Object getBeanByAlias(String[] beanAlias) { // TODO Auto-generated method stub return null; } @Override public <T> T getBean(String beanName, Class<T> requiredType) throws BeanException { // TODO Auto-generated method stub return null; } @Override public boolean containBean(String beanName) throws NoSuchBeanDefinitionException { // TODO Auto-generated method stub return false; } @Override public boolean isSingleton(String beanName) throws NoSuchBeanDefinitionException { // TODO Auto-generated method stub return false; } @Override public boolean isProtoType(String beanName) throws NoSuchBeanDefinitionException { // TODO Auto-generated method stub return false; } @Override public boolean isTypeMatched(String beanName, Class beanType) throws NoSuchBeanDefinitionException { // TODO Auto-generated method stub return false; } @Override public String getBeanType(String beanName) { // TODO Auto-generated method stub return null; } @Override public String[] getBeanAlias(String beanName) { // TODO Auto-generated method stub return null; } @Override public String[] getCodes() { // TODO Auto-generated method stub return null; } @Override public String[] getArguments() { // TODO Auto-generated method stub return null; } @Override public String getDefaultMessage() { // TODO Auto-generated method stub return null; } @Override public void publishEvent(ApplicationEvent event) { // TODO Auto-generated method stub } @Override public Resource[] getResources(String locationPattern) throws IOException { // TODO Auto-generated method stub return null; } @Override public Resource getResource(String location) { // TODO Auto-generated method stub return null; } @Override public void setId(String id) { // TODO Auto-generated method stub } @Override public void setParent(ApplicationContext parent) { // TODO Auto-generated method stub } @Override public void addBeanFactoryPostProcessor(BeanFactoryPostProcessor processor) { // TODO Auto-generated method stub } @Override public void addApplicationListener(ApplicationListener listener) { // TODO Auto-generated method stub } @Override public void refresh() throws BeanException, IllegalStateException { // TODO Auto-generated method stub } @Override public void close() { // TODO Auto-generated method stub } public void setConfigLocations(String[] locations) { if (locations != null) { this.configLocations = new String[locations.length]; for (int i = 0; i < locations.length; ++i) { //此处应该进行路径地址的解析,因不同的操作系统其地址的表示是有区别的 this.configLocations[i] = locations[i]; } } else { this.configLocations = locations; } } public String[] getConfigLocations() { return this.configLocations; } @Override public boolean isActive() { // TODO Auto-generated method stub return false; } public ApplicationContext getParent() { return parent; } @Override public void destroy() throws Exception { // TODO Auto-generated method stub } }
package com.deepakm.algo.dp.fibonacci.tabulation; /** * Created by dmarathe on 1/27/16. */ public class TabulatedFibonacci { public static long fibonacci(int n){ long fib[] = new long[n+1]; fib[0] = 0; fib[1] = 1; for(int i=2;i<=n;i++){ fib[i] = fib[i-1] + fib[i-2]; } return fib[n]; } public static void main(String[] args) { long f93 = fibonacci(90); System.out.println(f93); } }
package com.example.NFEspring.entity; import javax.persistence.*; import javax.persistence.Entity; import javax.validation.constraints.NotEmpty; import java.io.Serializable; @Entity @Table(name = "category") public class Category implements Serializable { @Id @Column(name = "ca_id") @GeneratedValue(strategy = GenerationType.IDENTITY) private Integer id; @Column(name = "ca_name") @NotEmpty private String name; @Column(name = "ca_shortname") @NotEmpty private String shortname; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getShortname() { return shortname; } public void setShortname(String shortname) { this.shortname = shortname; } }
package com.darshankateshiya.interviewdemo.Adapter; import android.content.Context; import android.support.annotation.NonNull; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import com.darshankateshiya.interviewdemo.R; import com.darshankateshiya.interviewdemo.model.VIdeoListPojo.Category; import com.squareup.picasso.Picasso; import java.util.List; public class CategoryAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> { List<Category> categories; Context context; public CategoryAdapter(List<Category> categories, Context context) { this.categories = categories; this.context = context; } @NonNull @Override public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) { return new ItemCategories(LayoutInflater.from(context).inflate(R.layout.adapter_category_layout, viewGroup, false)); } @Override public void onBindViewHolder(@NonNull RecyclerView.ViewHolder viewHolder, int i) { ItemCategories list = (ItemCategories) viewHolder; Picasso.get().load(categories.get(i).getImage200()).transform(new CircleTransform()).into(list.ImgCatRcyImage); list.tvCatRcyTitle.setText(categories.get(0).getName()); } @Override public int getItemCount() { return categories.size(); } class ItemCategories extends RecyclerView.ViewHolder { ImageView ImgCatRcyImage; TextView tvCatRcyTitle; public ItemCategories(@NonNull View itemView) { super(itemView); ImgCatRcyImage = (ImageView)itemView.findViewById( R.id.ImgCatRcyImage ); tvCatRcyTitle = (TextView)itemView.findViewById( R.id.tvCatRcyTitle ); } } }
/* * Do whatever you want with it. */ package genetic; import java.util.ArrayList; /** * * @author Olayinka S. Folorunso <olayinka.sf@gmail.com> olayinka.sf@gmail.com * @param <T> */ public final class Chromosome<T> { ArrayList<Gene> genes; T fitness; long index; private static long INDEX = 0; public long getIndex() { return index; } public Chromosome(ArrayList<Gene> genes, T value) { this.genes = genes; this.fitness = value; index = INDEX; INDEX++; } public T getFitness() { return fitness; } public ArrayList<Gene> getGenes() { return genes; } public void setGenes(ArrayList<Gene> genes) { this.genes = genes; } @Override public String toString() { return "Chromosome{\n" + "\t" + "genes=" + genes.toString() + ",\n" + "\tvalue=" + fitness + ", index=" + index + "\n" + "}"; } }
import javafx.embed.swing.SwingFXUtils; import javafx.fxml.FXML; import javafx.scene.control.RadioButton; import javafx.scene.control.ToggleGroup; import javafx.scene.image.ImageView; import javafx.stage.FileChooser; import javafx.stage.Stage; import javax.imageio.ImageIO; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; public class MainController { private Stage stage; private ImageProcessor imageProcessor = null; @FXML private ImageView originalImageView; @FXML private ImageView resultImageView; @FXML private RadioButton fftRadioButton; @FXML private RadioButton reverseFftRadioButton; @FXML private RadioButton battervortRadioButton; @FXML private RadioButton gaussianRadioButton; MainController(Stage stage) { this.stage = stage; } @FXML private void openImage() { FileChooser chooser = new FileChooser(); chooser.setTitle("Открыть изображение"); File file = chooser.showOpenDialog(stage); if (file == null) { return; } BufferedImage bufferedImage = null; try { bufferedImage = ImageIO.read(file); } catch (IOException ex) { ex.printStackTrace(); } if (bufferedImage == null) { return; } resetRadioButtons(); originalImageView.setImage(SwingFXUtils.toFXImage(bufferedImage, null)); imageProcessor = new ImageProcessor(bufferedImage, bufferedImageAfterConversion -> resultImageView.setImage(SwingFXUtils.toFXImage(bufferedImageAfterConversion, null))); } @FXML private void performConversion() { if (imageProcessor != null) { if (fftRadioButton.isSelected()) { imageProcessor.fft(); } else if (reverseFftRadioButton.isSelected()) { imageProcessor.reverseFft(); } else if (battervortRadioButton.isSelected()) { imageProcessor.battervort(15, 4, 1); } else if (gaussianRadioButton.isSelected()) { imageProcessor.gaussian(5, 4); } } } void setRadioButtonsGroup() { ToggleGroup toggleGroup = new ToggleGroup(); fftRadioButton.setToggleGroup(toggleGroup); reverseFftRadioButton.setToggleGroup(toggleGroup); battervortRadioButton.setToggleGroup(toggleGroup); gaussianRadioButton.setToggleGroup(toggleGroup); } private void resetRadioButtons() { fftRadioButton.setSelected(false); reverseFftRadioButton.setSelected(false); battervortRadioButton.setSelected(false); gaussianRadioButton.setSelected(false); } public interface ShowImage { void show(BufferedImage bufferedImage); } }
package Models; public class Equipment extends ProductDescription { private String type; private String description; public Equipment(int barcode, String name, String productType, double price, double supplyPrice, String countryOfOrigin, String type, String description) { super(barcode, name, productType, price, supplyPrice, countryOfOrigin); this.setType(type); this.setDescription(description); } public String getType() { return type; } public void setType(String type) { this.type = type; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } }
package com.pky.smartselling.controller;
package package1; public interface Ordered { public boolean precedes(Object o); public boolean follows(Object o); public static void main(String[] args) { // TODO Auto-generated method stub } }
public class Multiplo5{ private int num; public Multiplo5(int num){ this.num=num; } public void setNum(int num){ num=num; } public float getNum(){ return num; } public void mul5(){ if(num%5==0){ System.out.println("Es multiplo de 5."); }else{System.out.println("No es multiplo de 5."); } } }
//Author: James Jia package csp; public class Driver { public static void main(String[] args) { System.out.println("MAP PROBLEM"); System.out.println("---------"); MapCSP problem = new MapCSP(); ConstraintSatisfactionProblem p = new ConstraintSatisfactionProblem(problem); p.backtracker(); for(int i=0; i<p.assignment.length; i++){ int color = p.assignment[i]; String realColor = problem.colors[color]; String variableName = problem.countries[i]; System.out.println("State: "+variableName+" Color: "+realColor); } System.out.println("node count: "+p.nodes); System.out.println("revision count: "+p.revisions); System.out.println("\n"); System.out.println("CIRCUIT PROBLEM"); System.out.println("---------"); CircuitCSP problem1 = new CircuitCSP(); ConstraintSatisfactionProblem p1 = new ConstraintSatisfactionProblem(problem1); p1.backtracker(); for(int i=0; i<p1.assignment.length; i++){ String variableName = problem1.shapes[i]; int assign = p1.assignment[i]; int[] realCoord = problem1.coordinateMap.get(assign); System.out.println("Shape: "+variableName+" Bottom Left Corner Coordinate: " +"("+realCoord[0]+","+realCoord[1]+")"); } System.out.println("node count: "+p1.nodes); System.out.println("revision count: "+p1.revisions); System.out.println("\n"); System.out.println("CIRCUITBOARD ASCII REPRESENTATION"); for(int y=2; y>=0; y--){ String s = ""; for(int x=0; x<10; x++){ String val = "*"; if(x==2&&y==0){ val = "A"; } if(x==5&&y==0){ val = "B"; } if(x==0&&y==0){ val = "C"; } if(x==2&&y==2){ val = "E"; } s+=val; } System.out.println(s); } } }
package LibraryManagementFunctionFactory; import model.*; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.Transaction; import util.HibernateUtils; import java.time.LocalDate; import java.time.LocalDateTime; import java.util.ArrayList; import java.util.List; public class LibraryManagementOptionsFactory { Session session = HibernateUtils.getSessionFactory().openSession(); private ArrayList<Employee> employees; private ArrayList<Client> clients; private ArrayList<Book> books; public LibraryManagementOptionsFactory(Session session) { this.session = session; } public LibraryManagementOptionsFactory() { } public void setSession(Session session) { this.session = session; } public void deleteUser(Employee u) { employees.remove(u); } public void addUser(Employee u) { employees.add(u); } // public void update(Employee employee){ // employee.setFirstName(); // } // public Book findBooksID(int Id) { // System.out.println("-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_--_-_-_-_-"); // System.out.println("Print All From Employee by id: "); // return session.find(Book.class, Id); // } // public boolean createCartelButton(LocalDateTime createdOn, String modifiedBy, Client clientId, Employee employeeId) { // // // the data are okay // // create the user // Cartel cartel = new Cartel(createdOn, modifiedBy, clientId, employeeId); // //this.cartel.add(cartel); // createCartel(cartel); // return true; // // } // public boolean logOutButton() { // return false; // } }
package com.jgw.supercodeplatform.trace.dto.certificate; import io.swagger.annotations.ApiModelProperty; import java.util.Date; public class CertificatePrintInfoDtoWithTemplateInfo { private Long id; private String certificateInfoId; @ApiModelProperty(value = "合格证id") private String certificateId; @ApiModelProperty(value = "合格证编号") private String certificateNumber; @ApiModelProperty(value = "合格证名称") private String certificateName; @ApiModelProperty(value = "打印张数") private Integer printQuantity; @ApiModelProperty(value = "打印设备") private String printDrive; private String createId; @ApiModelProperty(value = "打印时间") private Date createTime; @ApiModelProperty(value = "打印人") private String createMan; @ApiModelProperty(value = "打印时信息") private String certificateInfoData; private Integer printHeight; private Integer printWidth; public Integer getPrintHeight() { return printHeight; } public void setPrintHeight(Integer printHeight) { this.printHeight = printHeight; } public Integer getPrintWidth() { return printWidth; } public void setPrintWidth(Integer printWidth) { this.printWidth = printWidth; } public String getCertificateId() { return certificateId; } public void setCertificateId(String certificateId) { this.certificateId = certificateId; } public String getCertificateInfoData() { return certificateInfoData; } public void setCertificateInfoData(String certificateInfoData) { this.certificateInfoData = certificateInfoData; } public String getPrintDrive() { return printDrive; } public String getCertificateNumber() { return certificateNumber; } public void setCertificateNumber(String certificateNumber) { this.certificateNumber = certificateNumber; } public String getCertificateName() { return certificateName; } public void setCertificateName(String certificateName) { this.certificateName = certificateName; } public void setPrintDrive(String printDrive) { this.printDrive = printDrive; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getCertificateInfoId() { return certificateInfoId; } public void setCertificateInfoId(String certificateInfoId) { this.certificateInfoId = certificateInfoId == null ? null : certificateInfoId.trim(); } public Integer getPrintQuantity() { return printQuantity; } public void setPrintQuantity(Integer printQuantity) { this.printQuantity = printQuantity; } public String getCreateId() { return createId; } public void setCreateId(String createId) { this.createId = createId == null ? null : createId.trim(); } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } public String getCreateMan() { return createMan; } public void setCreateMan(String createMan) { this.createMan = createMan == null ? null : createMan.trim(); } }
package com.mediafire.sdk.response_models.data_models; /** * Created by Chris on 2/25/2015. */ public class NotificationModel { private String actor; private String timestamp; private String resource; private String message; public String getActor() { return actor; } public String getTimestamp() { return timestamp; } public String getResource() { return resource; } public String getMessage() { return message; } }
package servlets; import java.io.IOException; import javax.servlet.RequestDispatcher; 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 Excepions.UsersNotFound; import models.Utente; import persistence.DatabaseManager; import persistence.PostgresDAOFactory; import persistence.dao.AmiciziaDao; import persistence.dao.UtenteDao; /** * Servlet implementation class Transaction */ @WebServlet("/Transaction") public class Transaction extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public Transaction() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub String emailUs=request.getParameter("emailUs"); String nameUs=request.getParameter("nameUs"); String surnameUs=request.getParameter("surnameUs"); request.setAttribute("emailUs", emailUs); if(nameUs!=null && surnameUs!=null) { request.setAttribute("nameUs", nameUs); request.setAttribute("surnameUs", surnameUs); } RequestDispatcher rd = request.getRequestDispatcher("transaction.jsp"); rd.forward(request, response); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { PostgresDAOFactory p = new PostgresDAOFactory(); UtenteDao dao=p.getUtenteDao(); Utente mittente=new Utente("a","a",(String)request.getSession().getAttribute("email"),"a",(int)request.getSession().getAttribute("saldo"),"",true); try { String email = (String)request.getSession().getAttribute("email"); String emailUs =(String)request.getParameter("email"); AmiciziaDao amd = DatabaseManager.getInstance().getDaoFactory().getAmiciziaDao(); if(dao.existUtente((String)request.getParameter("email")) && !amd.checkRelation(email, emailUs).getValue().equals("active")) { response.getWriter().append("notfriend"); } else { Utente destinatario=dao.getUtenteforTransaction((String)request.getParameter("email")); dao.transaction(mittente, destinatario, Integer.parseInt(request.getParameter("importo"))); int oldSaldo=(int)request.getSession().getAttribute("saldo"); request.getSession().setAttribute("saldo", oldSaldo-Integer.parseInt(request.getParameter("importo"))); //response.sendRedirect("confirm.html"); response.getWriter().append("confirm"); } } catch (UsersNotFound e) { response.getWriter().append("failed"); } catch (Exception e) { } } }
package com.zantong.mobilecttx.presenter.presenterinterface; /** * Created by Administrator on 2016/5/5. */ public interface SimplePresenter { void loadView(int index); }
package com.github.dongchan.scheduler.example; import com.github.dongchan.scheduler.Scheduler; import com.github.dongchan.scheduler.task.helper.RecurringTask; import com.github.dongchan.scheduler.task.helper.Tasks; import com.github.dongchan.scheduler.task.schedule.FixedDelay; import com.mysql.cj.jdbc.MysqlDataSource; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.sql.DataSource; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.time.Duration; import java.util.Properties; /** * @author DongChan * @date 2020/10/23 * @time 11:12 AM */ public class SchedulerMain { private static final Logger log = LoggerFactory.getLogger(SchedulerMain.class); private static void example(DataSource dataSource){ //Recurring with no data RecurringTask<Void> recurring1 = Tasks.recurring("recurring", FixedDelay.of(Duration.ofSeconds(3))) .onFailureReschedule() // default .onDeadExecutionRevive() .execute((taskInstance, executionContext) -> { sleep(100); log.info("Executing "+ taskInstance.getTaskAndInstance()); }); // recurring with contant data RecurringTask<Integer> recurring2 = Tasks.recurring("recurring_constant_data", FixedDelay.of(Duration.ofSeconds(7)), Integer.class) .initialData(1) .onFailureReschedule() // default .onDeadExecutionRevive() // default .execute((taskInstance, executionContext) -> { sleep(100); log.info("Executing " + taskInstance.getTaskAndInstance() + " , data: " + taskInstance.getData()); }); final Scheduler scheduler = Scheduler .create(dataSource) .startTasks(recurring1) .build(); scheduler.start(); } public static void main(String[] args){ testDataSource("mysql"); example(getMySQLDataSource()); } private static DataSource getMySQLDataSource(){ Properties props = new Properties(); FileInputStream fis = null; MysqlDataSource mysqlDS = null; String resourceName = "db.properties"; ClassLoader loader = Thread.currentThread().getContextClassLoader(); try { InputStream is = loader.getResourceAsStream(resourceName); props.load(is); mysqlDS = new MysqlDataSource(); mysqlDS.setURL(props.getProperty("MYSQL_DB_URL")); mysqlDS.setUser(props.getProperty("MYSQL_DB_USERNAME")); mysqlDS.setPassword(props.getProperty("MYSQL_DB_PASSWORD")); } catch (IOException e) { e.printStackTrace(); } return mysqlDS; } private static void testDataSource(String dbType) { DataSource ds = null; if ("mysql".equals(dbType)) { ds = getMySQLDataSource(); } else { System.out.println("invalid db type"); return; } } private static void sleep(int ms) { try { Thread.sleep(ms); } catch (InterruptedException e) { } } }
package org.endeavourhealth.im.client; import org.endeavourhealth.common.config.ConfigManager; import org.endeavourhealth.common.config.ConfigManagerException; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; public class ReadOnlyTests { @BeforeClass public static void initialize() throws ConfigManagerException { ConfigManager.Initialize("information-model"); } @Test public void getConceptDbidForSchemeCode_SNOMED() throws Exception { Integer dbid = IMClient.getConceptDbidForSchemeCode("SNOMED", "195967001"); assertNotNull(dbid); assertEquals(123732, dbid.intValue()); } @Test public void getConceptIdForSchemeCode_SNOMED() throws Exception { String id = IMClient.getConceptIdForSchemeCode("SNOMED", "195967001"); assertNotNull(id); assertEquals("SN_195967001", id); } @Test public void getConceptDbidForSchemeCode_Known() throws Exception { Integer dbid = IMClient.getConceptDbidForSchemeCode("READ2", "H33.."); assertNotNull(dbid); assertEquals(1098404, dbid.intValue()); } @Test public void getConceptDbidForSchemeCode_FHIR() throws Exception { Integer dbid = IMClient.getConceptDbidForSchemeCode("FHIR_AS", "noshow"); assertNotNull(dbid); assertEquals(1335326, dbid.intValue()); } @Test public void getMappedCoreConceptDbidForSchemeCode_SNOMED() throws Exception { Integer dbid = IMClient.getMappedCoreConceptDbidForSchemeCode("SNOMED", "195967001"); assertNotNull(dbid); assertEquals(16507, dbid.intValue()); } @Test public void getMappedCoreConceptDbidForSchemeCode_Known() throws Exception { Integer dbid = IMClient.getMappedCoreConceptDbidForSchemeCode("BartsCerner", "162592560"); assertNotNull(dbid); assertEquals(1473193, dbid.intValue()); } @Test public void getMappedCoreConceptDbidForSchemeCode_FHIR() throws Exception { Integer dbid = IMClient.getMappedCoreConceptDbidForSchemeCode("FHIR_RS", "D19"); assertNotNull(dbid); assertEquals(1210789, dbid.intValue()); } @Test public void getMappedCoreConceptDbidForSchemeCode_NoMap() throws Exception { Integer dbid = IMClient.getMappedCoreConceptDbidForSchemeCode("OPCS4", "A01"); assertNull(dbid); } @Test public void getCodeForConceptDbid_SNOMED() throws Exception { String code = IMClient.getCodeForConceptDbid(123732); assertNotNull(code); assertEquals("195967001", code); } @Test public void getCodeForConceptDbid_READ() throws Exception { String code = IMClient.getCodeForConceptDbid(1098404); assertNotNull(code); assertEquals("H33..", code); } @Test public void getConceptDbidForTypeTerm_Known() throws Exception { Integer dbid = IMClient.getConceptDbidForTypeTerm("DCE_type_of_encounter", "practice nurse clinic"); assertNotNull(dbid); assertEquals(1335073, dbid.intValue()); } @Test public void getConceptDbidForTypeTerm_KnownSpecialChars() throws Exception { Integer dbid = IMClient.getConceptDbidForTypeTerm("DCE_type_of_encounter", "test {fail} 50%"); assertNotNull(dbid); assertEquals(1335073, dbid.intValue()); } @Test public void getMappedCoreConceptDbidForTypeTerm_Known() throws Exception { Integer dbid = IMClient.getMappedCoreConceptDbidForTypeTerm("DCE_type_of_encounter", "practice nurse clinic"); assertNotNull(dbid); assertEquals(1335073, dbid.intValue()); } }
package com.taotao.freemarker; import freemarker.template.Configuration; import freemarker.template.Template; import org.junit.Test; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.Writer; import java.util.HashMap; import java.util.Map; import java.util.WeakHashMap; /** * 测试freemarker */ public class TestFreemarker { @Test public void testFreemarker() throws Exception { //1.创建一个模板文件(就是我们刚创建的hello.ftl模板) //2.创建一个Configuration对象 Configuration configuration = new Configuration(Configuration.getVersion()); //3.设置模板所在的路径 configuration.setDirectoryForTemplateLoading(new File("S:/develop/IdeaProjests/shopping/taotao-item-web/src/main/webapp/WEB-INF/ftl")); //4.设置模板的字符集,一般为utf-8 configuration.setDefaultEncoding("utf-8"); //5.使用Configuration对象加载一个模板文件,需要指定模板文件的文件名。 Template template = configuration.getTemplate("hello.ftl"); //6.创建一个数据集,可以是pojo也可以是map,推荐使用map Map data = new HashMap<>(); data.put("hello","hello freemarker"); //7.创建一个Writer对象,指定输出文件的路径及文件名 Writer out = new FileWriter("F:/freemarker/out/hello.html"); //8.使用模板对象的process方法输出文件 template.process(data,out); //9.关闭流 out.close(); } }
package com.chisw.timofei.booking.config.server; import com.chisw.timofei.booking.config.server.config.ConfigServerSpringConfig; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.Import; /** * @author timofei.kasianov 10/12/18 */ @SpringBootApplication @Import(ConfigServerSpringConfig.class) public class ConfigServerApp { public static void main(String[] args) { SpringApplication.run(ConfigServerApp.class, args); } }
/** * Contains two classes describing connection with TextStatistics server application * {@link textstatistics.client.connection.ServerResponseErrorException} class and * {@link textstatistics.client.connection.TextStatisticsClient} class. */ package textstatistics.client.connection;
package com.sample1.controller; 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; @Controller public class IndexController { @RequestMapping(value="/", method = RequestMethod.GET ) public String startHtml(){ return "/home"; } @RequestMapping(value="/index.html", method = RequestMethod.GET ) public String startHtsafml(){ return "/home"; } }
package com.twillio.onlinecoding; import java.util.List; /* * Prison is made of horizontal bars and vertical bars * If the list of horizontal bars are removed and vertical bars are removed * find the max open window created in the prison * */ public class LargestPrisonWindowArea { public static long prison(int n, int m, List<Integer> h, List<Integer> v) { boolean[] hArr = new boolean[n + 1]; boolean[] vArr = new boolean[m + 1]; for (int i : h) { hArr[i] = true; } for (int i : v) { vArr[i] = true; } int hMax = 0, vMax = 0; int diff = 0; for (int i = 1; i < n + 1; i++) { if (!hArr[i]) { diff = 0; } else { hMax = Math.max(hMax, ++diff); } } diff = 0; for (int i = 1; i < m + 1; i++) { if (!vArr[i]) { diff = 0; } else { vMax = Math.max(vMax, ++diff); } } return (long) (hMax + 1) * (vMax + 1); } }
package com.rankytank.client.model; /** * */ public class DataGenerator { }
/* * Author: RINEARN (Fumihiro Matsui), 2020-2021 * License: CC0 */ package org.vcssl.nano.plugin.system.xnci1; import java.util.LinkedList; import java.util.List; import org.vcssl.connect.ConnectorException; import org.vcssl.connect.EngineConnectorInterface1; import org.vcssl.connect.ExternalFunctionConnectorInterface1; import org.vcssl.connect.ExternalNamespaceConnectorInterface1; import org.vcssl.connect.ExternalStructConnectorInterface1; import org.vcssl.connect.ExternalVariableConnectorInterface1; import org.vcssl.nano.plugin.system.xfci1.AssertXfci1Plugin; //Interface Specification: https://www.vcssl.org/en-us/dev/code/main-jimpl/api/org/vcssl/connect/ExternalNamespaceConnectorInterface1.html //インターフェース仕様書: https://www.vcssl.org/ja-jp/dev/code/main-jimpl/api/org/vcssl/connect/ExternalNamespaceConnectorInterface1.html public class SystemTestXnci1Plugin implements ExternalNamespaceConnectorInterface1 { @Override public String getNamespaceName() { return "System"; } @Override public boolean isMandatoryToAccessMembers() { return false; } @Override public ExternalFunctionConnectorInterface1[] getFunctions() { List<ExternalFunctionConnectorInterface1> functionList = new LinkedList<ExternalFunctionConnectorInterface1>(); functionList.add(new AssertXfci1Plugin()); return functionList.toArray(new ExternalFunctionConnectorInterface1[0]); } @Override public ExternalVariableConnectorInterface1[] getVariables() { List<ExternalVariableConnectorInterface1> variableList = new LinkedList<ExternalVariableConnectorInterface1>(); // variableList.add(...); return variableList.toArray(new ExternalVariableConnectorInterface1[0]); } @Override public ExternalStructConnectorInterface1[] getStructs() { return new ExternalStructConnectorInterface1[0]; } @Override public Class<?> getEngineConnectorClass() { return EngineConnectorInterface1.class; } @Override public void preInitializeForConnection(Object engineConnector) throws ConnectorException { } @Override public void postInitializeForConnection(Object engineConnector) throws ConnectorException { } @Override public void preInitializeForExecution(Object engineConnector) throws ConnectorException { } @Override public void postInitializeForExecution(Object engineConnector) throws ConnectorException { } @Override public void preFinalizeForTermination(Object engineConnector) throws ConnectorException { } @Override public void postFinalizeForTermination(Object engineConnector) throws ConnectorException { } @Override public void preFinalizeForDisconnection(Object engineConnector) throws ConnectorException { } @Override public void postFinalizeForDisconnection(Object engineConnector) throws ConnectorException { } }
package com.bnade.wow.service; import com.bnade.wow.entity.Pet; import com.bnade.wow.repository.PetRepository; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cache.annotation.Cacheable; import org.springframework.stereotype.Service; /** * 物品service * Created by liufeng0103@163.com on 2017/6/12. */ @Service public class PetService { private static Logger logger = LoggerFactory.getLogger(PetService.class); @Autowired private PetRepository petRepository; /** * 通过id查询宠物信息 * * @param petId 宠物id,在拍卖数据中叫petSpeciesId * @return Pet 宠物信息 */ @Cacheable(cacheNames="pets", keyGenerator="customKeyGenerator") public Pet findById(Integer petId) { return petRepository.findOne(petId); } }
package com.haku.light.scene; import com.haku.lecs.LECSContext; import com.haku.lecs.system.Event; import com.haku.light.input.event.InputEvent; import com.haku.light.input.mapping.InputMapper; import com.haku.light.scene.gui.RootView; public abstract class Scene extends LECSContext { public final InputMapper inputMapper = new InputMapper(this); public final RootView gui = new RootView(this); public void onStart() { /* empty */ } public void onResume() { /* empty */ } public void onUpdate() { this.inputMapper.onUpdate(); this.update(); this.gui.onRender(); } public void onPause() { /* empty */ } public void onStop() { /* empty */ } public void onResize(int width, int height) { this.onEvent("windowResize", width, height); this.gui.onResize(width, height); } public void onInputEvent(InputEvent event) { this.inputMapper.onInputEvent(event); } public void onEvent(String eventName, Object... extra) { this.onEvent(new Event(eventName, extra)); } public void onEvent(Event event) { this.systems.onEvent(event); } }
package com.edasaki.rpg.particles.custom.spells; import org.bukkit.Color; import org.bukkit.Location; import com.edasaki.core.utils.RMath; import de.slikey.effectlib.Effect; import de.slikey.effectlib.EffectManager; import de.slikey.effectlib.EffectType; import de.slikey.effectlib.util.ParticleEffect; public class HweenPumpkinBombEffect extends Effect { private Location loc; public HweenPumpkinBombEffect(EffectManager effectManager, Location loc) { super(effectManager); type = EffectType.INSTANT; this.loc = loc; setLocation(loc); } @Override public void onRun() { double x, y, z; for (int i = 0; i < 50; i++) { int count = 20; do { count--; x = RMath.randDouble(0, 2); y = RMath.randDouble(0, 2); z = RMath.randDouble(0, 2); } while (count >= 0 && x * x + y * y + z * z > 4); x -= 1; z -= 1; loc.add(x, y, z); display(ParticleEffect.REDSTONE, loc, Color.ORANGE); loc.subtract(x, y, z); } } }
package au.edu.jcu.cp3406.smartereveryday; import android.content.Context; import android.content.SharedPreferences; import android.os.Bundle; import android.text.Html; import android.util.Log; import android.view.View; import android.widget.ImageButton; import android.widget.TextView; import android.widget.Toast; import androidx.appcompat.app.AppCompatActivity; import androidx.fragment.app.Fragment; import androidx.fragment.app.FragmentManager; import androidx.fragment.app.FragmentTransaction; import java.util.Locale; import au.edu.jcu.cp3406.smartereveryday.game1.NumberSeriesFragment; import au.edu.jcu.cp3406.smartereveryday.game2.BallDropFragment; import au.edu.jcu.cp3406.smartereveryday.utils.DatabaseHelper; import au.edu.jcu.cp3406.smartereveryday.utils.SystemUI; public class GameActivity extends AppCompatActivity implements View.OnClickListener { public static FragmentManager fragmentManager; public static boolean sound, online; private boolean isLargeScreen; View fragmentContainer; Fragment currentFragment; TextView daysView; int days, intDifficulty; String name, difficulty; String[] difficulties = {"easy", "medium", "hard", "expert"}; DatabaseHelper databaseHelper; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_game); SystemUI.hide(this); daysView = findViewById(R.id.textView_days); databaseHelper = new DatabaseHelper(this); ImageButton back = findViewById(R.id.imageButton_back); back.setOnClickListener(this); ImageButton game1 = findViewById(R.id.imageButton_game1); game1.setOnClickListener(this); ImageButton game2 = findViewById(R.id.imageButton_game2); game2.setOnClickListener(this); ImageButton info1 = findViewById(R.id.imageButton_game1_info); info1.setOnClickListener(this); ImageButton info2 = findViewById(R.id.imageButton_game2_info); info2.setOnClickListener(this); fragmentContainer = findViewById(R.id.fragment_container); fragmentManager = getSupportFragmentManager(); isLargeScreen = fragmentContainer != null; } @Override protected void onPause() { super.onPause(); if (days > 1) { databaseHelper.insertFact(databaseHelper.getWritableDatabase(), "DAYS", days, name); } } @Override protected void onResume() { super.onResume(); SystemUI.hide(this); SharedPreferences loadSh = getSharedPreferences("playerPref", Context.MODE_PRIVATE); intDifficulty = loadSh.getInt("difficulty", 0); difficulty = difficulties[intDifficulty]; days = loadSh.getInt("days", 0); name = loadSh.getString("name", ""); online = loadSh.getBoolean("online", true); sound = loadSh.getBoolean("sound", true); Log.i("date", "days loaded: " + days); daysView.setText(String.format(Locale.getDefault(), Integer.toString(days))); // } @Override public void onWindowFocusChanged(boolean hasFocus) { super.onWindowFocusChanged(hasFocus); if (hasFocus) { SystemUI.hide(this); } } public void onClick(View view) { switch (view.getId()) { case R.id.imageButton_back: finish(); break; case R.id.imageButton_game1: NumberSeriesFragment fragment1 = NumberSeriesFragment.newInstance(difficulty, name); setFrag(fragment1); break; case R.id.imageButton_game2: BallDropFragment fragment2 = BallDropFragment.newInstance(difficulty, name); setFrag(fragment2); break; case R.id.imageButton_game1_info: Toast.makeText(this, Html.fromHtml( "<big>How to play <strong>Memory Builder: </strong></big><br>" + "Memorise the sequence of numbers that appears on the screen. " + "One number will be added each time.<br><br>" + "(Improves: Memory, Concentration & Patience)" ), Toast.LENGTH_LONG).show(); break; case R.id.imageButton_game2_info: Toast.makeText(this, Html.fromHtml( "<big>How to play <strong>Ball Drop: </strong></big><br>" + "Tilt your device to roll the ball into the green goal." + "<br><br>" + "(Improves: Motor Skills, Coordination & Spacial Awareness)" ), Toast.LENGTH_LONG).show(); break; } } private void setFrag(Fragment fragment) { FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction(); if (isLargeScreen) { if (currentFragment != null) { fragmentTransaction.remove(currentFragment); } fragmentTransaction.add(R.id.fragment_container, fragment); fragmentTransaction.commit(); } else { fragmentTransaction.add(R.id.game_activity, fragment); fragmentTransaction.commit(); } currentFragment = fragment; } }
package com.diego.timetables; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.SeekBar; import java.util.ArrayList; public class MainActivity extends AppCompatActivity { public ArrayList<Integer> numeros; public ArrayList<Integer> numerosAux; public ListView listNumbers; public ArrayAdapter adapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); listNumbers = (ListView) findViewById(R.id.listNumbers); numeros = new ArrayList<Integer>(); numeros.add(1); numeros.add(2); numeros.add(3); numeros.add(4); numeros.add(5); numeros.add(6); numeros.add(7); numeros.add(8); numeros.add(9); numeros.add(10); numerosAux = new ArrayList<>(numeros); adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, numeros); listNumbers.setAdapter(adapter); SeekBar seekBar = (SeekBar) findViewById(R.id.seekBar); seekBar.setMax(20); seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { for (int i = 0; i < numeros.size(); i++) { numeros.set(i, progress * numerosAux.get(i)); } adapter.notifyDataSetChanged(); //minimum value 1 if (seekBar.getProgress() < 1) { seekBar.setProgress(1); } } @Override public void onStartTrackingTouch(SeekBar seekBar) { } @Override public void onStopTrackingTouch(SeekBar seekBar) { } }); } }
package com.example.demo.javaconfig; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import com.netflix.loadbalancer.AvailabilityFilteringRule; import com.netflix.loadbalancer.IRule; @Configuration public class ApplicationConfig { @Bean public IRule ribbonRule() { AvailabilityFilteringRule rule = new AvailabilityFilteringRule(); return rule; } }
package dev.nowalk.services; import java.util.List; import dev.nowalk.models.Movie; public interface MovieService { /* * You may have 'trivial' services that simply call/return a particular DAO method * This is because we have to have single responsibility for our layers, each layer should only talk with they layer directly below or * above them with no skips. this is to prevent chaos and maintain our order */ //in our banking api project we will need services like transfer funds and such public Movie getMovie(int id); public List<Movie> getAllMovies(); public Movie addMovie(Movie m); public Movie updateMovie(Movie change); public Movie deleteMovie(int id); //any methods that we would like to create in this service //these services 'feel' like a real service. they are going to require some business logic upon data that is returned from our DAOs. public List<Movie> getMoviesAbovePrice(double price); public Movie checkout(Movie m); public boolean checkin(Movie m); }
package com.shilong.jysgl.pojo.vo; import java.util.Date; import com.shilong.jysgl.pojo.po.Sourcefile; import com.shilong.jysgl.utils.MyUtil; /** * @Descriptrion : * @author mr-li * @Company www.shilong.com * @CreateDate 2015年12月9日 */ public class SourceFileCustom extends Sourcefile { private String scsjstr; private Date scsj_start; private Date scsj_end; private String scrxm; private String wjdx_; private String zywjlxmc; public String getScsjstr() { return MyUtil.dateToString2(getScsj()); } public Date getScsj_start() { return scsj_start; } public void setScsj_start(Date scsj_start) { this.scsj_start = scsj_start; } public Date getScsj_end() { return scsj_end; } public void setScsj_end(Date scsj_end) { this.scsj_end = scsj_end; } public String getScrxm() { return scrxm; } public void setScrxm(String scrxm) { this.scrxm = scrxm; } public String getZywjlxmc() { return zywjlxmc; } public void setZywjlxmc(String zywjlxmc) { this.zywjlxmc = zywjlxmc; } public String getWjdx_() { String str= getWjdx()/1000000f+""; str=str.substring(0, str.indexOf(".")+2); return str+"M"; } }
package ru.otus.sua.L12.dbservice.dao; import ru.otus.sua.L12.entity.DataSet; import java.io.Serializable; import java.util.List; public interface DAO<T extends DataSet, K extends Serializable> { K create(T entity); T read(K id); void update(T entity); void delete(T entity); T findByName(String name); long count(); List<T> readAll(); }
package com.buddybank.mdw.common.constants; public class MDWConstants { public static final String UNKNOWN = "unknown"; public static final String N_A = "n/a"; }
package com.noobs2d.superawesomejetgame; import java.util.ArrayList; import com.badlogic.gdx.graphics.Camera; import com.badlogic.gdx.graphics.g2d.SpriteBatch; import com.badlogic.gdx.graphics.g2d.TextureAtlas.AtlasRegion; import com.noobs2d.scene2d.DynamicSprite; public class Projectile { ArrayList<Projectile> projectiles; Camera camera; DynamicSprite model; Jet jet; float speed = 1f; float targetX; float targetY; float totalTraversedY; public Projectile(AtlasRegion region, Jet jet, Camera camera, ArrayList<Projectile> projectiles, float targetX, float targetY, float offsetX, float offsetY) { this.jet = jet; this.camera = camera; this.projectiles = projectiles; this.targetX = targetX; this.targetY = targetY; model = new DynamicSprite(region, offsetX, offsetY); model.setScale(2f, 2f); } public Projectile(Jet jet, Camera camera, ArrayList<Projectile> projectiles, float targetX, float targetY, float offsetX, float offsetY) { this.jet = jet; this.camera = camera; this.projectiles = projectiles; this.targetX = targetX; this.targetY = targetY; model = new DynamicSprite(Assets.atlas.findRegion("RAIDEN-PROJECTILE"), offsetX, offsetY); model.setWidth(17); model.setHeight(48); } public void render(SpriteBatch batch, float delta) { model.draw(batch, 1f); model.setX(model.getX() + targetX * delta * speed); model.setY(model.getY() + targetY * delta * speed); totalTraversedY += targetY * delta * speed; if (model.getY() >= camera.position.y + Settings.SCREEN_HEIGHT / 2) projectiles.remove(this); } }
package com.example.ManHire.Repository; import com.example.ManHire.Entity.Position; import org.springframework.data.repository.CrudRepository; import org.springframework.data.repository.query.Param; import org.springframework.stereotype.Repository; import java.util.List; @Repository public interface PositionRepository extends CrudRepository<Position, Long> { List<Position> findAll(); }
package com.example.demo.repository; import com.example.demo.dto.Data3DTO; import com.example.demo.dto.PlayerDTO; import com.example.demo.entity.Player; import java.util.List; public interface PlayerRepository { Player save(Player player); //Insert Update List<Player> findAll(); //Select * from Player findByName(String name); // select where from Player findById(int id); void deleteById(Integer id); Player update(Player player); // List<Data3DTO> fetchData(); // List<Data3DTO> fetchData(); }
package jp.ac.kyushu_u.csce.modeltool.vdmEditor.editor; /** * VDMエディター関連の定数クラス * * @author KBK yoshimura */ public class VDMConstants { /** VDMエディターのスコープ */ public static final String SCOPE_ID_VDMEDITOR = "jp.ac.kyushu_u.csce.modeltool.vdm.editorScope"; //$NON-NLS-1$ }
package br.com.candleanalyser.util; import junit.framework.TestCase; public class UtilTest extends TestCase { public void testFixedList() { FixedQueue<Integer> fl = new FixedQueue<Integer>(5); assertEquals(0, fl.getSize()); fl.add(1); fl.add(2); assertEquals(2, fl.getSize()); fl.add(3); fl.add(4); fl.add(5); assertEquals(5, fl.getSize()); fl.add(6); fl.add(7); assertEquals(5, fl.getSize()); assertEquals(3, fl.get(0).intValue()); assertEquals(7, fl.get(4).intValue()); } }
package com.example.wastemanagement.Adapters; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import com.example.wastemanagement.Models.BinsData; import com.example.wastemanagement.Models.UserListData; import com.example.wastemanagement.R; import java.util.List; import androidx.annotation.NonNull; import androidx.recyclerview.widget.RecyclerView; public class UsersListAdapter extends RecyclerView.Adapter<UsersListAdapter.ViewHolder> { List itemlist; Context context; public UsersListAdapter(List itemlist, Context context) { this.itemlist = itemlist; this.context = context; } @NonNull @Override public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View view = LayoutInflater.from(context).inflate(R.layout.users_raw, parent, false); return new UsersListAdapter.ViewHolder(view); } @Override public void onBindViewHolder(@NonNull ViewHolder holder, int position) { UserListData userListData = (UserListData) itemlist.get(position); holder.imageView.setImageResource(R.drawable.ic_manage_profile); holder.name.setText(userListData.getName()); holder.email.setText(userListData.getEmail()); } @Override public int getItemCount() { return itemlist.size(); } public class ViewHolder extends RecyclerView.ViewHolder { ImageView imageView; TextView name,email; public ViewHolder(@NonNull View itemView) { super(itemView); imageView = itemView.findViewById(R.id.user_image); name = itemView.findViewById(R.id.user_name); email = itemView.findViewById(R.id.user_email); } } }
package com.improlabs.auth.db; public class AuthDB extends DbConnector{ public AuthDB(String hostName, String port, String username, String password, String dbName) { this.hostName=hostName; this.port=port; this.username=username; this.password=password; this.dbName=dbName; } public void select() { } }
/* * Copyright (c) 2015 ICM Uniwersytet Warszawski All rights reserved. * See LICENCE.txt file for licensing information. */ package pl.edu.icm.unity.db.model; /** * Change of group membership * @author K. Benedyczak */ public class GroupElementChangeBean extends GroupElementBean { private long newEntityId; public GroupElementChangeBean(long groupId, long elementId, long newEntityId) { super(groupId, elementId); this.newEntityId = newEntityId; } public long getNewEntityId() { return newEntityId; } public void setNewEntityId(long newEntityId) { this.newEntityId = newEntityId; } }
package br.com.lucro.manager.dao; import br.com.lucro.manager.model.FileOperationResumeOutstandingBalanceCielo; /** * * @author Georjuan Taylor * */ public interface FileOperationResumeOutstandingBalanceCieloDAO extends CRUD<FileOperationResumeOutstandingBalanceCielo> { }
package com.company.springer; import java.util.HashSet; import java.util.Scanner; public class Canvas { int height, width; Cell[] cells; String[] undoStr; public void createCanvas(int w, int h) { this.height = h; this.width = w; generateCellList(); } public void clearCanvas() { storeCellVals(); for(Cell c: this.cells) { c.clear(); } } public void undo() { for(int i = 0; i < this.cells.length; i++) { String oldVal = this.undoStr[i]; this.cells[i].point(oldVal); } } private void storeCellVals() { this.undoStr = new String[this.height * this.width]; for(int i = 0; i < this.cells.length; i++) { this.undoStr[i] = this.cells[i].val; } } // Find a cell based off x and y coordinates private Cell findCell(int x, int y) { for(Cell c: this.cells) { if(c.x == x && c.y == y) { return c; } } return null; } // Create a flat array, which assigns an x and y coordinates to a new Cell (based on it's index) private void generateCellList() { int size = this.width * this.height; Cell[] cellList = new Cell[size]; for(int index = 0; index < cellList.length; index++) { int y = (int) (Math.floor(index/this.width)); int x = (index - (y * this.width)); cellList[index] = new Cell(x, y); } this.cells = cellList; storeCellVals(); } // Draws the canvas public String createRenderString() { String result = ""; String vertRow = ""; for(int col = 0; col < this.width + 2; col++) { vertRow += "-"; } result += vertRow + "\n"; for(int y = 0; y < this.height; y++) { String rowString = "|"; for(int x = 0; x < this.width; x++) { rowString += findCell(x, y).val; } rowString += "|\n"; result += rowString; } result += vertRow; return result; } // Draws the canvas to the console private void renderCanvas() { System.out.println(createRenderString()); } // Checks if the x or y coordinate is out of bounds, if not find the cell and draw a point public void drawPoint(int x, int y) { storeCellVals(); if(x < 0 || x >= this.width || y < 0 || y >= this.height) { int maxWidth = this.width - 1, maxHeight = this.height - 1; throw new IllegalArgumentException("Unable to draw point x:" + x + ", y:" + y + ". Outside of canvas (max x:" + maxWidth + ", max y: " + maxHeight + ")"); } findCell(x,y).point("x"); } // Checks if the line is horizontal or vertical, then draws the points between the start and end points public void drawLine(int x1, int y1, int x2, int y2) { storeCellVals(); if(x1 == x2) { for(int row = y1; row <= y2; row++) { drawPoint(x1, row); } } else { for(int col = x1; col <= x2; col++) { drawPoint(col, y1); } } } // Draws lines to all four corners of the square (also draws rectangles) public void drawSquare(int x1, int y1, int x2, int y2) { storeCellVals(); drawLine(x1, y1, x2, y1); drawLine(x1, y1, x1, y2); drawLine(x2, y1, x2, y2); drawLine(x1, y2, x2, y2); } // Checks if a previous hash has been provided, identfies the neighbouring cells // runs through the neighbouring cells, filling providing they are fillable // and not already filled - recursively calls until no more cells to fill public void bucketFill(int x, int y, String filler, HashSet<Cell> hset) { HashSet<Cell> prevHash; if(hset != null) { prevHash = hset; } else { storeCellVals(); prevHash = new HashSet<Cell>(); } int[][] neighbours = new int[][] { {0,-1},// N {1,-1},// NE {1,0}, // E {1,1}, // SE {0,1}, // S {-1,1},// SW {-1,0},// W {-1,-1}// NW }; for(int[] n: neighbours) { Cell toFill = findCell(x + n[0], y + n[1]); if(toFill != null && canFill(toFill.x, toFill.y) && !prevHash.contains(toFill)) { prevHash.add(toFill); toFill.point(filler); bucketFill(toFill.x, toFill.y, filler, prevHash); } } } // Checks if the cell is out of bounds, or that that the cell does not contain a point "x" private boolean canFill(int x, int y) { if(x < this.width && x >= 0 && y < this.height && y >= 0 && !findCell(x,y).val.equals("x")) { return true; } return false; } // Interprets the user input to make calls to the methods, splits the user input string public void parseInput(String input) { String[] splitInput = input.split(" "); String command = splitInput[0]; if(command.equals("C")) { int h = Integer.parseInt(splitInput[1]); int w = Integer.parseInt(splitInput[2]); createCanvas(h, w); renderCanvas(); } if(command.equals("P")) { int x1 = Integer.parseInt(splitInput[1]); int y1 = Integer.parseInt(splitInput[2]); drawPoint(x1, y1); renderCanvas(); } if(command.equals("L")) { int x1 = Integer.parseInt(splitInput[1]); int y1 = Integer.parseInt(splitInput[2]); int x2 = Integer.parseInt(splitInput[3]); int y2 = Integer.parseInt(splitInput[4]); drawLine(x1, y1, x2, y2); renderCanvas(); } if(command.equals("S")) { int x1 = Integer.parseInt(splitInput[1]); int y1 = Integer.parseInt(splitInput[2]); int x2 = Integer.parseInt(splitInput[3]); int y2 = Integer.parseInt(splitInput[4]); drawSquare(x1, y1, x2, y2); renderCanvas(); } if(command.equals("B")) { String filler = splitInput[3]; int x1 = Integer.parseInt(splitInput[1]); int y1 = Integer.parseInt(splitInput[2]); bucketFill(x1, y1, filler, null); renderCanvas(); } if(command.equals("E")) { clearCanvas(); renderCanvas(); } if(command.equals("U")) { undo(); renderCanvas(); } if(command.equals("Q")) { System.exit(0); } } public static void main(String[] args) { Scanner keyboard = new Scanner(System.in); Canvas instance = new Canvas(); while(true) { System.out.print("Enter command: "); instance.parseInput(keyboard.nextLine()); } } }
package kr.co.people_gram.app; import android.content.Intent; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.widget.LinearLayout; /** * Created by 광희 on 2015-09-15. */ public class SubPeopleFragment_tip extends Fragment { private LinearLayout subpeople_menu1, subpeople_menu2, subpeople_menu3, subpeople_menu4, subpeople_menu5, subpeople_menu6; private PeopleData pd; //private TextView MY_std, YOU_std; public SubPeopleFragment_tip() { } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.subpeople_fragment, container, false); /* MY_std = (TextView) rootView.findViewById(R.id.MY_std); YOU_std = (TextView) rootView.findViewById(R.id.YOU_std); if(SubPeopleListSelect_Activity.my_type_check == false) { MY_std.setText("나 : 내 진단 기준"); } else { MY_std.setText("나 : 타인 진단 기준"); } if(SubPeopleListSelect_Activity.people_type_check == false) { YOU_std.setText("상대방 : 내 진단 기준"); } else { YOU_std.setText("상대방 : 타인 진단 기준"); } */ subpeople_menu1 = (LinearLayout) rootView.findViewById(R.id.subpeople_menu1); subpeople_menu2 = (LinearLayout) rootView.findViewById(R.id.subpeople_menu2); subpeople_menu3 = (LinearLayout) rootView.findViewById(R.id.subpeople_menu3); subpeople_menu4 = (LinearLayout) rootView.findViewById(R.id.subpeople_menu4); subpeople_menu5 = (LinearLayout) rootView.findViewById(R.id.subpeople_menu5); subpeople_menu6 = (LinearLayout) rootView.findViewById(R.id.subpeople_menu6); subpeople_menu1.setOnTouchListener(onBtnTouchListener); subpeople_menu1.setOnClickListener(onBtnClickListener); subpeople_menu2.setOnTouchListener(onBtnTouchListener); subpeople_menu2.setOnClickListener(onBtnClickListener); subpeople_menu3.setOnTouchListener(onBtnTouchListener); subpeople_menu3.setOnClickListener(onBtnClickListener); subpeople_menu4.setOnTouchListener(onBtnTouchListener); subpeople_menu4.setOnClickListener(onBtnClickListener); subpeople_menu5.setOnTouchListener(onBtnTouchListener); subpeople_menu5.setOnClickListener(onBtnClickListener); subpeople_menu6.setOnTouchListener(onBtnTouchListener); subpeople_menu6.setOnClickListener(onBtnClickListener); return rootView; } private View.OnTouchListener onBtnTouchListener = new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { return false; } }; private View.OnClickListener onBtnClickListener = new View.OnClickListener() { @Override public void onClick(View v) { //String point_str = SharedPreferenceUtil.getSharedPreference(getActivity().getBaseContext(), "point"); //int point = Integer.parseInt(point_str); Intent intent; //point = 0; /* if(point == 0) { intent = new Intent(getActivity().getBaseContext(), GramPopupNotActivity.class); } else { intent = new Intent(getActivity().getBaseContext(), GramPopupActivity.class); } */ intent = new Intent(getActivity().getBaseContext(), SubPeopleContents_Activity.class); switch (v.getId()) { case R.id.subpeople_menu1: intent.putExtra("matchNum","1"); break; case R.id.subpeople_menu2: intent.putExtra("matchNum","2"); break; case R.id.subpeople_menu3: intent.putExtra("matchNum","3"); break; case R.id.subpeople_menu4: intent.putExtra("matchNum","4"); break; case R.id.subpeople_menu5: intent.putExtra("matchNum","5"); break; case R.id.subpeople_menu6: intent.putExtra("matchNum", "6"); break; } getActivity().startActivity(intent); getActivity().overridePendingTransition(R.anim.slide_up_info, R.anim.slide_down_info); } }; }
package com.citibank.ods.persistence.pl.dao; /** * @author m.nakamura * * Interface para acesso ao banco de dados de Processos de Carga. */ public interface TplLoadProcessDAO extends BaseTplLoadProcessDAO { }
public class exer1 { public static void main(String[] args) { System.out.println("e = " + Euler()); } private static double Euler() { double e=1; double f=1; for ( int i=1; i <= 1000; i++) { f = f * (1.0 / i); System.out.println(f); if ( f == 0 ) break; e += f; } return e; } }
package compiler.nodes; public enum ActionType { GET, CONST, PUT; }
package fj.swsk.cn.eqapp.main.V; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.widget.ImageButton; import android.widget.RelativeLayout; import fj.swsk.cn.eqapp.R; /** * Created by apple on 16/6/17. */ public class EarthquakeDetailPop extends BasePopWindow implements View.OnClickListener { Context context; public ImageButton dissmissBtn; public EarthquakeDetailPop(View trig,Context context) { super(R.layout.earthquake_detail, LayoutInflater.from(context),-1,-1); this.context=context; init(); RelativeLayout.LayoutParams lp = (RelativeLayout.LayoutParams)dissmissBtn.getLayoutParams(); int pos[]=new int[2]; trig.getLocationOnScreen(pos); lp.topMargin=pos[1]; } public EarthquakeDetailPop(Context context){ super(R.layout.earthquake_detail, LayoutInflater.from(context),-1,-1); this.context=context; init(); } private void init(){ dissmissBtn=(ImageButton)contentView.findViewById(R.id.dismiss); dissmissBtn.setOnClickListener(this); } @Override public void onClick(View v) { if(v==dissmissBtn){ dismiss(); } } @Override public void execute() throws Throwable { } @Override public void resetTrigger() {} }
package com.packt.backgroundservicedemo; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.support.v4.content.LocalBroadcastManager; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.TextView; public class MainActivity extends AppCompatActivity { private TextView txvResult; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); txvResult = findViewById(R.id.txvResults); } public void startBackgroundService(View view) { Intent myServiceIntent = new Intent(this,MyBackgroundService.class); myServiceIntent.putExtra("sleepTime",12); startService(myServiceIntent); } public void stopBackgroundService(View view) { Intent myServiceIntent = new Intent(this,MyBackgroundService.class); stopService(myServiceIntent); } public void startIntentService(View view) { Intent intent = new Intent(this, MyIntentService.class); intent.putExtra("sleepTime",12); startService(intent); } private BroadcastReceiver myLocalBroadCastReciver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { int result = intent.getIntExtra("result",-1); txvResult.setText("Task Executed in " + result + " Sec."); } }; @Override protected void onResume() { super.onResume(); IntentFilter intentFilter = new IntentFilter("my.own.broadcast"); LocalBroadcastManager.getInstance(this).registerReceiver(myLocalBroadCastReciver,intentFilter); } @Override protected void onPause() { super.onPause(); LocalBroadcastManager.getInstance(this).unregisterReceiver(myLocalBroadCastReciver); } public void stopIntentFilter(View view) { Intent localIntent = new Intent("my.own.ServiceBroadCast"); localIntent.putExtra("result", false); LocalBroadcastManager.getInstance(this).sendBroadcast(localIntent); } public void startJobIntentService(View view) { Intent i = new Intent(this, MyJobIntentService.class); i.putExtra("sleepTime",12); //context.startService(i); MyJobIntentService.enqueueWork(this,i); } }
import static org.junit.jupiter.api.Assertions.assertEquals; import org.junit.jupiter.api.Test; public class MyTestCase { @Test public void mult_4_9_equals_37() throws InterruptedException { Calculator c = new Calculator(); assertEquals(c.multiply(4, 9), 37); System.out.println("4*9=37"); // where will this output appear? } }
import java.util.*; import java.io.*; public class homework_16{ public static void main(String[] args)throws IOException{ System.out.println("name:cck,number:20151681310210"); System.out.println("welcome to java"); File sourceFile = new File(args[0]); File temp = new File("temp.txt"); Scanner input = new Scanner(sourceFile); PrintWriter output = new PrintWriter(temp); while(input.hasNext()){ String s1 = input.nextLine(); String s2 = s1.replaceAll(args[1],args[2]); output.println(s2); } input.close(); output.close(); File sourceFile1 = new File("temp.txt"); File targetFile1 = new File(args[0]); Scanner input1 = new Scanner(sourceFile1); PrintWriter output1 = new PrintWriter(targetFile1); while(input1.hasNext()){ String s1 = input1.nextLine(); output1.println(s1); } input1.close(); output1.close(); } }
package com.swapp.service; import org.springframework.beans.factory.annotation.Autowired; import com.swapp.dao.MemberDAO; import com.swapp.vo.MemberVO; public class MemberServiceImpl implements MemberService { @Autowired MemberDAO memberDAO; //회원가입 @Override public void MemberJoin(MemberVO vo) { System.out.println("회원가입 서비스 시작"); memberDAO.MemberJoin(vo); System.out.println("회원가입 서비스 끝"); } }
package pl.almestinio.countdowndays.ui.editCountdownView; import org.joda.time.DateTime; import pl.almestinio.countdowndays.database.DatabaseCountdownDay; import pl.almestinio.countdowndays.model.CountdownDay; /** * Created by mesti193 on 4/1/2018. */ public class EditCountdownPresenter implements EditCountdownContracts.Presenter { private EditCountdownContracts.View view; public EditCountdownPresenter(EditCountdownContracts.View view){ this.view = view; } @Override public void getColor(String color, int id) { view.showColorPicker(color, id); } @Override public void editCountdownToDatabase(CountdownDay countdownDay, String title, DateTime dateTime, String colorStroke, String colorSolid) { try { DatabaseCountdownDay.updateDays(countdownDay.getId(), title, dateTime, colorStroke, colorSolid); view.showSnackbarSuccess("Edit successful"); view.startMenuFragment(); }catch (Exception e){ view.showSnackbarError("Error with updating countdown to database"); e.printStackTrace(); } } }
package matthbo.mods.darkworld.proxy; public class ServerProxy extends CommonProxy { @Override public boolean fancyGraphics() { return true; } public void textureFix(){} }
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package org.dizitart.nitrite.datagate.impl.repository; import java.util.List; import org.dizitart.nitrite.datagate.entity.user.DatagateUser; /** * * @author tareq */ public interface DatagateUserRepository { /** * Gets a user by the username * * @param username the username to look for * @return the user if found, null otherwise */ DatagateUser getUserByUsername(String username); /** * Gets a list of all users * * @return a list of users */ List<DatagateUser> getAllUsers(); /** * Get a list of all expired users * * @return a list of expired users */ List<DatagateUser> getExpiredUsers(); /** * Add a new user * * @param user the user to add * @return true if the user was added successfully, false otherwise */ boolean addUser(DatagateUser user); /** * Update an existing user by matching the username * * @param user the user to update */ void update(DatagateUser user); }
package com.karya.bean; import javax.validation.constraints.NotNull; import org.hibernate.validator.constraints.NotEmpty; public class TerritoryBean { private int terId; @NotNull @NotEmpty(message = "Please enter territoryName") private String terName; public int getTerId() { return terId; } public void setTerId(int terId) { this.terId = terId; } public String getTerName() { return terName; } public void setTerName(String terName) { this.terName = terName; } }
package com.hwj.aspect; import javax.servlet.http.HttpServletRequest; import org.aspectj.lang.JoinPoint; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.AfterReturning; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Before; import org.aspectj.lang.annotation.Pointcut; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; import org.springframework.web.context.request.RequestContextHolder; import org.springframework.web.context.request.ServletRequestAttributes; /** * <p>Company: B505信息技术研究所 </p> * @Description: 对web请求进行日志记录 * @Create Date: 2017年5月11日下午9:45:00 * @Version: V1.00 */ @Aspect @Component public class HttpAspect { private final static Logger logger = LoggerFactory.getLogger(HttpAspect.class); //两个..代表所有子目录,最后括号里的两个..代表所有参数 @Pointcut("execution( public * com.hwj.web.*.*(..))") public void log(){ } @Before("log()") public void doBefore(JoinPoint joinPoint){ ServletRequestAttributes attributes =(ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); HttpServletRequest request = attributes.getRequest(); //url logger.info("请求地址:"+"url={}" , request.getRequestURL()); //method logger.info("请求方法:"+"method={}" ,request.getMethod()); //ip,也可以获取端口号 logger.info("IP地址:"+"ip={}" , request.getRemoteAddr()); //获取端口号 logger.info("请求端口:"+"host={}"+request.getRemoteHost()); //类方法 logger.info("请求方法:"+"class_method={}" , joinPoint.getSignature().getDeclaringTypeName()+"."+joinPoint.getSignature().getName()); //方法的参数 logger.info("方法参数:"+"args={}" , joinPoint.getArgs()); } @AfterReturning(returning = "object",pointcut = "log()") public void doAfterReturning(Object object){ logger.info("返回结果:"+"response={}" , object.toString()); } @Around("log()") public Object daRound(ProceedingJoinPoint pjp) throws Throwable{ long startTime = System.currentTimeMillis(); Object ob = pjp.proceed();// ob 为方法的返回值 logger.info("耗时 : " + (System.currentTimeMillis() - startTime)); return ob; } }
package middleware; import java.io.File; import javax.ws.rs.client.Client; import javax.ws.rs.client.ClientBuilder; import javax.ws.rs.client.Entity; import javax.ws.rs.client.Invocation; import javax.ws.rs.client.WebTarget; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import org.json.simple.JSONObject; import domain.IDescriptor; import domain.Operation; import domain.Property; import exceptions.MiddlewareException; public class RestClient { private static final RestClient INSTANCE = new RestClient(); private Client client; private WebTarget myResource; private UriBuilder uBuild; public static RestClient getINSTANCE() { return INSTANCE; } private RestClient(){ this.client = ClientBuilder.newClient(); this.uBuild = new UriBuilder(); } public File get() throws MiddlewareException{ this.uBuild.clear(); return this.makeTheCall(uBuild.add("/devices").getStringUri()); } public File get(IDescriptor desc) throws MiddlewareException{ this.uBuild.clear(); this.uBuild.add("/devices") .add("/") .add(desc.getId()) .add("/") .add("functions"); return makeTheCall(this.uBuild.getStringUri()); } private File makeTheCall(String uri) throws MiddlewareException { this.myResource = client.target(uri); Invocation.Builder invocationBuilder = this.myResource.request(MediaType.APPLICATION_JSON); Response response = invocationBuilder.get(); int stato = response.getStatus(); if (stato >= 300 ) { throw new MiddlewareException("si è riscontrato un problema di chiamata"); } return response.readEntity(File.class); } public File post(Property prop) throws MiddlewareException { this.uBuild.clear(); this.uBuild.add("/functions/"); this.uBuild.add(prop.getFunctionId()); JSONObject body = this.constructGetPropBody(prop); return this.makeTheCall(this.uBuild.getStringUri(), body); } private JSONObject constructGetPropBody(Property prop) { JSONObject body = new JSONObject(); String app = prop.getName().toString().substring(0, 1).toUpperCase() + prop.getName().toString().substring(1); body.put("operation", "get" + app); return body; } public File makeTheCall(String uri, JSONObject body) throws MiddlewareException{ this.myResource = client.target(uri); Invocation.Builder invocationBuilder = this.myResource.request(MediaType.APPLICATION_JSON); Response response = invocationBuilder.post(Entity.entity(body, MediaType.APPLICATION_JSON)); if (response.getStatus()>= 300 ) throw new MiddlewareException("si è riscontrato un problema di chiamata"); return response.readEntity(File.class); } public File post(Operation operation) throws MiddlewareException { this.uBuild.clear(); this.uBuild.add("/functions/"); this.uBuild.add(operation.getFunctionId()); JSONObject body = this.constructOperationBody(operation); return this.makeTheCall(this.uBuild.getStringUri(), body); } private JSONObject constructOperationBody(Operation operation) { JSONObject body = new JSONObject(); body.put("operation", (String) operation.getName()); return body; } }
package www.scientistx.saftafood; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.EditText; import android.widget.ImageButton; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.TextView; import android.text.format.DateFormat; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.fragment.app.DialogFragment; import com.firebase.ui.database.FirebaseListAdapter; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.database.FirebaseDatabase; public class notification_bar extends DialogFragment { private FirebaseListAdapter<vp_message> adapter; FirebaseDatabase database; FirebaseAuth auth; ImageButton Send; EditText message1; LinearLayout layoutt; ListView listView; @Nullable @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { super.onCreateView(inflater, container, savedInstanceState); View view= inflater.inflate(R.layout.notification_bar, container, false); layoutt=view.findViewById(R.id.hs); database=FirebaseDatabase.getInstance(); auth=FirebaseAuth.getInstance(); Send=view.findViewById(R.id.send); message1=view.findViewById(R.id.message1); listView=view.findViewById(R.id.list); String em=auth.getInstance().getCurrentUser().getEmail(); if(em.equals("mksa.sazzad@gmail.com")||em.equals("jayanta15-2641@diu.edu.bd")){ message1.setVisibility(View.VISIBLE); Send.setVisibility(View.VISIBLE); }else{ message1.setVisibility(View.INVISIBLE); Send.setVisibility(View.INVISIBLE); } Send.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String email="SAFTA Food"; String message= message1.getText().toString().trim(); database.getReference("users").push().setValue(new vp_message(email,message)); message1.setText(""); } }); displayMessage(); return view; } public void displayMessage(){ adapter=new FirebaseListAdapter<vp_message>(getActivity(),vp_message.class,R.layout.vp_message_list, database.getReference("users")) { @Override protected void populateView(View v, vp_message model, int position) { TextView name,mess,date; name=v.findViewById(R.id.user_vp); mess=v.findViewById(R.id.message_vp); date=v.findViewById(R.id.date_vp); name.setText(model.getName()); mess.setText(model.getBody()); date.setText(DateFormat.format("dd.MM.yyyy (hh:mm)",model.getTime())); } }; listView.setAdapter(adapter); } }
/** * */ package com.kaishengit.servlet; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * @ClassName: UpdateServlet * @Description: * @author: 刘忠伟 * @date: 2016年11月24日 下午4:12:27 * @version 1.0 * */ public class UpdateServlet extends HttpServlet{ private static final long serialVersionUID = 1L; /* (non-Javadoc) * 初始化 */ @Override public void init() throws ServletException { } /** * @Description:销毁 * @author: 刘忠伟 * @return:void * @time:2016年11月24日 下午4:13:56 */ private void destory() { } /* (non-Javadoc) * */ @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { } }
package common; public interface GameConstants { int CANVAS_WIDTH = 400; int CANVAS_HEIGHT = 300; int DELAY = 25; int STARTX = 50; int STARTY = CANVAS_HEIGHT/2; int STARTHP = 100; int GUN_DAMAGE = 5; int GUN_SPEED = 9; int MISSLE_DAMAGE = 10; int MISSLE_SPEED = 6; int LASER_DAMAGE = 40; // image file names String CREEP_IMAGENAME = "creep"; String MOVING_CREEP_IMAGENAME = "m_creep"; // path file names String CREEP_PATH_1 = "res/info/creep_paths/creep_path_1.txt"; String ERIC_PATH = "res/info/creep_paths/eric_path.txt"; String FONT_PATH = "res/font/emulogic.ttf"; }