text
stringlengths
10
2.72M
package com.company; public class User { private char[] message; private int[] messageNumber; private int[] cipher; private int publicKeyD; private int publicKeyN; boolean sendKey = false; boolean cipherInstalled = false; public void setMessageText(String text){ message = text.toCharArray(); messageNumber = new int[message.length]; cipher = new int [message.length]; for (int element = 0; element < message.length; element++){ messageNumber[element] = getNumber(message[element]); } } public String getMessageText(){ String messageText = String.valueOf(message); return messageText; } public String getMessageNumber(){ String messageNumberText = " "; for(int element = 0; element < messageNumber.length; element++){ messageNumberText += String.valueOf(messageNumber[element]); } return messageNumberText; } public String getCipherNumber(){ String cipherNumberText = " "; for(int element = 0; element < cipher.length; element++){ cipherNumberText += String.valueOf(cipher[element]); } return cipherNumberText; } public void setCipher(){ for (int element = 0; element < messageNumber.length; element++) { int tmp = 1; for (int degree = 1; degree <= publicKeyD; degree++) { tmp = (tmp * messageNumber[element]) % publicKeyN; } cipher[element] = tmp; cipherInstalled = true; } } public int[] getCipher(){ return cipher; } public void setPublicKey(int d, int n){ publicKeyD = d; publicKeyN = n; sendKey = true; } public int getPublicKeyN(){ return publicKeyN; } public int getPublicKeyD(){ return publicKeyD; } public void clear(){ publicKeyD = 0; publicKeyN = 0; cipher = null; messageNumber = null; message = null; sendKey = false; cipherInstalled = false; } public static int getNumber(char symbol){ int number; switch (symbol){ case 'a': number = 10; break; case 'b': number = 11; break; case 'c': number = 12; break; case 'd': number = 13; break; case 'e': number = 14; break; case 'f': number = 15; break; case 'g': number = 16; break; case 'h': number = 17; break; case 'i': number = 18; break; case 'j': number = 19; break; case 'k': number = 20; break; case 'l': number = 21; break; case 'm': number = 22; break; case 'n': number = 23; break; case 'o': number = 24; break; case 'p': number = 25; break; case 'q': number = 26; break; case 'r': number = 27; break; case 's': number = 28; break; case 't': number = 29; break; case 'u': number = 30; break; case 'v': number = 31; break; case 'w': number = 32; break; case 'x': number = 33; break; case 'y': number = 34; break; case 'z': number = 35; break; case 'A': number = 36; break; case 'B': number = 37; break; case 'C': number = 38; break; case 'D': number = 39; break; case 'E': number = 40; break; case 'F': number = 41; break; case 'G': number = 42; break; case 'H': number = 43; break; case 'I': number = 44; break; case 'J': number = 45; break; case 'K': number = 46; break; case 'L': number = 47; break; case 'M': number = 48; break; case 'N': number = 49; break; case 'O': number = 50; break; case 'P': number = 51; break; case 'Q': number = 52; break; case 'R': number = 53; break; case 'S': number = 54; break; case 'T': number = 55; break; case 'U': number = 56; break; case 'V': number = 57; break; case 'W': number = 58; break; case 'X': number = 59; break; case 'Y': number = 60; break; case 'Z': number = 61; break; case '.': number = 62; break; case ',': number = 63; break; case '?': number = 64; break; case '!': number = 65; break; case '/': number = 66; break; case '(': number = 67; break; case ')': number = 68; break; case ':': number = 69; break; case ';': number = 70; break; case ' ': number = 71; break; case '0': number = 72; break; case '1': number = 73; break; case '2': number = 74; break; case '3': number = 75; break; case '4': number = 76; break; case '5': number = 77; break; case '6': number = 78; break; case '7': number = 79; break; case '8': number = 80; break; case '9': number = 81; break; default: number = 0; break; } return number; } }
package MethodPractice; import java.util.Scanner; public class Prime { static String pri(int x) { int flag=0; for(int i=2;i<x;i++) { if(x%i==0) { flag=1; break; } } if(flag==1) return("not prime"); else return("prime"); } public static void main(String[] args) { int a; String r; Scanner S=new Scanner(System.in); System.out.println("Enter value"); a=S.nextInt(); r=pri(a); System.out.println(r); } }
package com.exemple.test.repository; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; import com.exemple.test.model.TestModel; @Repository("testRepository") public interface TestRepository extends JpaRepository<TestModel, Long> { }
public class Main { public static void main(String[] args) { AutoShutdownGUI gui = new AutoShutdownGUI(); } }
/* * 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.dthebus.gymweb.test.restapi; import com.dthebus.gymweb.domain.members.FullMember; import java.util.Collections; import org.junit.Assert; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; import org.springframework.web.client.RestTemplate; import static org.testng.Assert.*; import org.testng.annotations.AfterClass; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeClass; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; /** * * @author darren */ public class FullMemberControllerRestTest { private RestTemplate restTemplate = new RestTemplate(); private final static String URL = "http://localhost:8084/gymweb/"; @Test public void testCreate(){ FullMember m = new FullMember.Builder("Darren").build(); HttpEntity<FullMember> requestEntity = new HttpEntity<>(m, getContentType()); ResponseEntity<String> responseEntity = restTemplate. exchange(URL+"api/fullmember/create", HttpMethod.POST, requestEntity, String.class); Assert.assertEquals(responseEntity.getStatusCode(), HttpStatus.OK); } // @Test public void testgetAllFullMembers(){ HttpEntity<?> requestEntity = getHttpEntity(); ResponseEntity<FullMember[]> responseEntity = restTemplate.exchange(URL + "api/fullmember/allfullmembers", HttpMethod.GET, requestEntity, FullMember[].class); FullMember[] fullMembers = responseEntity.getBody(); for(FullMember f: fullMembers) System.out.println("The Member Name is " + f.getName()); org.testng.Assert.assertTrue(fullMembers.length != 0); } private HttpEntity<?> getHttpEntity() { HttpHeaders requestHeaders = new HttpHeaders(); requestHeaders.setAccept(Collections.singletonList(new MediaType("application", "json"))); HttpEntity<?> requestEntity = new HttpEntity<>(requestHeaders); restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter()); return requestEntity; } private HttpHeaders getContentType() { HttpHeaders requestHeaders = new HttpHeaders(); requestHeaders.setContentType(new MediaType("application", "json")); return requestHeaders; } }
package com.gsma.mobileconnect.r2.android.clientsidelibrary.filters; import android.text.InputFilter; import com.gsma.mobileconnect.r2.android.clientsidelibrary.constants.Constants; /* Contains methods to for validating input text and preventing errors. */ public class InputFilters { //Regular expression to validate the IP address private final static String IP_EXPRESSION = "^\\d{1,3}(\\.(\\d{1,3}(\\.(\\d{1,3}(\\.(\\d{1,3})?)?)?)?)?)?"; private final static String IP_SEPARATOR = "\\."; private final static int IP_MAX_VALUE = 255; /** * Contains regulations of IP address. * @return filter for IP address. */ public static InputFilter [] getIpFilter() { InputFilter[] inputFilter = new InputFilter[1]; inputFilter[0] = new InputFilter() { @Override public CharSequence filter(CharSequence source, int start, int end, android.text.Spanned dest, int dstart, int dend) { if (end > start) { String destTxt = dest.toString(); String resultingTxt = destTxt.substring(0, dstart) + source.subSequence(start, end) + destTxt.substring(dend); if (!resultingTxt .matches(IP_EXPRESSION)) { return Constants.EMPTY_STRING; } else { String[] splits = resultingTxt.split(IP_SEPARATOR); for (String split : splits) { if (Integer.valueOf(split) > IP_MAX_VALUE) { return Constants.EMPTY_STRING; } } } } return null; } }; return inputFilter; } }
/* * 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 pertemuan7; /** * * @author Angga */ public class StringBuilderChars { public static void main(String[] args) { StringBuilder buffer = new StringBuilder("Hello there"); System.out.printf("Buffer = %s\n",buffer.toString()); System.out.printf("Character at 0:%s\nCharacter at 4:%s\n\n", buffer.charAt(0), buffer.charAt(4)); char[] charArray= new char[buffer.length()]; buffer.getChars(0, buffer.length(), charArray, 0); System.out.print("The chracters are : "); for (char character:charArray) System.out.print(character); buffer.setCharAt(0, 'H'); buffer.setCharAt(6, 'T'); System.out.printf("\n\nbuffer = %s",buffer.toString()); buffer.reverse(); System.out.printf("\n\nbuffer = %s\n",buffer.toString()); } }
package com.java.dao; import com.java.domain.Permission; import org.apache.ibatis.annotations.Insert; import org.apache.ibatis.annotations.Select; import java.util.List; public interface IPermissionDao { /** * 角色拥有的权限 * @return * @throws Exception */ @Select("select * from permission where id in (SELECT permissionId FROM role_permission WHERE roleId = #{roleId})") List<Permission> findRoleByPermission(String roleId)throws Exception; @Select("select * from permission") List<Permission> findAll() throws Exception; @Insert("insert into permission values(#{id},#{PermissionName},#{url})") void savePermission(Permission permission) throws Exception; }
package four; /** * <li> if-else</li> * <li>if-then-else</li> * <li>switch</li> * <p> * switch-case-break * * <p>Petlje -> nizovima i sa kolekcijama</p> */ public class FourExecutor { public static void main(String[] args) { System.out.println("Hello"); } }
package com.syscxp.biz; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.autoconfigure.SpringBootApplication; //@SpringBootApplication(scanBasePackages = "com.syscxp.biz.core") @SpringBootApplication @EnableAutoConfiguration(exclude = { org.springframework.boot.autoconfigure.security.SecurityAutoConfiguration.class, org.activiti.spring.boot.SecurityAutoConfiguration.class }) public class BizApplication { public static void main(String[] args) { SpringApplication.run(BizApplication.class, args); } // 多数据源配置(不能自动配置流程) // @Bean // @Primary // @ConfigurationProperties(prefix = "spring.datasource.biz") // public DataSource primaryDataSource() { // return DataSourceBuilder // .create() // .url("jdbc:mysql://localhost:3306/biz?useUnicode=yes&characterEncoding=UTF-8&useSSL=false") // .username("root") // .password("123456") // .driverClassName("com.mysql.jdbc.Driver") // .build(); // } // @Bean // public CommandLineRunner init(final MyService myService) { // // return new CommandLineRunner() { // @Override // public void run(String... strings) throws Exception { // myService.createDemoUsers(); // } // }; // // } }
package com.rednovo.ace.widget.live; import android.content.Context; import android.content.res.Resources; import android.util.AttributeSet; import android.widget.FrameLayout; /** * 监听键盘的弹出和收回 * 当使用了透明电池栏后,此监听失效 */ public class MonitorSizeEventFrameLayout extends FrameLayout { private int mPreviousHeight; public MonitorSizeEventFrameLayout(Context context) { super(context); } /** * MonitorSizeEventFrameLayout * * @param context context * @param attrs attrs */ public MonitorSizeEventFrameLayout(Context context, AttributeSet attrs) { super(context, attrs); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { int measureHeight = MeasureSpec.getSize(heightMeasureSpec); if (mPreviousHeight != 0) { int navigationBarHeight = getNavigationBarHeight(); if (measureHeight < mPreviousHeight - navigationBarHeight) { // 减去底部虚拟键盘高度,过滤掉虚拟键盘显隐产生的页面高度变化 // EventBus.getDefault().post(new KeyBoardEvent(true)); } else if (measureHeight - navigationBarHeight > mPreviousHeight) { // EventBus.getDefault().post(new KeyBoardEvent(false)); } } mPreviousHeight = measureHeight; super.onMeasure(widthMeasureSpec, heightMeasureSpec); } /** * 获取底部虚拟键Navigation Bar的高度 * @return */ private int getNavigationBarHeight() { Resources resources = getResources(); int resourceId = resources.getIdentifier("navigation_bar_height","dimen", "android"); int height = resources.getDimensionPixelSize(resourceId); return height; } }
package model.dao; import java.util.LinkedList; import java.util.List; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import model.DetailBean; import model.MinorCategoryBean; import model.PrimaryCategoryBean; import model.Interface.IDAO; import model.misc.HibernateUtil; public class PrimaryCategoryBeanDAOHibernate implements IDAO<PrimaryCategoryBean> { public static Session session; public static SessionFactory factory; public static Transaction trx; public static void main(String[] args) { test(); } private static void test() { Insert( ); Select( ); Update( ); Delete( ); } private static void Insert() { factory = HibernateUtil.getSessionFactory(); session = factory.getCurrentSession(); PrimaryCategoryBeanDAOHibernate dao = new PrimaryCategoryBeanDAOHibernate(factory); // Insert try { trx = dao.getSession().beginTransaction(); String prodName = "redLine",category = "男裝2"; PrimaryCategoryBean bean = new PrimaryCategoryBean(prodName,category); bean.setId(0); PrimaryCategoryBean insert = dao.insert(bean); System.out.println("insert" + insert); trx.commit(); } catch (Exception e) { System.out.println("insert" + e.toString()); trx.rollback(); } } private static void Select() { factory = HibernateUtil.getSessionFactory(); session = factory.getCurrentSession(); PrimaryCategoryBeanDAOHibernate dao = new PrimaryCategoryBeanDAOHibernate(factory); // Select try { session = factory.getCurrentSession(); trx = session.beginTransaction(); List<PrimaryCategoryBean> select = dao.select(); System.out.println("select" + select); trx.commit(); } catch (Exception e) { trx.rollback(); } } private static void Update() { factory = HibernateUtil.getSessionFactory(); session = factory.getCurrentSession(); PrimaryCategoryBeanDAOHibernate dao = new PrimaryCategoryBeanDAOHibernate(factory); // Update try { session = factory.getCurrentSession(); trx = dao.getSession().beginTransaction(); String category = "男裝",prodName = "redLine"; PrimaryCategoryBean bean = new PrimaryCategoryBean(prodName,category); bean.setId(1); PrimaryCategoryBean update = dao.update(bean); System.out.println("update" + update); trx.commit(); } catch (Exception e) { trx.rollback(); } } private static void Delete() { factory = HibernateUtil.getSessionFactory(); session = factory.getCurrentSession(); PrimaryCategoryBeanDAOHibernate dao = new PrimaryCategoryBeanDAOHibernate(factory); // delete try { session = factory.getCurrentSession(); trx = dao.getSession().beginTransaction(); Boolean delete = dao.delete(1); System.out.println("delete" + delete); trx.commit(); } catch (Exception e) { trx.rollback(); } } public PrimaryCategoryBeanDAOHibernate(SessionFactory factory) { this.factory = factory; } @Override public Session getSession() { return factory.getCurrentSession(); } @Override public List<PrimaryCategoryBean> select() { List<MinorCategoryBean> list = new LinkedList<MinorCategoryBean>(); return this.getSession().createQuery("from PrimaryCategoryBean", PrimaryCategoryBean.class).getResultList(); } @Override public Boolean delete(int id) { PrimaryCategoryBean temp = select(id); if (temp != null) { this.getSession().delete(temp); return true; } else { return false; } } @Override public Boolean delete(PrimaryCategoryBean bean) { PrimaryCategoryBean temp = select(bean); if (temp != null) { this.getSession().delete(bean); return true; } else { return false; } } @Override public PrimaryCategoryBean select(PrimaryCategoryBean bean) { if (bean != null) { bean = this.getSession().get(PrimaryCategoryBean.class, bean.getId()); } return bean; } @Override public PrimaryCategoryBean select(int id) { return this.getSession().get(PrimaryCategoryBean.class, id); } public List<PrimaryCategoryBean> selectCategoryByProd (String prod) { return this.getSession() .createQuery("from PrimaryCategoryBean where prod_name=:param", PrimaryCategoryBean.class) .setParameter("param", prod) .getResultList(); } @Override public PrimaryCategoryBean insert(PrimaryCategoryBean bean) { PrimaryCategoryBean temp = select(bean); if (temp == null) { this.getSession().save(bean); } return bean; } @Override public PrimaryCategoryBean update(PrimaryCategoryBean bean) { PrimaryCategoryBean temp = select(bean.getId()); if (temp != null) { temp.setProdName(bean.getProdName()); temp.setCategory(bean.getCategory()); } return temp; } }
package com.zantong.mobilecttx.common; import android.content.Context; import android.support.annotation.NonNull; import com.zantong.mobilecttx.model.repository.LocalData; import com.zantong.mobilecttx.model.repository.RemoteData; import com.zantong.mobilecttx.model.repository.RepositoryManager; /** * Created by jianghw on 2017/4/26. * 依赖注入类 */ public class Injection { /** * 初始化数据仓库 * * @param applicationContext * @return */ public static RepositoryManager provideRepository(@NonNull Context applicationContext) { return RepositoryManager.getInstance( RemoteData.getInstance(), LocalData.getInstance(applicationContext)); } }
package entity.mob; import java.awt.Graphics2D; import java.awt.Image; import main.Game; import main.Pictures; import main.World; import particle.Blood; import entity.mob.controllers.EnemyController; import entity.mob.snake.weapon.Weapon; public class Enemy extends Mob { private Weapon wep; public Weapon getWep() { return wep; } private double v = 0; private double angle = Math.PI; @Override public void finalInit(World world) { super.finalInit(world); control = new EnemyController(this); } @Override public void tick() { v++; super.tick(); slowly(); lvx = v*Math.cos(angle); lvy = v*Math.sin(angle); } @Override protected boolean collideIslands(boolean verticalWalls) { return false; } @Override protected void slowly() { v *= getSpeed()/(getSpeed()+1); } @Override public void damage(int damage, int knockback, double dir) { if(damage == 0) return; hp -= Math.max(damage - getStrength(), 0); for(int q=0;q<2;q++) { new Blood(getCX(), getCY(), world); } } @Override public void onDeath() { super.onDeath(); quantity--; } public static int quantity = 0; @Override public void feed() { super.feed(); if(quantity<100) { quantity+=5; new Enemy().init(x, y, world); new Enemy().init(x, y, world); new Enemy().init(x, y, world); new Enemy().init(x, y, world); new Enemy().init(x, y, world); } } private Image img; @Override protected void initPictures() { img = Pictures.monster; } @Override public void draw(Graphics2D g) { int drawx = (int) (getCX()-Game.x); int drawy = (int) (getCY()-Game.y); g.rotate(angle+Math.PI/2, drawx, drawy); g.drawImage(img, drawx-img.getWidth(null)/2, drawy-3*img.getHeight(null)/4, null); g.rotate(-angle-Math.PI/2, drawx, drawy); // drawBounds(g); drawHealth(g); } @Override public double getSpeed() { return 16; } @Override public int getMaxHP() { return 400; } @Override public int getDamage() { return 10; } @Override public int getKnokback() { return 0; } @Override public double getStrength() { return 0; } public double getAngle() { return angle; } public void setNewWeapon(Weapon wep) { this.wep = wep.init(getCX(), getCY(), 0, 0, 0, 0, world, this); } public void setAngle(double angle) { this.angle = angle; } }
package com.show.comm.mybatis; /** * SQL打印服务工厂 * * @author heyuhua * @date 2017年6月7日 * */ public class SQLPrinterRegister { /** SQL打印服务 */ private static SQLPrinter printer = null; /** 获取SQL打印服务 */ public static SQLPrinter get() { return printer; } /** * 注册SQL打印服务 * * @param printer * SQL打印服务 */ public static void register(SQLPrinter printer) { SQLPrinterRegister.printer = printer; } /** * 注册缺省SQL打印服务 * * @param showSql * 是否打印SQL */ public static void register(boolean showSql) { SQLPrinterRegister.printer = new SQLPrinterDefaultImpl(showSql); } }
package com.vishaldwivedi.intelliJournal.Models; import java.util.Date; /** * Created by Vishal Dwivedi on 11/04/17. * This interface will act as a base for the journal types we will support in the system */ public interface JournalBase { public Date getDate(); public String getTitle(); public String getMood(); public boolean isLoved(); }
package io.magicthegathering.javasdk.filter; import io.magicthegathering.javasdk.filter.domain.Layout; /** * <p> * This {@link LayoutFilter filter} filters the request by * {@link Layout layout-types}. * </p> * * @author Timon Link - timon.link@gmail.com */ public class LayoutFilter extends AbstractListOrFilter { private static final String PARAMETER_NAME = "layout"; /** * Creates a new instance of {@link LayoutFilter}. * * @param filter The {@link Filter filter} to assign to <code>this</code> {@link Filter filter}. * @param layout The {@link Layout} to filter by. */ LayoutFilter(Filter filter, Layout layout) { super(filter); addValue(layout.getType()); } @Override protected String parameterName() { return PARAMETER_NAME; } /** * Chains together {@link Layout layoutTypes} by a logical <em>or</em>. * * @param layout The {@link Layout layout}. * * @return The {@link LayoutFilter} instance. */ public LayoutFilter or(Layout layout) { super.or(layout.getType()); return this; } }
package com.cheese.radio.ui.user.calendar; import android.text.TextUtils; import com.cheese.radio.inject.api.ContentParams; import java.util.Calendar; /** * Created by 29283 on 2018/3/31. */ public class ClassCalendarParams extends ContentParams { // 参数名 参数含义 是否必填 生成规则 样例 // method 方法名 是 固定 getClassCalendar // token 用户令牌 是 用户登录或注册后获取 // yearMonth 年月 是 yyyy-MM 2018-04 // age 年龄段 否 第一次需要用户选择 4-5,6-7 private String yearMonth; private String age; private Calendar now = Calendar.getInstance(); private Integer courseTypeId; private transient int year,month; public ClassCalendarParams(String method, String yearMonth) { super(method); this.yearMonth = yearMonth; } public ClassCalendarParams(String method) { super(method); } public String getYearMonth() { if (TextUtils.isEmpty(yearMonth)) { return String.valueOf(now.get(Calendar.YEAR)) + "-" + (now.get(Calendar.MONTH) + 1); } return yearMonth; } public ClassCalendarParams setYearMonth(int year, int month) { if (month > 12) { month -= 12; year += 1; } else if (month < 1) { month += 12; year -= 1; } this.year=year; this.month=month; yearMonth = String.valueOf(now.get(Calendar.YEAR)) + "-" + month; return this; } public String getAge() { return age; } public void setAge(String age) { this.age = age; } public int getCourseTypeId() { return courseTypeId; } public void setCourseTypeId(int courseTypeId) { this.courseTypeId = courseTypeId; } public int getYear() { return year; } public int getMonth() { return month; } }
package com.proyecto.server.mapper; import java.util.Calendar; import com.proyecto.dom.AbstractEntity; import com.proyecto.dom.User; import com.proyecto.dto.UsuarioAplicacionDTO; public final class MapperToEntity { public static User adapt(final UsuarioAplicacionDTO userAplicacion) { final User user = new User(); if (userAplicacion.getIdUsuarioAplicacion() != null) { user.setUserId(userAplicacion.getIdUsuarioAplicacion()); } user.setBirthDate(userAplicacion.getBirthday().getTime()); user.setDeleted(userAplicacion.isDeleted()); user.setEmail(userAplicacion.getEmail()); if (userAplicacion.getImagen() != null) { user.setImagen(userAplicacion.getImagen()); } user.setName(userAplicacion.getNombre()); user.setNickname(userAplicacion.getNickName()); user.setPassword(userAplicacion.getPassword()); user.setSexo(userAplicacion.getSexo()); user.setSurname1(userAplicacion.getApellido1()); user.setSurname2(userAplicacion.getApellido2()); user.setSurname3(userAplicacion.getApellido3()); user.setVersion(0); user.setInsertDate(Calendar.getInstance().getTime()); user.setPerfil(userAplicacion.getPefil()); adaptBase(user); return user; } public static <T extends AbstractEntity> void adaptBase(final T entity) { if (entity.getInsertDate() == null) { entity.setInsertDate(Calendar.getInstance().getTime()); } else { entity.setUpdateDate(Calendar.getInstance().getTime()); } entity.setVersion(0); } }
package slimeknights.tconstruct.library.materials; import com.google.common.collect.Lists; import net.minecraft.util.text.TextFormatting; import java.util.List; import slimeknights.tconstruct.library.Util; import slimeknights.tconstruct.library.client.CustomFontColor; import slimeknights.tconstruct.library.utils.HarvestLevels; public class HeadMaterialStats extends AbstractMaterialStats { @Deprecated public final static String TYPE = MaterialTypes.HEAD; public final static String LOC_Durability = "stat.head.durability.name"; public final static String LOC_MiningSpeed = "stat.head.miningspeed.name"; public final static String LOC_Attack = "stat.head.attack.name"; public final static String LOC_HarvestLevel = "stat.head.harvestlevel.name"; public final static String LOC_DurabilityDesc = "stat.head.durability.desc"; public final static String LOC_MiningSpeedDesc = "stat.head.miningspeed.desc"; public final static String LOC_AttackDesc = "stat.head.attack.desc"; public final static String LOC_HarvestLevelDesc = "stat.head.harvestlevel.desc"; public final static String COLOR_Durability = CustomFontColor.valueToColorCode(1f); public final static String COLOR_Attack = CustomFontColor.encodeColor(215, 100, 100); public final static String COLOR_Speed = CustomFontColor.encodeColor(120, 160, 205); public final int durability; // usually between 1 and 1000 public final int harvestLevel; // see HarvestLevels class public final float attack; // usually between 0 and 10 (in 1/2 hearts, so divide by 2 for damage in hearts) public final float miningspeed; // usually between 1 and 10 public HeadMaterialStats(int durability, float miningspeed, float attack, int harvestLevel) { super(MaterialTypes.HEAD); this.durability = durability; this.miningspeed = miningspeed; this.attack = attack; this.harvestLevel = harvestLevel; } @Override public List<String> getLocalizedInfo() { List<String> info = Lists.newArrayList(); info.add(formatDurability(durability)); info.add(formatHarvestLevel(harvestLevel)); info.add(formatMiningSpeed(miningspeed)); info.add(formatAttack(attack)); return info; } public static String formatDurability(int durability) { return formatNumber(LOC_Durability, COLOR_Durability, durability); } public static String formatDurability(int durability, int ref) { return String.format("%s: %s", Util.translate(LOC_Durability), CustomFontColor.formatPartialAmount(durability, ref)) + TextFormatting.RESET; } public static String formatHarvestLevel(int level) { return String.format("%s: %s", Util.translate(LOC_HarvestLevel), HarvestLevels.getHarvestLevelName(level)) + TextFormatting.RESET; } public static String formatMiningSpeed(float speed) { return formatNumber(LOC_MiningSpeed, COLOR_Speed, speed); } public static String formatAttack(float attack) { return formatNumber(LOC_Attack, COLOR_Attack, attack); } @Override public List<String> getLocalizedDesc() { List<String> info = Lists.newArrayList(); info.add(Util.translate(LOC_DurabilityDesc)); info.add(Util.translate(LOC_HarvestLevelDesc)); info.add(Util.translate(LOC_MiningSpeedDesc)); info.add(Util.translate(LOC_AttackDesc)); return info; } }
package gamePackage; import gamePackage.playerClass; import gamePackage.playerHumanClass; import gamePackage.playerMachineClass; public class playerGroupSingleton { private static final playerGroupSingleton instance = new playerGroupSingleton(); public playerClass[] player = new playerClass[2]; public playerGroupSingleton() { } public static final playerGroupSingleton getInstance() { return instance; } public void set(int kindGame) { if(kindGame > 0) { player[1] = new playerMachineClass(); if(kindGame > 1) { player[0] = new playerMachineClass(); } else { player[0] = new playerHumanClass(); } } else { player[0] = new playerHumanClass(); player[1] = new playerHumanClass(); } } }
package com.lenovohit.hcp.pharmacy.manager.impl; import java.math.BigDecimal; import java.util.ArrayList; import java.util.Date; import java.util.List; import javax.transaction.Transactional; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.lenovohit.core.manager.GenericManager; import com.lenovohit.core.utils.StringUtils; import com.lenovohit.hcp.base.model.HcpUser; import com.lenovohit.hcp.pharmacy.manager.PhaAdjustManager; import com.lenovohit.hcp.pharmacy.model.PhaAdjust; import com.lenovohit.hcp.pharmacy.model.PhaDrugInfo; import com.lenovohit.hcp.pharmacy.model.PhaStoreInfo; import com.lenovohit.hcp.pharmacy.model.PhaStoreSumInfo; @Service @Transactional public class PhaAdjustManagerImpl implements PhaAdjustManager { @Autowired private GenericManager<PhaAdjust, String> phaAdjustManager; @Autowired private GenericManager<PhaDrugInfo, String> phaDrugInfoManager; @Autowired private GenericManager<PhaStoreInfo, String> phaStoreInfoManager; @Autowired private GenericManager<PhaStoreSumInfo, String> phaStoreSumInfoManager; @Override public void create(List<PhaAdjust> adjustList, List<PhaDrugInfo> drugList, HcpUser user) { List<PhaAdjust> adjusUpdate = new ArrayList<PhaAdjust>(); List<PhaDrugInfo> drugListUpdate = new ArrayList<PhaDrugInfo>(); if(adjustList!=null && adjustList.size()>0){ Date now = new Date(); String userName = user.getName(); String userId = user.getUserId(); for (int i=0;i<adjustList.size();i++){ PhaAdjust model = adjustList.get(i); PhaDrugInfo drugInfo = drugList.get(i); model.setAdjustState("2"); //已执行状态 model.setStoreId("0"); //库存id暂时没有任何意义 model.setStartSale(drugInfo.getSalePrice());//原售价 model.setStartBuy(drugInfo.getBuyPrice()); //原进价 model.setSpecs(drugInfo.getDrugSpecs()); //药品规格 if(model!=null && StringUtils.isNotBlank(model.getEndSale())){ //更新库存信息表 updataStoreInfo(model.getDrugCode(),model.getEndSale()); //更新库存汇总表 BigDecimal sum = updataStoreSum(model.getDrugCode(),model.getEndSale()); if(sum!=null && StringUtils.isNotEmpty(sum)){//调价时库存数量 model.setChargeSum(sum); } if(model.getEndSale()!=null&&model.getStartSale().compareTo(model.getEndSale())==1){//起始价大于调整后的价格 model.setProfitFlag(-1); } drugInfo.setSalePrice(model.getEndSale()); //调整后价格 drugInfo.setUpdateOper(userName); drugInfo.setUpdateOperId(userId); drugInfo.setUpdateTime(now); //条件单相关值处理 model.setId(null);//其中保存的值为药品基本信息id //更新时间和人员信息保存 model.setCreateOper(userName); model.setCreateOperId(userId); model.setCreateTime(now); model.setUpdateOper(userName); model.setUpdateOperId(userId); model.setUpdateTime(now); adjusUpdate.add(model); drugListUpdate.add(drugInfo); } } } this.phaAdjustManager.batchSave(adjusUpdate); this.phaDrugInfoManager.batchSave(drugListUpdate); } /** * 功能描述:修改库存中药品价格 *@param drugCode *@param salePrice *@return *@author gw *@date 2017年4月18日 */ private void updataStoreInfo(String drugCode, BigDecimal salePrice) { if(StringUtils.isNotEmpty(salePrice)){//当调价为空时不更新库存中药品价格 StringBuilder jql = new StringBuilder(); List<Object> values = new ArrayList<Object>(); jql.append("from PhaStoreInfo store where store.drugCode = ? "); values.add(drugCode); //根据用品编码查询库存信息 List<PhaStoreInfo> storeInfoList = (List<PhaStoreInfo>) phaStoreInfoManager.find(jql.toString(), values.toArray()); if(storeInfoList!=null && storeInfoList.size()>0){ for(PhaStoreInfo storeInfo:storeInfoList){//循环修改库存表中相关数据 storeInfo.setSalePrice(salePrice); } phaStoreInfoManager.batchSave(storeInfoList); } } } /** * 功能描述:根据药品编码获取库存汇总相关信息并更新价格 *@param drugCode *@param salePrice *@return *@author gw *@date 2017年4月18日 */ private BigDecimal updataStoreSum(String drugCode, BigDecimal salePrice) { List<PhaStoreSumInfo> storeSumInfoList = null; BigDecimal sum = new BigDecimal(0);//库存数量 if(StringUtils.isNotEmpty(salePrice)){//调价为空时不更新药品价格 StringBuilder jql = new StringBuilder(); List<Object> values = new ArrayList<Object>(); jql.append("from PhaStoreSumInfo where drugCode = ? "); values.add(drugCode); storeSumInfoList = phaStoreSumInfoManager.find(jql.toString(), values.toArray()); if (storeSumInfoList!=null){ for(PhaStoreSumInfo info :storeSumInfoList){ sum = sum.add(info.getStoreSum()); info.setSalePrice(salePrice); } phaStoreSumInfoManager.batchSave(storeSumInfoList); } } return sum; } }
package by.training.epam.lab8; import by.training.epam.lab8.entity.impl.Dish; import by.training.epam.lab8.parser.IParser; import by.training.epam.lab8.parser.exception.ParseException; import by.training.epam.lab8.parser.impl.DomParser; import by.training.epam.lab8.parser.impl.StaxParser; import by.training.epam.lab8.parser.impl.sax.SaxParser; import org.xml.sax.SAXException; import javax.xml.transform.stream.StreamSource; import javax.xml.validation.Schema; import javax.xml.validation.SchemaFactory; import javax.xml.validation.Validator; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Scanner; public class Main { private final static String XML_FILE_PATH = "menu.xml"; private final static String XSD_FILE_PATH = "menu-schema.xsd"; public static void main(String[] args) throws IOException, ParseException { Scanner scanner = new Scanner(System.in); Map<String, IParser> parserMap = getParserMap(); try { System.out.printf("Enter the xml file path [default: %s]: ", XML_FILE_PATH); String filePath = scanner.nextLine().trim(); if (filePath.isEmpty()){ filePath = Main.class.getClassLoader().getResource(XML_FILE_PATH).getPath(); } File xmlFile = new File(filePath); if(!xmlFile.exists()) { throw new FileNotFoundException("file not found"); } System.out.print("Select the parser (DOM, SAX, STAX): "); IParser parser = parserMap.get(scanner.nextLine().trim().toUpperCase()); if (parser == null){ throw new ClassNotFoundException("Incorrect parser name"); } if(!isValidateXml(xmlFile)){ throw new IllegalArgumentException("Incorrect xml file structure"); } List<Dish> result = parser.parse(filePath); System.out.println(result.size() == 0 ? "Result: nothing" : "\n"); result.forEach(dish -> System.out.println(dish)); } catch (FileNotFoundException | ClassNotFoundException |IllegalArgumentException ex){ System.out.printf("Error: %s", ex.getMessage()); } } private static Map<String, IParser> getParserMap(){ Map<String, IParser> parserMap = new HashMap<>(); parserMap.put("DOM", new DomParser()); parserMap.put("SAX", new SaxParser()); parserMap.put("STAX", new StaxParser()); return parserMap; } private static boolean isValidateXml(File file) throws IOException { boolean result = true; SchemaFactory factory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema"); try { Schema schema = factory.newSchema(Main.class.getClassLoader().getResource(XSD_FILE_PATH)); Validator validator = schema.newValidator(); validator.validate(new StreamSource(file)); } catch (SAXException ex){ result = false; } return result; } }
package ua.com.rd.pizzaservice.repository.customer; import ua.com.rd.pizzaservice.domain.customer.Customer; import java.util.Set; public interface CustomerRepository { Customer saveCustomer(Customer customer); Customer getCustomerById(Long id); void updateCustomer(Customer customer); Customer deleteCustomer(Customer customer); /*Set<Order> getCustomersOrders(Customer customer);*/ Set<Customer> findAll(); }
package com.yea.core.loadbalancer; import java.net.SocketAddress; import java.util.Collection; import java.util.List; public interface ILoadBalancer { public void addNode(BalancingNode newNode); /** * Initial list of servers. * This API also serves to add additional ones at a later time * The same logical server (host:port) could essentially be added multiple times * (helpful in cases where you want to give more "weightage" perhaps ..) * * @param newServers new servers to add */ public void addNodes(Collection<BalancingNode> newNodes); /** * Choose a server from load balancer. * * @param key An object that the load balancer may use to determine which server to return. null if * the load balancer does not use this parameter. * @return server chosen */ public BalancingNode chooseNode(Object key); public Collection<BalancingNode> chooseNode(SocketAddress address) ; public Collection<BalancingNode> chooseNode(SocketAddress address, boolean availableOnly) ; public boolean contains(SocketAddress address) ; /** * To be called by the clients of the load balancer to notify that a Server is down * else, the LB will think its still Alive until the next Ping cycle - potentially * (assuming that the LB Impl does a ping) * * @param server Server to mark as down */ public void markNodeDown(BalancingNode node); /** * 修改了markNodeDown方法内容,只做标记 * 增加confirmNodeDown方法,节点真实下线 * @param node */ public void confirmNodeDown(BalancingNode node); /** * @deprecated 2016-01-20 This method is deprecated in favor of the * cleaner {@link #getReachableServers} (equivalent to availableOnly=true) * and {@link #getAllServers} API (equivalent to availableOnly=false). * * Get the current list of servers. * * @param availableOnly if true, only live and available servers should be returned */ @Deprecated public List<BalancingNode> getNodeList(boolean availableOnly); /** * @return Only the servers that are up and reachable. */ public List<BalancingNode> getReachableNodes(); /** * @return All known servers, both reachable and unreachable. */ public List<BalancingNode> getAllNodes(); }
//package com.turios.activities.fragments.task; // //import java.util.ArrayList; //import java.util.List; // //import android.app.Activity; //import android.content.DialogInterface; //import android.os.AsyncTask; //import android.os.Bundle; //import android.view.LayoutInflater; //import android.view.View; //import android.view.ViewGroup; //import android.widget.ProgressBar; // //import com.actionbarsherlock.app.SherlockDialogFragment; //import com.androidmapsextensions.GoogleMap; //import com.androidmapsextensions.MarkerOptions; //import com.turios.R; // ///** // * This Fragment manages a single background task and retains itself across // * configuration changes. // */ //public class LoadHydrantsToMapTaskFragment extends SherlockDialogFragment { // // public static final String TAG = LoadHydrantsToMapTaskFragment.class // .getSimpleName(); // // public interface LoadHydrantsToMapTaskCallback { // void onPreExecute(int maxProgress); // // void onProgressUpdate(int progress); // // void onCancelled(); // // void onPostExecute(); // } // // private LoadHydrantsToMapTask mTask; // private ProgressBar mProgressBar; // // private List<MarkerOptions> mHydrants; // // private GoogleMap map; // // public static LoadHydrantsToMapTaskFragment newInstance( // List<MarkerOptions> hydrants, GoogleMap map) { // LoadHydrantsToMapTaskFragment taskFragment = new LoadHydrantsToMapTaskFragment(); // taskFragment.mHydrants = hydrants; // taskFragment.map = map; // // return taskFragment; // } // // @Override public void onAttach(Activity activity) { // super.onAttach(activity); // // } // // @Override public View onCreateView(LayoutInflater inflater, // ViewGroup container, Bundle savedInstanceState) { // View view = inflater.inflate(R.layout.dialog_progress_task, container); // mProgressBar = (ProgressBar) view.findViewById(R.id.progress_downloading); // mProgressBar.setProgress(0); // mProgressBar.setMax(mHydrants.size()); // // getDialog().setTitle(getActivity().getString(R.string.adding_hydrants)); // // This dialog can't be canceled by pressing the back key. // getDialog().setCancelable(false); // getDialog().setCanceledOnTouchOutside(false); // // return view; // } // // /** // * This method will only be called once when the retained Fragment is first // * created. // */ // @Override public void onCreate(Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // setStyle(SherlockDialogFragment.STYLE_NORMAL, R.style.TuriosDialog); // // // Retain this fragment across configuration changes. // // setRetainInstance(true); // // mTask = new LoadHydrantsToMapTask(mHydrants); // mTask.setCallback(new LoadHydrantsToMapTaskCallback() { // // @Override public void onPreExecute(int maxProgress) { // } // // @Override public void onProgressUpdate(int progress) { // // mProgressBar.setProgress(progress); // } // // @Override public void onPostExecute() { // if (isResumed()) // dismiss(); // // mTask = null; // // } // // @Override public void onCancelled() { // if (isResumed()) // dismiss(); // // mTask = null; // } // }); // // mTask.execute(); // } // // @Override public void onResume() { // super.onResume(); // // // This is a little hacky, but we will see if the task has finished // // while we weren't // // in this activity, and then we can dismiss ourselves. // if (mTask == null) // dismiss(); // } // // @Override public void onDetach() { // super.onDetach(); // } // // // This is to work around what is apparently a bug. If you don't have it // // here the dialog will be dismissed on rotation, so tell it not to dismiss. // @Override public void onDestroyView() { // if (getDialog() != null && getRetainInstance()) // getDialog().setDismissMessage(null); // super.onDestroyView(); // } // // // Also when we are dismissed we need to cancel the task. // @Override public void onDismiss(DialogInterface dialog) { // super.onDismiss(dialog); // // If true, the thread is interrupted immediately, which may do bad // // things. // // If false, it guarantees a result is never returned (onPostExecute() // // isn't called) // // but you have to repeatedly call isCancelled() in your // // doInBackground() // // function to check if it should exit. For some tasks that might not be // // feasible. // if (mTask != null) // mTask.cancel(false); // // } // // private class LoadHydrantsToMapTask extends // AsyncTask<Void, Integer, List<MarkerOptions>> { // // Before running code in separate thread // List<MarkerOptions> mHydrants; // LoadHydrantsToMapTaskCallback mLoadHydrantsToMapTaskCallback; // // public LoadHydrantsToMapTask(List<MarkerOptions> hydrants) { // this.mHydrants = hydrants; // } // // public void setCallback( // LoadHydrantsToMapTaskCallback loadHydrantsToMapTaskCallback) { // this.mLoadHydrantsToMapTaskCallback = loadHydrantsToMapTaskCallback; // } // // @Override protected void onPreExecute() { // // if (mLoadHydrantsToMapTaskCallback != null) { // mLoadHydrantsToMapTaskCallback.onPreExecute(mHydrants.size()); // } // // } // // // The code to be executed in a background thread. // @Override protected List<MarkerOptions> doInBackground(Void... arg) { // List<MarkerOptions> markers = new ArrayList<MarkerOptions>(); // // for (MarkerOptions marker : mHydrants) { // // map.addMarker(marker); // // publishProgress(markers.size()); // } // return markers; // } // // // Update the progress // @Override protected void onProgressUpdate(Integer... values) { // if (mLoadHydrantsToMapTaskCallback != null) { // mLoadHydrantsToMapTaskCallback.onProgressUpdate(values[0]); // } // } // // @Override protected void onCancelled() { // if (mLoadHydrantsToMapTaskCallback != null) { // mLoadHydrantsToMapTaskCallback.onCancelled(); // } // } // // // after executing the code in the thread // @Override protected void onPostExecute(List<MarkerOptions> markers) { // // if (mLoadHydrantsToMapTaskCallback != null) { // mLoadHydrantsToMapTaskCallback.onPostExecute(); // } // // } // // } // // }
/* * Copyright (c) 2013 ICM Uniwersytet Warszawski All rights reserved. * See LICENCE file for licensing information. */ package pl.edu.icm.unity.server.api.registration; import org.springframework.stereotype.Component; /** * Definition of a template of a rejected registration request message. * @author P. Piernik */ @Component public class RejectRegistrationTemplateDef extends RegistrationWithCommentsTemplateDef { public static final String NAME = "RegistrationRequestRejected"; public RejectRegistrationTemplateDef() { super(NAME, "MessageTemplateConsumer.RejectForm.desc"); } }
package sr.hakrinbank.intranet.api.service.bean; import org.joda.time.DateTime; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.access.prepost.PostFilter; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; import sr.hakrinbank.intranet.api.model.NewsIct; import sr.hakrinbank.intranet.api.repository.NewsIctRepository; import sr.hakrinbank.intranet.api.service.NewsIctService; import sr.hakrinbank.intranet.api.util.Constant; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.LocalTime; import java.time.ZoneId; import java.time.format.DateTimeFormatter; import java.util.ArrayList; import java.util.Date; import java.util.List; /** * Created by clint on 5/29/17. */ @Service @Transactional(propagation = Propagation.SUPPORTS, readOnly = true) public class NewsIctServiceBean implements NewsIctService { @Autowired private NewsIctRepository newsIctRepository; @Override @PostFilter("filterObject.deleted() == false") public List<NewsIct> findAllNewsIct() { return newsIctRepository.findAll(); } @Override public NewsIct findById(long id) { return newsIctRepository.findOne(id); } @Override public void updateNewsIct(NewsIct newsIct) { if(newsIct.getDate() == null){ newsIct.setDate(new Date()); newsIctRepository.save(newsIct); }else{ newsIctRepository.save(newsIct); } } @Override public List<NewsIct> findAllActiveNewsIctOrderedByDate() { return newsIctRepository.findActiveNewsIctOrderedByDate(); } @Override public List<NewsIct> findAllActiveNewsIctBySearchQueryOrDate(String byTitle, String byDate) { if(byDate != null && !byDate.isEmpty() && byDate != "" && !byDate.contentEquals(Constant.UNDEFINED_VALUE) && !byDate.contentEquals(Constant.NULL_VALUE) && !byDate.contentEquals(Constant.INVALID_DATE)){ LocalDate localDate = LocalDate.parse(byDate, DateTimeFormatter.ofPattern(Constant.DATE_FIELD_FORMAT)); LocalDateTime todayStartOfDay = localDate.atStartOfDay(); Date startOfDay = Date.from(todayStartOfDay.atZone(ZoneId.systemDefault()).toInstant()); LocalDateTime todayEndOfDay = localDate.atTime(LocalTime.MAX); Date endOfDay = Date.from(todayEndOfDay.atZone(ZoneId.systemDefault()).toInstant()); if(byTitle != null && byTitle != "" && !byTitle.contentEquals(Constant.UNDEFINED_VALUE)){ return newsIctRepository.findAllActiveNewsIctBySearchQueryAndDate(byTitle, startOfDay, endOfDay); }else{ return newsIctRepository.findAllActiveNewsIctByDate(startOfDay, endOfDay); } }else { return newsIctRepository.findAllActiveNewsIctBySearchQuery(byTitle); } } @Override public int countNewsIctOfTheWeek() { List<NewsIct> newsIctList = newsIctRepository.findActiveNewsIct(); DateTime currentDate = new DateTime(); int weekOfCurrentDate = currentDate.getWeekOfWeekyear(); int yearOfCurrentDate = currentDate.getYear(); List<NewsIct> countList = new ArrayList<>(); for(NewsIct newsIct: newsIctList){ DateTime specificDate = new DateTime(newsIct.getDate()); int weekOfSpecificDate = specificDate.getWeekOfWeekyear(); int yearOfSpecificDate = specificDate.getYear(); if( (yearOfCurrentDate == yearOfSpecificDate) && (weekOfCurrentDate == weekOfSpecificDate) ){ countList.add(newsIct); } } return countList.size(); } @Override public List<NewsIct> findAllActiveNewsIct() { return newsIctRepository.findActiveNewsIct(); } @Override public NewsIct findByName(String name) { return newsIctRepository.findByName(name); } @Override public List<NewsIct> findAllActiveNewsIctBySearchQuery(String qry) { return newsIctRepository.findAllActiveNewsIctBySearchQuery(qry); } }
package com.qa.test; import org.testng.annotations.Test; import org.testng.AssertJUnit; import java.util.List; import java.util.Set; import org.openqa.selenium.Alert; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.interactions.Actions; import org.testng.Assert; import org.testng.annotations.Test; import com.qa.core.Base; public class HomePage extends Base { // OR String ExpectedHomePageTitle = "Online Shopping site in India: Shop Online for Mobiles, Books, Watches, Shoes and More - Amazon.in"; String newURL = "https://www.facebook.com"; // Verify that when user lands on HomePage , Page Title is displayed and it should be // "Online Shopping site in India: Shop Online for Mobiles, Books, Watches, Shoes and More - Amazon.in" public void verifyHomePageTitle() { browserSetup(); passSiteURL(); String ActualHomePageTitle = driver.getTitle(); AssertJUnit.assertEquals(ActualHomePageTitle, ExpectedHomePageTitle); browserClose(); } public void verifyHomePageBrowseElement() throws InterruptedException { browserSetup(); passSiteURL(); driver.navigate().to(newURL); driver.navigate().back(); Thread.sleep(5000); // driver.navigate().forward(); // driver.navigate().refresh(); browserClose(); } public void verifyHomePageHandleWindowPopUP() throws InterruptedException { browserSetup(); driver.get("https://html.com/input-type-file/"); driver.findElement(By.xpath("//input[@name='fileupload']")) .sendKeys("C:\\Users\\srini\\OneDrive\\Desktop\\HomeLoan\\Pictures"); Thread.sleep(8000); browserClose(); } public void verifyHomePageAlert() throws InterruptedException { browserSetup(); driver.get("https://mail.rediff.com/cgi-bin/login.cgi"); driver.findElement(By.xpath("//*[@class= 'signinbtn']")).click(); Alert alert = driver.switchTo().alert(); // get the Text on Alert System.out.println(alert.getText()); Thread.sleep(5000); alert.accept(); // Click on OK Thread.sleep(5000); System.out.println("Clicked on OK button"); // alert.dismiss(); //Click on Cancel // alert.sendKeys("Java"); //method is used to send Value browserClose(); } // Handle Menu public void verifyHomePageMenu() throws InterruptedException { browserSetup(); driver.get("https://www.timberland.co.uk"); driver.findElement(By.id("onetrust-accept-btn-handler")).click(); Thread.sleep(3000); driver.findElement(By.id("geo_popup_close")).click(); // Handle Menu Actions action = new Actions(driver); action.moveToElement(driver.findElement(By.xpath("//*[@data-navigation = 'men']"))).build().perform(); Thread.sleep(3000); // Click on Menu - Men- Shirts driver.findElement(By.linkText("Shirts")).click(); Thread.sleep(3000); browserClose(); } public void verifyHomePageFindElements() throws InterruptedException { browserSetup(); passSiteURL(); System.out.println("Test Execution Started!!!"); Thread.sleep(3000); List<WebElement> li = driver.findElements(By.tagName("a")); Thread.sleep(3000); int count = li.size(); System.out.println("Count of values on the page is " + count); for (int i = 0; i < count; i++) { System.out.println(li.get(i).getText()); } browserClose(); } public void verifyHomePageWindow() throws InterruptedException { browserSetup(); passSiteURL(); System.out.println("Test Execution Started!!!"); String parent = driver.getWindowHandle(); System.out.println("Parent window id is " + parent); driver.findElement(By.id("twotabsearchtextbox")).sendKeys("Java"); driver.findElement(By.id("nav-search-submit-button")).click(); driver.findElement(By.xpath("//*[@class = 'a-size-medium a-color-base a-text-normal']")).click(); Thread.sleep(3000); Set<String> totalwindow = driver.getWindowHandles(); int size = totalwindow.size(); for (String child : totalwindow) { if (!parent.equalsIgnoreCase(child)) { String secondwindow = child; driver.switchTo().window(secondwindow); driver.findElement(By.id("add-to-cart-button")).click(); driver.close(); } } Thread.sleep(3000); browserClose(); } }
package ManyToOne; import org.hibernate.Session; public class ManyToOne { public static void main(String[] args) { Session session = HibernateUtil.getSessionFactory().openSession(); session.beginTransaction(); College college = new College(); college.setName("NCCs"); session.save(college); Student student = new Student(); student.setName("raman"); student.setCollege(college); session.save(student); Student student1 = new Student(); student1.setCollege(college); student1.setName("rajiv"); session.save(student1); session.getTransaction().commit(); session.close(); Session session1 = HibernateUtil.getSessionFactory().openSession(); session1.beginTransaction(); Student student2=session1.get(Student.class,1L); System.out.println(student2); session1.getTransaction().commit(); session1.close(); HibernateUtil.shutdown(); } }
package com.aisino.invoice.xtjk.po; /** * @ClassName: FwkpZdhm * @Description: * @Copyright 2017 航天信息股份有限公司-版权所有 */ public class FwkpZdhm { private String zdmc; private Integer zdhm; private String lxr; private String lxdh; private Integer yxbz; private Double zpxe; private Double ppxe; private Double jdcxe; private Double dzxe; private Double jpxe; private Integer sgkp; public String getZdmc() { return zdmc; } public void setZdmc(String zdmc) { this.zdmc = zdmc; } public Integer getZdhm() { return zdhm; } public void setZdhm(Integer zdhm) { this.zdhm = zdhm; } public String getLxr() { return lxr; } public void setLxr(String lxr) { this.lxr = lxr; } public String getLxdh() { return lxdh; } public void setLxdh(String lxdh) { this.lxdh = lxdh; } public Integer getYxbz() { return yxbz; } public void setYxbz(Integer yxbz) { this.yxbz = yxbz; } public Double getZpxe() { return zpxe; } public void setZpxe(Double zpxe) { this.zpxe = zpxe; } public Double getPpxe() { return ppxe; } public void setPpxe(Double ppxe) { this.ppxe = ppxe; } public Double getJdcxe() { return jdcxe; } public void setJdcxe(Double jdcxe) { this.jdcxe = jdcxe; } public Double getDzxe() { return dzxe; } public void setDzxe(Double dzxe) { this.dzxe = dzxe; } public Double getJpxe() { return jpxe; } public void setJpxe(Double jpxe) { this.jpxe = jpxe; } public Integer getSgkp() { return sgkp; } public void setSgkp(Integer sgkp) { this.sgkp = sgkp; } }
package com.example.siddiq.bukhari___sharef; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentTransaction; import android.view.ContextMenu; import android.view.LayoutInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.ListView; import java.util.List; public class Fav_Frag extends Fragment { DatabaseHelper databaseHelper; List<String> list; ListView listView; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment View view= inflater.inflate(R.layout.fragment_fav_, container, false); databaseHelper = new DatabaseHelper(getContext()); MainActivity.notmain=true; MainActivity.lastloc="chapter"; list = databaseHelper.Get_Fav(); listView = (ListView) view.findViewById(R.id.fav_list); listView.setAdapter(new ArrayAdapter<String>(getActivity(),android.R.layout.simple_list_item_1, android.R.id.text1, list)); registerForContextMenu(listView); getActivity().setTitle("Favorites"); listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Hadith hadith = new Hadith(); String a[]=list.get(position).split("\\n"); String b[]= a[1].split(" "); Hadith.book=a[0]; Hadith.hadith=b[2]; Hadith.fav=false; FragmentManager fragmentManager = getFragmentManager(); FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction(); fragmentTransaction.replace(R.id.layout,hadith); fragmentTransaction.commit(); } }); return view; } @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) { super.onCreateContextMenu(menu, v, menuInfo); menu.setHeaderTitle("Select Action"); menu.add(0, v.getId(), 0, "Remove"); } @Override public boolean onContextItemSelected(MenuItem item) { if (item.getTitle() == "Remove") { AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo(); int listPosition = info.position; String a[]=list.get(listPosition).split("\\n"); String b[]= a[1].split(" "); databaseHelper.del(a[0],b[2]); list = databaseHelper.Get_Fav(); listView.setAdapter(new ArrayAdapter<String>(getActivity(),android.R.layout.simple_list_item_1, android.R.id.text1, list)); // String selectedFromList = (String) lv.getItemAtPosition(listPosition); //myDbHelper.recent(list3.get(listPosition), "new_fav"); // myDbHelper.recent((String) lv.getItemAtPosition(listPosition), "new_fav"); } return super.onContextItemSelected(item); } }
package org.apache.xml.xml_soap; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for DataHandler complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="DataHandler"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "DataHandler") public class DataHandler { }
package course.chapter11lab; import java.util.List; public class Main { public static void main(String[] args) { // Vehicle vehicle = new Vehicle(45, 3); // Bicycle bicycle = new Bicycle(30, 10); Object vehicles[] = new Object[3]; vehicles[0] = new Bicycle(15, 10); vehicles[1] = new Bicycle(15, 3); vehicles[2] = new Vehicle(); for (Object vehicle : vehicles) { System.out.println(vehicle); } } }
package test3; public class Document { private String text; public static void main( String[] args ) { Document d = new Document( "He was visiting th" + "e United States when Adolf Hitler came to power in " + "1933 and, being Jewish, did not go back to Germa ny," + " where he had been a professor at the Berlin Academy of Sciences. " + "He settled in the U.S., becoming an American citizen in 1940." + " On the eve of World War II, he endorsed a " + "letter to President Franklin D. Roosevelt" + " alerting him to the potential development " + "of \"extremely powerful bombs of a new type\" and recommending that " + "the U.S. begin similar research. This eventually led to " + "what would become the Manhattan "); System.out.print(d); } public Document( String text ){ if( text.equals("") ){ System.out.println("String is empty"); }else{ this.text = text; } }//constructor. @Override public String toString(){ String extract = ""; int len = text.length(); if( len <50 ) { return text.concat("\n"); } else{ int prev = 0,next = 50; while( next<text.length()) { if(text.charAt(next) == ' ' ) extract = extract.concat(text.substring(prev,next) ).concat("\n"); else{ while( text.charAt(next) != ' ' ){ next++; } extract = extract.concat(text.substring(prev,next) ).concat("\n"); } prev = next; next+=50; } extract = extract.concat(text.substring(next-50,text.length()) ).concat("\n"); return extract; } } }
package com.jeffdisher.thinktank.chat; import java.io.IOException; import java.net.InetSocketAddress; import java.util.UUID; import com.jeffdisher.laminar.client.ClientConnection; import com.jeffdisher.laminar.types.TopicName; import com.jeffdisher.laminar.utils.Assert; import com.jeffdisher.thinktank.chat.support.IListenerTopicShim; import com.jeffdisher.thinktank.chat.support.StringCodec; import com.jeffdisher.thinktank.chat.support.TopicListener; import com.jeffdisher.thinktank.chat.support.UUIDCodec; /** * The real implementation of IChatWriter which is back-ended on a Laminar cluster via the topic name "chat". */ public class ChatLaminar implements IChatWriter { private static final TopicName TOPIC_NAME = TopicName.fromString("chat"); private final ChatStore _chatStore; private final UUIDCodec _keyCodec; private final StringCodec _valueCodec; private final ClientConnection _writer; private final TopicListener<UUID, String> _listener; public ChatLaminar(ChatStore chatStore, InetSocketAddress laminarServer) throws IOException { _chatStore = chatStore; _keyCodec = new UUIDCodec(); _valueCodec = new StringCodec(); // Open the writing connection. _writer = ClientConnection.open(laminarServer); try { _writer.waitForConnectionOrFailure(); } catch (IOException e) { throw e; } catch (InterruptedException e) { // We don't use interruption. throw Assert.unexpected(e); } // Create chat topic (we don't care about whether it was accepted as this may already exist). try { _writer.sendCreateTopic(TOPIC_NAME).waitForCommitted(); } catch (InterruptedException e) { // We don't use interruption. throw Assert.unexpected(e); } // Open the listening connection. _listener = new TopicListener<UUID, String>(laminarServer, TOPIC_NAME, new ChatListenerShim(), _keyCodec, _valueCodec); try { _listener.waitForConnectionOrFailure(); } catch (IOException e) { throw e; } catch (InterruptedException e) { // We don't use interruption. throw Assert.unexpected(e); } } @Override public synchronized void post(UUID writer, String post) { Assert.assertTrue(null != post); // We will ignore the response, just waiting for it to commit. try { _writer.sendPut(TOPIC_NAME, _keyCodec.serialize(writer), _valueCodec.serialize(post)).waitForCommitted(); } catch (InterruptedException e) { // We don't use interruption. throw Assert.unexpected(e); } } @Override public void close() throws IOException { _writer.close(); _listener.close(); } private class ChatListenerShim implements IListenerTopicShim<UUID, String> { @Override public void delete(UUID key, long intentionOffset, long consequenceOffset) { throw Assert.unreachable("We don't delete keys"); } @Override public void put(UUID key, String value, long intentionOffset, long consequenceOffset) { // We will send in the consequenceOffset since it is the dense and non-duplicated value. _chatStore.newMessageArrived(key, value, consequenceOffset); } @Override public void create(long intentionOffset, long consequenceOffset) { // No special action on create. } @Override public void destroy(long intentionOffset, long consequenceOffset) { throw Assert.unreachable("We don't destroy the topic"); } } }
package com.legaoyi.storer.tjsatl.service.impl; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.legaoyi.storer.dao.GeneralDao; import com.legaoyi.storer.service.GeneralService; import com.legaoyi.storer.util.Constants; @Transactional @Service(Constants.ELINK_MESSAGE_STORER_BEAN_PREFIX + "1212" + Constants.ELINK_MESSAGE_STORER_MESSAGE_SERVICE_BEAN_SUFFIX) public class Tjsatl_1212_MessageServiceImpl implements GeneralService { @Autowired @Qualifier(Constants.ELINK_MESSAGE_STORER_BEAN_PREFIX + "0801" + Constants.ELINK_MESSAGE_STORER_MESSAGE_DAO_BEAN_SUFFIX) private GeneralDao mediaDataDao; @Autowired @Qualifier("deviceUpMessageDao") private GeneralDao deviceUpMessageDao; @Override public void batchSave(List<?> list) throws Exception { mediaDataDao.batchSave(list); deviceUpMessageDao.batchSave(list); } }
package com.beadhouse.domen; import java.io.Serializable; import java.util.Date; public class Collection implements Serializable{ /** * */ private static final long serialVersionUID = 1L; private Integer collectionid; private Integer chatId; private Integer loginUserId; private Integer elderUserId; private Date createDate; public Integer getElderUserId() { return elderUserId; } public void setElderUserId(Integer elderUserId) { this.elderUserId = elderUserId; } public Integer getCollectionid() { return collectionid; } public void setCollectionid(Integer collectionid) { this.collectionid = collectionid; } public Integer getChatId() { return chatId; } public void setChatId(Integer chatId) { this.chatId = chatId; } public Integer getLoginUserId() { return loginUserId; } public void setLoginUserId(Integer loginUserId) { this.loginUserId = loginUserId; } public Date getCreateDate() { return createDate; } public void setCreateDate(Date createDate) { this.createDate = createDate; } }
package com.appirio.service.member.resources; import com.appirio.service.member.api.MemberHistoryStats; import com.appirio.service.member.manager.MemberHistoryStatsManager; import com.appirio.supply.ErrorHandler; import com.appirio.tech.core.api.v3.request.FieldSelector; import com.appirio.tech.core.api.v3.request.annotation.APIFieldParam; import com.appirio.tech.core.api.v3.response.ApiResponse; import com.appirio.tech.core.api.v3.response.ApiResponseFactory; import com.codahale.metrics.annotation.Timed; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.ws.rs.*; import javax.ws.rs.core.MediaType; /** * Resource for Member history stats * * Created by rakeshrecharla on 8/20/15. */ @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) @Path("members/{handle}/stats/history") public class MemberHistoryStatsResource { /** * Logger for the class */ private Logger logger = LoggerFactory.getLogger(MemberHistoryStatsResource.class); /** * Member history stats manager */ private MemberHistoryStatsManager memberHistoryStatsManager; /** * Constructor to initialize Member history stats manager * @param memberHistoryStatsManager Member history stats manager */ public MemberHistoryStatsResource(MemberHistoryStatsManager memberHistoryStatsManager) { this.memberHistoryStatsManager = memberHistoryStatsManager; } /** * Get member history statistics * @param handle Handle of the user * @param selector Field selector * @return */ @GET @Timed public ApiResponse getMemberHistoryStats(@PathParam("handle") String handle, @APIFieldParam(repClass = MemberHistoryStats.class) FieldSelector selector) { try { logger.debug("getMemberHistoryStats, handle : " + handle); MemberHistoryStats memberHistoryStats = memberHistoryStatsManager.getMemberHistoryStats(handle); return ApiResponseFactory.createFieldSelectorResponse(memberHistoryStats, selector); } catch (Throwable ex) { return ErrorHandler.handle(ex, logger); } } }
/* * Copyright 1999-2017 Alibaba Group Holding Ltd. * * 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.alibaba.druid.bvt.sql.mysql.select; import com.alibaba.druid.DbType; import com.alibaba.druid.sql.MysqlTest; import com.alibaba.druid.sql.SQLUtils; import com.alibaba.druid.sql.ast.SQLStatement; import com.alibaba.druid.sql.ast.statement.SQLCreateTableStatement; import com.alibaba.druid.sql.ast.statement.SQLSelectStatement; import com.alibaba.druid.sql.dialect.mysql.parser.MySqlStatementParser; import com.alibaba.druid.sql.parser.SQLParserFeature; import java.util.List; public class MySqlSelectTest_94 extends MysqlTest { public void test_0() throws Exception { String sql = "select * from test where name = 'cail\\1';"; MySqlStatementParser parser = new MySqlStatementParser(sql, SQLParserFeature.IgnoreNameQuotes); List<SQLStatement> statementList = parser.parseStatementList(); assertEquals(1, statementList.size()); SQLSelectStatement stmt = (SQLSelectStatement) statementList.get(0); assertEquals("SELECT *\n" + "FROM test\n" + "WHERE name = 'cail1';", stmt.toString()); } public void test_2() throws Exception { String sql = "select * from test where name = 'cail\\\\1';"; MySqlStatementParser parser = new MySqlStatementParser(sql, SQLParserFeature.IgnoreNameQuotes); List<SQLStatement> statementList = parser.parseStatementList(); assertEquals(1, statementList.size()); SQLSelectStatement stmt = (SQLSelectStatement) statementList.get(0); assertEquals("SELECT *\n" + "FROM test\n" + "WHERE name = 'cail\\\\1';", stmt.toString()); } public void test_1() throws Exception { String sql = "select * from test where name like 'cai\\%1';"; MySqlStatementParser parser = new MySqlStatementParser(sql, SQLParserFeature.IgnoreNameQuotes); List<SQLStatement> statementList = parser.parseStatementList(); assertEquals(1, statementList.size()); SQLSelectStatement stmt = (SQLSelectStatement) statementList.get(0); assertEquals("SELECT *\n" + "FROM test\n" + "WHERE name LIKE 'cai\\\\%1';", stmt.toString()); } public void test_3() throws Exception { String sql = "select * from test where name = 'cai\\%1';"; MySqlStatementParser parser = new MySqlStatementParser(sql, SQLParserFeature.IgnoreNameQuotes); List<SQLStatement> statementList = parser.parseStatementList(); assertEquals(1, statementList.size()); SQLSelectStatement stmt = (SQLSelectStatement) statementList.get(0); assertEquals("SELECT *\n" + "FROM test\n" + "WHERE name = 'cai\\\\%1';", stmt.toString()); } public void test_4() throws Exception { String sql = "select * from test WHERE name = 'cailijun' or name like 'cai\\%1';"; MySqlStatementParser parser = new MySqlStatementParser(sql, SQLParserFeature.IgnoreNameQuotes); List<SQLStatement> statementList = parser.parseStatementList(); assertEquals(1, statementList.size()); SQLSelectStatement stmt = (SQLSelectStatement) statementList.get(0); assertEquals("SELECT *\n" + "FROM test\n" + "WHERE name = 'cailijun'\n" + "\tOR name LIKE 'cai\\\\%1';", stmt.toString()); } public void test_5() throws Exception { String sql = "select * from test WHERE name = 'cailijun' or name like 'cai\\1';"; MySqlStatementParser parser = new MySqlStatementParser(sql, SQLParserFeature.IgnoreNameQuotes); List<SQLStatement> statementList = parser.parseStatementList(); assertEquals(1, statementList.size()); SQLSelectStatement stmt = (SQLSelectStatement) statementList.get(0); assertEquals("SELECT *\n" + "FROM test\n" + "WHERE name = 'cailijun'\n" + "\tOR name LIKE 'cai1';", stmt.toString()); } public void test_6() throws Exception { String sql = "select * from test WHERE name = 'cai\t';"; MySqlStatementParser parser = new MySqlStatementParser(sql, SQLParserFeature.IgnoreNameQuotes); List<SQLStatement> statementList = parser.parseStatementList(); assertEquals(1, statementList.size()); SQLSelectStatement stmt = (SQLSelectStatement) statementList.get(0); assertEquals("SELECT *\n" + "FROM test\n" + "WHERE name = 'cai\t';", stmt.toString()); } public void test_7() throws Exception { String sql = "/*+ a=1,b=2*/select count(distinct a) from test WHERE name = 'cai\t';"; MySqlStatementParser parser = new MySqlStatementParser(sql, SQLParserFeature.IgnoreNameQuotes); List<SQLStatement> statementList = parser.parseStatementList(); assertEquals(1, statementList.size()); SQLSelectStatement stmt = (SQLSelectStatement) statementList.get(0); assertEquals("/*+ a=1,b=2*/\n" + "SELECT count(DISTINCT a)\n" + "FROM test\n" + "WHERE name = 'cai\t';", stmt.toString()); } public void test_8() throws Exception { String sql = "/*+engine=MPP*/ with tmp1 as ( select uid, ugroups_str from dw.test_multivalue1 where uid = 101 ) select tmp1.uid, tmp1.ugroups_str from tmp1"; MySqlStatementParser parser = new MySqlStatementParser(sql, SQLParserFeature.IgnoreNameQuotes); List<SQLStatement> statementList = parser.parseStatementList(); assertEquals(1, statementList.size()); SQLSelectStatement stmt = (SQLSelectStatement) statementList.get(0); assertEquals("/*+engine=MPP*/\n" + "WITH tmp1 AS (\n" + "\t\tSELECT uid, ugroups_str\n" + "\t\tFROM dw.test_multivalue1\n" + "\t\tWHERE uid = 101\n" + "\t)\n" + "SELECT tmp1.uid, tmp1.ugroups_str\n" + "FROM tmp1", stmt.toString()); } public void test_9() throws Exception { String sql = "create table testkey3( `key` varchar(4), `id` int, primary key (`key`) );"; MySqlStatementParser parser = new MySqlStatementParser(sql, SQLParserFeature.IgnoreNameQuotes); List<SQLStatement> statementList = parser.parseStatementList(); assertEquals(1, statementList.size()); SQLCreateTableStatement stmt = (SQLCreateTableStatement) statementList.get(0); assertEquals("CREATE TABLE testkey3 (\n" + "\tkey varchar(4),\n" + "\tid int,\n" + "\tPRIMARY KEY (key)\n" + ");", stmt.toString()); } }
package com.psl.semicolon.bitsplease.db; import org.junit.Before; import org.junit.Test; public class TestBitsPleaseDB { private String[] text = { "hello", "sachi", "is", "a", "sachi", "hello", "dada", "kaka" }; private String[] newText = { "abhi", "shek", "is", "a", "good", "hello", "daddy" }; @Before public void init() { } @Test public void test() { try (BitsPleaseDB db = new BitsPleaseDB("/home/user/Documents/sabya")) { for (String str : text) { System.out.println(str + " : " + db.findIndex(str)); } for (String str : newText) { System.out.println(str + " : " + db.findIndex(str)); } } catch (Exception ex) { ex.printStackTrace(); } } }
package com.androidbook.ShapeShifter; import android.app.Activity; import android.os.Bundle; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.widget.LinearLayout; public class TweenLayoutActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.tweenoflayout); // We will animate the imageview LinearLayout layoutToAnimate = (LinearLayout)findViewById(R.id.LayoutRow); // Load the appropriate animation Animation an = AnimationUtils.loadAnimation(this, R.anim.snazzyintro); // Start the animation layoutToAnimate.startAnimation(an); } }
package android.example.pietjesbak.utils; import android.example.pietjesbak.constant.Dices; import android.example.pietjesbak.models.Die; import android.util.Log; import java.util.Random; import static android.util.Log.w; public class DiceRoller { //houd een array van dice bij private Die[] dice; //rolt de dobbelstenen random private Random random; //constructor maken public DiceRoller(){ //aantal dobbelstenen (ingegeven bij dices klasse) dice = new Die[Dices.NUMBER_DICE]; //instantie van alle dobbelstenen dice[0] = new Die(); dice[1] = new Die(); dice[2] = new Die(); //random class initialiseren random = new Random(); //methode die uitgevoerd wordt rollDice(); } //random nummer gereren voor dobbelstenen tussen 1 en 6 public int generateDiceEyes(){ //verander het return getal in 1 voor een aap! return random.nextInt((2-1)+1)+1; //Zand //return 2; //soixante neuf //return random.nextInt((6-4)+1)+4; //zeven //return random.nextInt((3-2)+1)+2; //random //return random.nextInt(6) + 1; } public void rollDice(){ //cijfers genereren totdat alle dobbelstenen een nummer hebben for (int i = 0; i < Dices.NUMBER_DICE; i++){ //cijfers moeten een random getal krijgen //gebruik maken van de bestaande functie generateDiceEyes() dice[i].setDieResult(generateDiceEyes()); } } public Die[] getDice() { return dice; } }
package com.zaiou.common.filter.wrapper; import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.databind.JsonSerializer; import com.fasterxml.jackson.databind.SerializerProvider; import org.springframework.web.util.HtmlUtils; import java.io.IOException; /** * @Description: 序列化解析报文 * @auther: LB 2018/9/8 17:42 * @modify: LB 2018/9/8 17:42 */ public class XssStringJsonSerializer extends JsonSerializer<String> { @Override public Class<String> handledType() { return String.class; } @Override public void serialize(String value, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException { if (value != null) { String encodedValue = HtmlUtils.htmlEscape(value); jsonGenerator.writeString(encodedValue); } } }
package main.java.oop.Constant1; import java.util.Random; public class Test01 { public static void main(String[] args) { // 가위바위보를 랜덤으로 내는 프로그램을 작성 Random r = new Random(); int com = r.nextInt(3) + 1; // 상수 없이 아래와 같이 프로그램 작성시.. 아래처럼 주석을 달아줘야한다. // 또한 다른 곳에서 쓸 수 가 없다!! /** * 1 : 가위 * 2 : 바위 * 3 : 보 */ switch(com) { case 1: System.out.println("가위!"); break; case 2 : System.out.println("바위!"); break; case 3 : System.out.println("보!"); break; } } }
/* * 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 boletin18_2; import pedirDatos.PedirDatos; import Arrays.MetodosArrays; /** * * @author ceque */ public class Metodos { int [] notas=new int [6]; String [] nombres=new String[6]; public void crearArrays(){ for(int i=0;i<notas.length;i++){ notas[i]=(int)(Math.random()*10); nombres[i]=PedirDatos.pedirString(); } } public void amosarSuspensos(){ int aprobados=0; int suspensos=0; for(int i=0;i<notas.length;i++){ if (notas[i]>=5){ aprobados++; } else{ suspensos++; } } System.out.println("Aprobados="+aprobados+"\n Suspensos"+suspensos); } public void amosarMedia(){ int media=0; for(int i=0;i<notas.length;i++){ media=media+notas[i]; } System.out.println("A nota media ="+media/notas.length ); } public void amosarNotaMasAlta(){ int notaAlta=0; for(int i=0;i<notas.length;i++){ if (notaAlta<notas[i]) notaAlta=notas[i]; } System.out.println("A nota mais alta ="+notaAlta ); } public void amosarAlumnosAprobados(){ for(int i=0;i<notas.length;i++){ if (notas[i]>=5){ System.out.println("Alumno" + nombres[i]+"\n Nota"+notas[i]); } } } public void ordenarPorNotas(){ int aux; String auxNombre; for (int i=0;i<notas.length-1;i++){ for (int j=i+1;j<notas.length;j++){ if(notas[i]>notas[j]){ aux=notas[i]; notas[i]=notas[j]; notas[j]=aux; auxNombre=nombres[i]; nombres[i]=nombres[j]; nombres[j]=auxNombre; } } } } public void buscarPorNombre(){ int a=MetodosArrays.buscarString(nombres); if (a!=-1){ System.out.println("Nota="+notas[a]); } } }
package Teatrus.model; import java.io.Serializable; import java.util.ArrayList; import java.util.List; public class Istoric implements Serializable { private int idIstoric; private List<Spectacol> spectacole; private int idUser; public Istoric(){ this.idIstoric=0; this.spectacole=new ArrayList<Spectacol>(); this.idUser=0; } public Istoric(int idIstoric,List<Spectacol> spectacole,int idUser) { this.idIstoric=idIstoric; this.spectacole = spectacole; this.idUser=idUser; } public int getIdIstoric() { return idIstoric; } public void setIdIstoric(int idIstoric) { this.idIstoric = idIstoric; } public List<Spectacol> getSpectacole() { return spectacole; } public void setSpectacole(List<Spectacol> spectacole) { this.spectacole = spectacole; } public int getIdUser() { return idUser; } public void setIdUser(int idUser) { this.idUser = idUser; } }
package plugins.fmp.fmpTools; import java.awt.Polygon; import java.awt.Rectangle; import java.io.File; import java.util.Arrays; import java.util.Comparator; import javax.swing.JFileChooser; import javax.swing.filechooser.FileNameExtensionFilter; import icy.file.FileUtil; import icy.gui.dialog.ConfirmDialog; import icy.gui.frame.progress.AnnounceFrame; import icy.plugin.abstract_.Plugin; import icy.sequence.Sequence; import icy.roi.ROI; import icy.roi.ROI2D; import plugins.kernel.roi.roi2d.ROI2DLine; public class FmpTools extends Plugin { public static String saveFileAs(String defaultName, String directory, String csExt) { // load last preferences for loader String csFile = null; final JFileChooser fileChooser = new JFileChooser(); if (directory != null) { fileChooser.setCurrentDirectory(new File(directory)); } fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY ); FileNameExtensionFilter xlsFilter = new FileNameExtensionFilter(csExt+" files", csExt, csExt); fileChooser.addChoosableFileFilter(xlsFilter); fileChooser.setFileFilter(xlsFilter); if (defaultName != null) fileChooser.setSelectedFile(new File(defaultName)); final int returnValue = fileChooser.showSaveDialog(null); if (returnValue == JFileChooser.APPROVE_OPTION) { File f = fileChooser.getSelectedFile(); csFile = f.getAbsolutePath(); int dotOK = csExt.indexOf("."); if (dotOK < 0) csExt = "." + csExt; int extensionOK = csFile.indexOf(csExt); if (extensionOK < 0) { csFile += csExt; f = new File(csFile); } if(f.exists()) if (ConfirmDialog.confirm("Overwrite existing file ?")) FileUtil.delete(f, true); else csFile = null; } return csFile; } // TODO use LoaderDialog from Icy public static String[] selectFiles(String directory, String csExt) { // load last preferences for loader final JFileChooser fileChooser = new JFileChooser(); final String path = directory; fileChooser.setCurrentDirectory(new File(path)); fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY ); fileChooser.setMultiSelectionEnabled(true); FileNameExtensionFilter csFilter = new FileNameExtensionFilter(csExt+" files", csExt, csExt); fileChooser.addChoosableFileFilter(csFilter); fileChooser.setFileFilter(csFilter); final int returnValue = fileChooser.showDialog(null, "Load"); String[] liststrings = null; if (returnValue == JFileChooser.APPROVE_OPTION) { File[] files = fileChooser.getSelectedFiles(); liststrings = new String[files.length]; for (int i=0; i< files.length; i++) { liststrings[i] = files[i].getAbsolutePath(); } } return liststrings; } public static class ROI2DLineLeftXComparator implements Comparator<ROI2DLine> { @Override public int compare(ROI2DLine o1, ROI2DLine o2) { if (o1.getBounds().x == o2.getBounds().x) return 0; else if (o1.getBounds().x > o2.getBounds().x) return 1; else return -1; } } public static class ROI2DLineLeftYComparator implements Comparator<ROI2DLine> { @Override public int compare(ROI2DLine o1, ROI2DLine o2) { if (o1.getBounds().y == o2.getBounds().y) return 0; else if (o1.getBounds().y > o2.getBounds().y) return 1; else return -1; } } public static class ROI2DNameComparator implements Comparator<ROI2D> { @Override public int compare(ROI2D o1, ROI2D o2) { return o1.getName().compareTo(o2.getName()); } } public static class ROINameComparator implements Comparator<ROI> { @Override public int compare(ROI o1, ROI o2) { return o1.getName().compareTo(o2.getName()); } } public static class SequenceNameComparator implements Comparator<Sequence> { @Override public int compare(Sequence o1, Sequence o2) { return o1.getName().compareTo(o2.getName()); } } public static int[] rank(double[] values) { /** Returns a sorted list of indices of the specified double array. Modified from: http://stackoverflow.com/questions/951848 by N.Vischer. */ int n = values.length; final Integer[] indexes = new Integer[n]; final Double[] data = new Double[n]; for (int i=0; i<n; i++) { indexes[i] = new Integer(i); data[i] = new Double(values[i]); } Arrays.sort(indexes, new Comparator<Integer>() { public int compare(final Integer o1, final Integer o2) { return data[o1].compareTo(data[o2]); } }); int[] indexes2 = new int[n]; for (int i=0; i<n; i++) indexes2[i] = indexes[i].intValue(); return indexes2; } public static int[] rank(final String[] data) { /** Returns a sorted list of indices of the specified String array. */ int n = data.length; final Integer[] indexes = new Integer[n]; for (int i=0; i<n; i++) indexes[i] = new Integer(i); Arrays.sort(indexes, new Comparator<Integer>() { public int compare(final Integer o1, final Integer o2) { return data[o1].compareToIgnoreCase(data[o2]); } }); int[] indexes2 = new int[n]; for (int i=0; i<n; i++) indexes2[i] = indexes[i].intValue(); return indexes2; } public static Polygon orderVerticesofPolygon(Polygon roiPolygon) { if (roiPolygon.npoints > 4) new AnnounceFrame("Only the first 4 points of the polygon will be used..."); Polygon extFrame = new Polygon(); Rectangle rect = roiPolygon.getBounds(); Rectangle rect1 = new Rectangle(rect); // find upper left rect1.setSize(rect.width/2, rect.height/2); for (int i = 0; i< roiPolygon.npoints; i++) { if (rect1.contains(roiPolygon.xpoints[i], roiPolygon.ypoints[i])) { extFrame.addPoint(roiPolygon.xpoints[i], roiPolygon.ypoints[i]); break; } } // find lower left rect1.translate(0, rect.height/2 +2); for (int i = 0; i< roiPolygon.npoints; i++) { if (rect1.contains(roiPolygon.xpoints[i], roiPolygon.ypoints[i])) { extFrame.addPoint(roiPolygon.xpoints[i], roiPolygon.ypoints[i]); break; } } // find lower right rect1.translate(rect.width/2+2, 0); for (int i = 0; i< roiPolygon.npoints; i++) { if (rect1.contains(roiPolygon.xpoints[i], roiPolygon.ypoints[i])) { extFrame.addPoint(roiPolygon.xpoints[i], roiPolygon.ypoints[i]); break; } } // find upper right rect1.translate(0, -rect.height/2 - 2); for (int i = 0; i< roiPolygon.npoints; i++) { if (rect1.contains(roiPolygon.xpoints[i], roiPolygon.ypoints[i])) { extFrame.addPoint(roiPolygon.xpoints[i], roiPolygon.ypoints[i]); break; } } return extFrame; } public static File chooseDirectory(String rootdirectory) { File dummy_selected = null; JFileChooser fc = new JFileChooser(); if (rootdirectory != null) fc.setCurrentDirectory(new File(rootdirectory)); fc.setDialogTitle("Select a root directory..."); fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); fc.setAcceptAllFileFilterUsed(false); if (fc.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) { dummy_selected = fc.getSelectedFile(); } else { System.out.println("No directory selected "); } return dummy_selected; } }
/* * 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 milou; import generated.Carto; import generated.Carto.Markers.Marker; import generated.Station; import java.net.HttpURLConnection; import java.net.URL; import java.util.Scanner; import javax.xml.bind.JAXBContext; import javax.xml.bind.Unmarshaller; /** * * @author thomas.sauvajon */ public class Milou { /** * @param args the command line arguments */ public static void main(String[] args) throws Exception { JAXBContext cartoContext = JAXBContext.newInstance(Carto.class); Unmarshaller u = cartoContext.createUnmarshaller(); URL url = new URL("http://www.velib.paris/service/carto"); HttpURLConnection con = (HttpURLConnection) url.openConnection(); con.setRequestMethod("GET"); Carto cartale = (Carto) u.unmarshal(con.getInputStream()); Scanner sc = new Scanner(System.in); int idStation = sc.nextInt(); Marker randomStation = cartale.getMarkers().getMarker().get(idStation); URL stationURL = new URL("http://www.velib.paris/service/stationdetails/" + randomStation.getNumber()); HttpURLConnection stationConnection = (HttpURLConnection) stationURL.openConnection(); stationConnection.setRequestMethod("GET"); JAXBContext stationContext = JAXBContext.newInstance(Station.class); Unmarshaller u2 = stationContext.createUnmarshaller(); Station station = (Station) u2.unmarshal(stationConnection.getInputStream()); System.out.println("Station " + randomStation.getName()); System.out.println(randomStation.getFullAddress()); System.out.println("Coordonnées : [" + randomStation.getLat() + "; " + randomStation.getLng() + "]"); System.out.println("Google maps : https://www.google.fr/maps/@" + randomStation.getLat() + "," + randomStation.getLng() + ",15z"); System.out.println("Total de places " + station.getTotal()); System.out.println("Dont libres : " + station.getAvailable()); } }
package fema; import java.io.Serializable; import java.util.ArrayList; import java.util.List; import javax.enterprise.context.SessionScoped; import javax.inject.Inject; import javax.inject.Named; @Named @SessionScoped public class Controlador implements Serializable { private static final long serialVersionUID = 1L; private List<Banda> listaBanda = new ArrayList<Banda>(); @Inject private BandaDao bandaDao; public void mostrarDados() { listaBanda = bandaDao.getBandas(); for (Banda b : listaBanda) { System.out.println(b.getNome()); } } public List<Banda> getListaBanda() { return listaBanda; } public void setListaBanda(List<Banda> listaBanda) { this.listaBanda = listaBanda; } }
package Farming; public abstract class Product { public String name; public Unit unit; public double count; public int price; public Product(String name,Unit unit, double count, int price) { this.name = name; this.unit = unit; this.count = count; this.price = price; } final void checkFreshness(){ watchProduct(); getWater(); doUtilization(); } void watchProduct(){ System.out.println("Отбираем испорченные"); } abstract void getWater(); void doUtilization(){ System.out.println("Утилизировали"); } }
package com.haku.light.graphics.gl.texture; import com.haku.light.graphics.gl.GL20; public enum GLTextureFilter { LINEAR(GL20.GL_LINEAR), NEAREST(GL20.GL_NEAREST); public final int flag; private GLTextureFilter(int flag) { this.flag = flag; } }
package com.fruit.crawler.task.config; /** * Created by vincent * Created on 16/2/2 13:57. */ public class DbConfig { private String Server; private String port; private String name; private String user; private String pwd; private String colection; public String getServer() { return Server; } public void setServer(String server) { Server = server; } public String getPort() { return port; } public void setPort(String port) { this.port = port; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getUser() { return user; } public void setUser(String user) { this.user = user; } public String getPwd() { return pwd; } public void setPwd(String pwd) { this.pwd = pwd; } public String getColection() { return colection; } public void setColection(String colection) { this.colection = colection; } }
package com.alibaba.druid.bvt.sql.postgresql.expr; import org.junit.Assert; import com.alibaba.druid.sql.PGTest; import com.alibaba.druid.sql.dialect.postgresql.ast.expr.PGCidrExpr; import com.alibaba.druid.sql.dialect.postgresql.parser.PGExprParser; public class CidrTest extends PGTest { public void test_timestamp() throws Exception { String sql = "cidr '10.1.0.0/16'"; PGExprParser parser = new PGExprParser(sql); PGCidrExpr expr = (PGCidrExpr) parser.expr(); Assert.assertEquals("cidr '10.1.0.0/16'", expr.toString()); } }
package com.git.cloud.webservice.demo.service; import javax.jws.WebParam; import javax.jws.WebService; /** * @Description * @author yangzhenhai * @version v1.0 2014-9-24 */ @WebService public interface ITestService { String Test(@WebParam(name="name")String name); }
package Game; public class Hand { private Card [] hand; private int counter; private int numOfAses; private int cardSum; public Hand () { this.counter = 0; this.numOfAses = 0; this.cardSum = 0; this.hand = new Card[11] ; } public int addCard(Card card){ if(card.getVrijednost() == 11) numOfAses++; cardSum += card.getVrijednost(); if(cardSum > 21){ if(numOfAses>0){ cardSum -= 10; numOfAses--; } else{ return 2; } } else if(cardSum > 16 && cardSum <= 21){ return 1; } else{ hand[counter++] = card; return 3; } return 4; //return 1 - pobjeda //return 2 - poraz //return 3 - nova karta //retrun 4 - greska } public int getSuma(){ return cardSum; } }
package com.gxc.stu.back.controller; import javax.servlet.http.HttpServletRequest; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import com.gxc.stu.pojo.User; import com.gxc.stu.service.UserService; import utils.Page; @Controller public class UserController { @Autowired private UserService userService; /** * 根据条件,分页查询用户列表 * @param user * @param model * @param page * @param size * @return */ @RequestMapping("/back/userList") public String userList(User user, Model model, @RequestParam(defaultValue="1")Integer page, @RequestParam(defaultValue="20")Integer size, HttpServletRequest request){ //更新专业前,判断是否为登录状态 User user2 = (User)request.getAttribute("user"); //1.如果不是登录状态,提示暂无权限,请登录 if(user2 == null){ return "noAccess"; } //2.如果是登录状态,判断user的权限,如果权限不够,提示暂无权限更新 if(user2.getRole() == 2){ return "noAccess"; } Page<User> pageList = userService.findUserList(user,page,size); model.addAttribute("page", pageList); return "userList"; } }
/* * Copyright (c) 2014 ICM Uniwersytet Warszawski All rights reserved. * See LICENCE file for licencing information. * * Author: K. Benedyczak <golbi@icm.edu.pl> */ /** * Types defining bulk operations * @author K. Benedyczak */ package pl.edu.icm.unity.server.bulkops;
package com.generic.rest.mvc; import java.util.ArrayList; import java.util.List; import com.generic.core.onboarding.exceldto.ExcelLocationDto; import com.generic.core.validation.validate.GenericValidation; import com.generic.core.validation.validate.ValidationRules; import com.generic.rest.dto.ResponseDto; public class TestValidation { public static void main(String[] args) {/* List<ExcelLocationDto> locationList = new ArrayList<ExcelLocationDto>(); for(int i=0;i<5;i++) { locationList.add(new ExcelLocationDto("City" + i, "Area" + i, "Landmark" + i)); } GenericValidation validation = new GenericValidation(ExcelLocationDto.class, locationList, ValidationRules.locationRules); List<ResponseDto> results = null; try { results = validation.validate(); } catch (IllegalArgumentException | IllegalAccessException e) { // TODO Auto-generated catch block e.printStackTrace(); } for(ResponseDto resp : results) { System.out.println(resp); } */} }
import java.util.Comparator; import java.util.Iterator; import java.util.Stack; import edu.princeton.cs.algs4.MinPQ; import edu.princeton.cs.algs4.StdOut; import edu.princeton.cs.algs4.In; public class Solver { private Node result = null; private class Node { public Board board; public int moves; public Node prev; } public Solver(Board initial) { if (initial == null) throw new java.lang.IllegalArgumentException(); MinPQ<Node> pq = new MinPQ<Node>(new BoardComp()); Node init = new Node(); init.board = initial; init.moves = 0; init.prev = null; pq.insert(init); while (!pq.isEmpty()) { Node crnt = pq.delMin(); int mov = crnt.moves; if(mov > 100) break; if (crnt.board.isGoal()) { result = crnt; break; } for (Board brd : crnt.board.neighbors()) { Node brdNode = new Node(); brdNode.board = brd; brdNode.moves = mov + 1; brdNode.prev = crnt; if (crnt.prev != null && brd.equals(crnt.prev.board)) continue; pq.insert(brdNode); } } } private class BoardComp implements Comparator<Node> { public int compare(Node a, Node b) { int mv1 = a.moves + a.board.manhattan(); int mv2 = b.moves + b.board.manhattan(); if (mv1 < mv2) return -1; else if (mv1 == mv2) return 0; return 1; } } public boolean isSolvable() { if (result != null) return true; return false; } public int moves() { if (!this.isSolvable()) return -1; return result.moves; } public Iterable<Board> solution() { if (!isSolvable()) return null; Stack<Board> res = new Stack<Board>(); Node crnt = result; while (crnt != null) { res.push(crnt.board); crnt = crnt.prev; } Stack<Board> mainres = new Stack<Board>(); while (!res.empty()) { Board b = res.pop(); mainres.push(b); } return mainres; } public static void main(String[] args) { // create initial board from file In in = new In(args[0]); int n = in.readInt(); int[][] blocks = new int[n][n]; for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) blocks[i][j] = in.readInt(); Board initial = new Board(blocks); // solve the puzzle Solver solver = new Solver(initial); // print solution to standard output if (!solver.isSolvable()) { StdOut.println("No solution possible"); } else { StdOut.println("Minimum number of moves = " + solver.moves()); for (Board board : solver.solution()) StdOut.println(board); } } }
package com; import org.springframework.beans.factory.annotation.Value; public class TestProp { @Value("${testprop}") private static String enetEndpoint; public static void main(String[] args) { // TODO Auto-generated method stub System.out.println("Hi"); System.out.println(enetEndpoint); } }
package com.zjf.myself.codebase.dialog; import android.text.Spanned; import android.view.Gravity; import android.view.View; import android.widget.Button; import android.widget.TextView; import com.zjf.myself.codebase.R; import com.zjf.myself.codebase.util.CallBack; import com.zjf.myself.codebase.util.DesityUtil; import com.zjf.myself.codebase.util.StringUtil; import com.zjf.myself.codebase.util.ViewUtils; public class VerifyDialog extends BaseDialog implements View.OnClickListener{ public static final int RESULT_OK=1; private int result; private ResultListener resultListener; private Button btnCancel,btnOk; private CallBack callBack; private TextView txtMsg,txtTitle; private boolean isShowAnimation,isShowTitle=false; private View layoutTitle; String title=""; String msg=""; String ok=""; public VerifyDialog(){ } public VerifyDialog(String title,String msg,CallBack callBack){ this.callBack=callBack; this.title=title; this.msg=msg; } @Override protected void initView() { dialogWindow.getDecorView().setPadding(DesityUtil.dp2px(getContext(),30),0,DesityUtil.dp2px(getContext(),30),0); btnCancel=(Button) findViewById(R.id.btn_cancel); btnOk=(Button) findViewById(R.id.btn_ok); txtMsg= (TextView) findViewById(R.id.txt_msg); btnCancel.setOnClickListener(this); btnOk.setOnClickListener(this); layoutTitle=findViewById(R.id.layout_title); txtTitle=(TextView) findViewById(R.id.txtTitle); } public void setResultListener(ResultListener resultListener) { this.resultListener = resultListener; } @Override protected void doOnDismiss() { super.doOnDismiss(); if(resultListener!=null){ if(result==RESULT_OK){ resultListener.onOk(); result=0; }else { resultListener.onCancle(); } } } @Override protected boolean isShowAnimation() { return isShowAnimation; } public void setIsShowAnimation(boolean isShowAnimation){ this.isShowAnimation=isShowAnimation; } @Override public int getLayoutId() { return R.layout.dialog_verify; } @Override public int getGravity() { return Gravity.CENTER; } public void show(CallBack callBack,Spanned msg) { super.show(); this.callBack=callBack; txtMsg.setText(msg); } public void show(String title,String msg,CallBack callBack) { this.callBack=callBack; this.title=title; this.msg=msg; show(); } public void show(String title,String msg,String ok,CallBack callBack) { this.callBack=callBack; this.title=title; this.msg=msg; this.ok=ok; show(); } public void show(CallBack callBack) { if(isShowTitle) layoutTitle.setVisibility(View.VISIBLE); this.callBack=callBack; show(); } @Override public void show() { ViewUtils.setText(txtTitle,title); ViewUtils.setText(txtMsg,msg); if(!StringUtil.isNull(ok)) btnOk.setText(ok); super.show(); } @Override public void onClick(View v) { if(v==btnOk) { if(callBack!=null){ callBack.onCall(null); } result=RESULT_OK; } dismiss(); } public interface ResultListener{ void onOk(); void onCancle(); } }
package com.legaoyi.storer.service.impl; import java.util.HashMap; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.cache.annotation.Cacheable; import org.springframework.stereotype.Service; import com.legaoyi.common.util.Constants; import com.legaoyi.storer.dao.DeviceDao; import com.legaoyi.storer.service.ConfigService; @Service("configService") public class ConfigServiceImpl implements ConfigService { @Autowired @Qualifier("deviceDao") private DeviceDao deviceDao; @Override @Cacheable(value = Constants.CACHE_NAME_ENTERPRISE_CONFIG_CACHE, key = "#enterpriseId") public Map<String, Object> getEnterpriseConfig(String enterpriseId) throws Exception { Map<String, Object> map = deviceDao.getEnterpriseConfig(enterpriseId); if (map == null) { map = new HashMap<String, Object>(); } return map; } }
package com.master.springbatch.sample; import org.springframework.batch.core.StepContribution; import org.springframework.batch.core.scope.context.ChunkContext; import org.springframework.batch.core.step.tasklet.Tasklet; import org.springframework.batch.repeat.RepeatStatus; public class SimpleWriteTask implements Tasklet { private String msg; public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } @Override public RepeatStatus execute(StepContribution contribution, ChunkContext chunkContext) throws Exception { System.out.println(msg); return RepeatStatus.FINISHED; } }
package lesson3; import java.util.Scanner; // Команда для форматування коду - ctrl+alt+l public class lesson3_1 { public static void main(String[] args) { Scanner input = new Scanner(System.in); double m; double result; System.out.print("Ведіть m ="); m = input.nextDouble(); result = 0.4 - (m - 22); System.out.print("result=" + result); } }
package com.itheima.health.dao; import com.itheima.health.pojo.Menu; import org.apache.ibatis.annotations.Param; import java.util.List; import java.util.Map; /** * @Author: ZhangYongLiang * @Date: 2020/10/1 12:49 **/ public interface MenuDao { List<Menu> getMenuByUsername(String username); List<Map<String, Object>> getParentMenuID(); int getParentMenuTotal(); void addParentMenu(Map<String, Object> menu); int getChildrenMenuTotal(int parentMenuId); String getParentMenuPathById(int parentMenuId); void addChildrenMenu(Map<String, Object> menu); Map<String, Object> getMenuPathById(int id); void update(Map<String, Object> menu); List<Menu> getChildrenMenus(); List<Menu> getChildrenMenuByParentMenuId(int id); void updateParentMenuId(@Param("parentMenuId") int id,@Param("childrenId") Integer childrenId); void updatePathAndPriority(Map<String, Object> childrenMenuMap); void deleteManagerMenu(); List<Integer> getAllMenuId(); void addManagerMenu(Integer menuId); List<Integer> getChildrenIds(Integer id); List<Menu> getEditChildrenMenus(Integer id); Integer getMenuByName(String str); List<Integer> getRoleByMenuId(int id); void deleteById(int id); List<Menu> getAllMenu(); }
package com.mercadolibre.bootcampmelifrescos.service.impl; import com.mercadolibre.bootcampmelifrescos.dtos.InboundOrderDTO; import com.mercadolibre.bootcampmelifrescos.exceptions.api.ApiException; import com.mercadolibre.bootcampmelifrescos.exceptions.api.BadRequestApiException; import com.mercadolibre.bootcampmelifrescos.exceptions.api.NotFoundApiException; import com.mercadolibre.bootcampmelifrescos.model.Batch; import com.mercadolibre.bootcampmelifrescos.model.Product; import com.mercadolibre.bootcampmelifrescos.model.Section; import com.mercadolibre.bootcampmelifrescos.model.Warehouse; import com.mercadolibre.bootcampmelifrescos.repository.SectionRepository; import com.mercadolibre.bootcampmelifrescos.repository.WarehouseRepository; import com.mercadolibre.bootcampmelifrescos.service.Validator; import io.swagger.annotations.Api; import lombok.AllArgsConstructor; import org.springframework.stereotype.Service; import java.time.LocalDate; import java.time.temporal.ChronoUnit; import java.util.Set; @Service @AllArgsConstructor public class ValidatorImpl implements Validator { private WarehouseRepository warehouseRepository; private SectionRepository sectionRepository; @Override public void validateCategorySection(Section section, Set<Batch> batchSet) throws ApiException { for (Batch batch : batchSet) { Product product = batch.getProduct(); if (product.getCategory().getCode() != section.getCategory().getCode()) throw new BadRequestApiException("Product with id: " + product.getId() + " is in an incompatible section"); } } @Override public boolean hasDueDateEqualOrGreaterThanThreeWeeks(Batch batch) { return ChronoUnit.DAYS.between(LocalDate.now(), batch.getDueDate()) >= 21; } @Override public void validateWarehouseSection(Long sectionId, Long warehouseId, Section section) throws ApiException { Warehouse warehouse = warehouseRepository.findById(warehouseId).orElseThrow( () -> new NotFoundApiException("Warehouse with id " + warehouseId + " not found") ); if (!warehouse.getSections().contains(section)) throw new BadRequestApiException("Section " + sectionId + " don't belong to warehouse " + warehouseId); } @Override public boolean hasAvailableSpaceOnSection(InboundOrderDTO inboundOrderDTO) throws ApiException { int quantityOfBatches = inboundOrderDTO.getBatchStock().size(); Long sectionId = inboundOrderDTO.getSection().getSectionCode(); Section section = sectionRepository.findById(sectionId).orElseThrow( () -> new NotFoundApiException("Section " + sectionId + " not found") ); return section.getAvailableSpace() >= quantityOfBatches; } }
package projetobanco; import javax.swing.JOptionPane; /* * To change this template, choose Tools | Templates * and open the template in the editor. */ /** * * @author Codification */ public class ContaCorrente extends Conta { private double limite; @Override public boolean deposita(double valor) { this.setSaldo(getSaldo() + valor); return true; } @Override public boolean saca(double valor) { if ((getSaldo() - valor) > 0) { this.setSaldo(getSaldo() - valor); return true; } else { JOptionPane.showMessageDialog(null, "Saldo insulficiente. Ação cancelada."); } return false; } @Override public void remunera() { this.setSaldo(getSaldo() + getDono().getSalario()); } /** * @return the limite */ public double getLimite() { return limite; } /** * @param limite the limite to set */ public void setLimite(double limite) { this.limite = limite; } }
package com.example.tiny.controller; import com.example.tiny.provider.CancelOrderSender; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; /** * @ClassName: ProviderController * @Description: 生产者控制器 * @Author: yongchen * @Date: 2021/3/17 16:54 **/ @RestController @RequestMapping("/provider") public class OrderController { @Autowired private CancelOrderSender cancelOrderSender; @RequestMapping(value = "/sendMsg") public Long sendMsg(@RequestParam("orderId") Long orderId){ cancelOrderSender.sendTtlMessage(orderId, 30000L); return orderId; } }
package com.xlg.android.protocol; public class UserChestNumInfo { @StructOrder(0) private int vcbid; //当前用户所在的房间id @StructOrder(1) private int userid; //用户id @StructOrder(2) private byte newchestcount; //获取的新宝箱数目 @StructOrder(3) private byte totalchestcount; //用户剩余的宝箱数目 @StructOrder(4) private short reserve; //保留 public int getVcbid() { return vcbid; } public void setVcbid(int vcbid) { this.vcbid = vcbid; } public int getUserid() { return userid; } public void setUserid(int userid) { this.userid = userid; } public byte getNewchestcount() { return newchestcount; } public void setNewchestcount(byte newchestcount) { this.newchestcount = newchestcount; } public byte getTotalchestcount() { return totalchestcount; } public void setTotalchestcount(byte totalchestcount) { this.totalchestcount = totalchestcount; } public short getReserve() { return reserve; } public void setReserve(short reserve) { this.reserve = reserve; } }
package edu.inheritance.gabriel.mitchell; import edu.jenks.dist.inheritance.*; public class BarcodeItem extends Item implements Barcoded { public BarcodeItem(boolean bulk, double weight, double price){ super(bulk); setPrice(price); setWeight(weight); } public double getTax(double baseTaxRate){ return getPrice() * baseTaxRate; } public boolean initBuyable(ItemHandler itemHandler){ return false; } }
package terusus.avro.protobuf; import com.google.protobuf.Descriptors.FieldDescriptor; import org.apache.avro.Schema; import org.apache.avro.protobuf.ProtobufData; public class ExtendedProtobufData extends ProtobufData { final private static ExtendedProtobufData instance; final public static String KEY_NUMBER = "number"; final public static String KEY_WIRE = "wire"; final public static String KEY_PACKED = "packed"; static { instance = new ExtendedProtobufData(); } public static ExtendedProtobufData get() { return instance; } @Override public Schema getSchema(FieldDescriptor fieldDescriptor) { Schema schema = super.getSchema(fieldDescriptor); schema.addProp(KEY_NUMBER, fieldDescriptor.getNumber()); schema.addProp(KEY_WIRE, fieldDescriptor.getLiteType().getWireType()); if (fieldDescriptor.isRepeated()) { Schema elementSchema = schema.getElementType(); schema.addProp(KEY_PACKED, fieldDescriptor.isPacked()); elementSchema.addProp(KEY_NUMBER, fieldDescriptor.getNumber()); elementSchema.addProp(KEY_WIRE, fieldDescriptor.getLiteType().getWireType()); } return schema; } }
package com.crossengagetasktest; import com.crossenagetask.model.Product; import com.crossenagetask.services.CalculateService; import com.crossenagetask.services.CalculateServiceImpl; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; import java.math.BigDecimal; import java.time.LocalDate; import java.util.ArrayList; import java.util.List; /** * Created by NrapendraKumar on 14-03-2016. */ public class CalculateServiceImplTest { @Test public void testGetAmountOfOrder() { Product p1 = new Product(); p1.setCountryId("DEU"); p1.setDay(LocalDate.now()); p1.setPricePerItem(new BigDecimal(10.0)); p1.setProductCategoryId(1); p1.setQuantity(5); p1.setOrderId(1); p1.setProductId(2); Product p2 = new Product(); p2.setCountryId("DEU"); p2.setDay(LocalDate.now()); p2.setPricePerItem(new BigDecimal(10.0)); p2.setProductCategoryId(1); p2.setQuantity(5); p2.setOrderId(1); p2.setProductId(2); Product p3 = new Product(); p3.setCountryId("DEU"); p3.setDay(LocalDate.now()); p3.setPricePerItem(new BigDecimal(10.0)); p3.setProductCategoryId(1); p3.setQuantity(5); p3.setOrderId(1); p3.setProductId(2); Product p4 = new Product(); p4.setCountryId("DEU"); p4.setDay(LocalDate.now()); p4.setPricePerItem(new BigDecimal(10.0)); p4.setProductCategoryId(1); p4.setQuantity(5); p4.setOrderId(2); p4.setProductId(2); List<Product> productList = new ArrayList<>(); productList.add(p1); productList.add(p2); productList.add(p3); productList.add(p4); CalculateService calculateService = new CalculateServiceImpl(); Assert.assertEquals(calculateService.getAmountOfOrder(productList),2); } @Test public void testGetTotalNoOfItemSold() { Product p1 = new Product(); p1.setCountryId("DEU"); p1.setDay(LocalDate.now()); p1.setPricePerItem(new BigDecimal(10.0)); p1.setProductCategoryId(1); p1.setQuantity(5); p1.setOrderId(1); p1.setProductId(2); Product p2 = new Product(); p2.setCountryId("DEU"); p2.setDay(LocalDate.now()); p2.setPricePerItem(new BigDecimal(10.0)); p2.setProductCategoryId(1); p2.setQuantity(5); p2.setOrderId(1); p2.setProductId(2); Product p3 = new Product(); p3.setCountryId("DEU"); p3.setDay(LocalDate.now()); p3.setPricePerItem(new BigDecimal(10.0)); p3.setProductCategoryId(1); p3.setQuantity(5); p3.setOrderId(1); p3.setProductId(2); Product p4 = new Product(); p4.setCountryId("DEU"); p4.setDay(LocalDate.now()); p4.setPricePerItem(new BigDecimal(10.0)); p4.setProductCategoryId(1); p4.setQuantity(5); p4.setOrderId(2); p4.setProductId(2); List<Product> productList = new ArrayList<>(); productList.add(p1); productList.add(p2); productList.add(p3); productList.add(p4); CalculateService calculateService = new CalculateServiceImpl(); Assert.assertEquals(calculateService.getTotalNoOfItemSold(productList),20); } @Test public void testGetAvgNoOfItemPerOrder() { Product p1 = new Product(); p1.setCountryId("DEU"); p1.setDay(LocalDate.now()); p1.setPricePerItem(new BigDecimal(10.0)); p1.setProductCategoryId(1); p1.setQuantity(5); p1.setOrderId(1); p1.setProductId(2); Product p2 = new Product(); p2.setCountryId("DEU"); p2.setDay(LocalDate.now()); p2.setPricePerItem(new BigDecimal(10.0)); p2.setProductCategoryId(1); p2.setQuantity(5); p2.setOrderId(1); p2.setProductId(2); Product p3 = new Product(); p3.setCountryId("DEU"); p3.setDay(LocalDate.now()); p3.setPricePerItem(new BigDecimal(10.0)); p3.setProductCategoryId(1); p3.setQuantity(5); p3.setOrderId(1); p3.setProductId(2); Product p4 = new Product(); p4.setCountryId("DEU"); p4.setDay(LocalDate.now()); p4.setPricePerItem(new BigDecimal(10.0)); p4.setProductCategoryId(1); p4.setQuantity(5); p4.setOrderId(2); p4.setProductId(2); List<Product> productList = new ArrayList<>(); productList.add(p1); productList.add(p2); productList.add(p3); productList.add(p4); CalculateService calculateService = new CalculateServiceImpl(); Assert.assertEquals(calculateService.getAvgNoOfItemPerOrder(productList),10); } @Test public void testGetAvgNoOfOrderPerDay() { Product p1 = new Product(); p1.setCountryId("DEU"); p1.setDay(LocalDate.now()); p1.setPricePerItem(new BigDecimal(10.0)); p1.setProductCategoryId(1); p1.setQuantity(5); p1.setOrderId(1); p1.setProductId(2); Product p2 = new Product(); p2.setCountryId("DEU"); p2.setDay(LocalDate.now()); p2.setPricePerItem(new BigDecimal(10.0)); p2.setProductCategoryId(1); p2.setQuantity(5); p2.setOrderId(1); p2.setProductId(2); Product p3 = new Product(); p3.setCountryId("DEU"); p3.setDay(LocalDate.now()); p3.setPricePerItem(new BigDecimal(10.0)); p3.setProductCategoryId(1); p3.setQuantity(5); p3.setOrderId(1); p3.setProductId(2); Product p4 = new Product(); p4.setCountryId("DEU"); p4.setDay(LocalDate.now()); p4.setPricePerItem(new BigDecimal(10.0)); p4.setProductCategoryId(1); p4.setQuantity(5); p4.setOrderId(2); p4.setProductId(2); List<Product> productList = new ArrayList<>(); productList.add(p1); productList.add(p2); productList.add(p3); productList.add(p4); CalculateService calculateService = new CalculateServiceImpl(); Assert.assertEquals(calculateService.getAvgNoOfOrderPerDay(productList),2); } }
package com.bon.common.util; /** * @program: dubbo-wxmanage * @description: token工具类 * @author: Bon * @create: 2018-05-23 18:20 **/ public class TokenUtil { }
package Testabcd; import org.openqa.selenium.By; public class OversizeShirt extends Utils { private By _OversizeShirt = By.xpath("//div[@class='product-name']"); private By _AddToCart = By.xpath("//input[@id='add-to-cart-button-28']"); private By _greenBarOnTop = By.xpath("//div[@id='bar-notification']"); //for refering item to friend private By _emailFriend = By.xpath("//input[@value='Email a friend']"); public void OversizeTshirtAsser() { Utils.assertMessagetext(_OversizeShirt); } public void AddProductToCart1() { Utils.clickingElement(_AddToCart); } // asserting the green bar of product add to cart conformation public void userShouldSeeGreenBarOnTop() { Utils.assertMessagetext(_greenBarOnTop); } //Refering Item to friend public void clickOnEmailFriend() { Utils.clickingElement(_emailFriend); } }
package org.noear.solonboot.protocol; import org.noear.solonboot.XContext; /** 通用代理 */ @FunctionalInterface public interface XHandler { /** 处理 */ void handle(XContext context) throws Exception; }
package Sorting; /** * Created by Maaz on 7/15/2016. */ import java.io.*; import java.util.*; public class runningTimeOfAlgorithms { public static void main(String[] args) { /* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */ Scanner scan = new Scanner(System.in); int n = scan.nextInt(); int[] arr = new int[n]; for(int i=0;i<n;i++) arr[i] = scan.nextInt(); int shifts = 0; for(int i=1;i<n;i++){ int j = i-1; int key = arr[i]; while((j>=0)&&(arr[j]>key)){ arr[j+1] = arr[j]; shifts++; j--; } arr[j+1] = key; } System.out.println(shifts); } }
package com.metoo.msg.email; import org.springframework.expression.ParserContext; /** * * <p>Title: SpelTemplate.java</p> * <p> * Description:自定义SPEL模板。定义为以${#user.userName} 获取 user对象的userName。 </p> * <p>Copyright: Copyright (c) 2015</p> * <p>Company: 沈阳网之商科技有限公司 www.koala.com</p> * @author jinxinzhe * @date 2015-2-27 * @version koala_b2b2c 2015 */ public class SpelTemplate implements ParserContext{ @Override public String getExpressionPrefix() { // TODO Auto-generated method stub return "${"; } @Override public String getExpressionSuffix() { // TODO Auto-generated method stub return "}"; } @Override public boolean isTemplate() { // TODO Auto-generated method stub return true; } }
package damiano_p1; import java.util.Scanner; public class decryption { public static void main(String[] args) { //Decryption Scanner scnr = new Scanner(System.in); int[] data = new int[4]; int i,a,b,c,d,in; System.out.println("Please enter encrypted 4 digits:"); in =scnr.nextInt(); data[0]= in/1000; data[1]= (in %1000)/100; data[2]= ((in % 1000) % 100) / 10; data[3]= (((in % 1000) % 100) % 10); a = (data[2]+3)%10; b = (data[3]+3)%10; c = (data[0]+3)%10; d = (data[1]+3)%10; data[0] = a; data[1] = b; data[2] = c; data[3] = d; for (i=0; i<4;i++) { System.out.print(data[i]); } } }
package frc.robot; import edu.wpi.first.cameraserver.CameraServer; import edu.wpi.first.wpilibj.Compressor; import edu.wpi.first.wpilibj.DoubleSolenoid; import edu.wpi.first.wpilibj.TimedRobot; import edu.wpi.first.wpilibj.Joystick; import edu.wpi.first.wpilibj.Spark; import edu.wpi.first.wpilibj.SpeedControllerGroup; import edu.wpi.first.wpilibj.Victor; import edu.wpi.first.wpilibj.drive.DifferentialDrive; import edu.wpi.first.wpilibj.smartdashboard.SendableChooser; import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard; public class Robot extends TimedRobot { // Constants for the autonomous period private final String c_autoDefault = "Default"; // The different autonomous modes are handled in a switch statement private String m_autoSelected; private final SendableChooser<String> m_chooser = new SendableChooser<>(); // This is the main joystick Joystick m_flightStick = new Joystick(0); // Axis(0): X axis (left and right) // Axis(1): Y axis (forward and backwards) // Axis(2): Z axis (rotation) // Axis(3): Slider (rotating flap thing at the back of controller) // Dogtail motor/speed controllers Victor m_dogtailLeft = new Victor(4); Victor m_dogtailRight = new Victor(5); // Motor that controls if the dogtail if raised or lowered Spark m_dogtailPos = new Spark(7); // Drivetrain motor/speed controllers Spark m_leftFront = new Spark(0); // Green motor Spark m_leftBack = new Spark(1); // Yellow motor Spark m_rightFront = new Spark(2); // Blue motor Spark m_rightBack = new Spark(3); // White motor // Group drivetrain motors into sides SpeedControllerGroup m_motorsLeft = new SpeedControllerGroup(m_leftFront, m_leftBack); SpeedControllerGroup m_motorsRight = new SpeedControllerGroup(m_rightFront, m_rightBack); // Group motor sides together together DifferentialDrive m_drive = new DifferentialDrive(m_motorsLeft, m_motorsRight); // Compressor Compressor m_compressor = new Compressor(0); // Solenoids for manipulating the claw DoubleSolenoid m_solenoidClawPos = new DoubleSolenoid(0, 1); DoubleSolenoid m_solenoidClawGrab = new DoubleSolenoid(2, 3); // Solenoids for raising the robot DoubleSolenoid m_solenoidFrontRaise = new DoubleSolenoid(4, 5); DoubleSolenoid m_solenoidBackRaise = new DoubleSolenoid(6, 7); /** * This function is run when the robot is first started up and should be used * for any initialization code. */ @Override public void robotInit() { CameraServer.getInstance().startAutomaticCapture(); m_chooser.setDefaultOption("Default Auto", c_autoDefault); SmartDashboard.putData("Auto choices", m_chooser); System.out.println("** // Robot Ready // **"); m_compressor.start(); m_compressor.setClosedLoopControl(true); } /** * This autonomous (along with the chooser code above) shows how to select * between different autonomous modes using the dashboard. The sendable chooser * code works with the Java SmartDashboard. If you prefer the LabVIEW Dashboard, * remove all of the chooser code and uncomment the getString line to get the * auto name from the text box below the Gyro * * <p> * You can add additional auto modes by adding additional comparisons to the * switch structure below with additional strings. If using the SendableChooser * make sure to add them to the chooser code above as well. */ @Override public void autonomousInit() { m_autoSelected = m_chooser.getSelected(); } /** * CUSTOM * This function is a custom one that is used for raising or lowering a * certain solenoid based up a pair of buttons This function abstracts this away * so that the same code is not written 4 times for each solenoid */ private void activateSolenoid(boolean extend, boolean retract, DoubleSolenoid solenoid) { if (extend == retract) // We don't want to make a decision if both triggers are equal solenoid.set(DoubleSolenoid.Value.kOff); else if (extend) solenoid.set(DoubleSolenoid.Value.kForward); else if (retract) solenoid.set(DoubleSolenoid.Value.kReverse); } /** * CUSTOM * This function is a custom one that contain all the code for * controlling the robot This is to prevent rewriting the exact same code within * "autonomousPeriodic()" and "teleopPeriodic()" because of the ability for the driver * to control the robot (able to see only with the camera) during the autonomous period */ private void defaultControl() { // Main robot movement controls double robotRotate = m_flightStick.getRawAxis(0); // X axis is throttle double robotForward = m_flightStick.getRawAxis(1); // Y axis is rotation m_drive.arcadeDrive(-robotForward, robotRotate); // Dogtail movement controls boolean dogtailForward = m_flightStick.getRawButton(5); boolean dogtailBackward = m_flightStick.getRawButton(3); final double dogtailMoveSpeed = 1.0; if (dogtailForward == dogtailBackward) // Don't want to make a decision if the buttons in the same state { m_dogtailLeft.set(0); m_dogtailRight.set(0); } else if (dogtailForward) { m_dogtailLeft.set(-dogtailMoveSpeed); m_dogtailRight.set(dogtailMoveSpeed); } else if (dogtailBackward) { m_dogtailLeft.set(dogtailMoveSpeed); m_dogtailRight.set(-dogtailMoveSpeed); } // Dogtail raising and lowering controls boolean dogtailLower = m_flightStick.getRawButton(7); boolean dogtailRaise = m_flightStick.getRawButton(9); final double dogtailPosSpeed = .60; if (dogtailLower == dogtailRaise) // Don't make a decision if the buttons are in the same state m_dogtailPos.set(0); else if (dogtailLower) m_dogtailPos.set(-dogtailPosSpeed); else if (dogtailRaise) m_dogtailPos.set(dogtailPosSpeed); // This controls the position of the claw (if it is up and low) boolean clawUp = m_flightStick.getRawButton(2); boolean clawDown = m_flightStick.getRawButton(1); activateSolenoid(clawUp, clawDown, m_solenoidClawPos); // This controls whether the claw is ejected or not // The claw is folded in order fit within the required space boolean clawOpen = m_flightStick.getRawButton(4); // Opening the claw grabs the hatch panel boolean clawClose = m_flightStick.getRawButton(6); // Closing the claw releases the hatch panel activateSolenoid(clawOpen, clawClose, m_solenoidClawGrab); // Robot lifting controls boolean robotUp = m_flightStick.getRawButton(12); boolean frontDown = m_flightStick.getRawButton(8); boolean backDown = m_flightStick.getRawButton(10); activateSolenoid(robotUp, frontDown, m_solenoidFrontRaise); activateSolenoid(robotUp, backDown, m_solenoidBackRaise); } /** * This function is called periodically during autonomous. */ @Override public void autonomousPeriodic() { switch (m_autoSelected) { case c_autoDefault: default: // The case should never really be default defaultControl(); break; } } /** * This function is called periodically during operator control. */ @Override public void teleopPeriodic() { defaultControl(); } }
package networking; public class ServerSHandler { }
package com.springbook.biz.board.impl; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.util.ArrayList; import java.util.List; import org.springframework.stereotype.Repository; import com.springbook.biz.board.BoardVO; import com.springbook.biz.common.JDBCUtil; //DAO(Data Access Object) @Repository("boardDAO") public class BoardDAO { //JDBC관련 변수 private Connection c= null; private PreparedStatement ps = null; private ResultSet rs = null; //SQL명령어 private final String BOARD_INSERT = " insert into board(seq, title, writer, content) " + " values((select nvl(max(seq),0)+1 from board),?,?,? ) "; private final String BOARD_UPDATE = " update board set title = ?, content = ? , where seq = ? "; private final String BOARD_DELETE = " delete board where seq = ? "; private final String BOARD_GET = " select * from board where seq = ? "; private final String BOARD_LIST = " select * from board order by seq desc "; //CRUD 기능의 메소드 구현 //글등록 public void insertBoard(BoardVO vo) { System.out.println("===>JDBC로 insertBoard()기능 처리"); try { c = JDBCUtil.getConnection(); ps = c.prepareStatement(BOARD_INSERT); ps.setString(1, vo.getTitle()); ps.setString(2, vo.getWriter()); ps.setString(3, vo.getContent()); ps.executeQuery(); } catch (Exception e) { e.printStackTrace(); }finally { JDBCUtil.close(null, ps, c); } } // 글 수정 public void updateBoard(BoardVO vo) { System.out.println("===>JDBC로 updateBoard()기능 처리"); try { c = JDBCUtil.getConnection(); ps = c.prepareStatement(BOARD_UPDATE); ps.setString(1, vo.getTitle()); ps.setString(2, vo.getContent()); ps.setInt(3, vo.getSeq()); ps.executeQuery(); } catch (Exception e) { e.printStackTrace(); }finally { JDBCUtil.close(rs, ps, c); } } // 글 삭제 public void deleteBoard(BoardVO vo) { System.out.println("===>JDBC로 deleteBoard()기능 처리"); try { c = JDBCUtil.getConnection(); ps = c.prepareStatement(BOARD_DELETE); ps.setInt(1, vo.getSeq()); ps.executeQuery(); } catch (Exception e) { e.printStackTrace(); }finally { JDBCUtil.close(rs, ps, c); } } // 글 상세 조회 public BoardVO getBoard(BoardVO vo) { BoardVO board = null; try { c = JDBCUtil.getConnection(); ps = c.prepareStatement(BOARD_GET); ps.setInt(1, vo.getSeq()); rs = ps.executeQuery(); while(rs.next()) { board = new BoardVO(); board.setSeq(rs.getInt("seq")); board.setCnt(rs.getInt("cnt")); board.setContent(rs.getString("content")); board.setRegdate(rs.getDate("regdate")); board.setTitle(rs.getString("title")); board.setWriter(rs.getString("writer")); } } catch (Exception e) { // TODO: handle exception } finally { JDBCUtil.close(rs, ps, c); } return board; } //글 목록 조회 public List<BoardVO> getBoardList(BoardVO vo) { System.out.println("===> JDBC로 getBoardList()기능 처리"); List<BoardVO> list = new ArrayList<BoardVO>(); try { c = JDBCUtil.getConnection(); ps = c.prepareStatement(BOARD_LIST); rs = ps.executeQuery(); while(rs.next()) { BoardVO board = new BoardVO(); board.setSeq(rs.getInt("seq")); board.setCnt(rs.getInt("cnt")); board.setContent(rs.getString("content")); board.setRegdate(rs.getDate("regdate")); board.setTitle(rs.getString("title")); board.setWriter(rs.getString("writer")); list.add(board); } } catch (Exception e) { e.printStackTrace(); } finally { JDBCUtil.close(rs, ps, c); } return list; } }
/* * Copyright 2013 Basho Technologies Inc * * 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.basho.riak.client.api.commands.datatypes; import com.basho.riak.client.core.query.crdt.ops.RegisterOp; import com.basho.riak.client.core.util.BinaryValue; /** * An update to a Riak register datatype. * <p> * When building an {@link UpdateMap} command * this class is used to encapsulate the update to be performed on a * Riak register datatype contained in the map. It is used in conjunction with the * {@link MapUpdate}. * </p> * @author Dave Rusek <drusek at basho dot com> * @since 2.0 */ public class RegisterUpdate implements DatatypeUpdate { private final BinaryValue value; /** * Construct a RegisterUpdate with the provided bytes. * @param value the bytes representing the register. */ public RegisterUpdate(byte[] value) { this.value = BinaryValue.create(value); } /** * Construct a RegisterUpdate with the provided BinaryValue. * @param value the BinaryValue representing the register. */ public RegisterUpdate(BinaryValue value) { this.value = value; } /** * Construct a RegisterUpdate with the provided String. * <p> * Note the String is converted to bytes using the default Charset. * </p> * @param value the String representing the register. */ public RegisterUpdate(String value) { this.value = BinaryValue.create(value); } /** * Get the register contained in this update. * @return the register as a BinaryValue. */ public BinaryValue get() { return value; } /** * Returns the core update. * @return the update used by the client core. */ @Override public RegisterOp getOp() { return new RegisterOp(value); } @Override public String toString() { return value.toString(); } }
// ASM: a very small and fast Java bytecode manipulation framework // Copyright (c) 2000-2011 INRIA, France Telecom // 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 the copyright holders nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS 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 THE COPYRIGHT OWNER 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.springframework.asm; /** * A {@link ClassVisitor} that generates a corresponding ClassFile structure, as defined in the Java * Virtual Machine Specification (JVMS). It can be used alone, to generate a Java class "from * scratch", or with one or more {@link ClassReader} and adapter {@link ClassVisitor} to generate a * modified class from one or more existing Java classes. * * @see <a href="https://docs.oracle.com/javase/specs/jvms/se9/html/jvms-4.html">JVMS 4</a> * @author Eric Bruneton */ public class ClassWriter extends ClassVisitor { /** * A flag to automatically compute the maximum stack size and the maximum number of local * variables of methods. If this flag is set, then the arguments of the {@link * MethodVisitor#visitMaxs} method of the {@link MethodVisitor} returned by the {@link * #visitMethod} method will be ignored, and computed automatically from the signature and the * bytecode of each method. * * <p><b>Note:</b> for classes whose version is {@link Opcodes#V1_7} of more, this option requires * valid stack map frames. The maximum stack size is then computed from these frames, and from the * bytecode instructions in between. If stack map frames are not present or must be recomputed, * used {@link #COMPUTE_FRAMES} instead. * * @see #ClassWriter(int) */ public static final int COMPUTE_MAXS = 1; /** * A flag to automatically compute the stack map frames of methods from scratch. If this flag is * set, then the calls to the {@link MethodVisitor#visitFrame} method are ignored, and the stack * map frames are recomputed from the methods bytecode. The arguments of the {@link * MethodVisitor#visitMaxs} method are also ignored and recomputed from the bytecode. In other * words, {@link #COMPUTE_FRAMES} implies {@link #COMPUTE_MAXS}. * * @see #ClassWriter(int) */ public static final int COMPUTE_FRAMES = 2; /** * The flags passed to the constructor. Must be zero or more of {@link #COMPUTE_MAXS} and {@link * #COMPUTE_FRAMES}. */ private final int flags; // Note: fields are ordered as in the ClassFile structure, and those related to attributes are // ordered as in Section 4.7 of the JVMS. /** * The minor_version and major_version fields of the JVMS ClassFile structure. minor_version is * stored in the 16 most significant bits, and major_version in the 16 least significant bits. */ private int version; /** The symbol table for this class (contains the constant_pool and the BootstrapMethods). */ private final SymbolTable symbolTable; /** * The access_flags field of the JVMS ClassFile structure. This field can contain ASM specific * access flags, such as {@link Opcodes#ACC_DEPRECATED} or {@link Opcodes#ACC_RECORD}, which are * removed when generating the ClassFile structure. */ private int accessFlags; /** The this_class field of the JVMS ClassFile structure. */ private int thisClass; /** The super_class field of the JVMS ClassFile structure. */ private int superClass; /** The interface_count field of the JVMS ClassFile structure. */ private int interfaceCount; /** The 'interfaces' array of the JVMS ClassFile structure. */ private int[] interfaces; /** * The fields of this class, stored in a linked list of {@link FieldWriter} linked via their * {@link FieldWriter#fv} field. This field stores the first element of this list. */ private FieldWriter firstField; /** * The fields of this class, stored in a linked list of {@link FieldWriter} linked via their * {@link FieldWriter#fv} field. This field stores the last element of this list. */ private FieldWriter lastField; /** * The methods of this class, stored in a linked list of {@link MethodWriter} linked via their * {@link MethodWriter#mv} field. This field stores the first element of this list. */ private MethodWriter firstMethod; /** * The methods of this class, stored in a linked list of {@link MethodWriter} linked via their * {@link MethodWriter#mv} field. This field stores the last element of this list. */ private MethodWriter lastMethod; /** The number_of_classes field of the InnerClasses attribute, or 0. */ private int numberOfInnerClasses; /** The 'classes' array of the InnerClasses attribute, or {@literal null}. */ private ByteVector innerClasses; /** The class_index field of the EnclosingMethod attribute, or 0. */ private int enclosingClassIndex; /** The method_index field of the EnclosingMethod attribute. */ private int enclosingMethodIndex; /** The signature_index field of the Signature attribute, or 0. */ private int signatureIndex; /** The source_file_index field of the SourceFile attribute, or 0. */ private int sourceFileIndex; /** The debug_extension field of the SourceDebugExtension attribute, or {@literal null}. */ private ByteVector debugExtension; /** * The last runtime visible annotation of this class. The previous ones can be accessed with the * {@link AnnotationWriter#previousAnnotation} field. May be {@literal null}. */ private AnnotationWriter lastRuntimeVisibleAnnotation; /** * The last runtime invisible annotation of this class. The previous ones can be accessed with the * {@link AnnotationWriter#previousAnnotation} field. May be {@literal null}. */ private AnnotationWriter lastRuntimeInvisibleAnnotation; /** * The last runtime visible type annotation of this class. The previous ones can be accessed with * the {@link AnnotationWriter#previousAnnotation} field. May be {@literal null}. */ private AnnotationWriter lastRuntimeVisibleTypeAnnotation; /** * The last runtime invisible type annotation of this class. The previous ones can be accessed * with the {@link AnnotationWriter#previousAnnotation} field. May be {@literal null}. */ private AnnotationWriter lastRuntimeInvisibleTypeAnnotation; /** The Module attribute of this class, or {@literal null}. */ private ModuleWriter moduleWriter; /** The host_class_index field of the NestHost attribute, or 0. */ private int nestHostClassIndex; /** The number_of_classes field of the NestMembers attribute, or 0. */ private int numberOfNestMemberClasses; /** The 'classes' array of the NestMembers attribute, or {@literal null}. */ private ByteVector nestMemberClasses; /** The number_of_classes field of the PermittedSubclasses attribute, or 0. */ private int numberOfPermittedSubclasses; /** The 'classes' array of the PermittedSubclasses attribute, or {@literal null}. */ private ByteVector permittedSubclasses; /** * The record components of this class, stored in a linked list of {@link RecordComponentWriter} * linked via their {@link RecordComponentWriter#delegate} field. This field stores the first * element of this list. */ private RecordComponentWriter firstRecordComponent; /** * The record components of this class, stored in a linked list of {@link RecordComponentWriter} * linked via their {@link RecordComponentWriter#delegate} field. This field stores the last * element of this list. */ private RecordComponentWriter lastRecordComponent; /** * The first non standard attribute of this class. The next ones can be accessed with the {@link * Attribute#nextAttribute} field. May be {@literal null}. * * <p><b>WARNING</b>: this list stores the attributes in the <i>reverse</i> order of their visit. * firstAttribute is actually the last attribute visited in {@link #visitAttribute}. The {@link * #toByteArray} method writes the attributes in the order defined by this list, i.e. in the * reverse order specified by the user. */ private Attribute firstAttribute; /** * Indicates what must be automatically computed in {@link MethodWriter}. Must be one of {@link * MethodWriter#COMPUTE_NOTHING}, {@link MethodWriter#COMPUTE_MAX_STACK_AND_LOCAL}, {@link * MethodWriter#COMPUTE_MAX_STACK_AND_LOCAL_FROM_FRAMES}, {@link * MethodWriter#COMPUTE_INSERTED_FRAMES}, or {@link MethodWriter#COMPUTE_ALL_FRAMES}. */ private int compute; // ----------------------------------------------------------------------------------------------- // Constructor // ----------------------------------------------------------------------------------------------- /** * Constructs a new {@link ClassWriter} object. * * @param flags option flags that can be used to modify the default behavior of this class. Must * be zero or more of {@link #COMPUTE_MAXS} and {@link #COMPUTE_FRAMES}. */ public ClassWriter(final int flags) { this(null, flags); } /** * Constructs a new {@link ClassWriter} object and enables optimizations for "mostly add" bytecode * transformations. These optimizations are the following: * * <ul> * <li>The constant pool and bootstrap methods from the original class are copied as is in the * new class, which saves time. New constant pool entries and new bootstrap methods will be * added at the end if necessary, but unused constant pool entries or bootstrap methods * <i>won't be removed</i>. * <li>Methods that are not transformed are copied as is in the new class, directly from the * original class bytecode (i.e. without emitting visit events for all the method * instructions), which saves a <i>lot</i> of time. Untransformed methods are detected by * the fact that the {@link ClassReader} receives {@link MethodVisitor} objects that come * from a {@link ClassWriter} (and not from any other {@link ClassVisitor} instance). * </ul> * * @param classReader the {@link ClassReader} used to read the original class. It will be used to * copy the entire constant pool and bootstrap methods from the original class and also to * copy other fragments of original bytecode where applicable. * @param flags option flags that can be used to modify the default behavior of this class. Must * be zero or more of {@link #COMPUTE_MAXS} and {@link #COMPUTE_FRAMES}. <i>These option flags * do not affect methods that are copied as is in the new class. This means that neither the * maximum stack size nor the stack frames will be computed for these methods</i>. */ public ClassWriter(final ClassReader classReader, final int flags) { super(/* latest api = */ Opcodes.ASM9); this.flags = flags; symbolTable = classReader == null ? new SymbolTable(this) : new SymbolTable(this, classReader); if ((flags & COMPUTE_FRAMES) != 0) { compute = MethodWriter.COMPUTE_ALL_FRAMES; } else if ((flags & COMPUTE_MAXS) != 0) { compute = MethodWriter.COMPUTE_MAX_STACK_AND_LOCAL; } else { compute = MethodWriter.COMPUTE_NOTHING; } } // ----------------------------------------------------------------------------------------------- // Accessors // ----------------------------------------------------------------------------------------------- /** * Returns true if all the given flags were passed to the constructor. * * @param flags some option flags. Must be zero or more of {@link #COMPUTE_MAXS} and {@link * #COMPUTE_FRAMES}. * @return true if all the given flags, or more, were passed to the constructor. */ public boolean hasFlags(final int flags) { return (this.flags & flags) == flags; } // ----------------------------------------------------------------------------------------------- // Implementation of the ClassVisitor abstract class // ----------------------------------------------------------------------------------------------- @Override public final void visit( final int version, final int access, final String name, final String signature, final String superName, final String[] interfaces) { this.version = version; this.accessFlags = access; this.thisClass = symbolTable.setMajorVersionAndClassName(version & 0xFFFF, name); if (signature != null) { this.signatureIndex = symbolTable.addConstantUtf8(signature); } this.superClass = superName == null ? 0 : symbolTable.addConstantClass(superName).index; if (interfaces != null && interfaces.length > 0) { interfaceCount = interfaces.length; this.interfaces = new int[interfaceCount]; for (int i = 0; i < interfaceCount; ++i) { this.interfaces[i] = symbolTable.addConstantClass(interfaces[i]).index; } } if (compute == MethodWriter.COMPUTE_MAX_STACK_AND_LOCAL && (version & 0xFFFF) >= Opcodes.V1_7) { compute = MethodWriter.COMPUTE_MAX_STACK_AND_LOCAL_FROM_FRAMES; } } @Override public final void visitSource(final String file, final String debug) { if (file != null) { sourceFileIndex = symbolTable.addConstantUtf8(file); } if (debug != null) { debugExtension = new ByteVector().encodeUtf8(debug, 0, Integer.MAX_VALUE); } } @Override public final ModuleVisitor visitModule( final String name, final int access, final String version) { return moduleWriter = new ModuleWriter( symbolTable, symbolTable.addConstantModule(name).index, access, version == null ? 0 : symbolTable.addConstantUtf8(version)); } @Override public final void visitNestHost(final String nestHost) { nestHostClassIndex = symbolTable.addConstantClass(nestHost).index; } @Override public final void visitOuterClass( final String owner, final String name, final String descriptor) { enclosingClassIndex = symbolTable.addConstantClass(owner).index; if (name != null && descriptor != null) { enclosingMethodIndex = symbolTable.addConstantNameAndType(name, descriptor); } } @Override public final AnnotationVisitor visitAnnotation(final String descriptor, final boolean visible) { if (visible) { return lastRuntimeVisibleAnnotation = AnnotationWriter.create(symbolTable, descriptor, lastRuntimeVisibleAnnotation); } else { return lastRuntimeInvisibleAnnotation = AnnotationWriter.create(symbolTable, descriptor, lastRuntimeInvisibleAnnotation); } } @Override public final AnnotationVisitor visitTypeAnnotation( final int typeRef, final TypePath typePath, final String descriptor, final boolean visible) { if (visible) { return lastRuntimeVisibleTypeAnnotation = AnnotationWriter.create( symbolTable, typeRef, typePath, descriptor, lastRuntimeVisibleTypeAnnotation); } else { return lastRuntimeInvisibleTypeAnnotation = AnnotationWriter.create( symbolTable, typeRef, typePath, descriptor, lastRuntimeInvisibleTypeAnnotation); } } @Override public final void visitAttribute(final Attribute attribute) { // Store the attributes in the <i>reverse</i> order of their visit by this method. attribute.nextAttribute = firstAttribute; firstAttribute = attribute; } @Override public final void visitNestMember(final String nestMember) { if (nestMemberClasses == null) { nestMemberClasses = new ByteVector(); } ++numberOfNestMemberClasses; nestMemberClasses.putShort(symbolTable.addConstantClass(nestMember).index); } @Override public final void visitPermittedSubclass(final String permittedSubclass) { if (permittedSubclasses == null) { permittedSubclasses = new ByteVector(); } ++numberOfPermittedSubclasses; permittedSubclasses.putShort(symbolTable.addConstantClass(permittedSubclass).index); } @Override public final void visitInnerClass( final String name, final String outerName, final String innerName, final int access) { if (innerClasses == null) { innerClasses = new ByteVector(); } // Section 4.7.6 of the JVMS states "Every CONSTANT_Class_info entry in the constant_pool table // which represents a class or interface C that is not a package member must have exactly one // corresponding entry in the classes array". To avoid duplicates we keep track in the info // field of the Symbol of each CONSTANT_Class_info entry C whether an inner class entry has // already been added for C. If so, we store the index of this inner class entry (plus one) in // the info field. This trick allows duplicate detection in O(1) time. Symbol nameSymbol = symbolTable.addConstantClass(name); if (nameSymbol.info == 0) { ++numberOfInnerClasses; innerClasses.putShort(nameSymbol.index); innerClasses.putShort(outerName == null ? 0 : symbolTable.addConstantClass(outerName).index); innerClasses.putShort(innerName == null ? 0 : symbolTable.addConstantUtf8(innerName)); innerClasses.putShort(access); nameSymbol.info = numberOfInnerClasses; } // Else, compare the inner classes entry nameSymbol.info - 1 with the arguments of this method // and throw an exception if there is a difference? } @Override public final RecordComponentVisitor visitRecordComponent( final String name, final String descriptor, final String signature) { RecordComponentWriter recordComponentWriter = new RecordComponentWriter(symbolTable, name, descriptor, signature); if (firstRecordComponent == null) { firstRecordComponent = recordComponentWriter; } else { lastRecordComponent.delegate = recordComponentWriter; } return lastRecordComponent = recordComponentWriter; } @Override public final FieldVisitor visitField( final int access, final String name, final String descriptor, final String signature, final Object value) { FieldWriter fieldWriter = new FieldWriter(symbolTable, access, name, descriptor, signature, value); if (firstField == null) { firstField = fieldWriter; } else { lastField.fv = fieldWriter; } return lastField = fieldWriter; } @Override public final MethodVisitor visitMethod( final int access, final String name, final String descriptor, final String signature, final String[] exceptions) { MethodWriter methodWriter = new MethodWriter(symbolTable, access, name, descriptor, signature, exceptions, compute); if (firstMethod == null) { firstMethod = methodWriter; } else { lastMethod.mv = methodWriter; } return lastMethod = methodWriter; } @Override public final void visitEnd() { // Nothing to do. } // ----------------------------------------------------------------------------------------------- // Other public methods // ----------------------------------------------------------------------------------------------- /** * Returns the content of the class file that was built by this ClassWriter. * * @return the binary content of the JVMS ClassFile structure that was built by this ClassWriter. * @throws ClassTooLargeException if the constant pool of the class is too large. * @throws MethodTooLargeException if the Code attribute of a method is too large. */ public byte[] toByteArray() { // First step: compute the size in bytes of the ClassFile structure. // The magic field uses 4 bytes, 10 mandatory fields (minor_version, major_version, // constant_pool_count, access_flags, this_class, super_class, interfaces_count, fields_count, // methods_count and attributes_count) use 2 bytes each, and each interface uses 2 bytes too. int size = 24 + 2 * interfaceCount; int fieldsCount = 0; FieldWriter fieldWriter = firstField; while (fieldWriter != null) { ++fieldsCount; size += fieldWriter.computeFieldInfoSize(); fieldWriter = (FieldWriter) fieldWriter.fv; } int methodsCount = 0; MethodWriter methodWriter = firstMethod; while (methodWriter != null) { ++methodsCount; size += methodWriter.computeMethodInfoSize(); methodWriter = (MethodWriter) methodWriter.mv; } // For ease of reference, we use here the same attribute order as in Section 4.7 of the JVMS. int attributesCount = 0; if (innerClasses != null) { ++attributesCount; size += 8 + innerClasses.length; symbolTable.addConstantUtf8(Constants.INNER_CLASSES); } if (enclosingClassIndex != 0) { ++attributesCount; size += 10; symbolTable.addConstantUtf8(Constants.ENCLOSING_METHOD); } if ((accessFlags & Opcodes.ACC_SYNTHETIC) != 0 && (version & 0xFFFF) < Opcodes.V1_5) { ++attributesCount; size += 6; symbolTable.addConstantUtf8(Constants.SYNTHETIC); } if (signatureIndex != 0) { ++attributesCount; size += 8; symbolTable.addConstantUtf8(Constants.SIGNATURE); } if (sourceFileIndex != 0) { ++attributesCount; size += 8; symbolTable.addConstantUtf8(Constants.SOURCE_FILE); } if (debugExtension != null) { ++attributesCount; size += 6 + debugExtension.length; symbolTable.addConstantUtf8(Constants.SOURCE_DEBUG_EXTENSION); } if ((accessFlags & Opcodes.ACC_DEPRECATED) != 0) { ++attributesCount; size += 6; symbolTable.addConstantUtf8(Constants.DEPRECATED); } if (lastRuntimeVisibleAnnotation != null) { ++attributesCount; size += lastRuntimeVisibleAnnotation.computeAnnotationsSize( Constants.RUNTIME_VISIBLE_ANNOTATIONS); } if (lastRuntimeInvisibleAnnotation != null) { ++attributesCount; size += lastRuntimeInvisibleAnnotation.computeAnnotationsSize( Constants.RUNTIME_INVISIBLE_ANNOTATIONS); } if (lastRuntimeVisibleTypeAnnotation != null) { ++attributesCount; size += lastRuntimeVisibleTypeAnnotation.computeAnnotationsSize( Constants.RUNTIME_VISIBLE_TYPE_ANNOTATIONS); } if (lastRuntimeInvisibleTypeAnnotation != null) { ++attributesCount; size += lastRuntimeInvisibleTypeAnnotation.computeAnnotationsSize( Constants.RUNTIME_INVISIBLE_TYPE_ANNOTATIONS); } if (symbolTable.computeBootstrapMethodsSize() > 0) { ++attributesCount; size += symbolTable.computeBootstrapMethodsSize(); } if (moduleWriter != null) { attributesCount += moduleWriter.getAttributeCount(); size += moduleWriter.computeAttributesSize(); } if (nestHostClassIndex != 0) { ++attributesCount; size += 8; symbolTable.addConstantUtf8(Constants.NEST_HOST); } if (nestMemberClasses != null) { ++attributesCount; size += 8 + nestMemberClasses.length; symbolTable.addConstantUtf8(Constants.NEST_MEMBERS); } if (permittedSubclasses != null) { ++attributesCount; size += 8 + permittedSubclasses.length; symbolTable.addConstantUtf8(Constants.PERMITTED_SUBCLASSES); } int recordComponentCount = 0; int recordSize = 0; if ((accessFlags & Opcodes.ACC_RECORD) != 0 || firstRecordComponent != null) { RecordComponentWriter recordComponentWriter = firstRecordComponent; while (recordComponentWriter != null) { ++recordComponentCount; recordSize += recordComponentWriter.computeRecordComponentInfoSize(); recordComponentWriter = (RecordComponentWriter) recordComponentWriter.delegate; } ++attributesCount; size += 8 + recordSize; symbolTable.addConstantUtf8(Constants.RECORD); } if (firstAttribute != null) { attributesCount += firstAttribute.getAttributeCount(); size += firstAttribute.computeAttributesSize(symbolTable); } // IMPORTANT: this must be the last part of the ClassFile size computation, because the previous // statements can add attribute names to the constant pool, thereby changing its size! size += symbolTable.getConstantPoolLength(); int constantPoolCount = symbolTable.getConstantPoolCount(); if (constantPoolCount > 0xFFFF) { throw new ClassTooLargeException(symbolTable.getClassName(), constantPoolCount); } // Second step: allocate a ByteVector of the correct size (in order to avoid any array copy in // dynamic resizes) and fill it with the ClassFile content. ByteVector result = new ByteVector(size); result.putInt(0xCAFEBABE).putInt(version); symbolTable.putConstantPool(result); int mask = (version & 0xFFFF) < Opcodes.V1_5 ? Opcodes.ACC_SYNTHETIC : 0; result.putShort(accessFlags & ~mask).putShort(thisClass).putShort(superClass); result.putShort(interfaceCount); for (int i = 0; i < interfaceCount; ++i) { result.putShort(interfaces[i]); } result.putShort(fieldsCount); fieldWriter = firstField; while (fieldWriter != null) { fieldWriter.putFieldInfo(result); fieldWriter = (FieldWriter) fieldWriter.fv; } result.putShort(methodsCount); boolean hasFrames = false; boolean hasAsmInstructions = false; methodWriter = firstMethod; while (methodWriter != null) { hasFrames |= methodWriter.hasFrames(); hasAsmInstructions |= methodWriter.hasAsmInstructions(); methodWriter.putMethodInfo(result); methodWriter = (MethodWriter) methodWriter.mv; } // For ease of reference, we use here the same attribute order as in Section 4.7 of the JVMS. result.putShort(attributesCount); if (innerClasses != null) { result .putShort(symbolTable.addConstantUtf8(Constants.INNER_CLASSES)) .putInt(innerClasses.length + 2) .putShort(numberOfInnerClasses) .putByteArray(innerClasses.data, 0, innerClasses.length); } if (enclosingClassIndex != 0) { result .putShort(symbolTable.addConstantUtf8(Constants.ENCLOSING_METHOD)) .putInt(4) .putShort(enclosingClassIndex) .putShort(enclosingMethodIndex); } if ((accessFlags & Opcodes.ACC_SYNTHETIC) != 0 && (version & 0xFFFF) < Opcodes.V1_5) { result.putShort(symbolTable.addConstantUtf8(Constants.SYNTHETIC)).putInt(0); } if (signatureIndex != 0) { result .putShort(symbolTable.addConstantUtf8(Constants.SIGNATURE)) .putInt(2) .putShort(signatureIndex); } if (sourceFileIndex != 0) { result .putShort(symbolTable.addConstantUtf8(Constants.SOURCE_FILE)) .putInt(2) .putShort(sourceFileIndex); } if (debugExtension != null) { int length = debugExtension.length; result .putShort(symbolTable.addConstantUtf8(Constants.SOURCE_DEBUG_EXTENSION)) .putInt(length) .putByteArray(debugExtension.data, 0, length); } if ((accessFlags & Opcodes.ACC_DEPRECATED) != 0) { result.putShort(symbolTable.addConstantUtf8(Constants.DEPRECATED)).putInt(0); } AnnotationWriter.putAnnotations( symbolTable, lastRuntimeVisibleAnnotation, lastRuntimeInvisibleAnnotation, lastRuntimeVisibleTypeAnnotation, lastRuntimeInvisibleTypeAnnotation, result); symbolTable.putBootstrapMethods(result); if (moduleWriter != null) { moduleWriter.putAttributes(result); } if (nestHostClassIndex != 0) { result .putShort(symbolTable.addConstantUtf8(Constants.NEST_HOST)) .putInt(2) .putShort(nestHostClassIndex); } if (nestMemberClasses != null) { result .putShort(symbolTable.addConstantUtf8(Constants.NEST_MEMBERS)) .putInt(nestMemberClasses.length + 2) .putShort(numberOfNestMemberClasses) .putByteArray(nestMemberClasses.data, 0, nestMemberClasses.length); } if (permittedSubclasses != null) { result .putShort(symbolTable.addConstantUtf8(Constants.PERMITTED_SUBCLASSES)) .putInt(permittedSubclasses.length + 2) .putShort(numberOfPermittedSubclasses) .putByteArray(permittedSubclasses.data, 0, permittedSubclasses.length); } if ((accessFlags & Opcodes.ACC_RECORD) != 0 || firstRecordComponent != null) { result .putShort(symbolTable.addConstantUtf8(Constants.RECORD)) .putInt(recordSize + 2) .putShort(recordComponentCount); RecordComponentWriter recordComponentWriter = firstRecordComponent; while (recordComponentWriter != null) { recordComponentWriter.putRecordComponentInfo(result); recordComponentWriter = (RecordComponentWriter) recordComponentWriter.delegate; } } if (firstAttribute != null) { firstAttribute.putAttributes(symbolTable, result); } // Third step: replace the ASM specific instructions, if any. if (hasAsmInstructions) { return replaceAsmInstructions(result.data, hasFrames); } else { return result.data; } } /** * Returns the equivalent of the given class file, with the ASM specific instructions replaced * with standard ones. This is done with a ClassReader -&gt; ClassWriter round trip. * * @param classFile a class file containing ASM specific instructions, generated by this * ClassWriter. * @param hasFrames whether there is at least one stack map frames in 'classFile'. * @return an equivalent of 'classFile', with the ASM specific instructions replaced with standard * ones. */ private byte[] replaceAsmInstructions(final byte[] classFile, final boolean hasFrames) { final Attribute[] attributes = getAttributePrototypes(); firstField = null; lastField = null; firstMethod = null; lastMethod = null; lastRuntimeVisibleAnnotation = null; lastRuntimeInvisibleAnnotation = null; lastRuntimeVisibleTypeAnnotation = null; lastRuntimeInvisibleTypeAnnotation = null; moduleWriter = null; nestHostClassIndex = 0; numberOfNestMemberClasses = 0; nestMemberClasses = null; numberOfPermittedSubclasses = 0; permittedSubclasses = null; firstRecordComponent = null; lastRecordComponent = null; firstAttribute = null; compute = hasFrames ? MethodWriter.COMPUTE_INSERTED_FRAMES : MethodWriter.COMPUTE_NOTHING; new ClassReader(classFile, 0, /* checkClassVersion = */ false) .accept( this, attributes, (hasFrames ? ClassReader.EXPAND_FRAMES : 0) | ClassReader.EXPAND_ASM_INSNS); return toByteArray(); } /** * Returns the prototypes of the attributes used by this class, its fields and its methods. * * @return the prototypes of the attributes used by this class, its fields and its methods. */ private Attribute[] getAttributePrototypes() { Attribute.Set attributePrototypes = new Attribute.Set(); attributePrototypes.addAttributes(firstAttribute); FieldWriter fieldWriter = firstField; while (fieldWriter != null) { fieldWriter.collectAttributePrototypes(attributePrototypes); fieldWriter = (FieldWriter) fieldWriter.fv; } MethodWriter methodWriter = firstMethod; while (methodWriter != null) { methodWriter.collectAttributePrototypes(attributePrototypes); methodWriter = (MethodWriter) methodWriter.mv; } RecordComponentWriter recordComponentWriter = firstRecordComponent; while (recordComponentWriter != null) { recordComponentWriter.collectAttributePrototypes(attributePrototypes); recordComponentWriter = (RecordComponentWriter) recordComponentWriter.delegate; } return attributePrototypes.toArray(); } // ----------------------------------------------------------------------------------------------- // Utility methods: constant pool management for Attribute sub classes // ----------------------------------------------------------------------------------------------- /** * Adds a number or string constant to the constant pool of the class being build. Does nothing if * the constant pool already contains a similar item. <i>This method is intended for {@link * Attribute} sub classes, and is normally not needed by class generators or adapters.</i> * * @param value the value of the constant to be added to the constant pool. This parameter must be * an {@link Integer}, a {@link Float}, a {@link Long}, a {@link Double} or a {@link String}. * @return the index of a new or already existing constant item with the given value. */ public int newConst(final Object value) { return symbolTable.addConstant(value).index; } /** * Adds an UTF8 string to the constant pool of the class being build. Does nothing if the constant * pool already contains a similar item. <i>This method is intended for {@link Attribute} sub * classes, and is normally not needed by class generators or adapters.</i> * * @param value the String value. * @return the index of a new or already existing UTF8 item. */ // DontCheck(AbbreviationAsWordInName): can't be renamed (for backward binary compatibility). public int newUTF8(final String value) { return symbolTable.addConstantUtf8(value); } /** * Adds a class reference to the constant pool of the class being build. Does nothing if the * constant pool already contains a similar item. <i>This method is intended for {@link Attribute} * sub classes, and is normally not needed by class generators or adapters.</i> * * @param value the internal name of the class (see {@link Type#getInternalName()}). * @return the index of a new or already existing class reference item. */ public int newClass(final String value) { return symbolTable.addConstantClass(value).index; } /** * Adds a method type reference to the constant pool of the class being build. Does nothing if the * constant pool already contains a similar item. <i>This method is intended for {@link Attribute} * sub classes, and is normally not needed by class generators or adapters.</i> * * @param methodDescriptor method descriptor of the method type. * @return the index of a new or already existing method type reference item. */ public int newMethodType(final String methodDescriptor) { return symbolTable.addConstantMethodType(methodDescriptor).index; } /** * Adds a module reference to the constant pool of the class being build. Does nothing if the * constant pool already contains a similar item. <i>This method is intended for {@link Attribute} * sub classes, and is normally not needed by class generators or adapters.</i> * * @param moduleName name of the module. * @return the index of a new or already existing module reference item. */ public int newModule(final String moduleName) { return symbolTable.addConstantModule(moduleName).index; } /** * Adds a package reference to the constant pool of the class being build. Does nothing if the * constant pool already contains a similar item. <i>This method is intended for {@link Attribute} * sub classes, and is normally not needed by class generators or adapters.</i> * * @param packageName name of the package in its internal form. * @return the index of a new or already existing module reference item. */ public int newPackage(final String packageName) { return symbolTable.addConstantPackage(packageName).index; } /** * Adds a handle to the constant pool of the class being build. Does nothing if the constant pool * already contains a similar item. <i>This method is intended for {@link Attribute} sub classes, * and is normally not needed by class generators or adapters.</i> * * @param tag the kind of this handle. Must be {@link Opcodes#H_GETFIELD}, {@link * Opcodes#H_GETSTATIC}, {@link Opcodes#H_PUTFIELD}, {@link Opcodes#H_PUTSTATIC}, {@link * Opcodes#H_INVOKEVIRTUAL}, {@link Opcodes#H_INVOKESTATIC}, {@link Opcodes#H_INVOKESPECIAL}, * {@link Opcodes#H_NEWINVOKESPECIAL} or {@link Opcodes#H_INVOKEINTERFACE}. * @param owner the internal name of the field or method owner class (see {@link * Type#getInternalName()}). * @param name the name of the field or method. * @param descriptor the descriptor of the field or method. * @return the index of a new or already existing method type reference item. * @deprecated this method is superseded by {@link #newHandle(int, String, String, String, * boolean)}. */ @Deprecated public int newHandle( final int tag, final String owner, final String name, final String descriptor) { return newHandle(tag, owner, name, descriptor, tag == Opcodes.H_INVOKEINTERFACE); } /** * Adds a handle to the constant pool of the class being build. Does nothing if the constant pool * already contains a similar item. <i>This method is intended for {@link Attribute} sub classes, * and is normally not needed by class generators or adapters.</i> * * @param tag the kind of this handle. Must be {@link Opcodes#H_GETFIELD}, {@link * Opcodes#H_GETSTATIC}, {@link Opcodes#H_PUTFIELD}, {@link Opcodes#H_PUTSTATIC}, {@link * Opcodes#H_INVOKEVIRTUAL}, {@link Opcodes#H_INVOKESTATIC}, {@link Opcodes#H_INVOKESPECIAL}, * {@link Opcodes#H_NEWINVOKESPECIAL} or {@link Opcodes#H_INVOKEINTERFACE}. * @param owner the internal name of the field or method owner class (see {@link * Type#getInternalName()}). * @param name the name of the field or method. * @param descriptor the descriptor of the field or method. * @param isInterface true if the owner is an interface. * @return the index of a new or already existing method type reference item. */ public int newHandle( final int tag, final String owner, final String name, final String descriptor, final boolean isInterface) { return symbolTable.addConstantMethodHandle(tag, owner, name, descriptor, isInterface).index; } /** * Adds a dynamic constant reference to the constant pool of the class being build. Does nothing * if the constant pool already contains a similar item. <i>This method is intended for {@link * Attribute} sub classes, and is normally not needed by class generators or adapters.</i> * * @param name name of the invoked method. * @param descriptor field descriptor of the constant type. * @param bootstrapMethodHandle the bootstrap method. * @param bootstrapMethodArguments the bootstrap method constant arguments. * @return the index of a new or already existing dynamic constant reference item. */ public int newConstantDynamic( final String name, final String descriptor, final Handle bootstrapMethodHandle, final Object... bootstrapMethodArguments) { return symbolTable.addConstantDynamic( name, descriptor, bootstrapMethodHandle, bootstrapMethodArguments) .index; } /** * Adds an invokedynamic reference to the constant pool of the class being build. Does nothing if * the constant pool already contains a similar item. <i>This method is intended for {@link * Attribute} sub classes, and is normally not needed by class generators or adapters.</i> * * @param name name of the invoked method. * @param descriptor descriptor of the invoke method. * @param bootstrapMethodHandle the bootstrap method. * @param bootstrapMethodArguments the bootstrap method constant arguments. * @return the index of a new or already existing invokedynamic reference item. */ public int newInvokeDynamic( final String name, final String descriptor, final Handle bootstrapMethodHandle, final Object... bootstrapMethodArguments) { return symbolTable.addConstantInvokeDynamic( name, descriptor, bootstrapMethodHandle, bootstrapMethodArguments) .index; } /** * Adds a field reference to the constant pool of the class being build. Does nothing if the * constant pool already contains a similar item. <i>This method is intended for {@link Attribute} * sub classes, and is normally not needed by class generators or adapters.</i> * * @param owner the internal name of the field's owner class (see {@link Type#getInternalName()}). * @param name the field's name. * @param descriptor the field's descriptor. * @return the index of a new or already existing field reference item. */ public int newField(final String owner, final String name, final String descriptor) { return symbolTable.addConstantFieldref(owner, name, descriptor).index; } /** * Adds a method reference to the constant pool of the class being build. Does nothing if the * constant pool already contains a similar item. <i>This method is intended for {@link Attribute} * sub classes, and is normally not needed by class generators or adapters.</i> * * @param owner the internal name of the method's owner class (see {@link * Type#getInternalName()}). * @param name the method's name. * @param descriptor the method's descriptor. * @param isInterface {@literal true} if {@code owner} is an interface. * @return the index of a new or already existing method reference item. */ public int newMethod( final String owner, final String name, final String descriptor, final boolean isInterface) { return symbolTable.addConstantMethodref(owner, name, descriptor, isInterface).index; } /** * Adds a name and type to the constant pool of the class being build. Does nothing if the * constant pool already contains a similar item. <i>This method is intended for {@link Attribute} * sub classes, and is normally not needed by class generators or adapters.</i> * * @param name a name. * @param descriptor a type descriptor. * @return the index of a new or already existing name and type item. */ public int newNameType(final String name, final String descriptor) { return symbolTable.addConstantNameAndType(name, descriptor); } // ----------------------------------------------------------------------------------------------- // Default method to compute common super classes when computing stack map frames // ----------------------------------------------------------------------------------------------- /** * Returns the common super type of the two given types. The default implementation of this method * <i>loads</i> the two given classes and uses the java.lang.Class methods to find the common * super class. It can be overridden to compute this common super type in other ways, in * particular without actually loading any class, or to take into account the class that is * currently being generated by this ClassWriter, which can of course not be loaded since it is * under construction. * * @param type1 the internal name of a class (see {@link Type#getInternalName()}). * @param type2 the internal name of another class (see {@link Type#getInternalName()}). * @return the internal name of the common super class of the two given classes (see {@link * Type#getInternalName()}). */ protected String getCommonSuperClass(final String type1, final String type2) { ClassLoader classLoader = getClassLoader(); Class<?> class1; try { class1 = Class.forName(type1.replace('/', '.'), false, classLoader); } catch (ClassNotFoundException e) { throw new TypeNotPresentException(type1, e); } Class<?> class2; try { class2 = Class.forName(type2.replace('/', '.'), false, classLoader); } catch (ClassNotFoundException e) { throw new TypeNotPresentException(type2, e); } if (class1.isAssignableFrom(class2)) { return type1; } if (class2.isAssignableFrom(class1)) { return type2; } if (class1.isInterface() || class2.isInterface()) { return "java/lang/Object"; } else { do { class1 = class1.getSuperclass(); } while (!class1.isAssignableFrom(class2)); return class1.getName().replace('.', '/'); } } /** * Returns the {@link ClassLoader} to be used by the default implementation of {@link * #getCommonSuperClass(String, String)}, that of this {@link ClassWriter}'s runtime type by * default. * * @return ClassLoader */ protected ClassLoader getClassLoader() { // SPRING PATCH: prefer thread context ClassLoader for application classes ClassLoader classLoader = null; try { classLoader = Thread.currentThread().getContextClassLoader(); } catch (Throwable ex) { // Cannot access thread context ClassLoader - falling back... } return (classLoader != null ? classLoader : getClass().getClassLoader()); } }
/* * 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 mandelbrot.gui; /** * @author Raphaël **/ public class GlobalColorGradientViewer { }
package com.ifeng.recom.mixrecall.common.model; import com.google.gson.annotations.Expose; import lombok.Getter; import lombok.Setter; import java.util.List; /** * Created by liligeng on 2019/1/28. * 用户兴趣偏好 * */ @Getter @Setter public class UserCluster { @Expose private List<String> bad; //用户不感兴趣分类,前面更不感兴趣 @Expose private String cate; //文章分类 @Expose private List<String> good; //用户感兴趣分类 @Expose private String isdeep; //是否为深度用户 @Expose private String sens; //是否为标题党敏感用户 }
package com.AutoPractice_Selenium; import java.util.*; import org.testng.Assert; import org.testng.annotations.*; public class AutoPractice_Test extends BaseTest{ @Test(priority=2) public void signUpWithValidDetails(){ HomePage hm = new HomePage(driver); hm.clickSignInButton(); Assert.assertEquals(driver.getTitle(),"Login - My Store"); AuthPage ap = new AuthPage(driver); ap.emailCreateAndProceed(email); SignUpDetailsPage signUpPage = new SignUpDetailsPage(driver); Assert.assertEquals(signUpPage.text_H1() ,"CREATE AN ACCOUNT"); signUpPage.fillSignUpDetails(fname, lname, email, password, "long Street, Research Triangle Park", "Park", "Virginia", "02020", "United States", "01010010101"); Assert.assertEquals(hm.accountButton(), fname + " " + lname); hm.logOut(); } @Test(priority=1) public void signUpWithInvalidDetails(){ HomePage hm = new HomePage(driver); hm.clickSignInButton(); Assert.assertEquals(driver.getTitle(),"Login - My Store"); AuthPage ap = new AuthPage(driver); ap.emailCreateAndProceed(email); SignUpDetailsPage signUpPage = new SignUpDetailsPage(driver); Assert.assertEquals(signUpPage.text_H1() ,"CREATE AN ACCOUNT"); //Wrong postal code with 6 digits instead of 5 signUpPage.fillSignUpDetails(fname, lname , email, password, "long Street, Research Triangle Park", "Park", "Virginia", "020200", "United States", "01010010101"); Assert.assertEquals(signUpPage.errorText(), "The Zip/Postal code you've entered is invalid. It must follow this format: 00000"); } @Test(priority=3, dependsOnMethods={"signUpWithValidDetails"}) public void signInWithInvalidPassword(){ HomePage hm = new HomePage(driver); hm.clickSignInButton(); Assert.assertEquals(driver.getTitle(),"Login - My Store"); AuthPage ap = new AuthPage(driver); ap.login(email, "wrongPassword"); //using wrong password Assert.assertEquals(ap.errorMessage(),"Authentication failed."); } @Test(priority=4, dependsOnMethods={"signUpWithValidDetails"}) public void signInAndShowEmptyHistory(){ HomePage hm = new HomePage(driver); hm.clickSignInButton(); Assert.assertEquals(driver.getTitle(),"Login - My Store"); AuthPage ap = new AuthPage(driver); ap.login(email, password); Assert.assertEquals(hm.accountButton(), fname + " " + lname); hm.clickAccountButton(); AccountPage accP = new AccountPage(driver); Assert.assertEquals(accP.getPageHeading() ,"MY ACCOUNT"); accP.clickOrderHistory(); HistoryPage hp = new HistoryPage(driver); Assert.assertEquals(driver.getTitle(), "Order history - My Store"); Assert.assertTrue(hp.checkWarning()); //a warning should appear on the Order History page Assert.assertEquals(hp.checkOrdersNumber(), 0); hm.logOut(); } @Test(priority=5, dependsOnMethods={"signUpWithValidDetails"}) public void addToCartAndConfirmOrderAndCheckHistory(){ HomePage hm = new HomePage(driver); hm.clickSignInButton(); Assert.assertEquals(driver.getTitle(),"Login - My Store"); AuthPage ap = new AuthPage(driver); ap.login(email, password); Assert.assertEquals(hm.accountButton(), fname + " " + lname); MenuPage mp = new MenuPage(driver); try{ mp.hoverOverWomenMenuButton(); mp.clickBlousesButton(); }catch(Error e){ System.out.println("Physical Cursor should be out of the test browser"); //if physical cursor inside browser the test will fail. catching error and continue driver.get("http://automationpractice.com/index.php?id_category=7&controller=category"); } BlousesPage bp = new BlousesPage(driver); Assert.assertEquals(bp.getCategoryName(),"BLOUSES "); // scrolling down to see blouse img and link try{ bp.scrollToBlouseLink(); bp.clickOnBlouseLink(); }catch(Error e){ System.out.println("Couldn't scroll and click on the product"); driver.get("http://automationpractice.com/index.php?id_product=2&controller=product"); } ProductPage pp = new ProductPage(driver); Assert.assertEquals(pp.getProductName(), "Blouse"); //select 2 blouses of size 'M' and White(True) Product prod = new Product("", 2, true, 'M'); pp.addToCart(prod); Assert.assertTrue(pp.getMessage().contains("Product successfully added to your shopping cart")); pp.proceedCheckout(); CheckoutFormsPage cfp = new CheckoutFormsPage(driver); Assert.assertTrue(cfp.checkCurrentStep().contains("first")); Assert.assertTrue(cfp.CheckProductExists(prod)); cfp.scrollToProceedLink(); cfp.proceedCheckout(); Assert.assertTrue(cfp.checkCurrentStep().contains("third")); cfp.scrollToProceedLink(); cfp.proceedCheckout(); Assert.assertTrue(cfp.checkCurrentStep().contains("four")); cfp.scrollToProceedLink(); cfp.checkShippingbox(); cfp.proceedCheckout(); Assert.assertTrue(cfp.checkCurrentStep().contains("last")); cfp.scrollToProceedLink(); cfp.chooseBankWire(); String orderReference = cfp.confirmOrder(); Assert.assertTrue(cfp.getEndPaymentMessage().equals("Your order on My Store is complete.")); hm.clickAccountButton(); AccountPage accP = new AccountPage(driver); Assert.assertEquals(accP.getPageHeading() ,"MY ACCOUNT"); accP.clickOrderHistory(); HistoryPage hp = new HistoryPage(driver); Assert.assertEquals(driver.getTitle(), "Order history - My Store"); Assert.assertTrue(hp.checkOrderExists(orderReference)); hm.logOut(); } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package negocio; import datos.ClienteBD; import datos.VentasBD; import java.sql.SQLException; import java.util.logging.Level; import java.util.logging.Logger; /** * * @author F35 */ public class Venta { private String idFactura; private String idProcduto; private String cantidad; public String getIdFactura() { return idFactura; } public void setIdFactura(String idFactura) { this.idFactura = idFactura; } public String getIdProcduto() { return idProcduto; } public void setIdProcduto(String idProcduto) { this.idProcduto = idProcduto; } public String getCantidad() { return cantidad; } public void setCantidad(String cantidad) { this.cantidad = cantidad; } public void grabar(){ try { VentasBD ventaBD = new VentasBD(); ventaBD.grabar(this); } catch (SQLException ex) { Logger.getLogger(Cliente.class.getName()).log(Level.SEVERE, null, ex); } } public void modificar(){ /*try { ClienteBD clienteBD = new ClienteBD(); clienteBD.modificar(this); } catch (SQLException ex) { Logger.getLogger(Cliente.class.getName()).log(Level.SEVERE, null, ex); }*/ } public void eliminar(){ try { ClienteBD clienteBD = new ClienteBD(); clienteBD.eliminar(this.idFactura); } catch (SQLException ex) { Logger.getLogger(Cliente.class.getName()).log(Level.SEVERE, null, ex); } } public void buscar(){ /*try { Cliente aux; ClienteBD clienteBD = new ClienteBD(); aux = clienteBD.buscar(this.idFactura); setNombre(aux.getNombre()); setApellido(aux.getApellido()); } catch (SQLException ex) { Logger.getLogger(Cliente.class.getName()).log(Level.SEVERE, null, ex); }*/ } }
/** */ package org.eclipse.pss.dsl.metamodel.impl; import org.eclipse.emf.ecore.EAttribute; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.EEnum; import org.eclipse.emf.ecore.EPackage; import org.eclipse.emf.ecore.EReference; import org.eclipse.emf.ecore.impl.EPackageImpl; import org.eclipse.pss.dsl.metamodel.Abstract_Component; import org.eclipse.pss.dsl.metamodel.Action; import org.eclipse.pss.dsl.metamodel.Action_invocation; import org.eclipse.pss.dsl.metamodel.Activity; import org.eclipse.pss.dsl.metamodel.Buffer; import org.eclipse.pss.dsl.metamodel.Component; import org.eclipse.pss.dsl.metamodel.Component_Invocation; import org.eclipse.pss.dsl.metamodel.DataFlow_Object; import org.eclipse.pss.dsl.metamodel.Data_Object; import org.eclipse.pss.dsl.metamodel.MetamodelFactory; import org.eclipse.pss.dsl.metamodel.MetamodelPackage; import org.eclipse.pss.dsl.metamodel.PssModel; import org.eclipse.pss.dsl.metamodel.Resource; import org.eclipse.pss.dsl.metamodel.Resource_kind; import org.eclipse.pss.dsl.metamodel.RootComponent; import org.eclipse.pss.dsl.metamodel.Stream; import org.eclipse.pss.dsl.metamodel.pool; /** * <!-- begin-user-doc --> * An implementation of the model <b>Package</b>. * <!-- end-user-doc --> * @generated */ public class MetamodelPackageImpl extends EPackageImpl implements MetamodelPackage { /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ private EClass abstract_ComponentEClass = null; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ private EClass objectEClass = null; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ private EClass componentEClass = null; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ private EClass dataFlow_ObjectEClass = null; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ private EClass data_ObjectEClass = null; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ private EClass resourceEClass = null; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ private EClass rootComponentEClass = null; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ private EClass actionEClass = null; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ private EClass poolEClass = null; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ private EClass activityEClass = null; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ private EClass pssModelEClass = null; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ private EClass component_InvocationEClass = null; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ private EClass action_invocationEClass = null; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ private EClass streamEClass = null; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ private EClass bufferEClass = null; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ private EEnum resource_kindEEnum = null; /** * Creates an instance of the model <b>Package</b>, registered with * {@link org.eclipse.emf.ecore.EPackage.Registry EPackage.Registry} by the package * package URI value. * <p>Note: the correct way to create the package is via the static * factory method {@link #init init()}, which also performs * initialization of the package, or returns the registered package, * if one already exists. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see org.eclipse.emf.ecore.EPackage.Registry * @see org.eclipse.pss.dsl.metamodel.MetamodelPackage#eNS_URI * @see #init() * @generated */ private MetamodelPackageImpl() { super(eNS_URI, MetamodelFactory.eINSTANCE); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ private static boolean isInited = false; /** * Creates, registers, and initializes the <b>Package</b> for this model, and for any others upon which it depends. * * <p>This method is used to initialize {@link MetamodelPackage#eINSTANCE} when that field is accessed. * Clients should not invoke it directly. Instead, they should simply access that field to obtain the package. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #eNS_URI * @see #createPackageContents() * @see #initializePackageContents() * @generated */ public static MetamodelPackage init() { if (isInited) return (MetamodelPackage) EPackage.Registry.INSTANCE.getEPackage(MetamodelPackage.eNS_URI); // Obtain or create and register package Object registeredMetamodelPackage = EPackage.Registry.INSTANCE.get(eNS_URI); MetamodelPackageImpl theMetamodelPackage = registeredMetamodelPackage instanceof MetamodelPackageImpl ? (MetamodelPackageImpl) registeredMetamodelPackage : new MetamodelPackageImpl(); isInited = true; // Create package meta-data objects theMetamodelPackage.createPackageContents(); // Initialize created meta-data theMetamodelPackage.initializePackageContents(); // Mark meta-data to indicate it can't be changed theMetamodelPackage.freeze(); // Update the registry and return the package EPackage.Registry.INSTANCE.put(MetamodelPackage.eNS_URI, theMetamodelPackage); return theMetamodelPackage; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public EClass getAbstract_Component() { return abstract_ComponentEClass; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public EAttribute getAbstract_Component_Component_identifier() { return (EAttribute) abstract_ComponentEClass.getEStructuralFeatures().get(0); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public EReference getAbstract_Component_Action() { return (EReference) abstract_ComponentEClass.getEStructuralFeatures().get(1); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public EReference getAbstract_Component_Extends() { return (EReference) abstract_ComponentEClass.getEStructuralFeatures().get(2); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public EReference getAbstract_Component_Pool() { return (EReference) abstract_ComponentEClass.getEStructuralFeatures().get(3); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public EClass getObject() { return objectEClass; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public EAttribute getObject_Object_identifier() { return (EAttribute) objectEClass.getEStructuralFeatures().get(0); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public EClass getComponent() { return componentEClass; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public EReference getComponent_Data_object() { return (EReference) componentEClass.getEStructuralFeatures().get(0); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public EClass getDataFlow_Object() { return dataFlow_ObjectEClass; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public EClass getData_Object() { return data_ObjectEClass; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public EClass getResource() { return resourceEClass; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public EAttribute getResource_Type_identifier() { return (EAttribute) resourceEClass.getEStructuralFeatures().get(0); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public EClass getRootComponent() { return rootComponentEClass; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public EReference getRootComponent_Component_invocation() { return (EReference) rootComponentEClass.getEStructuralFeatures().get(0); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public EReference getRootComponent_Action_invocation() { return (EReference) rootComponentEClass.getEStructuralFeatures().get(1); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public EClass getAction() { return actionEClass; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public EAttribute getAction_Action_identifier() { return (EAttribute) actionEClass.getEStructuralFeatures().get(0); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public EReference getAction_Object() { return (EReference) actionEClass.getEStructuralFeatures().get(1); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public EReference getAction_Activity() { return (EReference) actionEClass.getEStructuralFeatures().get(2); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public EClass getpool() { return poolEClass; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public EReference getpool_Object() { return (EReference) poolEClass.getEStructuralFeatures().get(0); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public EClass getActivity() { return activityEClass; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public EReference getActivity_Action_invocation() { return (EReference) activityEClass.getEStructuralFeatures().get(0); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public EClass getPssModel() { return pssModelEClass; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public EReference getPssModel_Component_declaration() { return (EReference) pssModelEClass.getEStructuralFeatures().get(0); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public EReference getPssModel_Action() { return (EReference) pssModelEClass.getEStructuralFeatures().get(1); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public EClass getComponent_Invocation() { return component_InvocationEClass; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public EReference getComponent_Invocation_Component() { return (EReference) component_InvocationEClass.getEStructuralFeatures().get(0); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public EClass getAction_invocation() { return action_invocationEClass; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public EReference getAction_invocation_Action_instance() { return (EReference) action_invocationEClass.getEStructuralFeatures().get(0); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public EClass getStream() { return streamEClass; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public EAttribute getStream_Input() { return (EAttribute) streamEClass.getEStructuralFeatures().get(0); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public EAttribute getStream_Output() { return (EAttribute) streamEClass.getEStructuralFeatures().get(1); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public EClass getBuffer() { return bufferEClass; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public EAttribute getBuffer_Input() { return (EAttribute) bufferEClass.getEStructuralFeatures().get(0); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public EAttribute getBuffer_Output() { return (EAttribute) bufferEClass.getEStructuralFeatures().get(1); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public EEnum getResource_kind() { return resource_kindEEnum; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public MetamodelFactory getMetamodelFactory() { return (MetamodelFactory) getEFactoryInstance(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ private boolean isCreated = false; /** * Creates the meta-model objects for the package. This method is * guarded to have no affect on any invocation but its first. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void createPackageContents() { if (isCreated) return; isCreated = true; // Create classes and their features abstract_ComponentEClass = createEClass(ABSTRACT_COMPONENT); createEAttribute(abstract_ComponentEClass, ABSTRACT_COMPONENT__COMPONENT_IDENTIFIER); createEReference(abstract_ComponentEClass, ABSTRACT_COMPONENT__ACTION); createEReference(abstract_ComponentEClass, ABSTRACT_COMPONENT__EXTENDS); createEReference(abstract_ComponentEClass, ABSTRACT_COMPONENT__POOL); objectEClass = createEClass(OBJECT); createEAttribute(objectEClass, OBJECT__OBJECT_IDENTIFIER); componentEClass = createEClass(COMPONENT); createEReference(componentEClass, COMPONENT__DATA_OBJECT); dataFlow_ObjectEClass = createEClass(DATA_FLOW_OBJECT); data_ObjectEClass = createEClass(DATA_OBJECT); resourceEClass = createEClass(RESOURCE); createEAttribute(resourceEClass, RESOURCE__TYPE_IDENTIFIER); rootComponentEClass = createEClass(ROOT_COMPONENT); createEReference(rootComponentEClass, ROOT_COMPONENT__COMPONENT_INVOCATION); createEReference(rootComponentEClass, ROOT_COMPONENT__ACTION_INVOCATION); actionEClass = createEClass(ACTION); createEAttribute(actionEClass, ACTION__ACTION_IDENTIFIER); createEReference(actionEClass, ACTION__OBJECT); createEReference(actionEClass, ACTION__ACTIVITY); activityEClass = createEClass(ACTIVITY); createEReference(activityEClass, ACTIVITY__ACTION_INVOCATION); pssModelEClass = createEClass(PSS_MODEL); createEReference(pssModelEClass, PSS_MODEL__COMPONENT_DECLARATION); createEReference(pssModelEClass, PSS_MODEL__ACTION); component_InvocationEClass = createEClass(COMPONENT_INVOCATION); createEReference(component_InvocationEClass, COMPONENT_INVOCATION__COMPONENT); streamEClass = createEClass(STREAM); createEAttribute(streamEClass, STREAM__INPUT); createEAttribute(streamEClass, STREAM__OUTPUT); bufferEClass = createEClass(BUFFER); createEAttribute(bufferEClass, BUFFER__INPUT); createEAttribute(bufferEClass, BUFFER__OUTPUT); poolEClass = createEClass(POOL); createEReference(poolEClass, POOL__OBJECT); action_invocationEClass = createEClass(ACTION_INVOCATION); createEReference(action_invocationEClass, ACTION_INVOCATION__ACTION_INSTANCE); // Create enums resource_kindEEnum = createEEnum(RESOURCE_KIND); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ private boolean isInitialized = false; /** * Complete the initialization of the package and its meta-model. This * method is guarded to have no affect on any invocation but its first. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void initializePackageContents() { if (isInitialized) return; isInitialized = true; // Initialize package setName(eNAME); setNsPrefix(eNS_PREFIX); setNsURI(eNS_URI); // Create type parameters // Set bounds for type parameters // Add supertypes to classes componentEClass.getESuperTypes().add(this.getAbstract_Component()); dataFlow_ObjectEClass.getESuperTypes().add(this.getObject()); data_ObjectEClass.getESuperTypes().add(this.getObject()); resourceEClass.getESuperTypes().add(this.getData_Object()); rootComponentEClass.getESuperTypes().add(this.getAbstract_Component()); component_InvocationEClass.getESuperTypes().add(this.getComponent()); streamEClass.getESuperTypes().add(this.getDataFlow_Object()); bufferEClass.getESuperTypes().add(this.getDataFlow_Object()); action_invocationEClass.getESuperTypes().add(this.getAction()); // Initialize classes, features, and operations; add parameters initEClass(abstract_ComponentEClass, Abstract_Component.class, "Abstract_Component", IS_ABSTRACT, !IS_INTERFACE, IS_GENERATED_INSTANCE_CLASS); initEAttribute(getAbstract_Component_Component_identifier(), ecorePackage.getEString(), "Component_identifier", null, 0, 1, Abstract_Component.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEReference(getAbstract_Component_Action(), this.getAction(), null, "action", null, 0, -1, Abstract_Component.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, IS_COMPOSITE, !IS_RESOLVE_PROXIES, !IS_UNSETTABLE, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEReference(getAbstract_Component_Extends(), this.getAbstract_Component(), null, "extends", null, 0, -1, Abstract_Component.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_COMPOSITE, IS_RESOLVE_PROXIES, !IS_UNSETTABLE, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEReference(getAbstract_Component_Pool(), this.getpool(), null, "pool", null, 0, -1, Abstract_Component.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, IS_COMPOSITE, !IS_RESOLVE_PROXIES, !IS_UNSETTABLE, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEClass(objectEClass, org.eclipse.pss.dsl.metamodel.Object.class, "Object", IS_ABSTRACT, !IS_INTERFACE, IS_GENERATED_INSTANCE_CLASS); initEAttribute(getObject_Object_identifier(), ecorePackage.getEString(), "Object_identifier", null, 1, 1, org.eclipse.pss.dsl.metamodel.Object.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEClass(componentEClass, Component.class, "Component", !IS_ABSTRACT, !IS_INTERFACE, IS_GENERATED_INSTANCE_CLASS); initEReference(getComponent_Data_object(), this.getData_Object(), null, "data_object", null, 0, -1, Component.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, IS_COMPOSITE, !IS_RESOLVE_PROXIES, !IS_UNSETTABLE, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEClass(dataFlow_ObjectEClass, DataFlow_Object.class, "DataFlow_Object", IS_ABSTRACT, !IS_INTERFACE, IS_GENERATED_INSTANCE_CLASS); initEClass(data_ObjectEClass, Data_Object.class, "Data_Object", IS_ABSTRACT, !IS_INTERFACE, IS_GENERATED_INSTANCE_CLASS); initEClass(resourceEClass, Resource.class, "Resource", !IS_ABSTRACT, !IS_INTERFACE, IS_GENERATED_INSTANCE_CLASS); initEAttribute(getResource_Type_identifier(), this.getResource_kind(), "type_identifier", null, 0, 1, Resource.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEClass(rootComponentEClass, RootComponent.class, "RootComponent", !IS_ABSTRACT, !IS_INTERFACE, IS_GENERATED_INSTANCE_CLASS); initEReference(getRootComponent_Component_invocation(), this.getComponent_Invocation(), null, "component_invocation", null, 0, -1, RootComponent.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, IS_COMPOSITE, !IS_RESOLVE_PROXIES, !IS_UNSETTABLE, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEReference(getRootComponent_Action_invocation(), this.getAction_invocation(), null, "action_invocation", null, 0, 1, RootComponent.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_COMPOSITE, IS_RESOLVE_PROXIES, !IS_UNSETTABLE, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEClass(actionEClass, Action.class, "Action", !IS_ABSTRACT, !IS_INTERFACE, IS_GENERATED_INSTANCE_CLASS); initEAttribute(getAction_Action_identifier(), ecorePackage.getEString(), "action_identifier", null, 0, 1, Action.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEReference(getAction_Object(), this.getObject(), null, "object", null, 0, -1, Action.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, IS_COMPOSITE, !IS_RESOLVE_PROXIES, !IS_UNSETTABLE, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEReference(getAction_Activity(), this.getActivity(), null, "activity", null, 0, -1, Action.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, IS_COMPOSITE, !IS_RESOLVE_PROXIES, !IS_UNSETTABLE, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEClass(activityEClass, Activity.class, "Activity", !IS_ABSTRACT, !IS_INTERFACE, IS_GENERATED_INSTANCE_CLASS); initEReference(getActivity_Action_invocation(), this.getAction_invocation(), null, "action_invocation", null, 0, -1, Activity.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, IS_COMPOSITE, !IS_RESOLVE_PROXIES, !IS_UNSETTABLE, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEClass(pssModelEClass, PssModel.class, "PssModel", !IS_ABSTRACT, !IS_INTERFACE, IS_GENERATED_INSTANCE_CLASS); initEReference(getPssModel_Component_declaration(), this.getAbstract_Component(), null, "component_declaration", null, 0, -1, PssModel.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, IS_COMPOSITE, !IS_RESOLVE_PROXIES, !IS_UNSETTABLE, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEReference(getPssModel_Action(), this.getAction(), null, "action", null, 0, -1, PssModel.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, IS_COMPOSITE, !IS_RESOLVE_PROXIES, !IS_UNSETTABLE, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEClass(component_InvocationEClass, Component_Invocation.class, "Component_Invocation", !IS_ABSTRACT, !IS_INTERFACE, IS_GENERATED_INSTANCE_CLASS); initEReference(getComponent_Invocation_Component(), this.getComponent(), null, "component", null, 0, -1, Component_Invocation.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_COMPOSITE, IS_RESOLVE_PROXIES, !IS_UNSETTABLE, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEClass(streamEClass, Stream.class, "Stream", !IS_ABSTRACT, !IS_INTERFACE, IS_GENERATED_INSTANCE_CLASS); initEAttribute(getStream_Input(), ecorePackage.getEBoolean(), "input", null, 0, 1, Stream.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEAttribute(getStream_Output(), ecorePackage.getEBoolean(), "output", "true", 0, 1, Stream.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEClass(bufferEClass, Buffer.class, "Buffer", !IS_ABSTRACT, !IS_INTERFACE, IS_GENERATED_INSTANCE_CLASS); initEAttribute(getBuffer_Input(), ecorePackage.getEBoolean(), "input", "true", 0, 1, Buffer.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEAttribute(getBuffer_Output(), ecorePackage.getEBoolean(), "output", "false", 0, 1, Buffer.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_UNSETTABLE, !IS_ID, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEClass(poolEClass, pool.class, "pool", !IS_ABSTRACT, !IS_INTERFACE, IS_GENERATED_INSTANCE_CLASS); initEReference(getpool_Object(), this.getObject(), null, "object", null, 0, -1, pool.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, IS_COMPOSITE, !IS_RESOLVE_PROXIES, !IS_UNSETTABLE, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); initEClass(action_invocationEClass, Action_invocation.class, "Action_invocation", !IS_ABSTRACT, !IS_INTERFACE, IS_GENERATED_INSTANCE_CLASS); initEReference(getAction_invocation_Action_instance(), this.getAction(), null, "action_instance", null, 0, -1, Action_invocation.class, !IS_TRANSIENT, !IS_VOLATILE, IS_CHANGEABLE, !IS_COMPOSITE, IS_RESOLVE_PROXIES, !IS_UNSETTABLE, IS_UNIQUE, !IS_DERIVED, IS_ORDERED); // Initialize enums and add enum literals initEEnum(resource_kindEEnum, Resource_kind.class, "Resource_kind"); addEEnumLiteral(resource_kindEEnum, Resource_kind.NONE); addEEnumLiteral(resource_kindEEnum, Resource_kind.RAND); addEEnumLiteral(resource_kindEEnum, Resource_kind.LOCK); addEEnumLiteral(resource_kindEEnum, Resource_kind.SHARE); // Create resource createResource(eNS_URI); } } //MetamodelPackageImpl
package com.company.project.service; import com.company.project.model.TQkwz; import com.company.project.core.Service; /** * Created by CodeGenerator on 2018/11/01. */ public interface TQkwzService extends Service<TQkwz> { public void iterate(); }
package ch.bfh.bti7301.w2013.battleship.network; import java.io.*; import java.net.*; import java.util.ArrayList; import java.util.regex.Matcher; import java.util.regex.Pattern; import ch.bfh.bti7301.w2013.battleship.gui.SettingsPanel; public class NetworkScanner { private static NetworkScanner instance; MulticastSocket udpSocket; private static DiscoverySocketListener discoveryListener; private static DiscoverySocketSender discoverySender; private NetworkScanner() throws IOException { udpSocket = new MulticastSocket(Connection.GAMEPORT); udpSocket.setReuseAddress(true); udpSocket.joinGroup(NetworkInformation.MULTICAST_GROUP); discoveryListener = new DiscoverySocketListener(udpSocket); discoverySender = new DiscoverySocketSender(udpSocket); } public static NetworkScanner getInstance() { if (instance == null) { try { instance = new NetworkScanner(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return instance; } // private String matchIp(String str) { // // String IPADDRESS_PATTERN = "(([2]([0-4][0-9]|[5][0-5])|[0-1]?[0-9]?[0-9])[.]){3}(([2]([0-4][0-9]|[5][0-5])|[0-1]?[0-9]?[0-9]))"; // // Pattern pattern = Pattern.compile(IPADDRESS_PATTERN); // Matcher matcher = pattern.matcher(str); // if (matcher.find()) { // return matcher.group(); // } else { // return "0.0.0.0"; // } // // } // // private String matchName(String str) { // // String NAME_PATTERN = "-\\w*$"; // // Pattern pattern = Pattern.compile(NAME_PATTERN); // Matcher matcher = pattern.matcher(str); // if (matcher.find()) { // return matcher.group(); // } else { // return "no name"; // } // // } // // private boolean matchMsg(String str) { // // String MSG_PATTERN = "(BSG-)(([2]([0-4][0-9]|[5][0-5])|[0-1]?[0-9]?[0-9])[.]){3}(([2]([0-4][0-9]|[5][0-5])|[0-1]?[0-9]?[0-9]))(-\\w*)$"; // // Pattern pattern = Pattern.compile(MSG_PATTERN); // Matcher matcher = pattern.matcher(str); // return matcher.find(); // // } public void readUdpSocket(String ip,String name) { Connection.getInstance().foundOpponent(ip, name); } public void cleanUp() { // TODO: close all open sockets. } }
package andiamoTrust.commons; public class Utils { }
package connectfour; import processing.core.PApplet; /** * Displays the yellow game board and stores an array of tokens. * Contains methods to determine if a winning pattern is present on the board. */ public class Board { public Token[][] tokenarray; private int numtokens; PApplet parent; /** * Constructor * * @param parent, the base class for skethes that use processing.core */ Board(PApplet parent) { this.parent=parent; } /** * Initializes the 2D token array and populates it with blue tokens. */ public void initializeTokenArray() { tokenarray = new Token[7][6]; numtokens=0; for (int x = parent.width/2-150,i=0; i<7; x+=50,i++) { for (int y = parent.height/2+125,j=0;j<6;y-=50,j++) { Token temp = new Token(parent,x,y,"blue",false); tokenarray[i][j]=temp; } } } /** * Displays the yellow board and all tokens. */ public void display() { parent.fill(255,255,0); parent.rect(180,85,360,310,5); parent.noStroke(); for (int i=0; i<7; i++) { for (int j=0;j<6;j++) { tokenarray[i][j].display(); } } } /** * Draws a blue rectangle over the board's area. */ public void hide() { parent.fill(139,189,255); parent.rect(180,85,360,parent.height/2+125); } /** * Searches the entire board for a winning pattern, given a color as a parameter. * * @param color, the color to test. */ public boolean testWin(String color){ for (int x = 0; x < 7; x++) { for (int y = 0; y < 6; y++) { if(tokenarray[x][y].getColor().equals(color)) { //tests if the position is part of a "four" in any direction if( testWinDirection(color,x,y,1,0) || testWinDirection(color,x,y,0,1) || testWinDirection(color,x,y,1,1) || testWinDirection(color,x,y,1,-1) ) { return true; } } } } return false; } /** * Tests if the position specified begins a winning "four" pattern. * * Tests horizontal, vertical, left diagonal, and right diagonal. * Returns false if the iteration reaches the edge of the board or the pattern is interrupted. * * @param color, the color to test. * @param x, the x-coordinate of the starting position. * @param y, the y-coordinate of the starting position. * @param x-iterator, the direction to iterate x. * @param y-iterator, the direction to iterate y. */ public boolean testWinDirection(String color,int x,int y,int xiter, int yiter) { for (int i = 1; i < 4; i++) { //x is out of bounds if(x+(xiter*i)>6 || x+(xiter*i)<0 ) { return false; //y is out of bounds } else if(y+(yiter*i)>5 || y+(yiter*i)<0 ) { return false; //the pattern is interrupted } else if (!tokenarray[x+(xiter*i)][y+(yiter*i)].getColor().equals(color)) { return false; } } //once it is determined that there is a win, mark each winning token. for (int i = 0; i < 4; i++) { tokenarray[x+(xiter*i)][y+(yiter*i)].setIsWinner(true); } return true; } // Getters & Setters public int getNumTokens() { return this.numtokens; } public void setNumTokens(int numtokens) { this.numtokens=numtokens; } }
/* * Copyright (c) 2008-2019, Hazelcast, Inc. All Rights Reserved. * * 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.hazelcast.jet.beam.transforms.combine; import org.apache.beam.sdk.PipelineResult; import org.apache.beam.sdk.coders.KvCoder; import org.apache.beam.sdk.coders.VarIntCoder; import org.apache.beam.sdk.testing.PAssert; import org.apache.beam.sdk.transforms.Combine; import org.apache.beam.sdk.transforms.CombineTest; import org.apache.beam.sdk.transforms.Create; import org.apache.beam.sdk.transforms.DoFn; import org.apache.beam.sdk.transforms.PTransform; import org.apache.beam.sdk.transforms.ParDo; import org.apache.beam.sdk.transforms.SerializableFunction; import org.apache.beam.sdk.transforms.Sum; import org.apache.beam.sdk.transforms.Values; import org.apache.beam.sdk.transforms.display.DisplayData; import org.apache.beam.sdk.transforms.display.DisplayDataEvaluator; import org.apache.beam.sdk.transforms.windowing.AfterPane; import org.apache.beam.sdk.transforms.windowing.GlobalWindows; import org.apache.beam.sdk.transforms.windowing.Repeatedly; import org.apache.beam.sdk.transforms.windowing.Window; import org.apache.beam.sdk.values.KV; import org.apache.beam.sdk.values.PCollection; import org.apache.beam.sdk.values.POutput; import org.apache.beam.vendor.guava.v20_0.com.google.common.collect.ImmutableSet; import org.joda.time.Duration; import org.junit.Ignore; import org.junit.Test; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Set; import static junit.framework.TestCase.assertEquals; import static org.apache.beam.sdk.transforms.display.DisplayDataMatchers.hasDisplayItem; import static org.hamcrest.Matchers.hasItem; import static org.junit.Assert.assertThat; /* "Inspired" by org.apache.beam.sdk.transforms.CombineTest.BasicTests */ @SuppressWarnings({"ALL"}) public class BasicCombineTest extends AbstractCombineTest { private static final SerializableFunction<String, Integer> HOT_KEY_FANOUT = input -> "a".equals(input) ? 3 : 0; private static final SerializableFunction<String, Integer> SPLIT_HOT_KEY_FANOUT = input -> Math.random() < 0.5 ? 3 : 0; @Test public void testSimpleCombine() { runTestSimpleCombine( Arrays.asList(KV.of("a", 1), KV.of("a", 1), KV.of("a", 4), KV.of("b", 1), KV.of("b", 13)), 20, Arrays.asList(KV.of("a", "114"), KV.of("b", "113"))); } @Test public void testSimpleCombineEmpty() { runTestSimpleCombine(EMPTY_TABLE, 0, Collections.emptyList()); } @Test public void testBasicCombine() { runTestBasicCombine( Arrays.asList(KV.of("a", 1), KV.of("a", 1), KV.of("a", 4), KV.of("b", 1), KV.of("b", 13)), ImmutableSet.of(1, 13, 4), Arrays.asList(new KV[]{KV.of("a", ImmutableSet.of(1, 4)), KV.of("b", (Set<Integer>) ImmutableSet.of(1, 13))})); } @Test public void testBasicCombineEmpty() { runTestBasicCombine(EMPTY_TABLE, ImmutableSet.of(), Collections.emptyList()); } @Test public void testHotKeyCombining() { PCollection<KV<String, Integer>> input = copy( createInput( pipeline, Arrays.asList( KV.of("a", 1), KV.of("a", 1), KV.of("a", 4), KV.of("b", 1), KV.of("b", 13))), 10); Combine.CombineFn<Integer, ?, Double> mean = new MeanInts(); PCollection<KV<String, Double>> coldMean = input.apply( "ColdMean", Combine.<String, Integer, Double>perKey(mean).withHotKeyFanout(0)); PCollection<KV<String, Double>> warmMean = input.apply( "WarmMean", Combine.<String, Integer, Double>perKey(mean).withHotKeyFanout(HOT_KEY_FANOUT)); PCollection<KV<String, Double>> hotMean = input.apply("HotMean", Combine.<String, Integer, Double>perKey(mean).withHotKeyFanout(5)); PCollection<KV<String, Double>> splitMean = input.apply( "SplitMean", Combine.<String, Integer, Double>perKey(mean).withHotKeyFanout(SPLIT_HOT_KEY_FANOUT)); List<KV<String, Double>> expected = Arrays.asList(KV.of("a", 2.0), KV.of("b", 7.0)); PAssert.that(coldMean).containsInAnyOrder(expected); PAssert.that(warmMean).containsInAnyOrder(expected); PAssert.that(hotMean).containsInAnyOrder(expected); PAssert.that(splitMean).containsInAnyOrder(expected); PipelineResult.State state = pipeline.run().waitUntilFinish(); assertEquals(PipelineResult.State.DONE, state); } @Test public void testHotKeyCombiningWithAccumulationMode() { PCollection<Integer> input = pipeline.apply(Create.of(1, 2, 3, 4, 5)); PCollection<Integer> output = input .apply( Window.<Integer>into(new GlobalWindows()) .triggering(Repeatedly.forever(AfterPane.elementCountAtLeast(1))) .accumulatingFiredPanes() .withAllowedLateness(new Duration(0), Window.ClosingBehavior.FIRE_ALWAYS)) .apply(Sum.integersGlobally().withoutDefaults().withFanout(2)) .apply(ParDo.of(new GetLast())); PAssert.that(output) .satisfies( input1 -> { assertThat(input1, hasItem(15)); return null; }); PipelineResult.State state = pipeline.run().waitUntilFinish(); assertEquals(PipelineResult.State.DONE, state); } @Test public void testCombinePerKeyPrimitiveDisplayData() { DisplayDataEvaluator evaluator = DisplayDataEvaluator.create(); CombineTest.SharedTestBase.UniqueInts combineFn = new CombineTest.SharedTestBase.UniqueInts(); PTransform<PCollection<KV<Integer, Integer>>, ? extends POutput> combine = Combine.perKey(combineFn); Set<DisplayData> displayData = evaluator.displayDataForPrimitiveTransforms( combine, KvCoder.of(VarIntCoder.of(), VarIntCoder.of())); assertThat( "Combine.perKey should include the combineFn in its primitive transform", displayData, hasItem(hasDisplayItem("combineFn", combineFn.getClass()))); } @Test public void testCombinePerKeyWithHotKeyFanoutPrimitiveDisplayData() { int hotKeyFanout = 2; DisplayDataEvaluator evaluator = DisplayDataEvaluator.create(); CombineTest.SharedTestBase.UniqueInts combineFn = new CombineTest.SharedTestBase.UniqueInts(); PTransform<PCollection<KV<Integer, Integer>>, PCollection<KV<Integer, Set<Integer>>>> combine = Combine.<Integer, Integer, Set<Integer>>perKey(combineFn) .withHotKeyFanout(hotKeyFanout); Set<DisplayData> displayData = evaluator.displayDataForPrimitiveTransforms( combine, KvCoder.of(VarIntCoder.of(), VarIntCoder.of())); assertThat( "Combine.perKey.withHotKeyFanout should include the combineFn in its primitive " + "transform", displayData, hasItem(hasDisplayItem("combineFn", combineFn.getClass()))); assertThat( "Combine.perKey.withHotKeyFanout(int) should include the fanout in its primitive " + "transform", displayData, hasItem(hasDisplayItem("fanout", hotKeyFanout))); } /** * Tests creation of a per-key {@link Combine} via a Java 8 lambda. */ @Test public void testCombinePerKeyLambda() { PCollection<KV<String, Integer>> output = pipeline .apply(Create.of(KV.of("a", 1), KV.of("b", 2), KV.of("a", 3), KV.of("c", 4))) .apply( Combine.perKey( integers -> { int sum = 0; for (int i : integers) { sum += i; } return sum; })); PAssert.that(output).containsInAnyOrder(KV.of("a", 4), KV.of("b", 2), KV.of("c", 4)); PipelineResult.State state = pipeline.run().waitUntilFinish(); assertEquals(PipelineResult.State.DONE, state); } /** * Tests creation of a per-key {@link Combine} via a Java 8 method reference. */ @Test public void testCombinePerKeyInstanceMethodReference() { PCollection<KV<String, Integer>> output = pipeline .apply(Create.of(KV.of("a", 1), KV.of("b", 2), KV.of("a", 3), KV.of("c", 4))) .apply(Combine.perKey(new Summer()::sum)); PAssert.that(output).containsInAnyOrder(KV.of("a", 4), KV.of("b", 2), KV.of("c", 4)); PipelineResult.State state = pipeline.run().waitUntilFinish(); assertEquals(PipelineResult.State.DONE, state); } private void runTestSimpleCombine( List<KV<String, Integer>> table, int globalSum, List<KV<String, String>> perKeyCombines) { PCollection<KV<String, Integer>> input = createInput(pipeline, table); PCollection<Integer> sum = input.apply(Values.create()).apply(Combine.globally(new CombineTest.SharedTestBase.SumInts())); PCollection<KV<String, String>> sumPerKey = input.apply(Combine.perKey(new CombineTest.SharedTestBase.TestCombineFn())); PAssert.that(sum).containsInAnyOrder(globalSum); PAssert.that(sumPerKey).containsInAnyOrder(perKeyCombines); PipelineResult.State state = pipeline.run().waitUntilFinish(); assertEquals(PipelineResult.State.DONE, state); } private void runTestBasicCombine( List<KV<String, Integer>> table, Set<Integer> globalUnique, List<KV<String, Set<Integer>>> perKeyUnique) { PCollection<KV<String, Integer>> input = createInput(pipeline, table); PCollection<Set<Integer>> unique = input.apply(Values.create()).apply(Combine.globally(new CombineTest.SharedTestBase.UniqueInts())); PCollection<KV<String, Set<Integer>>> uniquePerKey = input.apply(Combine.perKey(new CombineTest.SharedTestBase.UniqueInts())); PAssert.that(unique).containsInAnyOrder(globalUnique); PAssert.that(uniquePerKey).containsInAnyOrder(perKeyUnique); PipelineResult.State state = pipeline.run().waitUntilFinish(); assertEquals(PipelineResult.State.DONE, state); } private static <T> PCollection<T> copy(PCollection<T> pc, final int n) { return pc.apply( ParDo.of( new DoFn<T, T>() { @ProcessElement public void processElement(ProcessContext c) throws Exception { for (int i = 0; i < n; i++) { c.output(c.element()); } } })); } private static class GetLast extends DoFn<Integer, Integer> { @ProcessElement public void processElement(ProcessContext c) { if (c.pane().isLast()) { c.output(c.element()); } } } }
package com.social.server.controller; import com.social.server.dto.UserDto; import com.social.server.http.Response; import com.social.server.service.FriendService; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.data.domain.PageImpl; import org.springframework.test.context.junit4.SpringRunner; import java.util.Arrays; import static org.mockito.Mockito.*; @RunWith(SpringRunner.class) @WebMvcTest(FriendController.class) public class FriendControllerTest extends CommonControllerTest { private final String api = "/api/v1/" + ID + "/friends"; @MockBean private FriendService friendService; @Test public void successFindFriends() throws Exception { UserDto u = new UserDto(); u.setEmail("test"); u.setName("desr"); when(friendService.find(ID, 1)).thenReturn(new PageImpl<>(Arrays.asList(u))); checkGetRequest(api + "?page=1", Response.ok(new PageImpl<>(Arrays.asList(u)))); } @Test public void successFindCountFriends() throws Exception { when(friendService.count(ID)).thenReturn(10L); checkGetRequest(api + "/count", Response.ok(10L)); } @Test public void successCheckExistFriend() throws Exception { when(friendService.isFriends(ID, ID2)).thenReturn(true); checkGetRequest(api + "/existence/" + ID2, Response.ok(true)); } @Test public void successRemoveFriend() throws Exception { checkDeleteRequest(api + "/" + ID2, null, Response.ok()); verify(friendService, times(1)).remove(eq(ID), eq(ID2)); } @Test public void failedAccessToRemoveFriend() throws Exception { failedAccessToEndpoint(api + "/remove/" + ID2); } @Test public void failedAccessToCheckExistFriend() throws Exception { failedAccessToEndpoint(api + "/existence/" + ID2); } @Test public void failedAccessToFindFriendCount() throws Exception { failedAccessToEndpoint(api + "/count"); } @Test public void failedAccessToFindFixFriend() throws Exception { failedAccessToEndpoint(api + "/3"); } @Test public void failedAccessToFindFriend() throws Exception { failedAccessToEndpoint(api); } }
package dev.mher.taskhunter.models; import dev.mher.taskhunter.utils.DataSourceUtils; import lombok.Getter; import lombok.Setter; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import javax.sql.DataSource; import java.sql.*; /** * User: MheR * Date: 12/2/19. * Time: 7:03 PM. * Project: taskhunter. * Package: dev.mher.taskhunter.models. */ @Component @Getter @Setter public class UserModel { private static final Logger logger = LoggerFactory.getLogger(UserModel.class); private DataSource dataSource; private int userId; private String email; private CharSequence password; private String firstName; private String lastName; private String createdAt; private String updatedAt; private String confirmationToken; private Timestamp confirmationSentAt; private String confirmedAt; private boolean isActive; public UserModel() { } @Autowired public UserModel(DataSource dataSource) { this.dataSource = dataSource; } public boolean signUp() { String queryString = "INSERT INTO users (email, password, confirmation_token, confirmation_sent_at, first_name, last_name) VALUES (?, ?, ?, ?, ?, ?);"; boolean isOk = false; Connection con = null; PreparedStatement pst = null; try { con = dataSource.getConnection(); pst = con.prepareStatement(queryString); pst.setString(1, getEmail()); pst.setString(2, getPassword().toString()); pst.setString(3, getConfirmationToken()); pst.setTimestamp(4, getConfirmationSentAt()); pst.setString(5, getFirstName()); pst.setString(6, getLastName()); pst.execute(); isOk = true; } catch (SQLException e) { logger.info(e.getMessage()); logger.error(e.getMessage(), e); } finally { DataSourceUtils.closeConnection(con, pst, null); } return isOk; } public boolean userConfirm(Timestamp interval) { String queryString = "UPDATE users SET is_active=?, confirmation_token=NULL WHERE confirmation_token=? AND confirmation_sent_at > ?;"; Connection con = null; PreparedStatement pst = null; boolean isUpdated = false; try { con = dataSource.getConnection(); pst = con.prepareStatement(queryString); pst.setBoolean(1, isActive()); pst.setString(2, getConfirmationToken()); pst.setTimestamp(3, interval); isUpdated = pst.executeUpdate() != 0; } catch (SQLException e) { logger.info(e.getMessage()); logger.error(e.getMessage(), e); } finally { DataSourceUtils.closeConnection(con, pst, null); } return isUpdated; } public UserModel findByEmail(String email) { String queryString = "SELECT user_id AS \"userId\",\n" + " email AS \"email\",\n" + " password AS \"password\",\n" + " created_at AS \"createdAt\",\n" + " first_name AS \"firstName\",\n" + " last_name AS \"lastName\",\n" + " is_active AS \"isActive\"\n" + "FROM users\n" + "WHERE email=? AND is_active=?\n" + "LIMIT 1;"; Connection con = null; PreparedStatement pst = null; ResultSet rs = null; try { con = dataSource.getConnection(); pst = con.prepareStatement(queryString); pst.setString(1, email); pst.setBoolean(2, true); rs = pst.executeQuery(); if (rs != null && rs.next()) { UserModel user = new UserModel(); user.setUserId(rs.getInt("userId")); user.setEmail(rs.getString("email")); user.setPassword(rs.getString("password")); user.setFirstName(rs.getString("firstName")); user.setLastName(rs.getString("lastName")); user.setActive(rs.getBoolean("isActive")); return user; } } catch (SQLException e) { logger.info(e.getMessage()); logger.error(e.getMessage(), e); } finally { DataSourceUtils.closeConnection(con, pst, rs); } return null; } }
package Functions; import java.util.Scanner; public class BookFair { String Bname; double price; public BookFair() { Bname = ""; price = 0.0; } public void input() { Scanner sc = new Scanner(System.in); System.out.print("Enter the name of the book: "); Bname = sc.nextLine(); System.out.print("Enter the price of the book: "); price = sc.nextDouble(); } public void calculate() { if (price <= 1000) price = price * 0.98; else if (price > 3000) price = price * 0.85; else price = price * 0.9; System.out.println("The new price is " + price); } public static void main(String args[]) { BookFair b1 = new BookFair(); b1.input(); b1.calculate(); } }
package com.bakerystudios.tools; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.awt.event.MouseMotionListener; public abstract class InputListener implements KeyListener, MouseListener, MouseMotionListener { public void keyTyped(KeyEvent e) { } @Override public void keyPressed(KeyEvent e) { // TODO Auto-generated method stub } @Override public void keyReleased(KeyEvent e) { // TODO Auto-generated method stub } @Override public void mouseClicked(MouseEvent e) { // TODO Auto-generated method stub } @Override public void mousePressed(MouseEvent e) { // TODO Auto-generated method stub } @Override public void mouseReleased(MouseEvent e) { // TODO Auto-generated method stub } @Override public void mouseEntered(MouseEvent e) { // TODO Auto-generated method stub } @Override public void mouseExited(MouseEvent e) { // TODO Auto-generated method stub } @Override public void mouseDragged(MouseEvent e) { // TODO Auto-generated method stub } @Override public void mouseMoved(MouseEvent e) { // TODO Auto-generated method stub } }
package Tutorial.P3_ActorTool.S3_Become_Unbecome.DatabaseOperation; import java.util.Optional; /** * Created by lam.nm on 6/10/2017. */ public class Operation { private DBOperation dbOperation; private User user; public Operation(DBOperation dbOperation, Optional<User> user) { this.dbOperation = dbOperation; this.user = (user.isPresent())?user.get(): null; } public DBOperation getDbOperation() { return dbOperation; } public User getUser() { return user; } @Override public String toString() { return "Operation{" + "dbOperation=" + dbOperation + ", user=" + user + '}'; } }
package com.mvc.language.controllers; //import java.awt.print.Book; import java.util.List; import javax.validation.Valid; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.ModelAttribute; //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.PostMapping; import com.mvc.language.models.Lang; import com.mvc.language.services.LangService; @Controller public class LangController { private final LangService langService; public LangController(LangService langService) { this.langService = langService; } @GetMapping("/") public String index(Model model) { List<Lang> users = langService.allLangs(); model.addAttribute("users", users); model.addAttribute("user", new Lang()); return "/languages/index.jsp"; } @PostMapping(value="/") public String create(@Valid @ModelAttribute("user") Lang user, BindingResult result) { if (result.hasErrors()) { return "/languages/index.jsp"; } else { langService.createOrUpdateLang(user); return "redirect:/books"; } } }