Dataset Viewer
Auto-converted to Parquet Duplicate
text
stringlengths
10
2.72M
package com.smxknife.mybatis._01_xml; import org.apache.ibatis.executor.resultset.ResultSetHandler; import org.apache.ibatis.plugin.Interceptor; import org.apache.ibatis.plugin.Intercepts; import org.apache.ibatis.plugin.Invocation; import org.apache.ibatis.plugin.Signature; import java.sql.Statement; /** * @author smxknife * 2021/6/23 */ @Intercepts({ // 这里的Signature定义的是拦截哪个类的哪个方法,比如这里拦截的是Executor类型,方法是query @Signature(type = ResultSetHandler.class, method = "handleResultSets", args = {Statement.class}) }) public class ResultSetHandlerPlugin implements Interceptor { @Override public Object intercept(Invocation invocation) throws Throwable { final Object proceed = invocation.proceed(); if (proceed != null) { System.out.println("ResultSetHandler intercept | " + proceed.getClass()); } return proceed; } @Override public Object plugin(Object target) { if (ResultSetHandler.class.isAssignableFrom(target.getClass())) { System.out.println("ResultSetHandler plugin target | " + target.getClass()); final Object plugin = Interceptor.super.plugin(target); System.out.println("ResultSetHandler plugin plugin | " + plugin.getClass()); return plugin; } else { return target; } } }
package org.cap.dao; import java.util.List; import org.cap.model.Product; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; import org.springframework.transaction.annotation.Transactional; @Repository("productDbDao") @Transactional public interface IProductDbDao extends JpaRepository<Product, Integer>{ public List<Product> findByquantity(int quantity); public List<Product> findByquantityAndPrice(int quantity,double price); public List<Product> findByproductNameContaining(String productName); }
package com.coding.java.lambda.part01; /** * Created by scq on 2018-07-26 11:11:17 */ @FunctionalInterface public interface MyPredicate<T> { public boolean test(T t); }
import java.util.Scanner; public class Problem5_10 { public static void main(String[] args) { final int NUMBERS_PER_LINE = 10; int count = 0 ; for(int i = 100 ; i<= 1000;i++) { //Test if number is divisible by 5 and 6 if( i % 5 == 0 && i % 6 == 0) { count ++; // increment count //Test if numbers per line is 10 if(count % NUMBERS_PER_LINE == 0) System.out.println(i); else System.out.print(i + " "); } } } } /*(Find numbers divisible by 5 and 6) Write a program that displays all the numbers from 100 to 1,000, ten per line, that are divisible by 5 and 6. Numbers are separated by exactly one space. */
package com.lotto.app; import org.apache.log4j.Logger; import com.lotto.app.ServiceLocator; import com.lotto.model.LottoResult; import com.lotto.services.LottoService; public class LottoApp { private static Logger logger = Logger.getLogger(LottoApp.class); private static LottoResult lottoResult; public static void main(String[] args) { lottoResult = new LottoResult(); try { LottoService lottoService = ServiceLocator.getLottoService(); lottoResult = lottoService.jouerLotto(); System.out.print( lottoResult.getFirstTirage() + lottoResult.getSecondTirage() + lottoResult.getThirdTirage()); } catch (Exception e) { logger.error("Une erreur est survenue : " + e.getMessage()); } } }
package com.qcwp.carmanager.enumeration; import com.qcwp.carmanager.R; /** * Created by qyh on 2017/1/3. */ public enum ProfessionalTestEnum { HectometerAccelerate(2), KilometersAccelerate(5), KilometersBrake(6), Noise(7), Unknown(0); private final int value; ProfessionalTestEnum(int value) { this.value = value; } public int getValue() { return value; } }
package com.project.loginservice.service; import com.project.loginservice.pojo.BuyerSignupPojo; public interface BuyerSignupService { BuyerSignupPojo validateBuyersignup(BuyerSignupPojo buyerSignupPojo); BuyerSignupPojo getBuyer(Integer id); }
package com.example.rashapp; import android.content.Context; import android.hardware.Sensor; import android.hardware.SensorEvent; import android.hardware.SensorEventListener; import android.hardware.SensorManager; import android.media.MediaPlayer; import android.os.AsyncTask; import android.os.Build; import android.os.Bundle; import android.os.VibrationEffect; import android.os.Vibrator; import android.util.Log; import android.view.MotionEvent; import android.view.View; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.Spinner; import android.widget.Toast; import androidx.appcompat.app.AppCompatActivity; import org.json.JSONException; import org.json.JSONObject; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; public class Collect_Data extends AppCompatActivity implements SensorEventListener { public static String ops[] ={"Select","Weaving","Lanechanging","Sudden Braking"}; Spinner sp; Button b,b1,b2; Sensor accelerometer; SensorManager sm; private SensorManager sensorManager; // private Sensor accelerometer; private float deltaXMax = 0; private float deltaYMax = 0; private float deltaZMax = 0; private float deltaX = 0; private float deltaY = 0; private float deltaZ = 0; boolean flag =false; private float vibrateThreshold = 0; public Vibrator v; private float lastX, lastY, lastZ; String data="",type= ""; Vibrator vibrator; MediaPlayer mediaPlayer; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_collect__data); sp = (Spinner) findViewById(R.id.sp); b = (Button) findViewById(R.id.button); b1 = (Button) findViewById(R.id.button1); b2=(Button)findViewById(R.id.btnTV); ArrayAdapter<String> adapterCategory = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item,ops); adapterCategory.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); sp.setAdapter(adapterCategory); sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE); if (sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER) != null) { // success! we have an accelerometer accelerometer = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER); sensorManager.registerListener(this, accelerometer, SensorManager.SENSOR_DELAY_NORMAL); vibrateThreshold = accelerometer.getMaximumRange() / 2; } else { // fai! we dont have an accelerometer! } vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE); //initialize vibration v = (Vibrator) this.getSystemService(Context.VIBRATOR_SERVICE); ((Button) findViewById(R.id.button)).setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View arg0, MotionEvent event) { if(event.getAction() == MotionEvent.ACTION_DOWN){ // start the thread Log.d(">>","Touched"); type=sp.getSelectedItem().toString(); flag =true; return true; } else if(event.getAction() == MotionEvent.ACTION_UP){ // stop the thread Log.d(">>","Released"); flag =false; new update_loc().execute(); return true; } return false; } }); ((Button) findViewById(R.id.button1)).setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View arg0, MotionEvent event) { if(event.getAction() == MotionEvent.ACTION_DOWN){ // start the thread Log.d(">>","Touched"); b2.setVisibility(View.INVISIBLE); flag =true; return true; } else if(event.getAction() == MotionEvent.ACTION_UP){ // stop the thread Log.d(">>","Released"); flag =false; new update_loc1().execute(); return true; } return false; } }); } private class update_loc extends AsyncTask<Void, String, String> { @Override public String doInBackground(Void... Void) { JSONObject jsn = new JSONObject(); String response = ""; try { URL url = new URL(Global.url +"train_data"); jsn.put("type", type); jsn.put("data", data); response = HttpClientConnection.getData(url,jsn); Log.d("Response",""+response); } catch (MalformedURLException e) { e.printStackTrace(); } catch(JSONException e) { e.printStackTrace(); } catch(IOException e) { e.printStackTrace(); } return response; } @Override protected void onPostExecute(String s) { if(s.endsWith("null")) { s=s.substring(0,s.length()-4); } Toast.makeText(getApplicationContext(),s, Toast.LENGTH_LONG).show(); data=""; } } private class update_loc1 extends AsyncTask<Void, String, String> { @Override public String doInBackground(Void... Void) { JSONObject jsn = new JSONObject(); String response = ""; try { URL url = new URL(Global.url +"predict_data"); jsn.put("data", data); response = HttpClientConnection.getData(url,jsn); Log.d("Response",""+response); } catch (MalformedURLException e) { e.printStackTrace(); } catch(JSONException e) { e.printStackTrace(); } catch(IOException e) { e.printStackTrace(); } return response; } @Override protected void onPostExecute(String s) { if(s.endsWith("null")) { s=s.substring(0,s.length()-4); } if(!s.equalsIgnoreCase("")) { b2.setVisibility(View.VISIBLE); b2.setText(s); Toast.makeText(getApplicationContext(),s, Toast.LENGTH_LONG).show(); if (Build.VERSION.SDK_INT >= 26) { vibrator.vibrate(VibrationEffect.createOneShot(4000, VibrationEffect.DEFAULT_AMPLITUDE)); } else { vibrator.vibrate(4000); } mediaPlayer = MediaPlayer.create(Collect_Data.this, R.raw.m); mediaPlayer.start(); // data=""; } } } @Override public void onSensorChanged(SensorEvent event) { //This is done to prevent multiple values above threshold being registered as multiple potholes long actualTime = event.timestamp; // get the change of the x,y,z values of the accelerometer deltaX = Math.abs(lastX - event.values[0]); deltaY = Math.abs(lastY - event.values[1]); deltaZ = Math.abs(lastZ - event.values[2]); // if the change is below 2, it is just plain noise if (deltaX < 2) deltaX = 0; if (deltaY < 2) deltaY = 0; if ((deltaZ >vibrateThreshold) || (deltaY > vibrateThreshold) || (deltaZ > vibrateThreshold)) { v.vibrate(50); } if(flag==true) { Log.d("moves", deltaX + "#" + deltaY + "#" + deltaZ + ""); data+=deltaX + "#" + deltaY + "#" + deltaZ + "\n"; } } @Override public void onAccuracyChanged(Sensor sensor, int accuracy) { } //onResume() register the accelerometer for listening the events protected void onResume() { super.onResume(); sensorManager.registerListener(this, accelerometer, SensorManager.SENSOR_DELAY_NORMAL); } //onPause() unregister the accelerometer for stop listening the events protected void onPause() { super.onPause(); sensorManager.unregisterListener(this); } }
package yincheng.gggithub.provider.viewholder; import android.graphics.Color; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.text.format.Formatter; import android.view.View; import android.view.ViewGroup; import java.text.NumberFormat; import butterknife.BindView; import yincheng.gggithub.R; import yincheng.gggithub.helper.InputHelper; import yincheng.gggithub.helper.LinkParserHelper; import yincheng.gggithub.helper.ParseDateFormat; import yincheng.gggithub.library.recyclerview.BaseRecyclerAdapter; import yincheng.gggithub.library.recyclerview.BaseViewHolder; import yincheng.gggithub.mvp.model.Repo; import yincheng.gggithub.view.widget.AvatarLayout; import yincheng.gggithub.view.widget.FontTextView; public class ReposViewHolder extends BaseViewHolder<Repo> { @BindView(R.id.title) FontTextView title; @BindView(R.id.date) FontTextView date; @BindView(R.id.stars) FontTextView stars; @BindView(R.id.forks) FontTextView forks; @BindView(R.id.language) FontTextView language; @BindView(R.id.size) FontTextView size; @Nullable @BindView(R.id.avatarLayout) AvatarLayout avatarLayout; // @BindString(R.string.forked) String forked; // @BindString(R.string.private_repo) String privateRepo; // @BindColor(R.color.material_indigo_700) int forkColor; // @BindColor(R.color.material_grey_700) int privateColor; private boolean isStarred; private boolean withImage; private ReposViewHolder(@NonNull View itemView, @Nullable BaseRecyclerAdapter adapter, boolean isStarred, boolean withImage) { super(itemView, adapter); this.isStarred = isStarred; this.withImage = withImage; } public static ReposViewHolder newInstance(ViewGroup viewGroup, BaseRecyclerAdapter adapter, boolean isStarred, boolean withImage) { if (withImage) { return new ReposViewHolder(getView(viewGroup, R.layout.item_repo_searched), adapter, isStarred, true); } else { return new ReposViewHolder(getView(viewGroup, R.layout.item_repo_searched_noimage), adapter, isStarred, false); } } @Override public void bind(@NonNull Repo repo) { if (repo.isFork() && !isStarred) { // title.setText(SpannableBuilder.builder() // .append(" " + forked + " ", new LabelSpan(forkColor)) // .append(" ") // .append(repo.getName(), new LabelSpan(Color.TRANSPARENT))); title.setText("fasdfa"); } else if (repo.isPrivateX()) { // title.setText(SpannableBuilder.builder() // .append(" " + privateRepo + " ", new LabelSpan(privateColor)) // .append(" ") // .append(repo.getName(), new LabelSpan(Color.TRANSPARENT))); title.setText("wodeshijie"); } else { title.setText(!isStarred ? repo.getName() : repo.getFull_name()); } if (withImage) { String avatar = repo.getOwner() != null ? repo.getOwner().getAvatar_url() : null; String login = repo.getOwner() != null ? repo.getOwner().getLogin() : null; boolean isOrg = repo.getOwner() != null && repo.getOwner().isSite_admin(); if (avatarLayout != null) { avatarLayout.setVisibility(View.VISIBLE); avatarLayout.setUrl(avatar, login, isOrg, LinkParserHelper.isEnterprise(repo .getHtml_url())); } } long repoSize = repo.getSize() > 0 ? (repo.getSize() * 1000) : repo.getSize(); size.setText(Formatter.formatFileSize(size.getContext(), repoSize)); NumberFormat numberFormat = NumberFormat.getNumberInstance(); stars.setText(numberFormat.format(repo.getStargazers_count())); forks.setText(numberFormat.format(repo.getForks())); date.setText(ParseDateFormat.getTimeAgo(repo.getUpdated_at())); if (!InputHelper.isEmpty(repo.getLanguage())) { language.setText(repo.getLanguage()); // language.setTextColor(ColorsProvider.getColorAsColor(repo.getLanguage(), language // .getContext())); language.setVisibility(View.VISIBLE); } else { language.setTextColor(Color.BLACK); language.setVisibility(View.GONE); language.setText(""); } } }
/* * created 09.01.2006 * * Copyright 2009, ByteRefinery * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * $Id$ */ package com.byterefinery.rmbench.test; import com.byterefinery.rmbench.external.IDDLFormatter; import com.byterefinery.rmbench.external.IDDLGenerator; import com.byterefinery.rmbench.external.IDDLScript; import com.byterefinery.rmbench.external.IDDLScript.Statement; /** * a test formatter that just writes statements through * * @author cse */ public class DDLFormatter implements IDDLFormatter { public static final class Factory implements IDDLFormatter.Factory { public IDDLFormatter createFormatter(IDDLGenerator generator) { return new DDLFormatter(); } } public void format(Statement statement, String terminator, IDDLScript.Writer writer) { writer.print(statement.getString()); writer.println(); } }
package com.phplogin.sidag.gcm; import android.app.IntentService; import android.content.Intent; import android.util.Log; import com.google.android.gms.gcm.GoogleCloudMessaging; import com.google.android.gms.iid.InstanceID; import java.io.IOException; /** * Created by Siddhant on 11/14/2015. */ public class RegistrationIntentService extends IntentService { /** * Creates an IntentService. Invoked by your subclass's constructor. * * @param name Used to name the worker thread, important only for debugging. */ private static final String name = "RegistrationService"; public RegistrationIntentService() { super(name); } public void onCreate(){ super.onCreate(); } @Override protected void onHandleIntent(Intent intent) { InstanceID instanceID = InstanceID.getInstance(this); try { String token = instanceID.getToken("939133146521", GoogleCloudMessaging.INSTANCE_ID_SCOPE, null); Log.d("token", "Token: " + token); } catch (IOException e) { e.printStackTrace(); } } private void sendTokenToServer(String token){ } }
package com.asen.android.lib.permissions.core; /** * 权限监测的监听调用 * * @author Asen * @version v2.0 * @email [email protected] * @date 2017/5/16 13:26 */ public interface OnCheckPermissionListener { /** * 成功授予权限时回调 */ public void permissionGranted(); }
package com.sales.entity; import java.util.Date; public class SalesOrderDetailEntity { private Integer salesDetailId; private Integer salesOrderId; private Integer productId; private String productName; private String productSpu; private String customCode; private Integer productDetailId; private String productSku; private String colorName; private String sizeName; private String productBarcode; private Integer productQuantity; private Integer salesPackageQuantity; private Double productPrice; private Double productTotalPrice; private Double productDiscount; private Integer storeId; private String salesDetailRemark; private Date createTime; private Date updateTime; public Integer getSalesDetailId() { return salesDetailId; } public void setSalesDetailId(Integer salesDetailId) { this.salesDetailId = salesDetailId; } public Integer getSalesOrderId() { return salesOrderId; } public void setSalesOrderId(Integer salesOrderId) { this.salesOrderId = salesOrderId; } public Integer getProductId() { return productId; } public void setProductId(Integer productId) { this.productId = productId; } public String getProductName() { return productName; } public void setProductName(String productName) { this.productName = productName == null ? null : productName.trim(); } public String getProductSpu() { return productSpu; } public void setProductSpu(String productSpu) { this.productSpu = productSpu == null ? null : productSpu.trim(); } public String getCustomCode() { return customCode; } public void setCustomCode(String customCode) { this.customCode = customCode == null ? null : customCode.trim(); } public Integer getProductDetailId() { return productDetailId; } public void setProductDetailId(Integer productDetailId) { this.productDetailId = productDetailId; } public String getProductSku() { return productSku; } public void setProductSku(String productSku) { this.productSku = productSku == null ? null : productSku.trim(); } public String getColorName() { return colorName; } public void setColorName(String colorName) { this.colorName = colorName == null ? null : colorName.trim(); } public String getSizeName() { return sizeName; } public void setSizeName(String sizeName) { this.sizeName = sizeName == null ? null : sizeName.trim(); } public String getProductBarcode() { return productBarcode; } public void setProductBarcode(String productBarcode) { this.productBarcode = productBarcode == null ? null : productBarcode.trim(); } public Integer getProductQuantity() { return productQuantity; } public void setProductQuantity(Integer productQuantity) { this.productQuantity = productQuantity; } public Integer getSalesPackageQuantity() { return salesPackageQuantity; } public void setSalesPackageQuantity(Integer salesPackageQuantity) { this.salesPackageQuantity = salesPackageQuantity; } public Double getProductPrice() { return productPrice; } public void setProductPrice(Double productPrice) { this.productPrice = productPrice; } public Double getProductTotalPrice() { return productTotalPrice; } public void setProductTotalPrice(Double productTotalPrice) { this.productTotalPrice = productTotalPrice; } public Double getProductDiscount() { return productDiscount; } public void setProductDiscount(Double productDiscount) { this.productDiscount = productDiscount; } public Integer getStoreId() { return storeId; } public void setStoreId(Integer storeId) { this.storeId = storeId; } public String getSalesDetailRemark() { return salesDetailRemark; } public void setSalesDetailRemark(String salesDetailRemark) { this.salesDetailRemark = salesDetailRemark == null ? null : salesDetailRemark.trim(); } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } public Date getUpdateTime() { return updateTime; } public void setUpdateTime(Date updateTime) { this.updateTime = updateTime; } }
import java.util.*; class kmax { public static void main(String args[]) { int j,i,n,k,max; Scanner in=new Scanner(System.in); n=in.nextInt(); int[] a=new int[n]; for(i=0;i<n;i++) { a[i]=in.nextInt(); } k=in.nextInt(); for(i=0;i<a.length-k;i++) { max=a[i]; for(j=1;j<k;j++) { if(a[i+j] > max) max=a[i+j]; }System.out.print(max + " "); } }}
public class whackAmoleRunner { public static void main(String[] args) { whackAmole wam=new whackAmole(); wam.makeButtons(); } }
/** * MOTECH PLATFORM OPENSOURCE LICENSE AGREEMENT * * Copyright (c) 2010-11 The Trustees of Columbia University in the City of * New York and Grameen Foundation USA. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. Neither the name of Grameen Foundation USA, Columbia University, or * their respective contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY GRAMEEN FOUNDATION USA, COLUMBIA UNIVERSITY * AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, * BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GRAMEEN FOUNDATION * USA, COLUMBIA UNIVERSITY OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.motechproject.server.omod.web.controller; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.motechproject.server.service.ContextService; import org.motechproject.server.omod.web.model.WebModelConverter; import org.motechproject.server.omod.web.model.WebPatient; import org.motechproject.server.svc.RegistrarBean; import org.motechproject.server.util.MotechConstants; import org.motechproject.ws.ContactNumberType; import org.motechproject.ws.Gender; import org.motechproject.ws.MediaType; import org.openmrs.Patient; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.beans.propertyeditors.CustomDateEditor; import org.springframework.beans.propertyeditors.StringTrimmerEditor; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.validation.Errors; import org.springframework.validation.ValidationUtils; import org.springframework.web.bind.WebDataBinder; import org.springframework.web.bind.annotation.InitBinder; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.SessionAttributes; import org.springframework.web.bind.support.SessionStatus; @Controller @RequestMapping("/module/motechmodule/pregnancy") @SessionAttributes("pregnancy") public class PregnancyController { private static Log log = LogFactory.getLog(PregnancyController.class); private WebModelConverter webModelConverter; @Autowired @Qualifier("registrarBean") private RegistrarBean registrarBean; private ContextService contextService; @Autowired public void setContextService(ContextService contextService) { this.contextService = contextService; } public void setRegistrarBean(RegistrarBean registrarBean) { this.registrarBean = registrarBean; } @Autowired public void setWebModelConverter(WebModelConverter webModelConverter) { this.webModelConverter = webModelConverter; } @InitBinder public void initBinder(WebDataBinder binder) { String datePattern = "dd/MM/yyyy"; SimpleDateFormat dateFormat = new SimpleDateFormat(datePattern); dateFormat.setLenient(false); binder.registerCustomEditor(Date.class, new CustomDateEditor( dateFormat, true, datePattern.length())); String timePattern = MotechConstants.TIME_FORMAT_DELIVERY_TIME; SimpleDateFormat timeFormat = new SimpleDateFormat(timePattern); dateFormat.setLenient(false); binder.registerCustomEditor(Date.class, "timeOfDay", new CustomDateEditor(timeFormat, true, timePattern.length())); binder .registerCustomEditor(String.class, new StringTrimmerEditor( true)); } @RequestMapping(method = RequestMethod.GET) public void viewForm(@RequestParam(required = false) Integer id, ModelMap model) { } @ModelAttribute("pregnancy") public WebPatient getWebPregnancy(@RequestParam(required = false) Integer id) { WebPatient result = new WebPatient(); if (id != null) { Patient patient = contextService.getPatientService().getPatient(id); if (patient != null) { webModelConverter.patientToWeb(patient, result); } } return result; } @RequestMapping(method = RequestMethod.POST) public String submitForm(@ModelAttribute("pregnancy") WebPatient pregnancy, Errors errors, ModelMap model, SessionStatus status) { log.debug("Register New Pregnancy on Existing Patient"); Patient patient = null; if (pregnancy.getId() != null) { patient = registrarBean.getPatientById(pregnancy.getId()); if (patient == null) { errors.reject("motechmodule.id.notexist"); } } else { errors.reject("motechmodule.id.required"); } if (!Gender.FEMALE.equals(pregnancy.getSex())) { errors.reject("motechmodule.sex.female.required"); } if (registrarBean.getActivePregnancy(pregnancy.getId()) != null) { errors.reject("motechmodule.Pregnancy.active"); } ValidationUtils.rejectIfEmptyOrWhitespace(errors, "dueDate", "motechmodule.dueDate.required"); if (pregnancy.getDueDate() != null) { Calendar calendar = Calendar.getInstance(); calendar.add(Calendar.MONTH, 9); if (pregnancy.getDueDate().after(calendar.getTime())) { errors.rejectValue("dueDate", "motechmodule.dueDate.overninemonths"); } } ValidationUtils.rejectIfEmptyOrWhitespace(errors, "dueDateConfirmed", "motechmodule.dueDateConfirmed.required"); ValidationUtils.rejectIfEmptyOrWhitespace(errors, "enroll", "motechmodule.enroll.required"); if (Boolean.TRUE.equals(pregnancy.getEnroll())) { if (!Boolean.TRUE.equals(pregnancy.getConsent())) { errors.rejectValue("consent", "motechmodule.consent.required"); } ValidationUtils.rejectIfEmptyOrWhitespace(errors, "phoneType", "motechmodule.phoneType.required"); if (pregnancy.getPhoneType() == ContactNumberType.PERSONAL || pregnancy.getPhoneType() == ContactNumberType.HOUSEHOLD) { ValidationUtils.rejectIfEmptyOrWhitespace(errors, "phoneNumber", "motechmodule.phoneNumber.required"); } ValidationUtils.rejectIfEmptyOrWhitespace(errors, "mediaType", "motechmodule.mediaType.required"); if (pregnancy.getPhoneType() == ContactNumberType.PUBLIC && pregnancy.getMediaType() != null && pregnancy.getMediaType() != MediaType.VOICE) { errors.rejectValue("mediaType", "motechmodule.mediaType.voice"); } ValidationUtils.rejectIfEmptyOrWhitespace(errors, "language", "motechmodule.language.required"); if (pregnancy.getMediaType() == MediaType.TEXT && pregnancy.getLanguage() != null && !pregnancy.getLanguage().equals("en")) { errors.rejectValue("language", "motechmodule.language.english"); } ValidationUtils.rejectIfEmptyOrWhitespace(errors, "interestReason", "motechmodule.interestReason.required"); ValidationUtils.rejectIfEmptyOrWhitespace(errors, "howLearned", "motechmodule.howLearned.required"); } if (pregnancy.getPhoneNumber() != null && !pregnancy.getPhoneNumber().matches( MotechConstants.PHONE_REGEX_PATTERN)) { errors.rejectValue("phoneNumber", "motechmodule.phoneNumber.invalid"); } validateTextLength(errors, "phoneNumber", pregnancy.getPhoneNumber(), MotechConstants.MAX_STRING_LENGTH_OPENMRS); if (!errors.hasErrors()) { registrarBean.registerPregnancy(patient, pregnancy.getDueDate(), pregnancy.getDueDateConfirmed(), pregnancy.getEnroll(), pregnancy.getConsent(), pregnancy.getPhoneNumber(), pregnancy.getPhoneType(), pregnancy.getMediaType(), pregnancy.getLanguage(), pregnancy.getDayOfWeek(), pregnancy.getTimeOfDay(), pregnancy.getInterestReason(), pregnancy.getHowLearned()); model.addAttribute("successMsg", "motechmodule.Pregnancy.register.success"); status.setComplete(); return "redirect:/module/motechmodule/viewdata.form"; } return "/module/motechmodule/pregnancy"; } void validateTextLength(Errors errors, String fieldname, String fieldValue, int lengthLimit) { if (fieldValue != null && fieldValue.length() > lengthLimit) { errors.rejectValue(fieldname, "motechmodule.string.maxlength", new Integer[] { lengthLimit }, "Specified text is longer than max characters."); } } }
package tsubulko.entity; import tsubulko.entity.Person; import lombok.*; import java.util.Date; import java.util.LinkedList; @Data public class Employee extends Person { public enum Education { None, Middle, Hight; } private double salary; private int experiense; // private LinkedList<String> workPlaces; private Education education; public Employee(int id,Birth dateOfBirth, String name, String surname, Sex sex, String email, Adress adress,Position position, double salary, int experiense, Education education) { super(id,dateOfBirth, name, surname, sex, email, adress, position); this.salary = salary; this.experiense = experiense; // this.workPlaces = workPlaces; this.education = education; } public Employee() { } }
package com.parkinglot; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import java.util.ArrayList; import java.util.List; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.Mockito.*; public class AttendantTest { @Test public void ShouldParkWhenSpacesAreAvailable() throws Exception{ ParkingLot availableLot = mock(ParkingLot.class); List<ParkingLot> allLots = new ArrayList<ParkingLot>(); allLots.add(availableLot); Attendant attendant = new Attendant(allLots); Parkable car = mock(Parkable.class); when(availableLot.isSpaceAvailable()).thenReturn(true); attendant.attendantPark(car); verify(availableLot).park(car); } @Test public void ShouldBeAllowedToParkInAvailableLotWhenOneLotIsFull() throws Exception{ ParkingLot fullLot = mock(ParkingLot.class); Parkable car= mock(Parkable.class); ParkingLot availableLot = mock(ParkingLot.class); List<ParkingLot> allLots = new ArrayList<ParkingLot>(); allLots.add(fullLot); allLots.add(availableLot); Attendant attendant = new Attendant(allLots); Parkable anotherCar = mock(Parkable.class); when(fullLot.isSpaceAvailable()).thenReturn(false); when(availableLot.isSpaceAvailable()).thenReturn(true); attendant.attendantPark(anotherCar); verify(availableLot).park(anotherCar); } @Test public void ShouldNotBeAllowedToParkWhenAllLotsFull() throws Exception{ ParkingLot fullLot = mock(ParkingLot.class); ParkingLot availableLot = mock(ParkingLot.class); List<ParkingLot> allLots = new ArrayList<ParkingLot>(); allLots.add(fullLot); allLots.add(availableLot); Attendant attendant = new Attendant(allLots); Parkable car = mock(Parkable.class); when(fullLot.isSpaceAvailable()).thenReturn(false); when(availableLot.isSpaceAvailable()).thenReturn(false); assertThrows(AllParkingLotsFullException.class, () -> attendant.attendantPark(car)); } }
package jawale.ankita.stateslistproject; 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.TextView; public class StatesAdapter extends RecyclerView.Adapter<StatesAdapter.StateViewHolder> { public interface ListItemClickListener{ void onListItemClick(int position); } private String[] stateLists; ListItemClickListener itemClickListener; public StatesAdapter(String[] stateLists,ListItemClickListener itemClickListener) { this.stateLists = stateLists; this.itemClickListener = itemClickListener; } @NonNull @Override public StateViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { Boolean attachViewImmediatelyToParent = false; View singleItemLayout = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item,parent,attachViewImmediatelyToParent); StateViewHolder myViewHolder = new StateViewHolder(singleItemLayout); return myViewHolder; } @Override public void onBindViewHolder(@NonNull StatesAdapter.StateViewHolder holder, int position) { holder.textToShow.setText(stateLists[position]); } @Override public int getItemCount() { return stateLists.length; } public class StateViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{ TextView textToShow; public StateViewHolder(View itemView) { super(itemView); textToShow = (TextView) itemView.findViewById(R.id.text_view); textToShow.setOnClickListener(this); } @Override public void onClick(View v) { itemClickListener.onListItemClick(getAdapterPosition()); } } }
package com.briup.apps.zhaopin.bean; public class City { /** * * This field was generated by MyBatis Generator. * This field corresponds to the database column zp_city.id * * @mbg.generated Wed Dec 11 22:10:15 CST 2019 */ private Long id; /** * * This field was generated by MyBatis Generator. * This field corresponds to the database column zp_city.name * * @mbg.generated Wed Dec 11 22:10:15 CST 2019 */ private String name; /** * * This field was generated by MyBatis Generator. * This field corresponds to the database column zp_city.province_id * * @mbg.generated Wed Dec 11 22:10:15 CST 2019 */ private Long provinceId; /** * This method was generated by MyBatis Generator. * This method returns the value of the database column zp_city.id * * @return the value of zp_city.id * * @mbg.generated Wed Dec 11 22:10:15 CST 2019 */ public Long getId() { return id; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column zp_city.id * * @param id the value for zp_city.id * * @mbg.generated Wed Dec 11 22:10:15 CST 2019 */ public void setId(Long id) { this.id = id; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column zp_city.name * * @return the value of zp_city.name * * @mbg.generated Wed Dec 11 22:10:15 CST 2019 */ public String getName() { return name; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column zp_city.name * * @param name the value for zp_city.name * * @mbg.generated Wed Dec 11 22:10:15 CST 2019 */ public void setName(String name) { this.name = name == null ? null : name.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column zp_city.province_id * * @return the value of zp_city.province_id * * @mbg.generated Wed Dec 11 22:10:15 CST 2019 */ public Long getProvinceId() { return provinceId; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column zp_city.province_id * * @param provinceId the value for zp_city.province_id * * @mbg.generated Wed Dec 11 22:10:15 CST 2019 */ public void setProvinceId(Long provinceId) { this.provinceId = provinceId; } }
/* * Copyright (c) 2010, 2018, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ import java.io.ByteArrayOutputStream; import java.io.Closeable; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.ArrayList; import java.util.List; import java.util.jar.JarFile; import java.util.jar.JarInputStream; import java.util.jar.JarOutputStream; import au.net.zeus.util.jar.Pack200; /* * @test * @bug 6985763 * @summary verify that proper exceptions are thrown * @compile -XDignore.symbol.file Utils.java TestExceptions.java * @run main TestExceptions * @author ksrini */ public class TestExceptions { static final File testJar = new File("test.jar"); static final File testPackFile = new File("test.pack"); static void init() { Utils.jar("cvf", testJar.getAbsolutePath(), "."); JarFile jf = null; try { jf = new JarFile(testJar); Utils.pack(jf, testPackFile); } catch (IOException ioe) { throw new Error("Initialization error", ioe); } finally { Utils.close(jf); } } // a test that closes the input jarFile. static void pack200Test1() { PackTestInput ti = null; // setup the scenario try { ti = new PackTestInput(new JarFile(testJar), new ByteArrayOutputStream()); } catch (Exception e) { throw new Error("Initialization error", e); } finally { Utils.close(ti.getJarFile()); } // test the scenario try { System.out.println(ti); Pack200.Packer p = Pack200.newPacker(); p.pack(ti.getJarFile(), ti.getOutputStream()); } catch (Exception e) { ti.checkException(e); } finally { if (ti != null) { ti.close(); } } } // test the Pack200.pack(JarFile, OutputStream); static void pack200Test2() { List<PackTestInput> tlist = new ArrayList<PackTestInput>(); try { // setup the test scenarios try { tlist.add(new PackTestInput((JarFile)null, null)); tlist.add(new PackTestInput(new JarFile(testJar), null)); tlist.add(new PackTestInput((JarFile)null, new ByteArrayOutputStream())); } catch (Exception e) { throw new Error("Initialization error", e); } // test the scenarios for (PackTestInput ti : tlist) { System.out.println(ti); try { Pack200.Packer p = Pack200.newPacker(); p.pack(ti.getJarFile(), ti.getOutputStream()); } catch (Exception e) { ti.checkException(e); } } } finally { // clean up for (TestInput ti : tlist) { if (ti != null) { ti.close(); } } } } // test the Pack200.pack(JarInputStream, OutputStream); static void pack200Test3() { List<PackTestJarInputStream> tlist = new ArrayList<PackTestJarInputStream>(); try { // setup the test scenarios try { tlist.add(new PackTestJarInputStream((JarInputStream)null, null)); tlist.add(new PackTestJarInputStream((JarInputStream)null, new ByteArrayOutputStream())); tlist.add(new PackTestJarInputStream( new JarInputStream(new FileInputStream(testJar)), null)); } catch (Exception e) { throw new Error("Initialization error", e); } for (PackTestJarInputStream ti : tlist) { System.out.println(ti); try { Pack200.Packer p = Pack200.newPacker(); p.pack(ti.getJarInputStream(), ti.getOutputStream()); } catch (Exception e) { ti.checkException(e); } } } finally { // clean up for (PackTestJarInputStream ti : tlist) { if (ti != null) { ti.close(); } } } } // test the Pack200.unpack(InputStream, OutputStream); static void unpack200Test1() { List<UnpackTestInput> tlist = new ArrayList<UnpackTestInput>(); try { // setup the test scenarios try { tlist.add(new UnpackTestInput((InputStream)null, null)); tlist.add(new UnpackTestInput(new FileInputStream(testPackFile), null)); tlist.add(new UnpackTestInput((InputStream) null, new JarOutputStream(new ByteArrayOutputStream()))); } catch (Exception e) { throw new Error("Initialization error", e); } // test the scenarios for (UnpackTestInput ti : tlist) { System.out.println(ti); try { Pack200.Unpacker unpacker = Pack200.newUnpacker(); unpacker.unpack(ti.getInputStream(), ti.getJarOutputStream()); } catch (Exception e) { ti.checkException(e); } } } finally { // clean up for (TestInput ti : tlist) { if (ti != null) { ti.close(); } } } } // test the Pack200.unpack(File, OutputStream); static void unpack200Test2() { List<UnpackTestFileInput> tlist = new ArrayList<UnpackTestFileInput>(); try { // setup the test scenarios try { tlist.add(new UnpackTestFileInput((File)null, null)); tlist.add(new UnpackTestFileInput(testPackFile, null)); tlist.add(new UnpackTestFileInput((File)null, new JarOutputStream(new ByteArrayOutputStream()))); } catch (Exception e) { throw new Error("Initialization error", e); } // test the scenarios for (UnpackTestFileInput ti : tlist) { System.out.println(ti); try { Pack200.Unpacker unpacker = Pack200.newUnpacker(); unpacker.unpack(ti.getInputFile(), ti.getJarOutputStream()); } catch (Exception e) { ti.checkException(e); } } } finally { // clean up for (TestInput ti : tlist) { if (ti != null) { ti.close(); } } } } public static void main(String... args) throws IOException { init(); pack200Test1(); pack200Test2(); pack200Test3(); unpack200Test1(); Utils.cleanup(); } // containers for test inputs and management static abstract class TestInput { private final Object in; private final Object out; final boolean shouldNPE; final String testname; public TestInput(String name, Object in, Object out) { this.testname = name; this.in = in; this.out = out; shouldNPE = (in == null || out == null); } @Override public String toString() { StringBuilder outStr = new StringBuilder(testname); outStr.append(", input:").append(in); outStr.append(", output:").append(this.out); outStr.append(", should NPE:").append(shouldNPE); return outStr.toString(); } void close() { if (in != null && (in instanceof Closeable)) { Utils.close((Closeable) in); } if (out != null && (out instanceof Closeable)) { Utils.close((Closeable) out); } } void checkException(Throwable t) { if (shouldNPE) { if (t instanceof NullPointerException) { System.out.println("Got expected exception"); return; } else { throw new RuntimeException("Expected NPE, but got ", t); } } if (t instanceof IOException) { System.out.println("Got expected exception"); return; } else { throw new RuntimeException("Expected IOException but got ", t); } } } static class PackTestInput extends TestInput { public PackTestInput(JarFile jf, OutputStream out) { super("PackTestInput", jf, out); } JarFile getJarFile() { return (JarFile) super.in; } OutputStream getOutputStream() { return (OutputStream) super.out; } }; static class PackTestJarInputStream extends TestInput { public PackTestJarInputStream(JarInputStream in, OutputStream out) { super("PackTestJarInputStream", in, out); } JarInputStream getJarInputStream() { return (JarInputStream) super.in; } OutputStream getOutputStream() { return (OutputStream) super.out; } }; static class UnpackTestInput extends TestInput { public UnpackTestInput(InputStream in, JarOutputStream out) { super("UnpackTestInput", in, out); } InputStream getInputStream() { return (InputStream) super.in; } JarOutputStream getJarOutputStream() { return (JarOutputStream) super.out; } }; static class UnpackTestFileInput extends TestInput { public UnpackTestFileInput(File in, JarOutputStream out) { super("UnpackTestInput", in, out); } File getInputFile() { return (File) super.in; } JarOutputStream getJarOutputStream() { return (JarOutputStream) super.out; } }; }
package jvm_test; import sun.misc.Launcher; import java.net.URL; /** * Description: 查看Bootstrap ClassLoader加载的jar或class文件 * * @author Baltan * @date 2019-05-30 17:16 */ public class Test2 { public static void main(String[] args) { URL[] urls = Launcher.getBootstrapClassPath().getURLs(); for (int i = 0; i < urls.length; i++) { System.out.println(urls[i].toExternalForm()); } System.out.println("---------------------------------------------"); System.out.println(System.getProperty("sun.boot.class.path")); } }
package org.apache.commons.net.examples.mail; import java.io.BufferedReader; import java.io.Console; import java.io.IOException; import java.io.InputStreamReader; import java.util.Locale; class Utils { static String getPassword(String username, String password) throws IOException { if ("-".equals(password)) { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); password = in.readLine(); } else if ("*".equals(password)) { Console con = System.console(); if (con != null) { char[] pwd = con.readPassword("Password for " + username + ": ", new Object[0]); password = new String(pwd); } else { throw new IOException("Cannot access Console"); } } else if (password.equals(password.toUpperCase(Locale.ROOT))) { String tmp = System.getenv(password); if (tmp != null) password = tmp; } return password; } } /* Location: C:\Users\BSV\AppData\Local\Temp\Rar$DRa6216.20396\Preview\Preview.jar!\org\apache\commons\net\examples\mail\Utils.class * Java compiler version: 8 (52.0) * JD-Core Version: 1.1.3 */
package project; public class Order { private Customer customer; private Employee employee; private Meal meal; private int workRemaining; public Order(Customer customer, Employee employee, Meal meal) { this.customer = customer; this.employee = employee; this.meal = meal; // Round down the work amount double work = meal.getWorkAmount() * employee.getPerformance(); this.workRemaining = (int) work; } public Customer getCustomer() { return this.customer; } public Employee getEmployee() { return this.employee; } public Meal getMeal() { return this.meal; } public int getWorkRemaining() { return this.workRemaining; } public void setCustomer(Customer customer) { this.customer = customer; } public void setEmployee(Employee employee) { this.employee = employee; } public void setMeal(Meal meal) { this.meal = meal; } public void work () { this.workRemaining--; } }
package edu.wpi.cs.justice.cardmaker; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.util.ArrayList; import org.json.simple.JSONObject; import com.amazonaws.services.lambda.runtime.Context; import com.amazonaws.services.lambda.runtime.LambdaLogger; import com.amazonaws.services.lambda.runtime.RequestStreamHandler; import com.google.gson.Gson; import edu.wpi.cs.justice.cardmaker.db.ElementDAO; import edu.wpi.cs.justice.cardmaker.http.ListImageResponse; /** List all the image urls existing in our RDS * * @author justice509 */ public class ListImageHandler implements RequestStreamHandler { public LambdaLogger logger = null; /** Load the images in RDS if exists * * @return list of urls for images * @throws Exception */ ArrayList<String> getImages() throws Exception { if (logger != null) { logger.log("in getImages"); } ElementDAO dao = new ElementDAO(); return dao.getAllImage(); } /** * * @param input * @param output * @param context * @throws IOException */ @Override public void handleRequest(InputStream input, OutputStream output, Context context) throws IOException { logger = context.getLogger(); logger.log("Loading Java Lambda handler to list all cards"); JSONObject headerJson = new JSONObject(); headerJson.put("Content-Type", "application/json"); // not sure if needed anymore? headerJson.put("Access-Control-Allow-Methods", "GET,POST,DELETE,OPTIONS"); headerJson.put("Access-Control-Allow-Origin", "*"); JSONObject responseJson = new JSONObject(); responseJson.put("headers", headerJson); ListImageResponse response; try { ArrayList<String> list = getImages(); response = new ListImageResponse(list, 200); } catch (Exception e) { response = new ListImageResponse(e.getMessage(), 403); } // compute proper response responseJson.put("body", new Gson().toJson(response)); responseJson.put("statusCode", response.statusCode); logger.log("end result:" + responseJson.toJSONString()); logger.log(responseJson.toJSONString()); OutputStreamWriter writer = new OutputStreamWriter(output, "UTF-8"); writer.write(responseJson.toJSONString()); writer.close(); } }
package com.zen.model.manage.service.impl; import com.zen.model.manage.bean.Feature; import com.zen.model.manage.dto.ModelInfoDto; import com.zen.model.manage.service.ManageService; import org.junit.jupiter.api.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; import javax.xml.bind.ValidationException; import java.util.ArrayList; import java.util.Arrays; import static org.junit.jupiter.api.Assertions.*; /** * @Author: morris * @Date: 2020/6/12 9:01 * @description * @reviewer */ @RunWith(SpringRunner.class) @SpringBootTest class ManageServiceImplTest { @Autowired private ManageService manageService; @Test void createModel() { ModelInfoDto modelInfoDto = new ModelInfoDto(); Feature feature = new Feature("gender","int","25"); Feature feature1 = new Feature("gender","int","26"); Feature feature2 = new Feature("region","string","深圳"); ArrayList<Feature> features = new ArrayList<>(); features.add(feature); features.add(feature1); features.add(feature2); modelInfoDto.setHdfsPath("hdfs://master:9000/input/article1234"); modelInfoDto.setModelType("mLeap"); modelInfoDto.setWarmUpFeature(features); manageService.createModel(modelInfoDto); } @Test void updateModel() throws ValidationException { ModelInfoDto modelInfoDto = new ModelInfoDto(); Feature feature = new Feature("gender","int","25"); Feature feature1 = new Feature("gender","int","26"); Feature feature2 = new Feature("region","string","深圳"); ArrayList<Feature> features = new ArrayList<>(); features.add(feature); features.add(feature1); features.add(feature2); modelInfoDto.setToken("602874adfe37587c"); modelInfoDto.setHdfsPath("hdfs://master:9000/input/article"); modelInfoDto.setModelType("mLeap"); modelInfoDto.setWarmUpFeature(features); System.out.println(manageService.updateModel(modelInfoDto)); } @Test void offlineModel() { System.out.printf(manageService.offlineModel("602874adfe37587c")); } @Test void rollbackModel() { manageService.rollbackModel("602874adfe37587c"); } @Test void deleteModel() { System.out.println(manageService.deleteModel("602874adfe37587c", 2)); } }
package net.sf.ardengine.rpg.multiplayer; import com.google.gson.JsonObject; import net.sf.ardengine.rpg.multiplayer.messages.*; import net.sf.ardengine.rpg.multiplayer.network.INetwork; /** * Handles client game logic. */ public abstract class AClientCore extends ANetworkCore { /**How many states is client delayed after server*/ public static final int CLIENT_LAGGED_STATES = 3; private static final int CLIENT_LAG = 100; private static final long CURRENT_TIME_INDEFINITE = -1; private long updateTimeStamp = CURRENT_TIME_INDEFINITE; private final JsonMessageHandler joinHandler = (JsonMessage message) -> { handlers.remove(JoinResponseMessage.TYPE); if(JoinResponseMessage.isOK(message)){ prepareClient(); }else{ throw new RuntimeException(JoinResponseMessage.getReason(message)); } }; private final JsonMessageHandler joinFinished = (JsonMessage message) -> { startPlaying(); }; private final JsonMessageHandler deltaStateHandler = (JsonMessage message) -> { INetworkedNode node = synchronizedNodes.get(message.getTargetNodeID()); if(node != null){ updateStateIfNotLate(node, message); } }; private final JsonMessageHandler stateHandler = (JsonMessage message) -> { INetworkedNode node = reconstructFromState(message.getContent()); if(node!= null && !synchronizedNodes.containsKey(node.getID())){ addNode(node); } }; /** * @param network Responsible for communicating with other clients */ protected AClientCore(INetwork network) { super(network); handlers.put(DeltaStateMessage.TYPE, deltaStateHandler); join(); } private void join(){ network.sendBroadcastMessage(new JoinRequestMessage().toString()); handlers.put(JoinResponseMessage.TYPE, joinHandler); handlers.put(StateMessage.TYPE, stateHandler); handlers.put(ClientReadyMessage.TYPE, joinFinished); } /** * Method for client, where he can exchange with server additional info * before obtaining game data from server. * * METHOD HAS TO END WITH:JoinRequestMessage * network.sendBroadcastMessage(new ClientPreparedMessage().toString()); */ protected abstract void prepareClient(); /** * Automatically called when server sends signal, * that client is synchronized. */ protected abstract void startPlaying(); @Override protected final void updateCoreLogic(long delta, int passedFrames) { if(updateTimeStamp != CURRENT_TIME_INDEFINITE) updateTimeStamp+= delta; synchronizedNodes.values().forEach((INetworkedNode iNetworkedNode) -> { iNetworkedNode.triggerState(actualIndex, actualFrame); }); updateClientLogic(passedFrames); } /** * Automatically called every game loop, * method for client related logic * @param passedFrames frames passed since last update */ protected abstract void updateClientLogic(int passedFrames); private void updateStateIfNotLate(INetworkedNode node, JsonMessage message){ long messageTimestamp = message.getValueAsLong(JsonMessage.TIMESTAMP); int messageIndex = message.getValueAsInt(DeltaStateMessage.STATE_INDEX); if(updateTimeStamp == CURRENT_TIME_INDEFINITE){ //initialize timestamp on start updateTimeStamp = messageTimestamp - CLIENT_LAG; initIndex(messageIndex); } if(serverIndexDifference(messageIndex) > CLIENT_LAGGED_STATES){ updateStateIndex(ANetworkCore.FRAMES_PER_STATE); } // If datagram arrived too late, we have to drop it if(messageTimestamp >= updateTimeStamp){ node.receiveState(message); } } protected int serverIndexDifference(int serverIndex){ if(serverIndex >= actualIndex){ return serverIndex - actualIndex; }else{ return serverIndex + INetworkedNode.StoredStates.STATES_BUFFER_SIZE - actualIndex; } } private void initIndex(int serverIndex){ actualIndex = serverIndex - 2; if(actualIndex < 0){ actualIndex = INetworkedNode.StoredStates.STATES_BUFFER_SIZE - serverIndex; }else if(actualIndex >= INetworkedNode.StoredStates.STATES_BUFFER_SIZE){ while(actualIndex >= INetworkedNode.StoredStates.STATES_BUFFER_SIZE){ actualIndex -= INetworkedNode.StoredStates.STATES_BUFFER_SIZE; } } } /** * Called automatically by client when joining game. * Method for user to create/synchronize nodes and add them to Game. * @param state Complete state of node returned by INetworkedNode.getJSONState() * @return reconstructed networked node */ protected abstract INetworkedNode reconstructFromState(JsonObject state); }
package com.qgbase.netty; /** * @author : Winner * @name : * @date : 2019/5/13 0013 * @desc : */ public class Constant { public static final short CMD_HEAD = (short) 29130; public static final short CHECK_CODE = (short) 26; public static Integer onOff = 0; }
package domain; public enum DeveloperType { LAZY, EXPERIENCED, JUNIOR }
package com.exercises.mmn12; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.*; /** * @author Ori Ben Nun */ class Segment1Test { @Test void getPoLeft() { Segment1 segment1 = new Segment1(new Point(2,4), new Point(6,0)); assertEquals(4,segment1.getPoLeft().getY(), 0.01); assertEquals(2,segment1.getPoLeft().getX(), 0.01); } @Test void getPoRight() { Segment1 segment1 = new Segment1(new Point(2,4), new Point(6,0)); Segment1 segment2 = new Segment1(2,4, 6,0); assertEquals(2, segment2.getPoLeft().getX(), 0.01); assertEquals(4, segment2.getPoLeft().getY(), 0.01); assertEquals(6, segment2.getPoRight().getX(), 0.01); assertEquals(4, segment2.getPoRight().getY(), 0.01); assertEquals(true, segment1.equals(segment2)); } @Test void getLength() { Segment1 segment1 = new Segment1(new Point(2,4), new Point(6,4)); assertEquals(4,segment1.getLength(), 0.01); Segment1 segment2 = new Segment1(new Point(2,4), new Point(2,6)); assertEquals(0,segment2.getLength(), 0.01); } @Test void testToString() { Segment1 segment1 = new Segment1(new Point(3,4), new Point(5,4)); assertEquals("(3.0,4.0)---(5.0,4.0)",segment1.toString()); } @Test void testEquals() { Segment1 segment1 = new Segment1(new Point(3,4), new Point(5,4)); Segment1 segment2 = new Segment1(new Point(3,4), new Point(5,4)); Segment1 segment3 = new Segment1(new Point(3,5), new Point(5,4)); assertEquals(true, segment1.equals(segment2)); assertEquals(false, segment1.equals(segment3)); } @Test void isAbove() { Segment1 segment1 = new Segment1(new Point(5,4), new Point(5,4)); Segment1 segment2 = new Segment1(new Point(5,4), new Point(5,4)); Segment1 segment3 = new Segment1(new Point(3,2), new Point(5,4)); assertEquals(false, segment1.isAbove(segment2)); assertEquals(true, segment1.isAbove(segment3)); } @Test void isUnder() { Segment1 segment1 = new Segment1(new Point(5,4), new Point(5,4)); Segment1 segment2 = new Segment1(new Point(5,4), new Point(5,4)); Segment1 segment3 = new Segment1(new Point(3,2), new Point(5,4)); assertEquals(false, segment1.isUnder(segment2)); assertEquals(false, segment1.isUnder(segment3)); assertEquals(true, segment3.isUnder(segment1)); } @Test void isLeft() { Segment1 segment1 = new Segment1(new Point(6,15), new Point(8,1024)); Segment1 segment2 = new Segment1(new Point(4,15), new Point(6,4)); Segment1 segment3 = new Segment1(new Point(2,108), new Point(4,4)); assertEquals(false, segment1.isLeft(segment2)); assertEquals(false, segment1.isLeft(segment3)); assertEquals(false, segment1.isLeft(segment1)); assertEquals(false, segment2.isLeft(segment3)); assertEquals(false, segment2.isLeft(segment1)); assertEquals(true, segment3.isLeft(segment1)); assertEquals(false, segment3.isLeft(segment3)); } @Test void isRight() { Segment1 segment1 = new Segment1(new Point(6,15), new Point(8,1024)); Segment1 segment2 = new Segment1(new Point(4,15), new Point(6,4)); Segment1 segment3 = new Segment1(new Point(2,108), new Point(4,4)); Segment1 segment4 = new Segment1(segment1); assertEquals(false, segment1.isRight(segment2)); assertEquals(true, segment1.isRight(segment3)); assertEquals(true, segment4.isRight(segment3)); assertEquals(false, segment4.isRight(segment1)); assertEquals(false, segment1.isRight(segment1)); assertEquals(false, segment2.isRight(segment3)); assertEquals(false, segment2.isRight(segment1)); assertEquals(false, segment3.isRight(segment1)); assertEquals(false, segment3.isRight(segment3)); } @Test void moveHorizontal() { Segment1 segment1 = new Segment1(new Point(6,15), new Point(8,1024)); Segment1 segment2 = new Segment1(new Point(4,15), new Point(6,4)); Segment1 segment3 = new Segment1(new Point(2,108), new Point(4,4)); Segment1 segment4 = new Segment1(segment1); assertEquals(false, segment1.isRight(segment2)); assertEquals(true, segment1.isRight(segment3)); assertEquals(true, segment4.isRight(segment3)); assertEquals(false, segment4.isRight(segment1)); assertEquals(false, segment1.isRight(segment1)); assertEquals(false, segment2.isRight(segment3)); assertEquals(false, segment2.isRight(segment1)); assertEquals(false, segment3.isRight(segment1)); assertEquals(false, segment3.isRight(segment3)); segment4.moveHorizontal(10); assertEquals(true, segment4.isRight(segment3)); assertEquals(true, segment4.isRight(segment1)); assertEquals(false, segment4.isRight(segment4)); segment1.moveHorizontal(10); assertEquals(false, segment4.isRight(segment1)); assertEquals(false, segment4.isLeft(segment1)); segment1.moveHorizontal(-10); segment4.moveHorizontal(-10); assertEquals(false, segment4.isRight(segment1)); assertEquals(false, segment4.isRight(segment2)); assertEquals(false, segment4.isLeft(segment1)); Segment1 segment5 = new Segment1(new Point(4,15), new Point(6,4)); Segment1 segment6 = new Segment1(segment5); segment5.moveHorizontal(-4.5); assertEquals(true, segment5.equals(segment6)); segment5.moveHorizontal(-3.5); assertEquals(false, segment5.equals(segment6)); assertEquals(true, segment5.isLeft(segment6)); Segment1 segment7 = new Segment1(new Point(0,0), new Point(0,4)); assertEquals(true, segment5.isRight(segment7)); assertEquals(true, segment7.isLeft(segment5)); } @Test void moveVertical() { Segment1 segment1 = new Segment1(new Point(6,15), new Point(8,1024)); Segment1 segment2 = new Segment1(segment1); segment1.moveVertical(-100); segment1.moveHorizontal(-100); segment2.moveHorizontal(-100); assertEquals(true, segment1.equals(segment2)); assertEquals(false, segment2.isAbove(segment1)); segment1.moveVertical(-10); assertEquals(false, segment1.equals(segment2)); assertEquals(true, segment1.isUnder(segment2)); segment2.moveVertical(1500); segment1.moveVertical(150); assertEquals(false, segment1.equals(segment2)); assertEquals(false, segment1.isAbove(segment2)); assertEquals(true, segment1.isUnder(segment2)); assertEquals(true, segment2.isAbove(segment1)); } @Test void changeSize() { Segment1 segment1 = new Segment1(new Point(3,10), new Point(6,10)); segment1.changeSize(-2); assertEquals(1, segment1.getLength(), 0.01); assertEquals(4, segment1.getPoRight().getX(), 0.01); segment1.changeSize(-2); assertEquals(1, segment1.getLength(), 0.01); assertEquals(4, segment1.getPoRight().getX(), 0.01); segment1.changeSize(10); assertEquals(11, segment1.getLength(), 0.01); assertEquals(14, segment1.getPoRight().getX(), 0.01); assertEquals(3, segment1.getPoLeft().getX(), 0.01); segment1.changeSize(-11); assertEquals(0, segment1.getLength()); assertEquals(3, segment1.getPoRight().getX(), 0.01); assertEquals(3, segment1.getPoLeft().getX(), 0.01); segment1.changeSize(-0.1); assertEquals(0, segment1.getLength()); assertEquals(3, segment1.getPoRight().getX(), 0.01); assertEquals(3, segment1.getPoLeft().getX(), 0.01); segment1.changeSize(0.1); assertEquals(0.1, segment1.getLength(), 0.01); assertEquals(3.1, segment1.getPoRight().getX(), 0.01); assertEquals(3, segment1.getPoLeft().getX(), 0.01); } @Test void pointOnSegment() { Segment1 segment1 = new Segment1(new Point(3,10), new Point(6,10)); Point point1 = new Point(2,7); assertEquals(false, segment1.pointOnSegment(point1)); point1.move(1,3); assertEquals(true, segment1.pointOnSegment(point1)); point1.move(2,0); assertEquals(true, segment1.pointOnSegment(point1)); point1.move(2,0); assertEquals(false, segment1.pointOnSegment(point1)); point1.move(-1,1); assertEquals(false, segment1.pointOnSegment(point1)); point1.move(0,-1); assertEquals(true, segment1.pointOnSegment(point1)); assertEquals(true, segment1.pointOnSegment(segment1.getPoLeft())); assertEquals(true, segment1.pointOnSegment(segment1.getPoRight())); segment1.moveVertical(10); assertEquals(false, segment1.pointOnSegment(point1)); assertEquals(true, segment1.pointOnSegment(segment1.getPoLeft())); assertEquals(true, segment1.pointOnSegment(segment1.getPoRight())); } @Test void isBigger() { Segment1 segment1 = new Segment1(new Point(3,10), new Point(6,10)); Segment1 segment2 = new Segment1(new Point(3,10), new Point(6,10)); assertEquals(false, segment1.isBigger(segment1)); assertEquals(false, segment1.isBigger(segment2)); segment2.changeSize(0.5); assertEquals(true, segment2.isBigger(segment1)); segment1.moveHorizontal(500); assertEquals(true, segment2.isBigger(segment1)); segment1.changeSize(0.5); assertEquals(false, segment2.isBigger(segment1)); assertEquals(false, segment1.isBigger(segment2)); segment1.changeSize(0.5); assertEquals(true, segment1.isBigger(segment2)); } @Test void overlap() { Segment1 segment1 = new Segment1(new Point(3,10), new Point(6,10)); Segment1 segment2 = new Segment1(new Point(3,80), new Point(6,50)); assertEquals(3, segment1.overlap(segment2), 0.01); assertEquals(3, segment1.overlap(segment1), 0.01); segment2.moveHorizontal(1); assertEquals(2, segment1.overlap(segment2), 0.01); segment2.changeSize(-2); assertEquals(1, segment1.overlap(segment2), 0.01); segment1.changeSize(-1); assertEquals(1, segment1.overlap(segment2), 0.01); segment1.changeSize(-1); assertEquals(0, segment1.overlap(segment2), 0.01); Segment1 segment3 = new Segment1(segment1); segment3.moveVertical(1024); assertEquals(segment1.getLength(), segment1.overlap(segment3), 0.01); segment3.changeSize(-1); assertEquals(segment1.getLength() -1, segment1.overlap(segment3), 0.01); segment3.moveHorizontal(1); assertEquals(segment1.getLength() -1, segment1.overlap(segment3), 0.01); Segment1 segment4 = new Segment1(new Point(3,4), new Point(5,4)); Segment1 segment5 = new Segment1(new Point(0,2), new Point(2,4)); Segment1 segment6 = new Segment1(new Point(1,1), new Point(4,1)); Segment1 segment7 = new Segment1(new Point(1,10), new Point(4,10)); assertEquals(1, segment6.overlap(segment4), 0.01); assertEquals(1, segment6.overlap(segment5), 0.01); assertEquals(segment7.getLength(), segment7.overlap(segment6), 0.01); segment7.changeSize(10); assertEquals(segment6.getLength(), segment7.overlap(segment6), 0.01); segment7.moveHorizontal(100); assertEquals(0, segment7.overlap(segment6), 0.01); } @Test void trapezePerimeter() { Segment1 segment1 = new Segment1(new Point(1,1), new Point(4,1)); Segment1 segment2 = new Segment1(new Point(1,2), new Point(4,2)); assertEquals(3 + 3 + 1 + 1, segment1.trapezePerimeter(segment2)); segment2.moveVertical(10); assertEquals(3 + 3 + 1 + 1 + 20, segment1.trapezePerimeter(segment2), 0.01); segment1.changeSize(2); assertEquals(3 + 3 + 1 + 1 + 20 + 2, segment1.trapezePerimeter(segment2), .5); segment1.changeSize(2); assertEquals(3 + 3 + 1 + 1 + 20 + 2 + 2, segment1.trapezePerimeter(segment2), 1); segment1.moveHorizontal(1); assertEquals(3 + 3 + 1 + 1 + 20 + 2 + 2 + 1, segment1.trapezePerimeter(segment2), .5); segment2.moveVertical(100); assertEquals(3 + 3 + 1 + 1 + 20 + 2 + 2 + 1 + 200, segment1.trapezePerimeter(segment2), 1); } @Test void arielTest(){ ArielSeg1Tester.main(); } @Test void teachersTester() { System.out.println("============ Testing class Segment1 ============="); Segment1 s11 = new Segment1(1.0 , 2.0, 3.0, 4.0); Segment1 s12 = new Segment1(1.0 , 2.0, 3.0, 4.0); if (!s11.equals(s12)) System.out.println("Check your equals method in class Segment1"); Point p3 = new Point(5.0, 6.0); Point p4 = new Point(7.0, 8.0); Segment1 s13 = new Segment1(p3, p4); Segment1 s14 = new Segment1(s12); Point p5 = s11.getPoLeft(); p5 = s11.getPoRight(); double d1 = s11.getLength(); if (s11.toString().indexOf('@') != -1) System.out.println("Check your toString method in class Segment1"); boolean b1 = s11.isAbove(s12); b1 = s11.isUnder(s12); b1 = s11.isLeft(s12); b1 = s11.isRight(s12); s11.moveHorizontal(1.0); s11.moveVertical(1.0); s11.changeSize(1.0); b1 = s11.pointOnSegment(p3); b1 = s11.isBigger(s12); d1 = s11.overlap(s12); d1 = s11.trapezePerimeter(s12); System.out.println("============ Testing class Segment1 Done ============="); } }
import com.thinking.machines.loyalty.dao.*; import com.thinking.machines.loyalty.interfaces.*; class GetCityByNameTestCase { public static void main(String data[]) { try { CityDAOInterface cityDAOInterface=new CityDAO(); CityInterface cityInterface=cityDAOInterface.getByName(data[0]); System.out.println(cityInterface.getCode()); System.out.println(cityInterface.getName()); System.out.println(cityInterface.getState()); System.out.println(cityInterface.getCountry()); } catch(Exception e) { System.out.println(e); } } }
package com.paleimitations.schoolsofmagic.common.data.books; import com.mojang.blaze3d.systems.RenderSystem; import net.minecraft.client.renderer.BufferBuilder; import net.minecraft.client.renderer.IRenderTypeBuffer; import net.minecraft.client.renderer.Tessellator; import net.minecraft.client.renderer.vertex.DefaultVertexFormats; import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.api.distmarker.OnlyIn; public class BookElement { public int page, subpage; public float x, y; public BookElement(float x, float y, int page, int subpage) { this.page = page; this.subpage = subpage; this.x = x; this.y = y; } @OnlyIn(Dist.CLIENT) public boolean shouldDraw(float mouseX, float mouseY, int x, int y, boolean isGUI, int subpage, int page) { return subpage == this.subpage && page == this.page; } @OnlyIn(Dist.CLIENT) public void drawElement(float mouseX, float mouseY, int x, int y, float zLevel, boolean isGUI, int subpage, int page) { } @OnlyIn(Dist.CLIENT) public void drawElement(float mouseX, float mouseY, int x, int y, float zLevel, boolean isGUI, int subpage, int page, IRenderTypeBuffer buffer) { this.drawElement(mouseX, mouseY, x, y, zLevel, isGUI, subpage, page); } @OnlyIn(Dist.CLIENT) public void drawTexturedModalRect(int x, int y, int textureX, int textureY, int width, int height, float zLevel) { Tessellator tessellator = Tessellator.getInstance(); BufferBuilder bufferbuilder = tessellator.getBuilder(); bufferbuilder.begin(7, DefaultVertexFormats.POSITION_TEX); bufferbuilder.vertex(x + 0, y + height, zLevel).uv((float)(textureX + 0) * 0.00390625F, (float)(textureY + height) * 0.00390625F).endVertex(); bufferbuilder.vertex(x + width, y + height, zLevel).uv((float)(textureX + width) * 0.00390625F, (float)(textureY + height) * 0.00390625F).endVertex(); bufferbuilder.vertex(x + width, y + 0, zLevel).uv((float)(textureX + width) * 0.00390625F, (float)(textureY + 0) * 0.00390625F).endVertex(); bufferbuilder.vertex(x + 0, y + 0, zLevel).uv((float)(textureX + 0) * 0.00390625F, (float)(textureY + 0) * 0.00390625F).endVertex(); tessellator.end(); } }
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.udea.session; import com.udea.Carro; import com.udea.Cliente; import java.util.List; import javax.ejb.Stateless; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import javax.persistence.Query; /** * * @author Santiago */ @Stateless public class ClienteFacade extends AbstractFacade<Cliente> implements ClienteFacadeLocal { @PersistenceContext(unitName = "com.udea_Laboratorio2-ejb_ejb_1.0-SNAPSHOTPU") private EntityManager em; @Override protected EntityManager getEntityManager() { return em; } public ClienteFacade() { super(Cliente.class); } @Override public Cliente getClienteById(int idCliente) { Query q = em.createNamedQuery("Cliente.findByCedula"); return (Cliente) q.getSingleResult(); } @Override public void registrar(final int cedula, String password, String nombre, String ciudad, String telefono, String email) { Cliente c = new Cliente(); c.setCedula(cedula); c.setPassword(password); c.setNombre(nombre); c.setCiudad(ciudad); c.setTelefono(telefono); c.setEmail(email); em.persist(c); } @Override public boolean checkLogin(int cedula, String password) { Query q =em.createQuery("select a from Cliente a" + " where a.cedula=:cedula and a.password=:password"); q.setParameter("cedula", cedula); q.setParameter("password", password); return q.getResultList().size()>0; } @Override public List<Cliente> getCliente() { Query q = em.createNamedQuery("Cliente.findAll"); return q.getResultList(); } @Override public List<Cliente> getClientes() { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } }
package ec.app.fixedpoint; import ec.util.*; import ec.*; import ec.gp.*; import xfp.trees.*; public class ExprData extends GPData { public CExpr x; // return value // copy content to other AffineData public void copyTo(final GPData gpd) { ((ExprData) gpd).x = x; } }
package com.rolandopalermo.facturacion.ec.common.util; import java.util.HashMap; public class Constantes { /** * Utility classes should not have a public constructor. */ private Constantes() { } public static final String API_DOC_ANEXO_1 = "Ver ficha técnica - Anexo 1"; @SuppressWarnings("serial") public static final HashMap<String, String> FORMAS_PAGO_MAP = new HashMap<String, String>() { { put("01", "SIN UTILIZACION DEL SISTEMA FINANCIERO"); put("15", "COMPENSACIÓN DE DEUDAS"); put("16", "TARJETA DE DÉBITO"); put("17", "DINERO ELECTRÓNICO"); put("18", "TARJETA PREPAGO"); put("19", "TARJETA DE CRÉDITO"); put("20", "OTROS CON UTILIZACION DEL SISTEMA FINANCIERO"); put("21", "ENDOSO DE TÍTULOS"); } }; }
package com.puti.pachong.service.wenda.impl; import com.puti.pachong.entity.http.HttpRequest; import com.puti.pachong.http.HttpRestRequest; import com.puti.pachong.service.wenda.IAutoWendaService; import lombok.SneakyThrows; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.net.URLEncoder; import java.util.Date; @Service public class ZhihuService implements IAutoWendaService { private String urlTemp = "https://www.zhihu.com/api/v4/search_v3?t=general&q=%s&correction=1&offset=0&limit=20&lc_idx=0&show_all_topics=0"; @Autowired private HttpRestRequest restRequest; @Override @SneakyThrows public String answer(String question) { HttpRequest httpRequest = HttpRequest.defaultGetRequest(String.format(urlTemp, question)); httpRequest.getHeaders().put("referer", "https://www.zhihu.com/search?type=content&q=" + URLEncoder.encode(question, "utf-8")); httpRequest.getHeaders().put("cookie", "_xsrf=cI9eZEtE5NPwXNz3A5XVxFIY36x7halv; _zap=69563ced-3661-4a7c-ba3a-13fba0632161; d_c0=\"AIDVfzOAJRGPTvHJ5vQFoh1blPCmnYr5sI0=|1587354411\"; Hm_lvt_98beee57fd2ef70ccdd5ca52b9740c49=1587353214,1587353220,1587353279,1587354412; _ga=GA1.2.1311183132.1587354412; _gid=GA1.2.1382588795.1587354412; capsion_ticket=\"2|1:0|10:1587364010|14:capsion_ticket|44:ODJjMTZjNTY2MmVlNDdlZDg1MzM1ZjEwMmFkZWIwN2I=|4195dc89e78601ab1296ef5371544834e3deb1e5c94fc3f3c82c8064c2016bc5\"; z_c0=\"2|1:0|10:1587364042|4:z_c0|92:Mi4xZXFZaURRQUFBQUFBZ05WX000QWxFU1lBQUFCZ0FsVk55bzZLWHdCY3NSa2xjSF9nMEF0QkZWMW5xekduRTdrTThR|cc1f8b948e4fd6b929fb95c7aee8d25566c579808fb2dc5567839af2bc63fd90\"; unlock_ticket=\"AABpKRl3gQ4mAAAAYAJVTdJHnV4HWa3Ov0Y4RWX1UkTlxA1oeXrzCg==\"; Hm_lpvt_98beee57fd2ef70ccdd5ca52b9740c49=1587365138; KLBRSID=b33d76655747159914ef8c32323d16fd|" + (new Date().getTime()) + "|1587363957"); String response = restRequest.request(httpRequest); return response; } }
package BlockchainUtil; import proto.BlockchainService; import java.util.*; public class Block { private BlockMeta metaData; List<BlockchainService.Transaction> transactionList = new ArrayList<BlockchainService.Transaction>(); List<BlockchainService.Balance> balanceList = new ArrayList<BlockchainService.Balance>(); public List<BlockchainService.Transaction> getTransactionList() { return this.transactionList; } public int getCreatedBy() { return this.metaData.getCreatedBy(); } public int getId() { return this.metaData.getId(); } public void setList(List<BlockchainService.Transaction> list) { this.transactionList = list; } public String toString(){ StringBuilder blockString = new StringBuilder(String.format("Block: %d - CreateBy: %d ", this.getId(), this.getCreatedBy())); for (BlockchainService.Transaction t: this.transactionList){ blockString.append(String.format("[%d->%d: %s], ", t.getSourceClient(), t.getDestClient(), t.getAmount())); } return blockString.toString(); } public Block(Block b) { this.metaData = new BlockMeta(b.getId(), b.getCreatedBy()); this.transactionList = new ArrayList<>(b.getTransactionList()); } public Block(BlockchainService.Block blockMsg) { this.metaData = new BlockMeta(blockMsg.getId(), blockMsg.getCreatedBy()); this.transactionList = new ArrayList<>(blockMsg.getTransactionsList()); } public Block(List<BlockchainService.Transaction> transactionList, int createdBy) { this.metaData = new BlockMeta(createdBy); this.transactionList = new ArrayList<>(transactionList); } }
package GUIModule; import javax.swing.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.ArrayList; public class ActionResultsReport implements ActionListener { public ArrayList<ArrayList<String>> previousResult; public JTable table; public ActionResultsReport(JTable table, ArrayList<ArrayList<String>> previousResult) { this.previousResult = previousResult; this.table = table; } public void actionPerformed(ActionEvent e) { int [] indexes; indexes = table.getSelectedRows(); if (indexes.length==0){ // TODO: Сделать вывод сообщения с подсказкой в диалоговом окне return; } if(indexes[0]>=previousResult.size()){ return; } new ResultsWindow(previousResult.get(indexes[0])); } }
package pro.javatar.security.acl; import org.springframework.security.acls.domain.BasePermission; import org.springframework.security.acls.domain.GrantedAuthoritySid; import org.springframework.security.acls.domain.PrincipalSid; import org.springframework.security.acls.model.Permission; import org.springframework.security.acls.model.Sid; import java.io.Serializable; public interface AclManager { /** * Add a permission for the given object * * @param clazz Domain class * @param identifier Id from the given domain * @param sid Security Identifier, could be a {@link PrincipalSid} or a {@link GrantedAuthoritySid} * @param permission The permission based on {@link BasePermission} */ <T> void addPermission(Class<T> clazz, Serializable identifier, Sid sid, Permission permission); /** * Grant a permission for the given object * * @param clazz Domain class * @param identifier Id from the given domain * @param sid Security Identifier, could be a {@link PrincipalSid} or a {@link GrantedAuthoritySid} * @param permission The permission based on {@link BasePermission} */ <T> void grantPermission(Class<T> clazz, Serializable identifier, Sid sid, Permission permission); /** * Remove a permission from the given object * * @param clazz Domain class * @param identifier Id from the given domain * @param sid Security Identifier, could be a {@link PrincipalSid} or a {@link GrantedAuthoritySid} * @param permission The permission based on {@link BasePermission} */ <T> void removePermission(Class<T> clazz, Serializable identifier, Sid sid, Permission permission); /** * Check whether the given object has permission * * @param clazz Domain class * @param identifier Id from the given domain * @param sid Security Identifier, could be a {@link PrincipalSid} or a {@link GrantedAuthoritySid} * @param permission The permission based on {@link BasePermission} * @return true or false */ <T> boolean isPermissionGranted(Class<T> clazz, Serializable identifier, Sid sid, Permission permission); }
package com.goldgov.dygl.module.portal.webservice.examrecord.web; import java.util.ArrayList; import java.util.List; import java.util.Properties; import javax.servlet.http.HttpServletRequest; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import com.goldgov.dygl.ShConstant; import com.goldgov.dygl.cache.SpyMemcachedImpl; import com.goldgov.dygl.module.partyMemberDuty.duty.service.IDutyService; import com.goldgov.dygl.module.partyMemberInfo.service.IPartyMemberService_AJ; import com.goldgov.dygl.module.partymember.service.IPartyMemberService_AA; import com.goldgov.dygl.module.partymemberrated.exam.domain.Exam; import com.goldgov.dygl.module.partymemberrated.exam.service.IExamService; import com.goldgov.dygl.module.partymemberrated.rated.services.IPartyMemberRatedService; import com.goldgov.dygl.module.partyorganization.service.PartyOrgMemberCountBean; import com.goldgov.dygl.module.partyorganization.service.PartyOrganization; import com.goldgov.dygl.module.portal.webservice.examrecord.domain.ExamPercentageBean; import com.goldgov.dygl.module.portal.webservice.examrecord.service.ExamrecordQuery; import com.goldgov.dygl.module.portal.webservice.examrecord.service.IExamrecordService; import com.goldgov.gtiles.core.security.AuthorizedDetails; import com.goldgov.gtiles.core.web.GoTo; import com.goldgov.gtiles.core.web.OperatingType; import com.goldgov.gtiles.core.web.UserHolder; import com.goldgov.gtiles.core.web.annotation.ModelQuery; import com.goldgov.gtiles.core.web.annotation.ModuleOperating; import com.goldgov.gtiles.core.web.annotation.ModuleResource; import com.goldgov.gtiles.module.user.service.User; @RequestMapping("/module/exam/examrecord") @Controller("examrecordController") @ModuleResource(name="同步考试系统数据表") public class ExamrecordController { public static final String PAGE_BASE_PATH = "portal/webservice/examrecord/web/pages/"; @Autowired @Qualifier("examrecordServiceImpl") private IExamrecordService examrecordService; @Autowired @Qualifier("partyMemberRatedService") private IPartyMemberRatedService partyMemberRatedService; @Autowired @Qualifier("dutyServiceImpl") private IDutyService dutyService; @Autowired @Qualifier("examServiceImpl") private IExamService examService; @Autowired @Qualifier("propertiesReader") private Properties prop; @Autowired @Qualifier("PartyMemberServiceImpl_AJ") private IPartyMemberService_AJ partyMemberServiceImpl_AJ; @Autowired @Qualifier("partyMemberService_AA") private IPartyMemberService_AA partyMemberService_AA; /** * 集团总部和子分公司考试排行榜 * @param query * @param request * @param model * @return * @throws Exception */ @SuppressWarnings("unchecked") @RequestMapping("/findInfoList") @ModuleOperating(name="信息查询",type=OperatingType.FindList) public String findList(@ModelQuery("query") ExamrecordQuery query,HttpServletRequest request,Model model) throws Exception{ AuthorizedDetails details = (AuthorizedDetails)UserHolder.getUserDetails(); User user = (User) details.getCustomDetails(ShConstant.USER_INFO); // PartyMemberInfoDuty memberInfo = dutyService.findInfoMemberInfo(user.getEntityID()); //个人信息 // PartyMemberRated rated = partyMemberRatedService.getTheLatestPublishedRatedId();//评价Id 查询 PartyOrganization currentOrganzation = (PartyOrganization) details.getCustomDetails(ShConstant.CURRENT_PARTY_ORGANZATION); // //查询党员的pm_aa_id // List<Map<String, Object>> pmList = partyMemberService_AA.findInfoByUserId(user.getEntityID()); // Map<String, Object> map = pmList.get(0); // String aaid = map.get("AA_ID").toString(); // // //根据党员的pm_aa_id查询照片ID // String photoID = null; // Map<String,Object> mapph=partyMemberServiceImpl_AJ.findInfoByAAID(aaid); // if(mapph!=null&&mapph.get("AJ1")!=null){ // photoID=mapph.get("AJ1").toString(); // } Exam exam = examService.findExamInfo(); query.setLoginId(user.getEntityID()); if(exam!=null){ query.setExamId(exam.getExamPaperId()); query.setSearchPaperid(exam.getExamPaperId()); } ExamPercentageBean findexamInfo = examrecordService.findexamInfo(query); // query.setSearchRatedId(rated.getRatedId()); //子分公司 if(query.getSearchOrgId()==null){ query.setSearchOrgId("-1"); } query.setSearchNoOrgId("8a00122b4941a4bf01496f804b544a52"); String key = "examPaihangbang"+query.getSearchOrgId()+query.getSearchNoOrgId()+query.getExamId(); List<ExamPercentageBean> resultList= SpyMemcachedImpl.get(key); if(resultList==null){ resultList = examrecordService.findPercentageList(query); SpyMemcachedImpl.put(key,resultList, 3600*12); } query.setResultList(resultList); //集团总部 query.setSearchOrgId("8a00122b4941a4bf01496f804b544a52"); query.setSearchNoOrgId(null); key = "examPaihangbang2"+query.getSearchOrgId()+query.getExamId(); List<ExamPercentageBean> resultListjitun= SpyMemcachedImpl.get(key); if(resultListjitun==null){ resultListjitun = examrecordService.findPercentageList(query); SpyMemcachedImpl.put(key,resultListjitun, 3600*12); } String el = prop.getProperty("el.domain"); model.addAttribute("el", el); model.addAttribute("findexamInfo", findexamInfo); model.addAttribute("exam", exam); model.addAttribute("user", user); // model.addAttribute("photoID", photoID); model.addAttribute("currentOrganzation", currentOrganzation); model.addAttribute("resultListjitun", resultListjitun); return new GoTo(this).sendPage("examindex.ftl"); } @RequestMapping("/findBinList") public String findPieList(Model model,HttpServletRequest request) throws Exception{ String pieType = request.getParameter("pieType"); List<PartyOrgMemberCountBean> list = new ArrayList<PartyOrgMemberCountBean>(); ExamrecordQuery query=new ExamrecordQuery(); Exam exam = examService.findExamInfo(); query.setExamId(exam.getExamPaperId()); if(pieType.equals("qjt")){ query.setSearchOrgId("-1"); }else if(pieType.equals("jt")){ query.setSearchOrgId("8a00122b4941a4bf01496f804b544a52"); query.setSearchNoOrgId(null); }else if(pieType.equals("zfg")){ query.setSearchOrgId("-1"); query.setSearchNoOrgId("8a00122b4941a4bf01496f804b544a52"); } Integer pmcount = 0; Integer examcount = 0; String key="findBinList_"+query.getExamId()+query.getSearchOrgId()+query.getSearchNoOrgId(); list=SpyMemcachedImpl.get(key); if(list==null){ list=new ArrayList<PartyOrgMemberCountBean>(); List<ExamPercentageBean> resultListjitun = examrecordService.findPercentageList(query); if(resultListjitun!=null&&resultListjitun.size()>0){ for (ExamPercentageBean examPercentageBean : resultListjitun) { pmcount += examPercentageBean.getPmcount(); examcount += examPercentageBean.getExamcount(); } } Double pcount = (Double.valueOf(examcount)/Double.valueOf(pmcount)*100); PartyOrgMemberCountBean bean = new PartyOrgMemberCountBean(); bean.setY(pcount); bean.setCount(examcount); bean.setName("已参与"); list.add(bean); PartyOrgMemberCountBean bean1 = new PartyOrgMemberCountBean(); bean1.setY(100-pcount); bean1.setName("未参与"); bean1.setCount(pmcount-examcount); list.add(bean1); SpyMemcachedImpl.put(key,list,3600*12); } model.addAttribute("dataList", list); return ""; } public static void main(String[] args) { System.out.println(4/20*100); } }
public class Rational { //instance variables private int numerator; private int denominator; // constructors public Rational(int numerator) { this(numerator, 1); } public Rational(int numerator, int denominator) { if(denominator < 0){ denominator = -1*denominator; numerator = -1*numerator; } this.numerator = numerator; this.denominator = denominator; reduce(); } //returns the numerator public int getNumerator() { return numerator; } //returns the denominator public int getDenominator() { return denominator; } //adds this Rational and other public Rational plus(Rational other) { //returns this Rational plus the other Rational int newDenominator = denominator * other.denominator; int newNumerator = numerator * other.denominator; int newOtherNumerator = other.numerator * denominator; int sum = newNumerator + newOtherNumerator; return new Rational(sum, newDenominator); } //adds Rational a and Rational b public static Rational plus(Rational a, Rational b) { return a.plus(b); //cals the plus method to add Rational a with Rational b } // Transforms this number into its reduced form private void reduce() { if(numerator ==0){ denominator =1; } else{ int reduced = gcd(Math.abs(numerator), denominator); //find the greatest commom divisor of the numerator and denominator numerator = numerator/reduced; //divide the numerator by this gcd denominator = denominator/reduced; //divide the denminator by this gcd } } // Euclid's algorithm for calculating the greatest common divisor private int gcd(int a, int b) { while (a != b) if (a > b) a = a - b; else b = b - a; return a; } //compares other to this Rational public int compareTo(Rational other) { int thisNewNum = other.denominator * numerator; int otherNewNum = other.numerator * denominator; return thisNewNum - otherNewNum; } //checks if this Rational equals other public boolean equals(Rational other) { if(numerator == other.numerator && denominator == other.denominator){ return true; } return false; } //returns a string representation of the fraction (ex. 1/2) public String toString() { return numerator + "/" + denominator; //returns the fraction in string form } }
package com.meti.asset; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; public class DefaultBuilder implements AssetBuilder { @Override public Asset build(File file) throws IOException { FileReader reader = new FileReader(file); //might be a bit memory intensive ArrayList<Integer> integerList = new ArrayList<>(); int b; while ((b = reader.read()) != -1) { integerList.add(b); } int[] array = new int[integerList.size()]; for (int i = 0; i < array.length; i++) { array[i] = integerList.get(i); } return new ByteAsset(array); } }
package com.vinmein.foodiehuts.login.di; import com.vinmein.foodiehuts.components.ResourceProvider; import com.vinmein.foodiehuts.components.data.Prefs; import com.vinmein.foodiehuts.components.Navigator; import com.vinmein.foodiehuts.di.PerActivity; import com.vinmein.foodiehuts.login.LoginActivity; import com.vinmein.foodiehuts.login.presenters.LoginPresenter; import dagger.Module; import dagger.Provides; @Module public class LoginActivityModule { private LoginActivity activity; public LoginActivityModule(LoginActivity activity) { this.activity = activity; } @Provides @PerActivity public LoginPresenter loginPresenter(Navigator navigator, ResourceProvider provider, Prefs prefs) { return new LoginPresenter(navigator, provider, prefs); } @Provides @PerActivity public Navigator navigator() { return new Navigator(activity); } }
package com.xm.user.domain; import java.util.Date; /** * Created by xm on 2017/2/21. */ public class Blog { private int id; private String title; private String author; private String content; private Date updateTime; private String blogCatalog; public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getAuthor() { return author; } public void setAuthor(String author) { this.author = author; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } public int getId() { return id; } public void setId(int id) { this.id = id; } public Date getUpdateTime() { return updateTime; } public void setUpdateTime(Date updateTime) { this.updateTime = updateTime; } public String getBlogCatalog() { return blogCatalog; } public void setBlogCatalog(String blogCatalog) { this.blogCatalog = blogCatalog; } }
import java.io.*; import java.sql.*; import javax.servlet.*; import javax.servlet.http.*; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; public class Login extends HttpServlet { public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); String un=request.getParameter("username"); try{ System.out.println("1"); Class.forName("com.mysql.jdbc.Driver"); System.out.println("2"); Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/test","root",""); //PreparedStatement ps=con.prepareStatement("select f_name from user_info where username = '"+un+"'"); //ps.setString(1,n); System.out.println(un); //int i=ps.executeUpdate(); //if(i>0) request.setAttribute("username", un); System.out.print("successfully img retrieved..."); request.getRequestDispatcher("Login_Pass.jsp").forward(request,response); }catch (Exception e2) {System.out.println(e2);} out.close(); } }
package com.liu.Class; import java.io.Serializable; public class leave implements Serializable{ private String leaveId; private int leaveVin; private int position; public String getLeaveId() { return leaveId; } public void setLeaveId(String leaveId) { this.leaveId = leaveId; } public int getPosition() { return position; } public void setPosition(int position) { this.position = position; } public int getLeaveVin() { return leaveVin; } public void setLeaveVin(int leaveVin) { this.leaveVin = leaveVin; } }
package testSel.testSelVal; import java.util.ArrayList; import java.util.List; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; public class genericMethod { WebDriver driver; public genericMethod(WebDriver driver) { this.driver=driver; } public WebElement getElement(String locator,String type) { type=type.toLowerCase(); if (type.equals("id")) { return this.driver.findElement(By.id(locator)); }else { System.out.println("Invalid locator type"); return null; } } public List<WebElement> getElementList(String locator,String type) { type=type.toLowerCase(); List<WebElement> ElementList=new ArrayList<WebElement>(); if (type.equals("xpath")) { ElementList= this.driver.findElements(By.xpath(locator)); }else { System.out.println("Invalid locator type"); } if (ElementList.isEmpty()) { System.out.println("Element not found"); }else { System.out.println("Element found"); } return ElementList; } }
/* * Copyright (C) 2019-2023 Hedera Hashgraph, LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.hedera.mirror.test.e2e.acceptance.props; import java.util.ArrayList; import java.util.List; import lombok.Data; @Data public class MirrorNetworkNode { private String description; private String fileId; private String memo; private String nodeAccountId; private long nodeId; private String nodeCertHash; private String publicKey; private List<MirrorServiceEndpoint> serviceEndpoints = new ArrayList<>(); private TimestampRange timestamp; @Data public static class MirrorServiceEndpoint { private String ipAddressV4; private int port; } }
package syncAlgorithm; import java.util.Hashtable; public class TreeAndPathEntryTable { private FileTree tree; private Hashtable<String, FileEntry> pathEntryTable; public FileTree getTree() { return tree; } public Hashtable<String, FileEntry> getPathEntryTable() { return pathEntryTable; } public TreeAndPathEntryTable(FileTree tree, Hashtable<String, FileEntry> pathEntryTable) { this.tree = tree; this.pathEntryTable = pathEntryTable; } }
package database; import agenda.DB_AgendaManagement; import document.DB_DocumentManagement; import org.junit.After; import org.junit.Before; import request.DB_RequestManagement; import user.DB_UserManagement; import voting.DB_VotingManagement; import java.io.File; import java.io.IOException; import java.net.URI; import java.nio.file.Paths; public abstract class DatabaseTests { private URI path; private DB_UserManagement generalUserDB; private DB_AgendaManagement agendaDB; private DB_DocumentManagement documentDB; private DB_RequestManagement requestDB; private DB_VotingManagement votingDB; @Before public void init() throws IOException { String path = "testdb/database.db"; this.generalUserDB = new DB_UserManager(path); this.agendaDB = new DB_AgendaManager(path); this.documentDB = new DB_DocumentManager(path); this.requestDB = new DB_RequestManager(path); this.votingDB = new DB_VotingManager(path); } @After public void cleanup() { path = Paths.get("testdb/database.db").toUri(); new File(path).delete(); } protected DB_UserManagement getGeneralUserDB() { return this.generalUserDB; } protected DB_AgendaManagement getAgendaDB() { return this.agendaDB; } protected DB_DocumentManagement getDocumentDB() { return this.documentDB; } protected DB_RequestManagement getRequestDB() { return this.requestDB; } protected DB_VotingManagement getVotingDB() { return this.votingDB; } }
package com.ssm.wechatpro.controller; import javax.annotation.Resource; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import com.ssm.wechatpro.object.InputObject; import com.ssm.wechatpro.object.OutputObject; import com.ssm.wechatpro.service.WechatAdminRoleMenuService; @Controller public class WechatAdminRoleMenuController { @Resource private WechatAdminRoleMenuService wechatAdminRoleMenuService; @RequestMapping("post/WechatAdminRoleMenuController/selectRoleByMenuId") @ResponseBody public void selectRoleByMenuId(InputObject inputObject,OutputObject outputObject) throws Exception{ wechatAdminRoleMenuService.selectRoleByMenuId(inputObject, outputObject); } }
package Question4; public class main { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub StackArray<Integer> stack = new StackArray<Integer>(); boolean expansionRule = false; for(int i = 0; i< 30000; i++) { if(expansionRule) stack.setExpansionRule('c'); else stack.setExpansionRule('d'); long startTime = System.currentTimeMillis(); stack.push(i); long finishTime = System.currentTimeMillis(); //stack.truncate(); if(i%100 == 0) { if(finishTime - startTime > 0) System.out.println(finishTime-startTime + " " + i + " " + expansionRule); expansionRule = !expansionRule; } } /*System.out.println(stack.isEmpty()); stack.push(1); stack.push(2); stack.push(3); stack.push(4); stack.push(5); stack.push(6); stack.push(7); stack.push(8); stack.push(9); stack.push(10); stack.truncate(); stack.push(11); stack.push(12); stack.truncate(); /*System.out.println(stack.size()); System.out.println(stack.peek()); System.out.println(stack.pop()); System.out.println(stack.isEmpty()); System.out.println(stack.pop()); /*System.out.println(stack.isEmpty()); stack.truncate();/* /*System.out.println(stack.pop()); System.out.println(stack.isEmpty()); System.out.println(stack.pop()); System.out.println(stack.isEmpty()); //System.out.println(stack.pop()); System.out.println(stack.isEmpty()); System.out.println(stack.size());*/ } }
import java.time.LocalDate; import java.util.Scanner; class Main { public static void main(String[] args) { // put your code here Scanner scanner = new Scanner(System.in); int year = scanner.nextInt(); int month = scanner.nextInt(); int minus = scanner.nextInt(); System.out.println(LocalDate.of(year, month + 1, 1). minusDays(minus)); } }
package nb.queryDomain; import java.io.Serializable; import java.math.BigDecimal; import java.util.Date; public class CreditAccPriceHistory implements Serializable { private Date date; private BigDecimal acceptedPrice; public CreditAccPriceHistory() { } public CreditAccPriceHistory(Date date, BigDecimal acceptedPrice) { this.date = date; this.acceptedPrice = acceptedPrice; } public Date getDate() { return date; } public void setDate(Date date) { this.date = date; } public BigDecimal getAcceptedPrice() { return acceptedPrice; } public void setAcceptedPrice(BigDecimal acceptedPrice) { this.acceptedPrice = acceptedPrice; } }
package zuoshen.array; import java.util.HashMap; import java.util.Map; import java.util.Scanner; public class 子数组中0和1个数相等的最长子数组长度 { public static int sub_sum0(int[]arr){ if(arr==null||arr.length==0){ return 0; } for (int i = 0; i <arr.length ; i++) { arr[i]=arr[i]==0?-1:arr[i]; } Map<Integer,Integer> map=new HashMap<>(); int sum=0; int max=0; map.put(0,-1); for (int i = 0; i <arr.length ; i++) { sum+=arr[i]; if(map.containsKey(sum)){ max=Math.max(i-map.get(sum),max); } if(!map.containsKey(sum)){ map.put(sum,i); } } return max; } public static void main(String[] args) { Scanner sc=new Scanner(System.in); while (sc.hasNext()){ int n=sc.nextInt(); int[]arr=new int[n]; for (int i = 0; i <n ; i++) { arr[i]=sc.nextInt(); } System.out.println(sub_sum0(arr)); } } }
package mashup.spring.elegant.search.application;
package org.dempsay.demo.freemaker.api; /** * A Sample immutable * * @author shawn * */ public class Sample { public final String data; protected Sample(final SampleBuilder builder) { this.data = builder.data; } public static String data(final Sample sample) { return sample.data; } }
package Estruturas; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Objects; /** * Estrutura que representa uma palavra e suas ocorrências em vários documentos. * Possui um String texto que representa a palavra em sí e um HashMap onde a * chave é o id do documento e o valor um contador de ocorrências da palavra em * um documento. * * @author Lucas */ public class PalavraMap implements InterfacePalavra { private String texto; private final HashMap<Integer, Integer> documentos; /** * Construtor: cria um novo HashMap insere uma nova key. */ public PalavraMap(String texto, int id_documento) { this.texto = texto; this.documentos = new HashMap<>(); this.documentos.put(id_documento, 1); } /** * Caso a lista de pares já contenha aquele documento, incrementa o * contador. Caso contrário insere um novo nó. */ public void insere(int id_documento) { Integer v = this.documentos.get(id_documento); if (v == null) { this.documentos.put(id_documento, 1); } else { this.documentos.put(id_documento, v + 1); } // if (this.documentos.containsKey(id_documento)) { // this.documentos.put(id_documento, documentos.get(id_documento) + 1); // } else { // this.documentos.put(id_documento, 1); // } } /* * Retorna a palavra em sí; */ public String getTexto() { return texto; } public HashMap<Integer, Integer> getDocumentos() { return documentos; } /** * Compara se dois objetos Palavra são iguais. A condição é a string palavra * que ambos contém ser a mesma, independente do HashMap. */ @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final PalavraMap other = (PalavraMap) obj; return Objects.equals(this.texto, other.texto); } /** * Imprime todos os documentos do HashMap. */ public void imprimePares() { System.out.println("A palavra " + this.texto + " foi encontrada nos seguintes documentos:"); for (Map.Entry<Integer, Integer> i : this.documentos.entrySet()) { System.out.print(i.getKey() + " - "); } System.out.println(); } /** * Retorna o numero de documentos em que a palavra ocorre */ public int numeroDocumentos() { if (this.documentos != null) { return this.documentos.size(); } return 0; } /** * Retorna o numero de ocorrencias da palavra no documento */ public int numeroOcorrenciasPalavraNoDocumento(int id_documento) { return this.documentos.get(id_documento); } /** * Retorna um iterator para percorrer a estrutura */ public Iterator getIterator() { if (this.documentos == null || this.documentos.isEmpty()) { return null; } return this.documentos.entrySet().iterator(); } @Override public int hashCode() { int hash = 7; hash = 67 * hash + Objects.hashCode(this.texto); return hash; } }
package br.com.pizzaria.controller; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import br.com.pizzaria.dao.PizzaDAO; import br.com.pizzaria.entidades.Item; import br.com.pizzaria.entidades.Pizza; import br.com.pizzaria.parser.PizzaParser; @RestController @RequestMapping("/pizzas") public class PizzaController { @Autowired private PizzaDAO dao; @RequestMapping(method = RequestMethod.GET) public List<Item> carregarTodas() { return PizzaParser.fromPizzas(dao.carregarTodos(Pizza.class)); } @RequestMapping(value = "/{id}", method = RequestMethod.GET) public Pizza obterPizza(@PathVariable long id) { Pizza pizza = dao.obter(Pizza.class, id); return pizza; } }
package basics; import org.openqa.selenium.WebDriver; import util.Commons; /** Req: open the browser and Hit the URL "https://gmail.com" using the Java Steps: ------- 1.Provide the driver software location ""C:\\chromedriver.exe" to the System. Create the web driver Object using the driver software. System.setProperty("webdriver.chrome.driver", "C:\\chromedriver.exe"); WebDriver driver = new ChromeDriver(); 2.Open the URL driver.get("https://www.gmail.com"); 3.close the browser driver.quit() */ public class Ex4Comm { public static void main(String[] args) throws InterruptedException { WebDriver driver = Commons.getChromeDriver(); //open the url driver.get("http://www.google.com"); Thread.sleep(5000); // close the browser driver.quit(); } public static void main1(String[] args) { WebDriver driver = Commons.getDriver(); driver.get("http://www.google.com"); driver.close(); } }
package com.mobica.rnd.parking.parkingbetests; import com.mobica.rnd.parking.parkingbetests.support.TestSuiteData; import com.mobica.rnd.parking.parkingbetests.support.RestAssuredProcessor; import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.TestPropertySource; import org.springframework.test.context.junit4.SpringRunner; import javax.annotation.PostConstruct; /** * Created by int_eaja on 2017-07-26. */ @RunWith(SpringRunner.class) @SpringBootTest @TestPropertySource("classpath:application-test.properties") public class Issue_6_ParkingConfigurationTest { private static final String ISSUE_NAME = "6-ParkingConfiguration"; @Autowired private RestAssuredProcessor processor; private TestSuiteData suiteData; @PostConstruct public void setUp() { suiteData = new TestSuiteData(processor.getBaseURL(), ISSUE_NAME); } @Test public void parking_configuration_success_test() { suiteData.createTestCaseExecutor("parking_configuration_success") .performTests(processor, suiteData); } @Test public void parking_configuration_with_correct_boundary_values_success_test() { suiteData.createTestCaseExecutor("parking_configuration_with_correct_boundary_values_success") .performTests(processor, suiteData); } @Test public void parking_configuration_without_capacity_failure_test() { suiteData.createTestCaseExecutor("parking_configuration_without_capacity_failure") .performTests(processor, suiteData); } @Test public void parking_configuration_without_name_failure_test() { suiteData.createTestCaseExecutor("parking_configuration_without_name_failure") .performTests(processor, suiteData); } @Test public void parking_configuration_with_capacity_not_as_a_number_value_failure_test() { suiteData.createTestCaseExecutor("parking_configuration_with_capacity_not_as_a_number_value_failure") .performTests(processor, suiteData); } @Test public void parking_configuration_with_capacity_too_long_length_failure_test() { suiteData.createTestCaseExecutor("parking_configuration_with_capacity_too_long_length_failure") .performTests(processor, suiteData); } @Test public void parking_configuration_with_capacity_too_long_not_numerical_length_failure_test() { suiteData.createTestCaseExecutor("parking_configuration_with_capacity_too_long_not_numerical_length_failure") .performTests(processor, suiteData); } @Test public void parking_configuration_with_name_too_long_length_failure_test() { suiteData.createTestCaseExecutor("parking_configuration_with_name_too_long_length_failure") .performTests(processor, suiteData); } @Test public void parking_configuration_with_incorrect_boundary_values_failure_test() { suiteData.createTestCaseExecutor("parking_configuration_with_incorrect_boundary_values_failure") .performTests(processor, suiteData); } }
package primeiros_exercicios; import java.util.Date; import java.util.Scanner; public class NumerosPrimos { public static void main(String[] args) { int a; boolean primo=true; Scanner valor = new Scanner(System.in); System.out.print("Digite um numero: "); a = valor.nextInt(); if (a <= 0) { System.out.println("Digito errado"); System.out.print("digite um valor valido: "); a = valor.nextInt(); } for (int i = 2; i <a; i++) { if (a % i == 0) { primo = false; break; } } if (primo==true){ System.out.println("e primo"); } else { System.out.println("nao e primo"); } } }
package com.youthchina.controller.user; import com.youthchina.annotation.ResponseBodyDTO; import com.youthchina.controller.DomainCRUDController; import com.youthchina.domain.zhongyang.Gender; import com.youthchina.domain.zhongyang.User; import com.youthchina.dto.Response; import com.youthchina.dto.StatusDTO; import com.youthchina.dto.security.ModifiedUserDTO; import com.youthchina.dto.security.UserDTO; import com.youthchina.dto.util.InfluenceDTO; import com.youthchina.exception.zhongyang.exception.ClientException; import com.youthchina.exception.zhongyang.exception.ForbiddenException; import com.youthchina.exception.zhongyang.exception.InternalStatusCode; import com.youthchina.exception.zhongyang.exception.NotFoundException; import com.youthchina.service.DomainCRUDService; import com.youthchina.service.application.CompanyCURDService; import com.youthchina.service.application.JobService; import com.youthchina.service.application.JobServiceImpl; import com.youthchina.service.community.*; import com.youthchina.service.user.StudentService; import com.youthchina.service.user.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.http.ResponseEntity; import org.springframework.security.core.annotation.AuthenticationPrincipal; import org.springframework.web.bind.annotation.*; import javax.validation.Valid; import java.net.URI; import java.net.URISyntaxException; import java.sql.Timestamp; /** * Created by zhongyangwu on 11/8/18. */ @RestController @RequestMapping("${web.url.prefix}/users/**") public class UserController extends DomainCRUDController<User, Integer> { private final StudentService studentService; private final AttentionService attentionService; private final EssayService essayService; private final QuestionService questionService; private final VideoService videoService; private final AnswerService answerService; private final JobService jobService; private final BriefReviewService briefReviewService; private final CompanyCURDService companyCURDService; private final InfluenceService influenceService; private UserService userService; private String url; @Autowired public UserController(UserService userService, @Value("${web.url.prefix}") String prefix, StudentService studentService, AttentionServiceImpl attentionService, EssayServiceImpl essayService, QuestionServiceImpl questionService, VideoServiceImpl videoService, AnswerServiceImpl answerService, JobServiceImpl jobService, BriefReviewService briefReviewService, CompanyCURDService companyCURDService , InfluenceService influenceService) { this.userService = userService; this.url = prefix + "/users/"; this.studentService = studentService; this.attentionService = attentionService; this.essayService = essayService; this.questionService = questionService; this.videoService = videoService; this.answerService = answerService; this.jobService = jobService; this.briefReviewService = briefReviewService; this.companyCURDService = companyCURDService; this.influenceService = influenceService; } @GetMapping("/{id}") public ResponseEntity<?> findUser(@PathVariable Integer id, @AuthenticationPrincipal User user) throws ForbiddenException, NotFoundException { if (user.getId().equals(id)) { return get(id); } else { throw new ForbiddenException(); } } @GetMapping("/{id}/influence") public ResponseEntity<?> getMyInfluence(@PathVariable Integer id, @AuthenticationPrincipal User user) throws ForbiddenException { if (user.getId().equals(id)) { Integer influence = influenceService.getUserInfluence(id); return ResponseEntity.ok(new Response(new InfluenceDTO(influence), new StatusDTO(200, "success"))); } else { throw new ForbiddenException(); } } @PatchMapping("/{id}") @ResponseBodyDTO(UserDTO.class) public ResponseEntity<?> modifyUser(@PathVariable Integer id, @AuthenticationPrincipal User user, @RequestBody @Valid ModifiedUserDTO body) throws ClientException, ForbiddenException, NotFoundException { // Role control if (id.equals(user.getId())) { if (body.getGender() != null) { try { Gender gender = Gender.valueOf(body.getGender()); user.setGender(gender); } catch (IllegalArgumentException ex) { throw new ClientException("gender must be MALE, FEMALE or OTHER"); } } user.setFirstName(body.getFirstName() == null ? user.getFirstName() : body.getFirstName()); user.setLastName(body.getLastName() == null ? user.getLastName() : body.getLastName()); user.setAvatarUrl(body.getAvatarUrl() == null ? user.getAvatarUrl() : body.getAvatarUrl()); user.setDateOfBirth(body.getDateOfBirth() == null ? user.getDateOfBirth() : new Timestamp(body.getDateOfBirth())); User resultUser = userService.update(user); return ResponseEntity.ok(new Response(resultUser)); } else { throw new ForbiddenException(InternalStatusCode.ACCESS_DENY); } } @Override protected DomainCRUDService<User, Integer> getService() { return this.userService; } @Override protected URI getUriForNewInstance(Integer id) throws URISyntaxException { return new URI(this.url + id); } }
package Bank; public class ClientsAccount { Branch branch; Account account; Client client; }
/* * 2012-3 Red Hat Inc. and/or its affiliates and other contributors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.overlord.rtgov.epn; import static org.junit.Assert.*; import java.io.Serializable; import org.junit.Test; import org.overlord.rtgov.epn.AbstractEPNManager; import org.overlord.rtgov.epn.EPNContainer; import org.overlord.rtgov.epn.EventList; import org.overlord.rtgov.epn.Network; import org.overlord.rtgov.epn.NetworkListener; import org.overlord.rtgov.epn.Node; import org.overlord.rtgov.epn.Notification; import org.overlord.rtgov.epn.NotificationType; import org.overlord.rtgov.epn.Subscription; import org.overlord.rtgov.epn.testdata.TestEvent1; import org.overlord.rtgov.epn.testdata.TestEvent2; import org.overlord.rtgov.epn.testdata.TestEventProcessorA; import org.overlord.rtgov.epn.testdata.TestNotificationListener; public class AbstractEPNManagerTest { private static final String SUBJECT1 = "SUBJECT1"; private static final String DUMMY_SUBJECT = "DummySubject"; private static final String N1 = "N1"; private static final String N2 = "N2"; private static final String N3 = "N3"; private static final String TEST_NETWORK = "TestNetwork"; private static final String TEST_SUBJECT1 = "TestSubject1"; private static final String TEST_SUBJECT2 = "TestSubject2"; private static final String VER1 = "1"; private static final String VER2 = "2"; protected AbstractEPNManager getManager() { return(new AbstractEPNManager() { public void publish(String subject, java.util.List<? extends java.io.Serializable> events) throws Exception { } public EPNContainer getContainer() { return null; } }); } @Test public void testRegisterNetworkIncorrectRootNodeName() { Network net=new Network(); net.setName(TEST_NETWORK); // Root should be incorrect, to test exception Subscription sub=new Subscription(); sub.setNodeName(N2); sub.setSubject(TEST_SUBJECT1); net.getSubscriptions().add(sub); Node n1=new Node(); n1.setName(N1); n1.setEventProcessor(new TestEventProcessorA()); net.getNodes().add(n1); AbstractEPNManager mgr=getManager(); try { mgr.register(net); fail("Network registration should fail due to missing or incorrect root node"); } catch(Exception e) { } } @Test public void testRegisterInvalidNetwork() { Network net=new Network(); AbstractEPNManager mgr=getManager(); try { mgr.register(net); fail("Network registration should fail due to validation issues"); } catch(Exception e) { } } @Test public void testNetworkListenerNotified() { Network net=new Network(); net.setName(TEST_NETWORK); net.setVersion(VER1); Node n1=new Node(); n1.setName(N1); n1.setEventProcessor(new TestEventProcessorA()); net.getNodes().add(n1); AbstractEPNManager mgr=getManager(); TestNetworkListener l=new TestNetworkListener(); mgr.addNetworkListener(l); if (l._registered.size() != 0) { fail("No networks should be registered"); } if (l._unregistered.size() != 0) { fail("No networks should be unregistered"); } try { mgr.register(net); } catch(Exception e) { fail("Failed: "+e); } if (l._registered.size() != 1) { fail("1 network should be registered: "+l._registered.size()); } if (l._unregistered.size() != 0) { fail("Still no networks should be unregistered"); } try { mgr.unregister(net.getName(), net.getVersion()); } catch(Exception e) { fail("Failed: "+e); } if (l._registered.size() != 1) { fail("Still 1 network should be registered: "+l._registered.size()); } if (l._unregistered.size() != 1) { fail("1 network should be unregistered: "+l._unregistered.size()); } } @Test public void testRegisterNetworkNodeNoEventProcessor() { Network net=new Network(); net.setName(TEST_NETWORK); //net.setRootNodeName(N1); Node n1=new Node(); n1.setName(N1); net.getNodes().add(n1); AbstractEPNManager mgr=getManager(); try { mgr.register(net); fail("Network registration should fail due to node with missing event processor"); } catch(Exception e) { } } @Test public void testNetworkAndNodeLookup() { Network net=new Network(); net.setName(TEST_NETWORK); net.setVersion(VER1); //net.setRootNodeName(N1); Node n1=new Node(); n1.setName(N1); n1.setEventProcessor(new TestEventProcessorA()); net.getNodes().add(n1); Node n2=new Node(); n2.setName(N2); n2.setEventProcessor(new TestEventProcessorA()); net.getNodes().add(n2); Node n3=new Node(); n3.setName(N3); n3.setEventProcessor(new TestEventProcessorA()); net.getNodes().add(n3); AbstractEPNManager mgr=getManager(); try { mgr.register(net); } catch(Exception e) { fail("Failed to register network: "+e); } if (mgr.getNetwork(TEST_NETWORK, null) != net) { fail("Failed to find test network"); } try { if (mgr.getNode(TEST_NETWORK, null, N1) != n1) { fail("Failed to find node n1"); } if (mgr.getNode(TEST_NETWORK, null, N2) != n2) { fail("Failed to find node n2"); } if (mgr.getNode(TEST_NETWORK, null, N3) != n3) { fail("Failed to find node n3"); } } catch(Exception e) { fail("Failed to find node"); } } @Test public void testRegisterNotificationListenerNotifyProcessed() { Network net=new Network(); net.setName(TEST_NETWORK); net.setVersion(VER1); TestEventProcessorA tep=new TestEventProcessorA(); Node n1=new Node(); n1.setName(N1); n1.setEventProcessor(tep); Notification not1=new Notification(); not1.setSubject(SUBJECT1); not1.setType(NotificationType.Processed); n1.getNotifications().add(not1); net.getNodes().add(n1); AbstractEPNManager mgr=getManager(); try { mgr.register(net); TestNotificationListener nl=new TestNotificationListener(); mgr.addNotificationListener(SUBJECT1, nl); TestNotificationListener anothernl=new TestNotificationListener(); mgr.addNotificationListener(DUMMY_SUBJECT, anothernl); TestEvent1 te1=new TestEvent1(2); TestEvent2 te2=new TestEvent2(5); java.util.List<Serializable> elList=new java.util.ArrayList<Serializable>(); EventList el=new EventList(elList); elList.add(te1); elList.add(te2); tep.retry(te2); EventList retries=mgr.process(net, n1, null, el, 3); if (retries == null) { fail("Retries is null"); } if (retries.size() != 1) { fail("Retries should have 1 event: "+retries.size()); } if (!retries.contains(te2)) { fail("Retries did not contain te2"); } if (nl.getEntries().size() != 1) { fail("Notification listener should have 1 processed event: "+nl.getEntries().size()); } if (!nl.getEntries().get(0).getEvents().contains(te1)) { fail("Processed Event te1 should have been processed"); } if (!nl.getEntries().get(0).getSubject().equals(SUBJECT1)) { fail("Processed Event subject name incorrect"); } if (anothernl.getEntries().size() > 0) { fail("Should be no entries in other listener"); } } catch(Exception e) { e.printStackTrace(); fail("Failed with exception: "+e); } } @Test public void testRegisterNotificationListenerDontNotifyProcessed() { Network net=new Network(); net.setName(TEST_NETWORK); net.setVersion(VER1); TestEventProcessorA tep=new TestEventProcessorA(); Node n1=new Node(); n1.setName(N1); n1.setEventProcessor(tep); Notification not1=new Notification(); not1.setSubject(SUBJECT1); not1.setType(NotificationType.Results); n1.getNotifications().add(not1); net.getNodes().add(n1); AbstractEPNManager mgr=getManager(); try { mgr.register(net); TestNotificationListener nl=new TestNotificationListener(); mgr.addNotificationListener(SUBJECT1, nl); TestNotificationListener anothernl=new TestNotificationListener(); mgr.addNotificationListener(DUMMY_SUBJECT, anothernl); TestEvent1 te1=new TestEvent1(2); TestEvent2 te2=new TestEvent2(5); java.util.List<Serializable> elList=new java.util.ArrayList<Serializable>(); EventList el=new EventList(elList); elList.add(te1); elList.add(te2); tep.retry(te2); EventList retries=mgr.process(net, n1, null, el, 3); if (retries == null) { fail("Retries is null"); } if (retries.size() != 1) { fail("Retries should have 1 event: "+retries.size()); } if (!retries.contains(te2)) { fail("Retries did not contain te2"); } if (nl.getEntries().size() != 0) { fail("Node listener should have 0 processed event: "+nl.getEntries().size()); } if (anothernl.getEntries().size() > 0) { fail("Should be no entries in other listener"); } } catch(Exception e) { e.printStackTrace(); fail("Failed with exception: "+e); } } @Test public void testRegisterMultipleNetworkVersions() { Network net1=new Network(); net1.setName(TEST_NETWORK); net1.setVersion(VER1); Subscription sub1=new Subscription(); sub1.setNodeName(N1); sub1.setSubject(TEST_SUBJECT1); net1.getSubscriptions().add(sub1); TestEventProcessorA tep=new TestEventProcessorA(); Node n1=new Node(); n1.setName(N1); n1.setEventProcessor(tep); net1.getNodes().add(n1); Network net2=new Network(); net2.setName(TEST_NETWORK); net2.setVersion(VER2); Subscription sub2=new Subscription(); sub2.setNodeName(N2); sub2.setSubject(TEST_SUBJECT2); net2.getSubscriptions().add(sub2); Node n2=new Node(); n2.setName(N2); n2.setEventProcessor(tep); net2.getNodes().add(n2); AbstractEPNManager mgr=getManager(); try { mgr.register(net1); // Check if network subscribed to subject java.util.List<Network> res1=mgr.getNetworksForSubject(TEST_SUBJECT1); if (res1 == null) { fail("Network list is null"); } if (res1.size() != 1) { fail("Network list should have 1 entry: "+res1.size()); } if (res1.get(0) != net1) { fail("Network should be net1"); } mgr.register(net2); // Refresh subject list res1 = mgr.getNetworksForSubject(TEST_SUBJECT1); if (res1 != null) { fail("List for subject1 should now be null"); } // Check if network subscribed to subject java.util.List<Network> res2=mgr.getNetworksForSubject(TEST_SUBJECT2); if (res2 == null) { fail("Network list2 is null"); } if (res2.size() != 1) { fail("Network list2 should have 1 entry: "+res2.size()); } if (res2.get(0) != net2) { fail("Network should be net2"); } // Finally check that unsubscribing the current version will reinstate the old subjects mgr.unregister(net2.getName(), net2.getVersion()); res2 = mgr.getNetworksForSubject(TEST_SUBJECT2); if (res2 != null) { fail("List for subject2 should now be null"); } res1 = mgr.getNetworksForSubject(TEST_SUBJECT1); if (res1 == null) { fail("List for subject1 should now be available again"); } if (res1.size() != 1) { fail("Network list1 should have 1 entry again: "+res1.size()); } if (res1.get(0) != net1) { fail("Network should be net1 again"); } } catch(Exception e) { fail("Failed with exception: "+e); } } public class TestNetworkListener implements NetworkListener { protected java.util.List<Network> _registered=new java.util.ArrayList<Network>(); protected java.util.List<Network> _unregistered=new java.util.ArrayList<Network>(); public void registered(Network network) { _registered.add(network); } public void unregistered(Network network) { _unregistered.add(network); } } }
package raktar; import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.List; public class Raktar { private List<Termek> termekek; private List<Szett> szettek; public Raktar() { termekek = new ArrayList<>(); szettek = new ArrayList<>(); } public int termekekSzama() { return termekek.size(); } public int szettekSzama() { return szettek.size(); } public Termek getTermek(int index) { if (termekek.size() > 0) { if (termekek.size()-1 <= index) { return termekek.get(index); } } return null; } public Szett getSzett(int index) { if (szettek.size() > 0) { if (szettek.size()-1 <= index) { return szettek.get(index); } } return null; } public Termek termekKeres(int azonosito) { for (int i = 0; i < termekek.size(); i++) { if (azonosito == termekek.get(i).getAzonosito()) { return termekek.get(i); } return null; } return null; } public void termekBeolvas(String fNev) throws FileNotFoundException, IOException { BufferedReader br = new BufferedReader(new FileReader(fNev)); String line = br.readLine(); // termekek = new ArrayList<Termek>(); termekek.add(Termek.createTermek(line)); while (line != null) { if (Termek.createTermek(line) != null) { for (int i = 0; i < termekek.size(); i++) { if (Termek.createTermek(line).getAzonosito() == getTermek(i).getAzonosito()) { // nullpointerex... br.readLine(); } } termekek.add(Termek.createTermek(line)); } line = br.readLine(); } } public void szettBeolvas(String fNev) throws FileNotFoundException, IOException { BufferedReader br = new BufferedReader(new FileReader(fNev)); String line = br.readLine(); while (line != null) { // String[] tmp = line.split(","); // Szett.ar = arKiszamol(termekKeres(Integer.parseInt(tmp[2])).getAr()); szettek.add(Szett.createSzett(line)); line = br.readLine(); } } @Override public String toString() { StringBuilder sb = new StringBuilder(); for (int i = 0; i < termekek.size(); i++) { sb.append(termekek.get(i).toString()).append("/n"); } for (int j = 0; j < szettek.size(); j++) { sb.append(szettek.get(j).toString()).append("/n"); } return sb.toString(); } }
package com.osce.server.portal; import com.osce.entity.SysParam; import com.osce.enums.SysParamEnum; import com.osce.result.Result; import com.osce.server.security.rsa.RsaKeyPairQueue; import com.osce.server.utils.ImageCodeUtil; import com.osce.server.utils.ParamUtil; import com.sm.open.care.core.enums.YesOrNo; import com.sm.open.care.core.utils.rsa.RsaKeyPair; import org.apache.commons.codec.binary.Base64; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import javax.annotation.Resource; import javax.imageio.ImageIO; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.UUID; /** * @ClassName: IndexController * @Description: 首页控制器跳转 */ @Controller public class LoginController extends BaseController { private static final Logger LOGGER = LoggerFactory.getLogger(LoginController.class); /** * 用户业务错误信息显示的常量变量名 */ private static final String ERROR_MSG = "errorMsg"; /** * rsa公钥常量变量名 */ private static final String PUBLIC_KEY = "publicKey"; @Resource(name = "rsaKeyPairQueue") private RsaKeyPairQueue rsaKeyPairQueue; @Resource private ImageCodeUtil imageCodeUtil; @Resource private ParamUtil paramUtil; /** * 网站名称 */ @Value("${website.name}") private String websiteName; @Value("${website.copyright}") private String websiteCopyright; @Value("${website.approve}") private String websiteApprove; @RequestMapping(value = "/login") public String home(Model model, HttpServletRequest request) { this.setModelAttr(model, request); model.addAttribute("websiteName", websiteName); model.addAttribute("websiteCopyright", websiteCopyright); model.addAttribute("websiteApprove", websiteApprove); SysParam sysParam = paramUtil.getParamInfo(SysParamEnum.VISITOR_SWITCH.getCode()); model.addAttribute(SysParamEnum.VISITOR_SWITCH.getCode(), sysParam != null ? sysParam.getParamValue() : YesOrNo.NO.getCode()); return "login"; } @RequestMapping(value = "/login/{errorMsg}") public String homeError(@PathVariable String errorMsg, Model model, HttpServletRequest request) { if (StringUtils.isNotBlank(errorMsg)) { model.addAttribute(ERROR_MSG, new String(Base64.decodeBase64(errorMsg))); } else { model.addAttribute(ERROR_MSG, ""); } model.addAttribute("websiteName", websiteName); model.addAttribute("websiteCopyright", websiteCopyright); model.addAttribute("websiteApprove", websiteApprove); this.setModelAttr(model, request); return "login"; } private void setModelAttr(Model model, HttpServletRequest request) { RsaKeyPair keyPair; try { keyPair = rsaKeyPairQueue.takeQueue(request); model.addAttribute(PUBLIC_KEY, keyPair.getPublicKey()); } catch (InterruptedException e) { logger.error("进入首页时,rsa公私钥队列相关操作异常", e); } } @RequestMapping(value = "login/verificationCode", method = RequestMethod.GET) @ResponseBody public String loginVerificationCode(HttpServletRequest request, HttpServletResponse response) { // 禁止图像缓存。 response.setHeader("Pragma", "no-cache"); response.setHeader("Cache-Control", "no-cache"); response.setDateHeader("Expires", 0); response.setContentType("image/jpeg"); // 将图像输出到Servlet输出流中。 try { ServletOutputStream sos = response.getOutputStream(); ImageIO.write(imageCodeUtil.getImage(request), "jpeg", sos); sos.close(); } catch (IOException e) { LOGGER.error("LoginController-loginVerificationCode error: {}", e); } return null; } @RequestMapping("/loginScanCode") @ResponseBody public Result loginScanCode(HttpServletRequest request) { Result result = new Result(true, null, null); try { String authKey = UUID.randomUUID().toString().replaceAll("-", ""); //生产二维码信息至redis //二维码信息(qr地址+uuid) request.getSession().setAttribute("authKey", authKey); } catch (Exception e) { String errMsg = StringUtils.isBlank(e.getMessage()) ? e.getMessage() : "登录失败!"; LOGGER.error("LoginController-loginScanCode error: {},e: {}", errMsg, e); result.change(false, errMsg, errMsg); } return result; } @RequestMapping("/loginTimeout") public String loginTimeout(HttpServletRequest request) { return "pages/common/loginTimeout"; } }
package com.veveup.dao; import com.veveup.domain.User; import java.util.List; public interface UserDao { /** * 查找所有用户 * * @return */ List<User> findAll(); /** * 通过传入name获得用户实例 * * @param name * @return */ User findUserByName(String name); /** * 保存新用户 */ void insertUser(User user); /** * 传入一个更改过的用户实例 通过uid更新用户信息 可以更改name和password、email * * @param user */ void updateUserByUser(User user); }
package com.oracle.demosjon.demojson; import java.sql.Connection; import oracle.soda.OracleCollection; import oracle.soda.OracleCursor; import oracle.soda.OracleDatabase; import oracle.soda.OracleDocument; import oracle.soda.rdbms.OracleRDBMSClient; public class SodaController { private Connection conn; public SodaController(Connection conn) { this.conn = conn; } public void doSodaWork() { try { OracleRDBMSClient cl = new OracleRDBMSClient(); OracleDatabase db = cl.getDatabase(conn); // Create a collection with the name "MyJSONCollection". OracleCollection col = db.admin().createCollection("MyJSONCollection"); // Create a JSON document. OracleDocument doc = db.createDocumentFromString("{ \"name\" : \"Borja\" }"); // Insert the document into a collection, and get back its // auto-generated key. System.out.println("Before inserting document"); String k = col.insertAndGet(doc).getKey(); // Find a document by its key. The following line // fetches the inserted document from the collection // by its unique key, and prints out the document's content System.out.println("Inserted content:" + col.find().key(k).getOne().getContentAsString() + "with Key: "+ k); // Find all documents in the collection matching a query-by-example (QBE). // The following lines find all JSON documents in the collection that have // a field "name" that starts with "A". OracleDocument f = db.createDocumentFromString("{\"name\" : { \"$startsWith\" : \"A\" }}"); OracleCursor c = col.find().filter(f).getCursor(); while (c.hasNext()) { // Get the next document. OracleDocument resultDoc = c.next(); // Print the document key and content. System.out.println("Key: " + resultDoc.getKey()); System.out.println("Content: " + resultDoc.getContentAsString()); } } catch (Exception e) { System.out.println(e); } } }
package ru.itis.javalab.repositories; import org.springframework.dao.DataAccessException; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.RowMapper; import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate; import org.springframework.jdbc.core.simple.SimpleJdbcInsert; import org.springframework.stereotype.Repository; import ru.itis.javalab.models.Post; import ru.itis.javalab.models.User; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; /** * created: 19-11-2020 - 0:24 * project: 07. Fremarker * * @author dinar * @version v0.1 */ @Repository public class PostRepositoryJdbcTemplateImpl implements CrudPostRepository { // language=SQL private static final String SQL_SELECT_BY_ID = "select * " + "from post " + "where id = ?"; // language=SQL private static final String SQL_SELECT_BY_USER_ID = "select * " + "from post " + "where user_id = ?"; // language=SQL private static final String SQL_SELECT_ALL = "select * " + "from post"; // language=SQL private static final String SQL_INSERT_POST = "insert into post(user_id, time, place, description, people, file_name) " + "values (?, ?, ?, ?, ?, ?)"; // language=SQL private static final String SQL_UPDATE_POST = "update post " + "set place = :place, description = :description, people = :people " + "where id = :id"; // language=SQL private static final String SQL_DELETE_POST = "delete from post " + "where id = ?"; // language=SQL private static final String SQL_SELECT_BY_FILENAME = "select * " + "from post " + "where file_name = ?"; private final SimpleJdbcInsert simpleJdbcInsert; private final JdbcTemplate jdbcTemplate; private final NamedParameterJdbcTemplate namedParameterJdbcTemplate; private final RowMapper<Post> rowMapper = (resultSet, i) -> Post.builder() .id(resultSet.getLong("id")) .user((User) resultSet.getObject("user_id")) .time(resultSet.getTimestamp("time")) .place(resultSet.getString("place")) .description(resultSet.getString("description")) .people(resultSet.getString("people")) .fileName(resultSet.getString("file_name")) .build(); public PostRepositoryJdbcTemplateImpl(SimpleJdbcInsert simpleJdbcInsert, JdbcTemplate jdbcTemplate, NamedParameterJdbcTemplate namedParameterJdbcTemplate) { this.simpleJdbcInsert = simpleJdbcInsert; this.jdbcTemplate = jdbcTemplate; this.namedParameterJdbcTemplate = namedParameterJdbcTemplate; } @Override public List<Post> findAllByUserId(Long id) { return jdbcTemplate.query(SQL_SELECT_BY_USER_ID, rowMapper, id); } @Override public Optional<Post> findById(Long id) { Post post; try { post = jdbcTemplate.queryForObject(SQL_SELECT_BY_ID, rowMapper, id); } catch (DataAccessException e) { return Optional.empty(); } return Optional.ofNullable(post); } @Override public Optional<Post> findByFileName(String fileName) { Post post; try { post = jdbcTemplate.queryForObject(SQL_SELECT_BY_FILENAME, rowMapper, fileName); } catch (DataAccessException e) { return Optional.empty(); } return Optional.ofNullable(post); } @Override public Long save(Post entity) { simpleJdbcInsert.withTableName("post") .usingColumns( "user_id", "time", "place", "description", "people", "file_name") .usingGeneratedKeyColumns("id"); Map<String, Object> map = new HashMap<>(); map.put("user_id", entity.getUser()); map.put("time", entity.getTime()); map.put("place", entity.getPlace()); map.put("description", entity.getDescription()); map.put("people", entity.getPeople()); map.put("file_name", entity.getFileName()); return (Long) simpleJdbcInsert.executeAndReturnKey(map); } @Override public List<Post> findAll() { return jdbcTemplate.query(SQL_SELECT_ALL, rowMapper); } @Override public void update(Post entity) { Map<String, String> map = new HashMap<>(); map.put("id", String.valueOf(entity.getId())); map.put("place", entity.getPlace()); map.put("description", entity.getDescription()); map.put("people", entity.getPeople()); namedParameterJdbcTemplate.update(SQL_UPDATE_POST, map); } @Override public void delete(Post entity) { jdbcTemplate.update(SQL_DELETE_POST, entity.getId()); } }
package com.jk.jkproject.net.im.info; import android.app.Activity; import android.text.TextUtils; import android.util.SparseArray; import android.view.View; import com.jk.jkproject.R; import com.jk.jkproject.ui.msg.IUploadProgress; import com.jk.jkproject.utils.Constants; import com.jk.jkproject.utils.DateUtils; import java.io.Serializable; import java.lang.ref.WeakReference; import java.util.List; import java.util.Observable; import java.util.Observer; import java.util.UUID; /** * @author zhoujiyu * @Description 消息列表中的消息实体 * @date 2015-2-5 */ public class MessageEntity implements Serializable, Observer { private static final long serialVersionUID = 1L; public static final int STATUS_NOT = 0; public static final int STATUS_SUCCESS = 1; public static final int STATUS_FAILED = 2; public static final int STATUS_LOADING = 3; private boolean IsSend = false; public long SessionId; private long UserID;// 用户ID private long FromID; // 发送者 private long ToID; // 接收者 private long SmsID;// 服务器自己会话内消息编号 private long SmsKey; // 服务器消息池会话的唯一编号 private String MsgID; // 客户端对所有消息的唯一编号(UUID) 主要是设置状态的消息唯一编号 private long GroupID;// 群IDz // add by xiaosong.xu private String thumbPath = null; // 本地小图路径 private String thumbUrl = null; // 小图url private String imagePath = null; // 本地大图路径 private String imageUrl = null; // 大图URL private int photoType =0; //0是相册 1 是实景相机 2是瞬间照片 private int progress = 0; private String voicePath = null; private String voiceUrl = null; private int voiceTime = 0; private int mediaDownloadStatus = 0;//0代表未下载,1代表未读,2代表已读 private int oldProgress = 0; // end by xiaosong.xu private String Text;// 聊天内容 private General.ETextType TextType = General.ETextType.ETT_TEXT; private General.EChatType ChatType = General.EChatType.ECT_NORMAL; // ECT_NORMAL = 1;正常聊天 // ECT_SYSTEM = 2;系统聊天 // ECT_READSTATE = 3;聊天消息已读状态设置 // ECT_PRODUCT = 4;产品消息 // ECT_GROUP = 5;群聊 private long Time;// 时间 private int MessageState = Constants.MESSAGE_STATE_LOADDING; // 是发送中,1是送达,2是已阅,3是发送失败,4是对方发过来接受成功的消息 private String savePath = null; // 图片或语音保存路径 private String url = null; // 图片或语音链接 private int displayType = Constants.MSG_DISPLAY_TYPE_NORMAL; // 消息显示类型 0气泡, 1系统浮框 ,2居中显示,3是系统打分图文混排 private int playTime = 0; // 语音播放时长 private boolean resend = false; private int action; // 发过来的消息协议编号 private String errDes;// 消息发送失败的原因 private List<Long> StateSmsKeyID; // 设置状态的消息唯一编号 private String sTime; private String systemHint; private int snapState;//0是瞬间图片未看 1是是瞬间图片看了 /** 上传状态 */ private int mUploadStatus = STATUS_NOT; /** 上传进度(数字) */ private int mProgress; /** 气泡索引(id)*/ private String bubble; //add by zjy //livechat public MessageEntity() { String msg = UUID.randomUUID().toString(); setMsgID(msg); } public long getUserID() { return UserID; } public void setUserID(long userID) { UserID = userID; } public long getFromID() { return FromID; } public void setFromID(long fromID) { FromID = fromID; } public long getSmsID() { return SmsID; } public void setSmsID(long smsID) { SmsID = smsID; } public String getText() { return Text; } public void setText(String text) { Text = text; } public long getTime() { return Time; } public void setTime(long time) { Time = time; sTime = DateUtils.getMsgItemTime(time); } public long getSmsKey() { return SmsKey; } public void setSmsKey(long smsKey) { SmsKey = smsKey; } public long getGroupID() { return GroupID; } public void setGroupID(long groupID) { GroupID = groupID; } public static long getSerialversionuid() { return serialVersionUID; } public General.ETextType getTextType() { return TextType; } public void setTextType(General.ETextType textType) { TextType = textType; } public General.EChatType getChatType() { return ChatType; } public void setChatType(General.EChatType chatType) { ChatType = chatType; } public long getToID() { return ToID; } public void setToID(long toID) { ToID = toID; } public int getMessageState() { return MessageState; } public void setMessageState(int messageState) { MessageState = messageState; } public long getSessionId() { return IsSend ? ToID : FromID; } public boolean isIsSend() { return IsSend; } public void setIsSend(boolean isSend) { IsSend = isSend; } public String getSavePath() { return savePath; } public void setSavePath(String savePath) { this.savePath = savePath; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public int getDisplayType() { return displayType; } public void setDisplayType(int displayType) { this.displayType = displayType; } public int getPlayTime() { return playTime; } public void setPlayTime(int playTime) { this.playTime = playTime; } public boolean isResend() { return resend; } public void setResend(boolean resend) { this.resend = resend; } public void setSessionId(long sessionId) { SessionId = sessionId; } public String getMsgID() { return MsgID; } public void setMsgID(String msgID) { MsgID = msgID; } public String getUUID() { String uuid = UUID.randomUUID().toString(); return uuid; } public int getAction() { return action; } public void setAction(int action) { this.action = action; } public String getErrDes() { return errDes; } public void setErrDes(String errDes) { this.errDes = errDes; } public List<Long> getStateSmsKeyID() { return StateSmsKeyID; } public void setStateSmsKeyID(List<Long> stateSmsKeyID) { StateSmsKeyID = stateSmsKeyID; } public String getThumbPath() { return thumbPath; } public void setThumbPath(String thumbPath) { this.thumbPath = thumbPath; } public String getThumbUrl() { return thumbUrl; } public void setThumbUrl(String thumbUrl) { this.thumbUrl = thumbUrl; } public String getImagePath() { return imagePath; } public void setImagePath(String imagePath) { this.imagePath = imagePath; } public String getImageUrl() { return imageUrl; } public void setImageUrl(String imageUrl) { this.imageUrl = imageUrl; } @Override public void update(Observable observable, Object data) { } public int getProgress() { return progress; } public void setProgress(int progress) { this.progress = progress; } public String getVoicePath() { return voicePath; } public void setVoicePath(String voicePath) { this.voicePath = voicePath; } public String getVoiceUrl() { return voiceUrl; } public void setVoiceUrl(String voiceUrl) { this.voiceUrl = voiceUrl; } public int getVoiceTime() { return voiceTime; } public void setVoiceTime(int voiceTime) { this.voiceTime = voiceTime; } public int getOldProgress() { return oldProgress; } public void setOldProgress(int oldProgress) { this.oldProgress = oldProgress; } public int getMediaDownloadStatus() { return mediaDownloadStatus; } public void setMediaDownloadStatus(int mediaDownloadStatus) { this.mediaDownloadStatus = mediaDownloadStatus; } public String getsTime() { return sTime; } public void setsTime(String sTime) { this.sTime = sTime; } public int getSnapState() { return snapState; } public void setSnapState(int snapState) { this.snapState = snapState; } public String getSystemHint() { return systemHint; } public void setSystemHint(String systemHint) { this.systemHint = systemHint; } public int getPhotoType() { return photoType; } public void setPhotoType(int photoType) { this.photoType = photoType; } public String getBubble() { return bubble; } public void setBubble(String bubble) { this.bubble = bubble; } public int getmUploadStatus() { return mUploadStatus; } public void setmUploadStatus(int mUploadStatus) { this.mUploadStatus = mUploadStatus; } public int getmProgress() { return mProgress; } public void setmProgress(int progress) { this.mProgress = progress; } private SparseArray<WeakReference<IUploadProgress>> callbacks = new SparseArray<>(); public synchronized void addProgressViews(IUploadProgress... progressViews) { for (IUploadProgress callback : progressViews) { if (callback instanceof View) { View view = (View) callback; Object obj = view.getTag(R.id.upload_id); if (obj != null && !TextUtils.isEmpty((CharSequence) obj)) { callbacks.put(callback.hashCode(), new WeakReference<IUploadProgress>(callback)); } else { throw new RuntimeException("the callback must setTag and use R.id.upload_id as the key"); } } else { throw new RuntimeException("the callback isn't the instance of View!"); } } } public void notifyProgress() { notifyProgress(null); } public synchronized void notifyProgress(Activity activity) { int size; if (callbacks != null && (size = callbacks.size()) > 0) { for (int i = 0; i < size; i++) { final IUploadProgress callback = callbacks.valueAt(i).get(); if (callback == null) { callbacks.removeAt(i); i--; size--; } else { if (callback instanceof View) { final View v = (View) callback; final Object u = v.getTag(R.id.upload_id); if (u != null) { if (u.equals(MsgID)) { Runnable run = new Runnable() { @Override public void run() { if (u.equals(v.getTag(R.id.upload_id))) { callback.showStatus(MessageEntity.this); callback.showProgress(mProgress); } } }; if (activity == null) { v.post(run); } else { activity.runOnUiThread(run); } } else { callbacks.removeAt(i); i--; size--; } } else { callbacks.removeAt(i); i--; size--; } } else { callbacks.removeAt(i); i--; size--; } } } } } }
package spi.movieorganizer.repository; import spi.movieorganizer.controller.tmdb.ITMDBController; import spi.movieorganizer.controller.tmdb.TMDBController; import spi.movieorganizer.controller.usermovie.IUserMovieController; import spi.movieorganizer.controller.usermovie.UserMovieController; import spi.movieorganizer.display.MovieOrganizerClient; import spi.movieorganizer.display.MovieOrganizerClient.ActionExecutor; public class MovieOrganizerControllerRepository { private final ITMDBController tmdbController; private final IUserMovieController userMovieController; public MovieOrganizerControllerRepository(final MovieOrganizerClient session) { this.tmdbController = new TMDBController(session, new ActionExecutor()); this.userMovieController = new UserMovieController(session, new ActionExecutor()); } public ITMDBController getTmdbController() { return this.tmdbController; } public IUserMovieController getUserMovieController() { return this.userMovieController; } }
package org.browsexml.timesheetjob.dao.hibernate; import java.util.List; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.browsexml.timesheetjob.dao.FulltimeAgreementDao; import org.browsexml.timesheetjob.model.FulltimeAgreements; import org.hibernate.HibernateException; import org.hibernate.Query; import org.hibernate.Session; import org.springframework.dao.DataIntegrityViolationException; import org.springframework.orm.hibernate3.HibernateTemplate; import org.springframework.orm.hibernate3.support.HibernateDaoSupport; public class FulltimeAgreementDaoHibernate extends HibernateDaoSupport implements FulltimeAgreementDao { private static Log log = LogFactory.getLog(FulltimeAgreementDaoHibernate.class); public void removeFulltimeAgreement(Integer id) throws DataIntegrityViolationException { FulltimeAgreements job = getHibernateTemplate().load(FulltimeAgreements.class, id); long count = getHoursWorkedCount(job.getPeople().getPeopleId(), job.getJob().getDepartment()); if (count == 0) { log.debug("delete"); getHibernateTemplate().delete(job); } else { log.debug("THROW"); throw new DataIntegrityViolationException("The person has already punched in to this job"); } } @Override public Long getHoursWorkedCount(String peopleId, String department) { log.debug("getHoursWorkedCount " + peopleId + " " + department); String strQuery = "select count(*) " + "from HoursWorked " + "where peopleId = :people and job.department = :department "; HibernateTemplate ht = getHibernateTemplate(); Session s = ht.getSessionFactory().getCurrentSession(); Query sqlQuery = s.createQuery(strQuery); log.debug("HERE"); sqlQuery.setParameter("people", peopleId); log.debug("HERE1"); sqlQuery.setParameter("department", "" + department); log.debug("HERE2"); Long ret = null; try { ret = (Long) sqlQuery.uniqueResult(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } log.debug("HERE 3 -- count = " + ret); return ret; } public void saveFulltimeAgreement(FulltimeAgreements agreement) { Session s = getHibernateTemplate().getSessionFactory().getCurrentSession(); log.debug("Fulltime save or update "); s.saveOrUpdate(agreement); log.debug("Fulltime save or update DONE "); } public FulltimeAgreements getFulltimeAgreement(Integer id) { return (FulltimeAgreements) getHibernateTemplate().get(FulltimeAgreements.class, id); } public List<FulltimeAgreements> getFulltimeAgreements(Integer people) { String strQuery = "from FulltimeAgreements a " + "where a.people.id = :people"; List<FulltimeAgreements> ret = null; HibernateTemplate ht = getHibernateTemplate(); Session s = ht.getSessionFactory().getCurrentSession(); Query sqlQuery = s.createQuery(strQuery).setParameter("people", people); ret = (List<FulltimeAgreements>) sqlQuery.list(); return ret; } }
package capitulo08; public class DateAndTimeTest { public static void main(String[] args) { DateAndTime Time1 = new DateAndTime (0,0,0,1,1,1); DateAndTime Time2 = new DateAndTime (11,30,0,26,05,1998); DateAndTime Time3 = new DateAndTime (18,57,0,21,12,2020); DateAndTime Time4 = new DateAndTime (23,59,59,1,12,2000); DateAndTime Time5 = new DateAndTime (23,59,59,31,12,2020); displayTime("Data 1:", Time1); Time1.Tick(); displayTime("Data 1 depois do primeiro Tick:", Time1); displayTime("Data 2:", Time2); Time2.Tick(); displayTime("Data 2 depois do primeiro Tick:", Time2); displayTime("Data 3:", Time3); Time3.Tick(); displayTime("Data 3 depois do primeiro Tick:", Time3); displayTime("Data 4:", Time4); Time4.Tick(); displayTime("Data 4 depois do primeiro Tick:", Time4); displayTime("Data 5:", Time5); Time5.Tick(); displayTime("Data 5 depois do primeiro Tick:", Time5); } private static void displayTime(String header, DateAndTime t) { System.out.printf("%s%n%s%n", header, t.toUniversalString()); } }
End of preview. Expand in Data Studio
README.md exists but content is empty.
Downloads last month
4