text
stringlengths
10
2.72M
public enum Classe { Aerobic, Steps, Ioga }
package com.git.cloud.resmgt.common.model.po; import java.util.List; import com.git.cloud.common.model.base.BaseBO; import com.git.cloud.resmgt.compute.model.po.RmClusterPo; public class RmResPoolPo extends BaseBO implements java.io.Serializable{ // Fields /** * */ private static final long serialVersionUID = 6997663773772673432L; private String id; private String datacenterId; private String poolName; private String ename; private String status; private String poolType; private String isActive; private String remark; // Constructors /** default constructor */ public RmResPoolPo() { } /** minimal constructor */ public RmResPoolPo(String id) { this.id = id; } /** full constructor */ public RmResPoolPo(String id, String datacenterId, String poolName, String ename, String status, String poolType, String isActive, String remark) { this.id = id; this.datacenterId = datacenterId; this.poolName = poolName; this.ename = ename; this.status = status; this.poolType = poolType; this.isActive = isActive; this.remark = remark; } // Property accessors public String getId() { return this.id; } public void setId(String id) { this.id = id; } public String getPoolName() { return this.poolName; } public void setPoolName(String poolName) { this.poolName = poolName; } public String getEname() { return this.ename; } public void setEname(String ename) { this.ename = ename; } public String getStatus() { return this.status; } public void setStatus(String status) { this.status = status; } public String getPoolType() { return this.poolType; } public void setPoolType(String poolType) { this.poolType = poolType; } public String getIsActive() { return this.isActive; } public void setIsActive(String isActive) { this.isActive = isActive; } public String getRemark() { return this.remark; } public void setRemark(String remark) { this.remark = remark; } public String getDatacenterId() { return datacenterId; } public void setDatacenterId(String datacenterId) { this.datacenterId = datacenterId; } @Override public String getBizId() { // TODO Auto-generated method stub return null; } public List<RmClusterPo> getClusterList() { return clusterList; } public void setClusterList(List<RmClusterPo> clusterList) { this.clusterList = clusterList; } private List<RmClusterPo> clusterList; }
import java.util.ArrayList; import java.util.Calendar; import java.util.Date; public class Customer extends Account { private double balance; private Date birthday; private ArrayList<TrolleyItem> shoppingTrolley; private Membership member; public Customer(String userID, String password, String name, Date birthday, double balance) { super(userID, password, name); this.birthday = birthday; this.balance = balance; this.shoppingTrolley = new ArrayList<TrolleyItem>(); this.member = Normal.getInstance(); } public Membership getMembership() { return member; } public String getName() { return super.getName(); } public double getBalance() { return balance; } public boolean isBirthdayToday() { Date today = new Date(); Calendar calendar = Calendar.getInstance(); Calendar bday = Calendar.getInstance(); calendar.setTime(today); bday.setTime(birthday); return (calendar.get(Calendar.MONTH) == bday.get(Calendar.MONTH)) && (calendar.get(Calendar.DAY_OF_MONTH) == bday.get(Calendar.DAY_OF_MONTH)); } @Override public String toString() { return super.getName() + ", current balance: " + balance + ", no. items in trolley: " + shoppingTrolley.size(); } public void deposit(double amount) { balance += amount; } public void withdraw(double amount) { balance -= amount; } public Date getBirthday() { return birthday; } public void setBirthday(Date birthday) { this.birthday = birthday; } public ArrayList<TrolleyItem> getTrolley() { return shoppingTrolley; } public void setTrolley(ArrayList<TrolleyItem> shoppingTrolley) { this.shoppingTrolley = shoppingTrolley; } public void setMembership(Membership member) { this.member = member; } public void emptyTrolley() { shoppingTrolley.clear(); } public TrolleyItem searchTrolleyByPid(int pid) throws NoSuchProductException { for (TrolleyItem item : shoppingTrolley) { if (item.getProduct().getPid() == pid) return item; } throw new NoSuchProductException("No Such Product in shopping trolley."); } public void removeTrolleyItem(TrolleyItem customerItem) { shoppingTrolley.remove(customerItem); } }
package adcar.com.adcar; import android.app.IntentService; import android.content.Intent; import android.content.Context; import android.location.Location; import android.os.Looper; import android.util.Log; import adcar.com.handler.CoordinatesHandler; /** * An {@link IntentService} subclass for handling asynchronous task requests in * a service on a separate handler thread. * <p/> * TODO: Customize class - update intent actions, extra parameters and static * helper methods. */ public class GPSProcessorService extends IntentService { private static final String LATITUDE = "LATITUDE"; private static final String LONGITUDE = "LONGITUDE"; public static CoordinatesHandler coordinatesHandler = new CoordinatesHandler(); public GPSProcessorService() { super("GPSProcessorService"); } /** * Starts this service to perform action Baz with the given parameters. If * the service is already performing a task this action will be queued. * * @see IntentService */ public static void startGPSLocationDigest(Context context, Double lat, Double lng) { Intent intent = new Intent(context, GPSProcessorService.class); intent.putExtra(LATITUDE, lat); intent.putExtra(LONGITUDE, lng); Log.i("GPSPROCESSOR", "inside start location digest with location = " + lat + " - " + lng); context.startService(intent); } @Override protected void onHandleIntent(Intent intent) { if (intent != null) { Double lat = intent.getDoubleExtra(LATITUDE, -1); Double lng = intent.getDoubleExtra(LONGITUDE, -1); Location location = new Location("MANUAL"); location.setLatitude(lat); location.setLongitude(lng); Log.i("GPSPROCESSOR", "start making use of new location in coordinateHandler"); coordinatesHandler.makeUseOfNewLocation(location); } } }
package com.springbook.biz.common; import org.aopalliance.intercept.Joinpoint; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Before; import org.aspectj.lang.annotation.Pointcut; import org.springframework.context.annotation.Bean; import org.springframework.stereotype.Service; @Service @Aspect //Aspect = Pointcut + Advice public class LogAdvice { //Advice @Before("PointcutCommon.allPointcut()") public void printLLog() { //System.out.println("[공통 로그] 비즈니스 로직 수행 전 동작"); } }
package com.huffingtonpost.chronos.agent; import java.util.concurrent.atomic.AtomicLong; import com.huffingtonpost.chronos.model.SupportedDriver; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonSubTypes; import com.fasterxml.jackson.annotation.JsonTypeInfo; import com.fasterxml.jackson.annotation.JsonSubTypes.Type; import com.huffingtonpost.chronos.model.JobDao; import com.huffingtonpost.chronos.model.MailInfo; import com.huffingtonpost.chronos.model.PlannedJob; import javax.mail.Session; @JsonIgnoreProperties(ignoreUnknown=true) @JsonTypeInfo(use=JsonTypeInfo.Id.NAME, include=JsonTypeInfo.As.PROPERTY, property="type") @JsonSubTypes({ @Type(value=SleepyCallableQuery.class, name="SleepyCallableQuery") }) public class SleepyCallableQuery extends CallableQuery { private final int sleepFor; private final AtomicLong sleepyFinish = new AtomicLong(0); public SleepyCallableQuery(PlannedJob plannedJob, JobDao dao, Reporting reporting, String hostname, MailInfo mailInfo, Session session, SupportedDriver driver, int attemptNumber, int sleepFor) { super(plannedJob, dao, reporting, hostname, mailInfo, session, driver, attemptNumber); this.sleepFor = sleepFor; } @Override public Void call() throws Exception { try { super.call(); } catch (Exception ex) { ex.printStackTrace(); } finally { try { Thread.sleep(sleepFor); } catch (InterruptedException ex) { CallableQuery.LOG.debug("interrupted"); } catch (Exception ex) { ex.printStackTrace(); } finish.set(System.currentTimeMillis()); sleepyFinish.set(System.currentTimeMillis()); dao.updateJobRun(this); } return null; } @Override protected void end() { // do nothing, we'll handle after we've slept } @Override public boolean isRunning() { return start.get() > 0 && sleepyFinish.get() == 0; } @Override public boolean isDone() { return start.get() > 0 && sleepyFinish.get() > 0; } }
package com.raiff.SolarisApp; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class SolarisAppApplication { public static void main(String[] args) { SpringApplication.run(SolarisAppApplication.class, args); } }
package com.esum.framework.jms.topic; import javax.jms.JMSException; import javax.jms.Message; import javax.jms.MessageListener; import javax.jms.MessageProducer; import javax.jms.Session; import javax.jms.TextMessage; import org.apache.log4j.PropertyConfigurator; import org.junit.Before; import org.junit.Test; import com.esum.framework.FrameworkSystemVariables; import com.esum.framework.core.component.ComponentConstants; import com.esum.framework.core.config.Configurator; import com.esum.framework.core.queue.JmsMessageHandler; import com.esum.framework.core.queue.QueueHandlerFactory; import com.esum.framework.core.queue.TopicHandlerFactory; import com.esum.framework.core.queue.mq.JmsTopicMessageHandler; import com.esum.framework.core.queue.mq.ProducerCallback; import com.esum.framework.net.queue.HornetQServer; public class DurableSubscriptionTest { @Before public void init() throws Exception { System.setProperty("xtrus.home", "D:/test/xtrus-4.4.1"); try { PropertyConfigurator.configure("conf/log4j.properties"); Configurator.init(System.getProperty("xtrus.home")+"/conf/env.properties"); Configurator.init(Configurator.DEFAULT_DB_PROPERTIES_ID, System.getProperty("xtrus.home")+"/conf/db.properties"); System.setProperty(FrameworkSystemVariables.NODE_ID, Configurator.getInstance().getString("node.id")); System.setProperty(FrameworkSystemVariables.NODE_TYPE, ComponentConstants.LOCATION_TYPE_MAIN); System.setProperty(FrameworkSystemVariables.NODE_CODE, Configurator.getInstance().getString("node.code")); Configurator.init(QueueHandlerFactory.CONFIG_QUEUE_HANDLER_ID, Configurator.getInstance().getString("queue.properties")); HornetQServer.getInstance().start(); } catch (Exception e) { throw e; } } @Test public void durableScription() throws Exception { // send message. JmsMessageHandler handler = TopicHandlerFactory.getTopicHandler("testTopic"); handler.send(new ProducerCallback() { @Override public void execute(Session session, MessageProducer producer) throws JMSException { Message message = session.createTextMessage("test message1"); producer.send(message); } }); // durablescriber TEST1 handler = TopicHandlerFactory.getTopicHandler("testTopic"); handler.setClientId("TEST1"); ((JmsTopicMessageHandler)handler).setDurableSubscription(true); ((JmsTopicMessageHandler)handler).setSubscriptionId("TestScriber"); handler.setMessageListener(new MessageListener(){ @Override public void onMessage(Message message) { try { TextMessage t = (TextMessage)message; System.out.println("TEST1 ::: "+t.getText()); } catch (JMSException e) { e.printStackTrace(); } finally { try { message.acknowledge(); } catch (JMSException e) { } } } }); // durablescriber TEST2 handler = TopicHandlerFactory.getTopicHandler("testTopic"); handler.setClientId("TEST2"); ((JmsTopicMessageHandler)handler).setDurableSubscription(true); ((JmsTopicMessageHandler)handler).setSubscriptionId("TestScriber"); handler.setMessageListener(new MessageListener(){ @Override public void onMessage(Message message) { try { TextMessage t = (TextMessage)message; System.out.println("TEST2 ::: "+t.getText()); } catch (JMSException e) { e.printStackTrace(); } finally { try { message.acknowledge(); } catch (JMSException e) { } } } }); // send message. handler = TopicHandlerFactory.getTopicHandler("testTopic"); handler.send(new ProducerCallback() { @Override public void execute(Session session, MessageProducer producer) throws JMSException { Message message = session.createTextMessage("test message2"); producer.send(message); } }); Thread.sleep(5*1000); handler.close(); } }
package com.show.comm.mybatis; import java.io.Serializable; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import com.fasterxml.jackson.annotation.JsonIgnore; /** * 分页数据对象 * * <pre> * 使用Paging执行分页查询(PagingInterceptor)务必保证: * 1、SQL中字段、表名不能包含“form”、“group by”、“order by”等关键字(拦截器会根据这些关键字进行解析) * 2、复杂SQL语句,请尽量使用#c#统计标签,详细信息{@link SQLInterceptor} * 3、使用order(column,asc)执行排序时,请保证SQL中已有的order by条件在SQL句末(如有) * 4、请在service impl实现中,自行调用setData方法填充查询数据 * </pre> * * @author heyuhua * @date 2017年6月6日 * */ public class Paging implements Serializable { private static final long serialVersionUID = -8687427837954125779L; /** 当前页(默认1) */ private int currentPage = 1; /** 每页数据量(1~Integer.MAX_VALUE-1,默认10) */ private int pageSize = 10; /** 总数据量 */ private int amount = 0; /** 总页数 */ private int pages = 0; /** 查询到的数据集合 */ private List<?> data = null; /** 添加参数map */ @JsonIgnore transient private Map<String, Object> params = new HashMap<String, Object>(); /** 排序<字段,顺序> */ @JsonIgnore transient private Map<String, String> orders = null; /** 排序SQL */ @JsonIgnore transient private String order = ""; /** * 添加排序 * * @param column * 排序字段(查询SQL中完整的字段名称[0-9A-Za-z_\\-\\.]{1,32}) * @param asc * 是否升序 */ public void order(String column, boolean asc) { if (null != column && column.matches("[0-9A-Za-z_\\-\\.]{1,32}")) { if (null == orders) { orders = new LinkedHashMap<String, String>(); } orders.put(column, asc ? "asc" : "desc"); } } /** * 添加条件(params.put(key,value)) * * @param key * 条件KEY * @param value * 条件value(为null时不做任何操作) */ public void add(String key, Object value) { if (null != key && null != value) { params.put(key, value); } } /** * 添加like条件(params.put(key,value)) * * @param key * 条件KEY * @param value * 条件value(自动添加%value%,为null时不做任何操作) */ public void like(String key, String value) { if (null != key && null != value) { params.put(key, "%" + value + "%"); } } /** * 添加like条件(params.put(key,value)) * * @param key * 条件KEY * @param value * 条件value(自动添加%value,为null时不做任何操作) */ public void llike(String key, String value) { if (null != key && null != value) { params.put(key, "%" + value); } } /** * 添加like条件(params.put(key,value)) * * @param key * 条件KEY * @param value * 条件value(自动添加value%,为null时不做任何操作) */ public void rlike(String key, String value) { if (null != key && null != value) { params.put(key, value + "%"); } } /** * 添加手机号码匹配添加(params.put(key,value)) * * @param key * 条件KEY * @param phone * 手机号码(自动添加%phone%,要求[0-9]{1,11},长度为11时不添加通配符) */ public boolean phone(String key, String phone) { if (null != key && null != phone && phone.matches("[0-9]{1,11}")) { if (phone.length() == 11) { params.put(key, phone); return true; } else { params.put(key, "%" + phone + "%"); return true; } } return false; } /** * 添加卡号匹配添加(params.put(key,value)) * * @param key * 条件KEY * @param card * 卡号(自动添加%card%,要求[0-9]{4,10},长度为10时不添加通配符) */ public boolean card(String key, String card) { if (null != key && null != card && card.matches("[0-9]{4,10}")) { if (card.length() == 10) { params.put(key, card); return true; } else { params.put(key, "%" + card + "%"); return true; } } return false; } /** * 移除条件 * * @param key * 条件KEY */ public void rmv(String key) { if (null != key) { params.remove(key); } } /** * 获取条件值 * * @param key * 条件KEY * @return 值 */ public Object get(String key) { return null != key ? params.get(key) : null; } /** * 分页数据对象 - 缺省构造 */ public Paging() { } /** * 分页数据对象 - 构造 * * @param currentPage * 当前页 */ public Paging(Integer currentPage) { if (null != currentPage) { int p = currentPage.intValue(); if (p > 0) { this.currentPage = p; } } } /** * 分页数据对象 - 构造 * * @param currentPage * 当前页 * @param pageSize * 每页数据量 */ public Paging(Integer currentPage, Integer pageSize) { if (null != currentPage) { int p = currentPage.intValue(); if (p > 0) { this.currentPage = p; } } if (null != pageSize) { setPageSize(pageSize.intValue()); } } /** * @return 当前页,缺省1 */ public int getCurrentPage() { return currentPage; } /** * @param currentPage * 当前页,缺省1 */ public void setCurrentPage(int currentPage) { this.currentPage = currentPage; } /** * @return 每页数据量,缺省10 */ public int getPageSize() { return pageSize; } /** * @param pageSize * 每页数据量,缺省10 */ public void setPageSize(int pageSize) { if (pageSize > 0) { if (pageSize == Integer.MAX_VALUE) { pageSize--; } this.pageSize = pageSize; } } /** * @return 总数据量 */ public int getAmount() { return amount; } /** * @param amount * 总数据量 */ public void setAmount(int amount) { this.amount = amount; if (this.amount > 0) { this.pages = amount % pageSize == 0 ? amount / pageSize : amount / pageSize + 1; } else { this.pages = 0; } } /** * @return 总页数 */ public int getPages() { return pages; } /** * @param pages * 总页数 */ public void setPages(int pages) { this.pages = pages; } /** * @return 查询到的数据集合 */ public List<?> getData() { return data; } /** * @param data * 查询到的数据集合 */ public void setData(List<?> data) { this.data = data; } /** * 获取条件,请在sql中自行具体实现 */ public Map<String, Object> getParams() { return params; } /** * @param params * 查询条件,特殊情况请调用次方法自行传入完整条件 */ public void setParams(Map<String, Object> params) { this.params = params; } /** * 获取排序<字段,顺序> */ public Map<String, String> getOrders() { return orders; } /** * 获取排序条件sql */ public String getOrder() { if (null != orders) { StringBuilder sb = new StringBuilder(); orders.forEach((key, val) -> { sb.append(", ").append(key).append(" ").append(val); }); if (sb.length() != 0) { order = sb.substring(1); } } return order; } @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append("Paging [currentPage="); builder.append(currentPage); builder.append(", pageSize="); builder.append(pageSize); builder.append(", amount="); builder.append(amount); builder.append(", pages="); builder.append(pages); builder.append(", params="); builder.append(params); builder.append(", orders="); builder.append(orders); builder.append("]"); return builder.toString(); } }
package com.example.herokuexample.controllers; import com.example.herokuexample.persons.Person; import com.example.herokuexample.persons.PersonsRepository; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import com.google.gson.JsonSyntaxException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import java.util.List; @RestController @RequestMapping("person") public class PersonsController { @Autowired PersonsRepository personsRepository; @RequestMapping(value = "/create", method = RequestMethod.PUT) public void createUser(@RequestBody String jsonParam) { try { JsonObject obj = JsonParser.parseString(jsonParam).getAsJsonObject(); String name = obj.getAsJsonPrimitive("name").getAsString(); personsRepository.insertPerson(name); } catch(JsonSyntaxException e) { e.printStackTrace(); } } @RequestMapping(value = "{id}", method = RequestMethod.GET) public Person getPerson(@PathVariable Integer id) { return personsRepository.selectPerson(id); } @RequestMapping(value = "all", method = RequestMethod.GET) public List<Person> getPersons() { return personsRepository.selectAllPersons(); } }
package edu.nyu.cs9053.homework4.hierarchy; public abstract class FreshWater extends BodyOfWater { private final double isSalty; public FreshWater(String name, double volume, double isSalty) { super(name, volume); this.isSalty = isSalty; } public double getIsSalty() { return isSalty; } public abstract String getDescription(); }
package mx.jovannypcg.shortener.links; import android.app.ProgressDialog; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.Toast; import java.util.ArrayList; import java.util.List; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.OnClick; import butterknife.OnItemClick; import butterknife.OnItemSelected; import mx.jovannypcg.shortener.R; import mx.jovannypcg.shortener.browser.BrowserActivity; import mx.jovannypcg.shortener.destination.DestinationActivity; import mx.jovannypcg.shortener.rest.model.ApiShortLink; public class LinksActivity extends AppCompatActivity implements LinksView { @BindView(R.id.lv_links) ListView lvLinks; private LinksPresenter presenter; private LinksAdapter linksAdapter; private ProgressDialog progressDialog; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_links); ButterKnife.bind(this); presenter = new LinksPresenterImpl(this); progressDialog = new ProgressDialog(this); progressDialog.setIndeterminate(true); progressDialog.setMessage(getResources().getString(R.string.retrieving)); List<ApiShortLink> emptyList = new ArrayList<>(); linksAdapter = new LinksAdapter(this, emptyList); lvLinks.setAdapter(linksAdapter); } @OnClick(R.id.btn_get_links) public void getLinks() { presenter.submitRequest(); } @Override public void refreshList(List<ApiShortLink> items) { linksAdapter.clear(); linksAdapter.addAll(items); linksAdapter.notifyDataSetChanged(); } @OnItemClick(R.id.lv_links) public void onItemClick(int position) { String currentSlug = (String) linksAdapter.getItem(position); presenter.handleClickedSlug(currentSlug); } @Override public void navigateToDestinationDetail(String slug) { Intent destinationDetailIntent = new Intent(this, DestinationActivity.class); destinationDetailIntent.putExtra("slug", slug); startActivity(destinationDetailIntent); } @Override public void showProgress() { progressDialog.show(); } @Override public void dismissProgress() { progressDialog.dismiss(); } @Override public void showMessage(String message) { Toast.makeText(this, message, Toast.LENGTH_SHORT).show(); } }
package com.kywpcm.DaQ; import java.util.Scanner; public class P1074_DY { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int r = sc.nextInt(); int c = sc.nextInt(); int sum=0; such(n, r, c, sum); } private static void such(int n, int r, int c, int sum) { if(n == 0) System.out.println(sum); else { if(r>=Math.pow(2,n)/2 && c>=Math.pow(2, n)/2){ sum += 3*Math.pow(Math.pow(2,n-1), 2); r = (int) (r - (Math.pow(2,n)/2)); c = (int) (c - (Math.pow(2,n)/2)); } else if(r>=Math.pow(2,n)/2) { sum += 2*Math.pow(Math.pow(2,n-1), 2); r = (int) (r - (Math.pow(2,n)/2)); } else if(c>=Math.pow(2, n)/2) { sum += Math.pow(Math.pow(2,n-1), 2); c = (int) (c - (Math.pow(2,n)/2)); } such(n-1, r, c, sum); } } }
package LimpBiscuit.Demo.Entity; import javax.persistence.*; @Entity @Table(uniqueConstraints = @UniqueConstraint(columnNames = {"name", "family"})) public class RequestOperatingSystem { @Id @GeneratedValue(strategy = GenerationType.SEQUENCE) private Integer id; private String name; private String family; public RequestOperatingSystem() { } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getFamily() { return family; } public void setFamily(String group) { this.family = group; } }
package net.imglib2.view.ijmeta; import net.imglib2.transform.integer.Mixed; import net.imglib2.view.meta.MetaSpace; import net.imglib2.view.meta.MetaSpaceView; public class IjMetaSpaceView extends MetaSpaceView< IjMetaSpace, MetaDataSet > implements IjMetaSpace { public IjMetaSpaceView( final IjMetaSpace source, final Mixed transformToSource ) { super( source, transformToSource ); } @Override public MetaDataSetFactory elementFactory() { return MetaDataSetFactory.instance; } @Override public MetaSpace.ViewFactory< IjMetaSpace > viewFactory() { return Factory.instance; } static class Factory implements MetaSpace.ViewFactory< IjMetaSpace > { private Factory() {} public static final Factory instance = new Factory(); @Override public IjMetaSpace createView( final IjMetaSpace source, final Mixed transformToSource ) { return new IjMetaSpaceView( source, transformToSource ); } } }
package EEV_v3; import java.net.PasswordAuthentication; import java.util.ArrayList; import java.util.Arrays; import java.util.Random; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; public class draft { static Random rd=new Random(); public static void main(String[] args) { testDieVarince(); //testGaussianProbabiliities(); //testWorldDistributions(); //testThreading(); //testForLoop(); //cloneTest(); //arrayCopy(); //compareDoubles(); //worldSizes(2); //charTOInt(); //testTernary(4); //testIntToObject(); //testArrayList(); //testArrayPass(); //testProb(); //shuffleArray(); } private static void testDieVarince(){ rd = new Random(); for (int i = 10; i > 0; i--) { int Die1 = rd.nextInt(i + 1); System.out.println (Die1); // Simple swap /*double a = ar[index]; ar[index] = ar[i]; ar[i] = a;*/ } } public static double calculateSampleSD(double numArray[]) { double sum = 0.0, standardDeviation = 0.0; int length = numArray.length; for(double num : numArray) { sum += num; } double mean = sum/length; for(double num: numArray) { standardDeviation += Math.pow(num - mean, 2); } return Math.sqrt(standardDeviation/length); } public static double calculatePopulationSD(double numArray[]) { double sum = 0.0, standardDeviation = 0.0; int length = numArray.length; for(double num : numArray) { sum += num; } double mean = sum/length; for(double num: numArray) { standardDeviation += Math.pow(num - mean, 2); } return Math.sqrt(standardDeviation/length-1); } private static void shuffleArray() { int[] x={100, 101, 102}; int order = 2, myIndex = 0; for (int f= 0; f<10; f++) for (int i = x.length - 1; i > 0; i--) { int index = rd.nextInt(i + 1); if (i == index) continue; int temp; temp = x[index]; x[index] = x[i]; x[i] = temp; if (i == order) { order = index; } else if (order == index) order = i; if (i == myIndex) { myIndex = index; } else if (myIndex == index) myIndex = i; } System.out.println ( " order " + order + " myindex " + myIndex + " " + x[0] + " " + x[1] + " " + x[2]); } private static void testProb() { int size=8; double total = 10000, war = 0, nowar = 0; int temp1, temp2, temp3; for (int j = 0; j < total; j++) { boolean atWar[]=new boolean[size]; for (int i = 1; i < size; i++) { if (atWar[i]) continue; temp1 = rd.nextInt(size*1); if (i == temp1) continue; if (temp1 == 0) { war++; break; } if (temp1 >= size) continue; atWar[i] = true; atWar[temp1] = true; continue; /*for (int k = 1; k < size; k++) { if (atWar[k]) continue; temp2 = rd.nextInt(3); if (temp2 == 0) continue; atWar[k] = true; }*/ /*temp2 = rd.nextInt(4); temp3 = rd.nextInt(4); if (rd.nextInt(1) == 0) { if (temp1 == 0) { war++; continue; } else if (temp1 == 1) { if (temp2 == 0) { war++; continue; } else if (temp2 == 1) { if (temp3 == 0) { war++; continue; } } } } nowar++;*/ } } System.out.println(war / total ); } private static void testArrayPass() { boolean[] sideA = new boolean[2]; Pass(sideA); System.out.println(sideA[0] + " " + sideA[1]); } private static void Pass(boolean[] sideA) { sideA[1]=true; } private static void testArrayList() { ArrayList<Outcome> xArrayList=new ArrayList<Outcome>(); System.out.println(xArrayList.size()); Outcome xOutcome=new Outcome(null); xArrayList.add(xOutcome); System.out.println(xArrayList.size()); } private static void testIntToObject() { Integer yInteger=1; System.out.println(yInteger); Integer zInteger = yInteger; yInteger=2; System.out.println(yInteger + " " + zInteger); } private static void testTernary(int worldSize) { System.out.println("Num combinations " + Math.pow(3, worldSize - 1)); long[] output = new long[worldSize - 1]; for (int numCounter = 0; numCounter < Math.pow(3, worldSize - 1); numCounter++) { output = decToTernary(numCounter, worldSize - 1); System.out.print(numCounter + ": "); for (int i = 0; i < output.length; i++) System.out.print(output[i] + " "); System.out.println(); } } static long[] decToTernary(long input, int arraySize){ long ret = 0, factor = 1; while (input > 0) { ret += input % 3 * factor; input /= 3; factor *= 10; } return numToArray(ret, arraySize); } static long[] numToArray(long number, int arraySize){ long[] iarray = new long[arraySize]; for (int index = 0; index < arraySize; index++) { iarray[index] = number % 10; number /= 10; } return iarray; } private static void charTOInt() { char x; int y=rd.nextInt(2); x = (char) y; System.out.print((int)x + " " + y); } private static void worldSizes(int worldSize) { int[][] x = createRelation(worldSize); for (int i = 0; i < x.length; i++) { for (int j = 0; j < x[i].length; j++) { System.out.print(x[i][j]); } System.out.println(); } } private static int[][] createRelation(int worldSize) { int[][] GTRelations = new int[Integer.MAX_VALUE][worldSize - 2]; int countWorlds = 0; return GTRelations; } private static void compareDoubles() { rd = new Random(); for (int k=0; k<100; k++){ double f= 0.05; boolean[] x = new boolean[200000000]; double[] a = new double[200000000]; //double[] b = new double[100000000]; int counter=0, z=0; for (int i = 0; i < 200000000; i++) a[i] = rd.nextDouble(); //b[i] = rd.nextDouble(); while(counter<200000000 - 5) { if (a[counter++] < a[counter++]) { x[z++] = true; } } for (int i = 0; i < 200000000; i++) { if (a[i] < f & x[i] == false){ System.out.print("error"); System.exit(0); } } System.out.println("here"); } } private static void arrayCopy() { // TODO Auto-generated method stub char[] c=new char[3]; c[0]='A'; c[1]='B'; c[2]='C'; char[] d = Arrays.copyOfRange(c, 2, 3); System.out.print(c[2] + " " + d[0]); } private static void cloneTest() { char[] c=new char[3]; c[0]='A'; c[1]='B'; c[2]='C'; char[] d=c.clone(); d[0]='X'; System.out.print(c[0] + " " + d[0]); } private static void testForLoop() { for (int i=1; i<1; i++) System.out.print("here"); } private static void testThreading() { int processors = Runtime.getRuntime().availableProcessors(); final ExecutorService executor; executor = Executors.newFixedThreadPool(processors);// creating a // pool // of 5 threads for (int k = 0; k < 2; k++) { Future<Void>[] tasks = new Future[10]; String[] strings = new String[10]; for (int i = 0; i < 10; i++) { Callable<Void> draft2_test = new draft2("hello"); tasks[i] = executor.submit(draft2_test); } for (int i = 0; i < 10; i++) { try { tasks[i].get(); System.out.println("got string " + i); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ExecutionException e) { // TODO Auto-generated catch block e.printStackTrace(); } } System.out.println("I am here!!!!!!!!!!!!"); } executor.shutdown(); while (!executor.isTerminated()) { } System.out.println("Finished all threads"); } private static void testWorldDistributions() { rd = new Random(); double counter1 = 0, counter2 = 0, counter3 = 0, counter4 = 0; double[] capabilities = new double[4]; for (int i = 0; i < 100000; i++) { double remainder = 1; capabilities[0] = remainder * rd.nextDouble(); remainder -= capabilities[0]; capabilities[1] = remainder * rd.nextDouble(); remainder -= capabilities[1]; capabilities[2] = remainder * rd.nextDouble(); remainder -= capabilities[2]; capabilities[3] = remainder; shuffleArray(capabilities); counter1 += capabilities[0]; counter2 += capabilities[1]; counter3 += capabilities[2]; counter4 += capabilities[3]; } System.out.println((double)counter1/100000 + " " + (double)counter2/100000 + " " + (double)counter3/100000 + " " + (double)counter4/100000); } static void shuffleArray(double[] ar) { // If running on Java 6 or older, use `new Random()` on RHS here rd = new Random(); for (int i = ar.length - 1; i > 0; i--) { int index = rd.nextInt(i + 1); // Simple swap double a = ar[index]; ar[index] = ar[i]; ar[i] = a; } } private static void testGaussianProbabiliities() { int N = 10000000; rd = new Random(); int counter1 = 0, counter2 = 0, counter3 = 0, counter4 = 0; double d, sum = 0; double capSS = 0; double[] numbers= new double[N]; for (int i = 0; i < N; i++) { d = Math.abs(rd.nextGaussian()* 0.315); numbers[i]= d; sum +=d; if (d > 0 & d < 0.5) counter1++; if (d > 0.5 & d<1) counter2++; if (d > 1 ) counter3++; if (d > 0 & d<0.25) counter4++; } double capAvg = sum / N; for (int i = 0; i < N; i++) capSS += (numbers[i] - capAvg) * (numbers[i] - capAvg); double capSD = Math.sqrt(capSS / N); System.out.println((double) counter1/ N + " " + (double) counter2 / N + " " + (double) counter3 / N + " " + (double) counter4 / N); System.out.println("Mean " + capAvg + " SD " + capSD); } }
/** */ package CFG.util; import CFG.*; import org.eclipse.emf.common.notify.Adapter; import org.eclipse.emf.common.notify.Notifier; import org.eclipse.emf.common.notify.impl.AdapterFactoryImpl; import org.eclipse.emf.ecore.EObject; /** * <!-- begin-user-doc --> * The <b>Adapter Factory</b> for the model. * It provides an adapter <code>createXXX</code> method for each class of the model. * <!-- end-user-doc --> * @see CFG.CFGPackage * @generated */ public class CFGAdapterFactory extends AdapterFactoryImpl { /** * The cached model package. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected static CFGPackage modelPackage; /** * Creates an instance of the adapter factory. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public CFGAdapterFactory() { if (modelPackage == null) { modelPackage = CFGPackage.eINSTANCE; } } /** * Returns whether this factory is applicable for the type of the object. * <!-- begin-user-doc --> * This implementation returns <code>true</code> if the object is either the model's package or is an instance object of the model. * <!-- end-user-doc --> * @return whether this factory is applicable for the type of the object. * @generated */ @Override public boolean isFactoryForType(Object object) { if (object == modelPackage) { return true; } if (object instanceof EObject) { return ((EObject)object).eClass().getEPackage() == modelPackage; } return false; } /** * The switch that delegates to the <code>createXXX</code> methods. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected CFGSwitch<Adapter> modelSwitch = new CFGSwitch<Adapter>() { @Override public Adapter caseMControlFlowGraph(MControlFlowGraph object) { return createMControlFlowGraphAdapter(); } @Override public Adapter caseAbstractNode(AbstractNode object) { return createAbstractNodeAdapter(); } @Override public Adapter caseNode(Node object) { return createNodeAdapter(); } @Override public Adapter caseConditionalNode(ConditionalNode object) { return createConditionalNodeAdapter(); } @Override public Adapter caseIterativeNode(IterativeNode object) { return createIterativeNodeAdapter(); } @Override public Adapter caseVar(Var object) { return createVarAdapter(); } @Override public Adapter caseParam(Param object) { return createParamAdapter(); } @Override public Adapter defaultCase(EObject object) { return createEObjectAdapter(); } }; /** * Creates an adapter for the <code>target</code>. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param target the object to adapt. * @return the adapter for the <code>target</code>. * @generated */ @Override public Adapter createAdapter(Notifier target) { return modelSwitch.doSwitch((EObject)target); } /** * Creates a new adapter for an object of class '{@link CFG.MControlFlowGraph <em>MControl Flow Graph</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see CFG.MControlFlowGraph * @generated */ public Adapter createMControlFlowGraphAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link CFG.AbstractNode <em>Abstract Node</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see CFG.AbstractNode * @generated */ public Adapter createAbstractNodeAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link CFG.Node <em>Node</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see CFG.Node * @generated */ public Adapter createNodeAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link CFG.ConditionalNode <em>Conditional Node</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see CFG.ConditionalNode * @generated */ public Adapter createConditionalNodeAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link CFG.IterativeNode <em>Iterative Node</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see CFG.IterativeNode * @generated */ public Adapter createIterativeNodeAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link CFG.Var <em>Var</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see CFG.Var * @generated */ public Adapter createVarAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link CFG.Param <em>Param</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see CFG.Param * @generated */ public Adapter createParamAdapter() { return null; } /** * Creates a new adapter for the default case. * <!-- begin-user-doc --> * This default implementation returns null. * <!-- end-user-doc --> * @return the new adapter. * @generated */ public Adapter createEObjectAdapter() { return null; } } //CFGAdapterFactory
package com.zzping.fix.mapper; import java.util.List; import com.zzping.fix.entity.FixDorm; import com.zzping.fix.entity.FixDormCriteria; import com.zzping.fix.model.FixDormModel; import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Param; @Mapper public interface FixDormMapper { long countByExample(FixDormCriteria example); int deleteByExample(FixDormCriteria example); int deleteByPrimaryKey(String dormId); int insert(FixDorm record); int insertSelective(FixDorm record); List<FixDorm> selectByExample(FixDormCriteria example); FixDorm selectByPrimaryKey(String dormId); int updateByExampleSelective(@Param("record") FixDorm record, @Param("example") FixDormCriteria example); int updateByExample(@Param("record") FixDorm record, @Param("example") FixDormCriteria example); int updateByPrimaryKeySelective(FixDorm record); int updateByPrimaryKey(FixDorm record); List<FixDormModel> selectCommunityByCampus(@Param("campus") String campus); List<FixDormModel> selectDormByBuildingNo(@Param("buildingNo") String buildingNo,@Param("communityNo") String communityNo); List<FixDormModel> selectBuildingByCommunityNo(@Param("communityNo") String communityNo); List<FixDormModel> selectByBuildingNoAndDormNo(@Param("buildingNo") String buildingNo, @Param("dormNo") String dormNo); }
package util; /** * Created by Mitchell on 20-May-17. * Used for containing individual Moves within a @MoveSet.java */ public class MoveKey { private final int key; public MoveKey(int id) { this.key = id; } public MoveKey(MoveKey mK) { this.key = mK.getKey(); } public int getKey() { return this.key; } @Override public int hashCode() { return (key * 31); } @Override public boolean equals(Object obj) { if(obj == null) { return false; } if(obj instanceof MoveKey) { MoveKey temp = (MoveKey) obj; return (temp.getKey() == this.getKey()); } return false; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(this.key); return sb.toString(); } }
/* * Copyright 2002-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.beans.factory.annotation; import org.springframework.beans.factory.wiring.BeanWiringInfo; import org.springframework.beans.factory.wiring.BeanWiringInfoResolver; import org.springframework.lang.Nullable; import org.springframework.util.Assert; import org.springframework.util.ClassUtils; /** * {@link org.springframework.beans.factory.wiring.BeanWiringInfoResolver} that * uses the Configurable annotation to identify which classes need autowiring. * The bean name to look up will be taken from the {@link Configurable} annotation * if specified; otherwise the default will be the fully-qualified name of the * class being configured. * * @author Rod Johnson * @author Juergen Hoeller * @since 2.0 * @see Configurable * @see org.springframework.beans.factory.wiring.ClassNameBeanWiringInfoResolver */ public class AnnotationBeanWiringInfoResolver implements BeanWiringInfoResolver { @Override @Nullable public BeanWiringInfo resolveWiringInfo(Object beanInstance) { Assert.notNull(beanInstance, "Bean instance must not be null"); Configurable annotation = beanInstance.getClass().getAnnotation(Configurable.class); return (annotation != null ? buildWiringInfo(beanInstance, annotation) : null); } /** * Build the {@link BeanWiringInfo} for the given {@link Configurable} annotation. * @param beanInstance the bean instance * @param annotation the Configurable annotation found on the bean class * @return the resolved BeanWiringInfo */ protected BeanWiringInfo buildWiringInfo(Object beanInstance, Configurable annotation) { if (!Autowire.NO.equals(annotation.autowire())) { // Autowiring by name or by type return new BeanWiringInfo(annotation.autowire().value(), annotation.dependencyCheck()); } else if (!annotation.value().isEmpty()) { // Explicitly specified bean name for bean definition to take property values from return new BeanWiringInfo(annotation.value(), false); } else { // Default bean name for bean definition to take property values from return new BeanWiringInfo(getDefaultBeanName(beanInstance), true); } } /** * Determine the default bean name for the specified bean instance. * <p>The default implementation returns the superclass name for a CGLIB * proxy and the name of the plain bean class else. * @param beanInstance the bean instance to build a default name for * @return the default bean name to use * @see org.springframework.util.ClassUtils#getUserClass(Class) */ protected String getDefaultBeanName(Object beanInstance) { return ClassUtils.getUserClass(beanInstance).getName(); } }
package factoring.math; import org.junit.Test; /** * Created by Thilo Harich on 08.01.2018. */ public class SqrtTest { private static final long bit61 = 1l<<61; private static final long bit52 = 1l<<52; private static final double ONE_HALF = 1.0 / 2; private static final double BALANCE = 1.0 / 2.03; double [] sqrts; double [] sqrtInvs; int loops = 6000; @Test public void testSqrt () { final long range = 1l << 15; // sqrts = new double [range+1]; sqrts = new double[(int) range]; sqrtInvs = new double[(int) range]; for (int i = 0; i < sqrts.length; i++) { sqrts[i] = Math.sqrt(i); sqrtInvs[i] = 1.0/Math.sqrt(i); } long start, end; start = System.currentTimeMillis(); doSqrtTable(range); end = System.currentTimeMillis(); System.out.println(" time sqrt table: " + (end- start)); System.out.println(Math.sqrt(range)); start = System.currentTimeMillis(); doSqrt1(range); end = System.currentTimeMillis(); System.out.println(" time sqrt 1 : " + (end- start)); System.out.println(sqrt1(range)); start = System.currentTimeMillis(); doSqrtDouble(range); end = System.currentTimeMillis(); System.out.println(" time sqrt doub : " + (end- start)); System.out.println(sqrtDouble(range)); start = System.currentTimeMillis(); doSqrt(range); end = System.currentTimeMillis(); System.out.println(" time Math.sqrt : " + (end- start)); System.out.println(sqrtTable((int) range)); start = System.currentTimeMillis(); doSqrtMix(range); end = System.currentTimeMillis(); System.out.println(" time sqrt mix : " + (end- start)); System.out.println(sqrtMix(range)); // start = System.currentTimeMillis(); // array2(range); // end = System.currentTimeMillis(); // System.out.println(" time array2 : " + (end- start)); // // start = System.currentTimeMillis(); // array(range); // end = System.currentTimeMillis(); // System.out.println(" time array : " + (end- start)); // } private double array(long range) { double prod = 1; final long n = 1l << 21; final double sqrtN = Math.sqrt(n); for (int j = 1; j <loops; j++) { for (int i = 1; i < range; i++) { final double sqrt = sqrts[i] * sqrtN; prod += sqrt + 1d/sqrt ; } } return prod; } private double array2(long range) { double prod = 1; final long n = 1l << 21; final double sqrtN = Math.sqrt(n); final double sqrtNInv = 1d/Math.sqrt(n); for (int j = 1; j <loops; j++) { for (int i = 1; i < range; i++) { final double sqrt = sqrts[i] * sqrtN; final double sqrtInv = sqrtInvs[i] * sqrtNInv; prod += sqrt + sqrtInv ; } } return prod; } private double clever(int range) { double prod = 1; final double sqrt2 = Math.sqrt(2); final double sqrt3 = Math.sqrt(3); for (int j = 0; j <loops; j++) { for (int i = 0; i < range; i++) { sqrts[i] = 0; } for (int i = 0; i < range; i++) { if (sqrts[i] == 0) { final double sqrt = Math.sqrt(i); sqrts[i] = sqrt; prod *= sqrt; final int i2 = 2*i; if (i2 < range) { if(sqrts[i2] == 0) { sqrts[i2] = sqrt * sqrt2; prod *= sqrts[i2]; } final int i3 = 3*i; if (i3 < range) { if(sqrts[i3] == 0) { sqrts[i3] = sqrt * sqrt3; prod *= sqrts[i3]; } final int i4 = 4*i; if (i4 < range && sqrts[i4] == 0) { sqrts[i4] = sqrt * 2; prod *= sqrts[i4]; } } } } } } return prod; } private double cleverMask(int range) { double prod = 1; final double sqrt2 = Math.sqrt(2); final double sqrt3 = Math.sqrt(3); for (int j = 0; j <loops; j++) { for (int i = 0; i < range; i++) { sqrts[i] = 0; } for (int i = 0; i < range; i++) { if (sqrts[i] == 0) { final double sqrt = Math.sqrt(i); sqrts[i] = sqrt; prod *= sqrt; final int i2 = 2*i; if (i2 < range) { if(sqrts[i2] == 0) { sqrts[i2] = sqrt * sqrt2; prod *= sqrts[i2]; } final int i3 = 3*i; if (i3 < range) { if(sqrts[i3] == 0) { sqrts[i3] = sqrt * sqrt3; prod *= sqrts[i3]; } final int i4 = 4*i; if (i4 < range && sqrts[i4] == 0) { sqrts[i4] = sqrt * 2; prod *= sqrts[i4]; } } } } } } return prod; } private double doSqrt(long range) { double prod = 1; for (int j = 0; j < loops; j++) for (long i = 0; i < range; i++) { final long sqrt = (long) Math.sqrt(i); prod += sqrt; } return prod; } private double doSqrt1(long range) { double prod = 1; for (int j = 0; j < loops; j++) for (long i = 0; i < range; i++) { final long sqrt = sqrt1(i); prod += sqrt; } return prod; } private double doSqrtDouble(long range) { double prod = 1; for (int j = 0; j < loops; j++) for (long i = 0; i < range; i++) { final long sqrt = (long) sqrtDouble(i); prod += sqrt; } return prod; } private double doSqrtTable(long range) { double prod = 1; for (int j = 0; j < loops; j++) for (int i = 0; i < range; i++) { final long sqrt = (long) sqrtTable(i); prod += sqrt; } return prod; } private double doSqrtMix(long range) { double prod = 1; for (long i = 0; i < range; i++) { final long sqrt = sqrtMix(i); prod += sqrt; } return prod; } public static float sqrtTable(int x) { return SquareRoot.sqrt(x); } public static double sqrtDouble(double f) { final double y = Double.longBitsToDouble(0x5fe6ec85e7de30daL - (Double.doubleToLongBits(f) >> 1)); // evil floating point bit level hacking -- Use 0x5f375a86 instead of 0x5f3759df, due to slight accuracy increase. (Credit to Chris Lomont) // y = y * (1.5F - (0.5F * f * y * y)); // Newton step, repeating increases accuracy return f * y; } public static double sqrt2(double f) { final double y = Double.longBitsToDouble(0x5fe6ec85e7de30daL - (Double.doubleToLongBits(f) >> 1)); // evil floating point bit level hacking -- Use 0x5f375a86 instead of 0x5f3759df, due to slight accuracy increase. (Credit to Chris Lomont) // y = y * (1.5F - (0.5F * f * y * y)); // Newton step, repeating increases accuracy return f * y; } /** * sqrt(x*2^k) = sqrt((1-a)*2^k) = sqrt((1-a))*2^(k/2) ~ * 1-a/2 * 2^(k/2) * Bei x*2^k als long aufgefasst und durch 2 geteilt ist x/2 * 2^(k/2) * 1 - x*2^k als long aufgefasst ist (1-x/2) * 2^(k/2) * also finde die Long Darstellung von 1D * * @param x * @return */ public static long sqrt1(double x) { // final double sqrtReal = Math.sqrt(x); // final double sqrt2 = Double.longBitsToDouble(((Double.doubleToRawLongBits(x) >> 32) + 1072632448 ) << 31); final double sqrt = Double.longBitsToDouble( ( ( Double.doubleToLongBits( x )- bit52 )>>1 ) + bit61 ); // final double sqrt = (sqrt1 + sqrt2) * ONE_HALF; // final double sqrt3 = (1.03D * x * 1/sqrt2 + sqrt2) * BALANCE; // final double sqrt4 = (1.03D * x * 1/sqrt3 + sqrt3) * BALANCE; final long sqrt3 = (long)(x/sqrt) + ((long)sqrt) >> 1 ; // final double sqrt4 = (x * 1/sqrt3 + sqrt3) * ONE_HALF; return sqrt3; } /** * ((sqrt(x)+e)^2-x)/sqrt(x) = (2*e*sqrt(x)+e^2)/sqrt(x) = * 2e + e^2/sqrt(x) * @param x * @return */ public static long sqrtMix(double x) { final double sqrt = Double.longBitsToDouble(( ( Double.doubleToLongBits( x )- bit52 )>>1 ) + bit61); final double correction = (x/sqrt-sqrt)/2; final double sqrt2 = correction + sqrt; return (long) sqrt2; } private double primemod(long range) { double prod = 1; final double inv63 = 1.0 / 63; final long n = 1l << 21; for (int j = 0; j <loops; j++) { for (long i = 0; i < range; i++) { final long mod = PrimeMath.mod(i*n, 63, inv63 ); prod += mod; } } return prod; } private double mod(long range) { long prod = 1; final long n = 1l << 21; for (int j = 0; j <loops; j++) { for (long i = 0; i < range; i++) { final long mod = i*n % 8190; prod += mod; } } return prod; } private double cast(long range) { final double prod = .001324; final long n = 1l << 21; for (int j = 0; j <loops; j++) { for (long i = 0; i < range; i++) { final long mod = (long) (i*j*prod); } } return prod; } private double floor(long range) { final double prod = .001324; final long n = 1l << 21; for (int j = 0; j <loops; j++) { for (long i = 0; i < range; i++) { final double mod = Math.floor(i*j*prod); } } return prod; } private double div(long range) { double prod = 1; final long bigVal = 1l << 40 + 78931; final long n = 1l << 21; for (int j = 1; j <loops; j++) { for (long i = 1; i < range; i++) { final long sqrt = bigVal/(i*n); prod += sqrt; } } return prod; } /** * 1 -> 1,2 * 3 -> 3,6 * 4 * 5 -> 5, 10 * 7 -> 7, 14 * 8 * 9 -> 9, 18 * 11->11, 22 * 12 * * @param range * @return */ private double sqrt2(long range) { double prod = 1; final long n = 1l << 21; final double sqrt2 = Math.sqrt(2); final double sqrt2Inv = 1d / sqrt2; for (int j = 1; j <loops; j++) { for (long i = 1; i < range; i +=2) { final double sqrt = Math.sqrt(i*n); final double sqrtInv = 1.0/sqrt; prod += sqrt + sqrtInv; if (2*j < loops) { final double sqrt2IN = sqrt2 * sqrt; // prod += sqrt2IN + sqrt2Inv * sqrtInv; prod += sqrt2IN + 1d / sqrt2IN; } } for (long i = 4; i < range; i+=4) { final double sqrt = Math.sqrt(i*n); prod += sqrt + 1/sqrt; } } return prod; } private double sqrtBig(long range) { double prod = 1; final long n = 1l << 21; final double sqrtN = Math.sqrt(n); for (int j = 0; j <loops; j++) { for (long i = 0; i < range; i++) { final double sqrt = Math.sqrt(i) * sqrtN; prod += sqrt + 1/sqrt ; } } return prod; } private double multiply(long range) { double prod = 1; for (int j =1; j <loops; j++) { for (int i = 1; i < range; i++) { prod += i*i; } } return prod; } @Test public void testPerformance () { final int bits = 16; final long begin = (1L << bits) + 3534; final long range = 10000000L; final int n3 = 1 << (bits / 3); long start = System.currentTimeMillis(); hart(begin, range, n3); long end = System.currentTimeMillis(); System.out.println(" time hart : " + (end- start)); start = System.currentTimeMillis(); floor(begin, range, n3); end = System.currentTimeMillis(); System.out.println(" time floor : " + (end- start)); start = System.currentTimeMillis(); hart(begin, range, n3); end = System.currentTimeMillis(); System.out.println(" time hart : " + (end- start)); start = System.currentTimeMillis(); floor(begin, range, n3); end = System.currentTimeMillis(); System.out.println(" time floor : " + (end- start)); } public void hart(long begin, long range, int n3) { boolean found = false; // long n = begin; for(long n = begin; n < begin + range; n++) { final long sqrt = PrimeMath.sqrt(n); long x = sqrt; for (; x< sqrt + n3; x++) { final long x2 = x*x; final long right = x2 - n; if (PrimeMath.isSquare(right)) { found = ! found; } } } } public void floor(long begin, long range, int n3) { boolean found = false; final int onLevel = 3; // long n = begin; for(long n = begin; n < begin + range; n++) { final int sqrt = (int) PrimeMath.sqrt(n); final int x = sqrt; final long x2 = x*x; int right = (int) (x2 - n); int x21 = 2 * x + 1; for (; x21< (sqrt + n3)*2; x21+=2) { if (PrimeMath.isSquare(right)) { found = ! found; } right += x21; } } } }
package com.example.table; import android.os.Parcel; import android.os.Parcelable; import com.example.table.ActionFunctional.TimeInterval; import java.util.ArrayList; public class Day implements Parcelable { private ArrayList<TimeInterval> intervals; Day() { intervals = new ArrayList<>(); } protected Day(Parcel in) { intervals = (ArrayList<TimeInterval>)in.readSerializable(); } public static final Creator<Day> CREATOR = new Creator<Day>() { @Override public Day createFromParcel(Parcel in) { return new Day(in); } @Override public Day[] newArray(int size) { return new Day[size]; } }; public void setInterval(TimeInterval iInterval) { intervals.add(iInterval); } public ArrayList<TimeInterval> getIntervals() { return intervals; } @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeSerializable(intervals); } }
package io.qtechdigital.onlineTutoring.dto.user.request; import lombok.Getter; import lombok.Setter; import java.util.List; @Getter @Setter public class UserUpdateDto { private String username; private String firstName; private String lastName; private String password; private List<Long> roleIds; }
package Client; import Server.Login; import Server.LoginServer; import Server.Server; import util.*; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import java.util.concurrent.CopyOnWriteArrayList; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JPasswordField; import javax.swing.JTextField; import javax.swing.SwingConstants; import javax.swing.WindowConstants; public class ClientGUI implements ActionListener{ //GUI Stuff: JFrame frame; JPanel panel; JLabel usernameLbl, pwLbl; JTextField username; JPasswordField password; JButton submit; JButton launchGame; JLabel feedback; JLabel lobby; JButton register; //Important stuff private int playerCount = 0; private LoginServer loginServer1 = new LoginServer(); private BoundedBuffer<LoginPacket> bb = new BoundedBuffer<LoginPacket>(10); private BoundedBuffer<LoggingPacket> loggingPacketBoundedBuffer = new BoundedBuffer<LoggingPacket>(10000); Login clientLogin = new Login(); CopyOnWriteArrayList<Snake> snakes = new CopyOnWriteArrayList<Snake>(); MoveSet[] moveSetArray = {new MoveSet(new MoveKey(KeyEvent.VK_UP), new MoveKey(KeyEvent.VK_LEFT), new MoveKey(KeyEvent.VK_DOWN), new MoveKey(KeyEvent.VK_RIGHT)), new MoveSet(new MoveKey(KeyEvent.VK_W), new MoveKey(KeyEvent.VK_A), new MoveKey(KeyEvent.VK_S), new MoveKey(KeyEvent.VK_D)), new MoveSet(new MoveKey(KeyEvent.VK_T), new MoveKey(KeyEvent.VK_F), new MoveKey(KeyEvent.VK_G), new MoveKey(KeyEvent.VK_H)), new MoveSet(new MoveKey(KeyEvent.VK_I), new MoveKey(KeyEvent.VK_J), new MoveKey(KeyEvent.VK_K), new MoveKey(KeyEvent.VK_L))}; public ClientGUI() { frame = new JFrame(); frame.setSize(500, 200); panel = new JPanel(); GridBagConstraints c = new GridBagConstraints(); panel.setLayout(new GridBagLayout()); usernameLbl = new JLabel("Username"); pwLbl = new JLabel("Password"); username = new JTextField(10); password = new JPasswordField(10); submit = new JButton("Submit"); submit.setActionCommand("login"); launchGame = new JButton("Launch Game."); launchGame.setActionCommand("launch"); launchGame.addActionListener(this); submit.addActionListener(this); lobby = new JLabel(" "); register = new JButton("Register"); register.setActionCommand("register"); register.addActionListener(this); usernameLbl.setLabelFor(username); pwLbl.setLabelFor(password); c.fill = GridBagConstraints.HORIZONTAL; c.gridx = 0; c.gridy = 0; panel.add(usernameLbl,c); c.fill = GridBagConstraints.HORIZONTAL; c.gridx = 1; c.gridy = 0; panel.add(username,c); c.fill = GridBagConstraints.HORIZONTAL; c.gridx = 0; c.gridy = 1; panel.add(pwLbl,c); c.fill = GridBagConstraints.HORIZONTAL; c.gridx = 1; c.gridy = 1; panel.add(password,c); c.fill = GridBagConstraints.HORIZONTAL; c.gridx = 0; c.gridy = 2; panel.add(register,c); c.fill = GridBagConstraints.HORIZONTAL; c.gridx = 1; c.gridy = 2; panel.add(launchGame,c); c.fill = GridBagConstraints.HORIZONTAL; c.gridx = 2; c.gridy = 2; panel.add(submit,c); c.fill = GridBagConstraints.HORIZONTAL; c.gridx = 0; c.gridy = 3; c.gridwidth = 3; lobby.setHorizontalAlignment(SwingConstants.CENTER); panel.add(lobby,c); frame.add(panel); frame.setTitle("User Login"); frame.setVisible(true); frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); } @Override public void actionPerformed(ActionEvent arg0) { if(arg0.getActionCommand() == "launch") { //check lobby, if 1 or more players, launch game. if(!bb.isEmpty()) { this.loginWithPackets(); } } if(arg0.getActionCommand() == "login") { if(playerCount < 4) { if((username.getText() != null && !username.getText().isEmpty()) && (password.getPassword().toString() != null && !password.getPassword().toString().isEmpty())) { LoginPacket received = new LoginPacket(username.getText(), new String(password.getPassword())); try { //If password is correct run rest of game. boolean triggered = false; if (loginServer1.login(received)) { for (Snake snakex : snakes) { if(snakex.name.equals(received.getUsername())) { triggered = true; } } if(!triggered) { snakes.add(new Snake(received.getUsername(), moveSetArray[playerCount])); playerCount++; bb.put(clientLogin.send()); lobby.setText("Logged in as: " + received.getUsername()); } } else { lobby.setText("Incorrect Username/Password"); loggingPacketBoundedBuffer.put(new LoggingPacket("Wrong Username/Password match")); } } catch (InterruptedException e) { e.printStackTrace(); } } } else { System.out.println("Incorrect login."); } } if(arg0.getActionCommand().equals("register")) { if(loginServer1.register(username.getText(), new String(password.getPassword()))) { lobby.setText("Registered new user: \"" + username.getText() + "\""); } else { lobby.setText("User \"" + username.getText() + "\" Already registered"); } } } public void loginWithPackets() { try { for(Snake snake : snakes) { loggingPacketBoundedBuffer.put(new LoggingPacket("Added " + snake.name + " to HumanPlayersList")); } Thread mainTester = new Thread(new Server(snakes, loggingPacketBoundedBuffer)); loggingPacketBoundedBuffer.put(new LoggingPacket("About to start mainThread with these HumanPlayers: " + snakes.toString())); mainTester.start(); } catch(Exception e) { e.printStackTrace(); } } public static void main(String[] args) { new ClientGUI(); } }
package com.example.demo1.shoppingcart.fragment; import android.content.Context; import android.graphics.Color; import android.util.Log; import android.view.View; import android.widget.TextView; import com.example.demo1.base.BaseFragment; public class ShoppingcartFragment extends BaseFragment { private TextView textView; public static String TAG= ShoppingcartFragment.class.getSimpleName();//获取当前Fragment的名称 @Override protected View initView() { textView=new TextView(mContext); textView.setTextColor(Color.GREEN); return textView; } public void initData() { Log.e("TAG","主页面数据被初始化了"); textView.setText("This is ShoppingCartFragment"); } }
public class Tools { public Tools() { } public void displayVector(int[] v) { for (int i = 0; i < v.length; i++) { System.out.print(v[i] + "\t"); } System.out.println(); } }
package cc.anjun.wechat.domain.res; import cc.anjun.wechat.domain.BaseMessage; public class ImageMessage extends BaseMessage { private Image Image;//Image节点 public Image getImage() { return Image; } public void setImage(Image image) { Image = image; } }
package br.crud.spring.model; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; import org.hibernate.annotations.GenericGenerator; //passando o nome da tabela, dentro do banco, pessoas @Entity @Table(name = "pessoas") public class Pessoa { // para ele sempre gerar numeros de id diferentes, caso já tenha dados // cadastrados no banco por outro lugar // GenerationType.AUTO, atribui o valor padrão, deixa com que o provedor de // persistencia decida. @Id @GeneratedValue(strategy = GenerationType.AUTO, generator = "native") @GenericGenerator(name = "native", strategy = "native") // a pessoa tem um um id private Long id; // a pessoa tem um nome private String nome; // a pessoa tem uma idade private Integer idade; // getters e setters public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getNome() { return nome; } public void setNome(String nome) { this.nome = nome; } public Integer getIdade() { return idade; } public void setIdade(Integer idade) { this.idade = idade; } }
import java.io.IOException; import java.net.ServerSocket; import java.net.Socket; public class MyServer { ServerSocket socket; Socket client_socket; private int port; int client_id = 0; UtenteList Ulist = new UtenteList(); TavoloList TList = new TavoloList(); PiattoList PList = new PiattoList(); Menu MList = new Menu(); public static void main(String args[]){ if (args.length!=1){ System.out.println("Usage java MyServer <port>"); return; } MyServer server = new MyServer(Integer.parseInt(args[0])); server.start(); } public MyServer(int port){ System.out.println("Initializing server with port " + port); this.port=port; } public void start(){ try { System.out.println("Starting Server on port " + port); socket = new ServerSocket(port); System.out.println("Started Server on port " + port); while (true){ System.out.println("Listening on port " + port); client_socket = socket.accept(); System.out.println("Accepted connection from " + client_socket.getRemoteSocketAddress()); ClientManager cm = new ClientManager(client_socket,Ulist,TList,PList,MList); Thread t = new Thread(cm, "client: " + client_id); client_id++; t.start(); } } catch (IOException e) { System.out.println("Non può partire il Server sulla porta " + port); e.printStackTrace(); } } }
package com.beike.action.coupon; import java.io.IOException; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.ModelAndView; import com.beike.action.LogAction; import com.beike.action.merchant.BrandSearchAction; import com.beike.action.user.BaseUserAction; import com.beike.common.catlog.service.CouponCatlogService; import com.beike.common.listener.CatlogListener; import com.beike.common.search.SearchStrategy; import com.beike.dao.coupon.CouponDao; import com.beike.entity.catlog.CouponCatlog; import com.beike.entity.catlog.RegionCatlog; import com.beike.entity.user.User; import com.beike.form.CouponForm; import com.beike.form.GoodsForm; import com.beike.form.MerchantForm; import com.beike.form.SmsInfo; import com.beike.page.Pager; import com.beike.page.PagerHelper; import com.beike.service.common.SmsService; import com.beike.service.goods.GoodsService; import com.beike.service.merchant.MerchantService; import com.beike.service.merchant.ShopsBaoService; import com.beike.service.seo.SeoService; import com.beike.util.BeanUtils; import com.beike.util.CatlogUtils; import com.beike.util.Constant; import com.beike.util.DateUtils; import com.beike.util.PropertyUtil; import com.beike.util.StringUtils; import com.beike.util.WebUtils; import com.beike.util.cache.cachedriver.service.MemCacheService; import com.beike.util.cache.cachedriver.service.impl.MemCacheServiceImpl; import com.beike.util.ipparser.CityUtils; import com.beike.util.json.JsonUtil; /** * <p> * Title:优惠券Controller * </p> * <p> * Description: * </p> * <p> * Copyright: Copyright (c) 2011 * </p> * <p> * Company: Sinobo * </p> * @date May 26, 2011 * @author ye.tian * @version 1.0 */ @Controller public class CouponAction extends BaseUserAction { private final SearchStrategy searchStrategy = new SearchStrategy(); private static Log log = LogFactory.getLog(BrandSearchAction.class); private final MemCacheService memCacheService = MemCacheServiceImpl.getInstance(); private static int pageSize = 48; private static String REGION_CATLOG = "BASE_REGION_CATLOG"; private static final String SMS_TYPE = "15"; private final PropertyUtil propertyUtil = PropertyUtil.getInstance("project"); private final String SERVICE_NAME = "couponCatlogService"; @Autowired private CouponCatlogService couponCatlogService; @Autowired private MerchantService merchantService; @Autowired private CouponDao couponDao; @Autowired private GoodsService goodsService; @Autowired private SmsService smsService; @Autowired private SeoService seoService; @Autowired private ShopsBaoService shopsBaoService; private static String CITY_CATLOG = "CITY_CATLOG"; private static String COUPON_URL = "/coupon/"; public SmsService getSmsService() { return smsService; } public void setSmsService(SmsService smsService) { this.smsService = smsService; } public GoodsService getGoodsService() { return goodsService; } public void setGoodsService(GoodsService goodsService) { this.goodsService = goodsService; } @SuppressWarnings("unchecked") @RequestMapping("/coupon/getCouponById.do") public Object getCouponById(ModelMap model, HttpServletRequest request, HttpServletResponse response) { try { // 设置urlcookie super.setCookieUrl(request, response); String couponid = request.getParameter("couponid"); if (couponid == null || "".equals(couponid)) { request.setAttribute("ERRMSG", "没有找到该优惠券!"); return new ModelAndView("redirect:../500.html"); } CouponForm couponForm = null; try { couponForm = couponDao.getCouponDetailById(Integer.parseInt(couponid)); } catch (Exception e) { e.printStackTrace(); request.setAttribute("ERRMSG", "没有找到该优惠券!"); return new ModelAndView("redirect:../500.html"); } if (couponForm == null) { request.setAttribute("ERRMSG", "没有找到该优惠券!"); return new ModelAndView("redirect:../500.html"); } // 记录浏览优惠券详细 // 获得优惠券城市 String uppercity = couponDao.getCouponCity(Integer.parseInt(couponid)); String city = uppercity.toLowerCase(); // 获取当前城市ID Map<String, Long> mapCity = (Map<String, Long>) memCacheService.get("CITY_CATLOG"); if (mapCity == null) { mapCity = BeanUtils.getCity(request, "regionCatlogDao"); memCacheService.set("CITY_CATLOG", mapCity); } Long cityid = null; if (mapCity != null) { cityid = mapCity.get(city.trim()); } response.addCookie(WebUtils.cookie(CityUtils.CITY_COOKIENAME, city, CityUtils.validy)); String staticurl = propertyUtil.getProperty("STATIC_URL"); // 假如请求路径里 城市 和当前商品城市不一样 String refer = request.getRequestURL().toString(); String xcity = "http://" + city; if (!refer.startsWith(xcity)) { if ("true".equals(staticurl)) { return new ModelAndView("redirect:http://" + city + ".qianpin.com/coupon/" + couponid + ".html"); } else { return new ModelAndView("redirect:http://" + city + ".qianpin.com/coupon/getCouponById.do?couponid=" + couponid); } } CouponCatlog couponCatlog = couponDao.getCouponCatlogById(Integer.parseInt(couponid)); request.setAttribute("couponCatlog", couponCatlog); request.setAttribute("couponForm", couponForm); // 浏览次数 Long browsecount = (Long) memCacheService.get(Constant.MEM_COUPON_BROWCOUNT + couponForm.getCouponid()); // 下载次数 Long downcount = (Long) memCacheService.get(Constant.MEM_COUPON_DOWNCOUNT + couponForm.getCouponid()); if (browsecount == null) { browsecount = couponForm.getBrowsecounts(); } int validy = 60 * 60 * 24; if (downcount == null) { downcount = couponForm.getDowncount(); memCacheService.set(Constant.MEM_COUPON_DOWNCOUNT + couponForm.getCouponid(), downcount, validy); } // 增加浏览次数 memCacheService.set(Constant.MEM_COUPON_BROWCOUNT + couponForm.getCouponid(), browsecount + 1, validy); // 下载次数浏览次数 request.setAttribute("browsecount", browsecount); request.setAttribute("downcount", downcount); MerchantForm merchantForm = null; try { merchantForm = shopsBaoService.getMerchantDetailById(couponForm.getMerchantid()); // merchantForm = // merchantService.getMerchantFormById(couponForm.getMerchantid()); } catch (Exception e) { e.printStackTrace(); request.setAttribute("ERRMSG", "没有找到该优惠券!"); return new ModelAndView("redirect:../500.html"); } if (merchantForm == null) { request.setAttribute("ERRMSG", "没有找到该优惠券!"); return new ModelAndView("redirect:../500.html"); } request.setAttribute("merchantForm", merchantForm); // 商圈、属性分类 Map<String, Map<Long, List<RegionCatlog>>> regionMap = (Map<String, Map<Long, List<RegionCatlog>>>) memCacheService.get(REGION_CATLOG); Map<Long, Map<Long, List<RegionCatlog>>> propertCatlogMap = (Map<Long, Map<Long, List<RegionCatlog>>>) memCacheService.get(CatlogListener.PROPERTY_CATLOG); Map<Long, List<RegionCatlog>> property_catlog = null; // 假如memcache里没有就从数据库里查 if (regionMap == null) { regionMap = BeanUtils.getCityCatlog(request, "regionCatlogDao"); memCacheService.set(REGION_CATLOG, regionMap); } if (propertCatlogMap == null) { propertCatlogMap = BeanUtils.getCatlog(request, "propertyCatlogDao"); property_catlog = propertCatlogMap.get(cityid); memCacheService.set(CatlogListener.PROPERTY_CATLOG, propertCatlogMap, 60 * 60 * 24 * 360); } else { property_catlog = propertCatlogMap.get(cityid); } // 当前城市商圈 Map<Long, List<RegionCatlog>> curRegionMap = regionMap.get(city); // Map<Long, RegionCatlog> regionKeyMap = new HashMap<Long, RegionCatlog>(); if (curRegionMap != null && !curRegionMap.isEmpty()) { for (Long regionKey : curRegionMap.keySet()) { List<RegionCatlog> lstRegion = curRegionMap.get(regionKey); if (lstRegion != null && lstRegion.size() > 0) { for (RegionCatlog region : lstRegion) { regionKeyMap.put(region.getCatlogid(), region); } } } } Map<Long, RegionCatlog> tagKeyMap = new HashMap<Long, RegionCatlog>(); if (property_catlog != null && !property_catlog.isEmpty()) { for (Long tagKey : property_catlog.keySet()) { List<RegionCatlog> lstTag = property_catlog.get(tagKey); if (lstTag != null && lstTag.size() > 0) { for (RegionCatlog region : lstTag) { tagKeyMap.put(region.getCatlogid(), region); } } } } // 推荐商品 List<Map<String, Object>> lstRegionIds = goodsService.getCouponRegionIds(Long.parseLong(couponid)); // 相关分类 List<Object[]> lstGoodsTag = new LinkedList<Object[]>(); // 相关商圈 List<Object[]> lstGoodsRegion = new LinkedList<Object[]>(); // 用于处理二级地域重复 int iNextRegionCount = 0; String tmpGoodsRegionId = ""; if (lstRegionIds != null && lstRegionIds.size() > 0) { Map<String, Object> mapRegionIds = lstRegionIds.get(0); for (int i = 0; i < lstRegionIds.size(); i++) { Map<String, Object> catlog = lstRegionIds.get(i); // 分类 if (i == 0) { Object[] aryGoodTag1 = new Object[3]; RegionCatlog tag1 = tagKeyMap.get(catlog.get("tagid")); if (tag1 != null) { aryGoodTag1[0] = tag1.getRegion_enname(); aryGoodTag1[2] = tag1.getCatlogName(); lstGoodsTag.add(aryGoodTag1); } Object[] aryGoodTag2 = new Object[3]; RegionCatlog tag2 = tagKeyMap.get(catlog.get("tagextid")); if (tag1 != null && tag2 != null) { aryGoodTag2[0] = tag1.getRegion_enname(); aryGoodTag2[1] = tag2.getRegion_enname(); aryGoodTag2[2] = tag2.getCatlogName(); lstGoodsTag.add(aryGoodTag2); } } // 只有一个区域 if (lstRegionIds.size() == 1) { Object[] aryGoodRegion1 = new Object[3]; RegionCatlog region1 = regionKeyMap.get(catlog.get("regionid")); if (region1 != null) { aryGoodRegion1[0] = region1.getRegion_enname(); aryGoodRegion1[2] = region1.getCatlogName(); lstGoodsRegion.add(aryGoodRegion1); } Object[] aryGoodRegion2 = new Object[3]; RegionCatlog region2 = regionKeyMap.get(catlog.get("regionextid")); if (region1 != null && region2 != null) { aryGoodRegion2[0] = region1.getRegion_enname(); aryGoodRegion2[1] = region2.getRegion_enname(); aryGoodRegion2[2] = region2.getCatlogName(); lstGoodsRegion.add(aryGoodRegion2); } tmpGoodsRegionId = String.valueOf(catlog.get("regionextid")); } else { if (i == 0) { Object[] aryGoodRegion1 = new Object[3]; RegionCatlog region1 = regionKeyMap.get(catlog.get("regionid")); if (region1 != null) { aryGoodRegion1[0] = region1.getRegion_enname(); aryGoodRegion1[2] = region1.getCatlogName(); lstGoodsRegion.add(aryGoodRegion1); } Object[] aryGoodRegion2 = new Object[3]; RegionCatlog region2 = regionKeyMap.get(catlog.get("regionextid")); if (region1 != null && region2 != null) { aryGoodRegion2[0] = region1.getRegion_enname(); aryGoodRegion2[1] = region2.getRegion_enname(); aryGoodRegion2[2] = region2.getCatlogName(); lstGoodsRegion.add(aryGoodRegion2); } iNextRegionCount = 1; tmpGoodsRegionId = String.valueOf(catlog.get("regionextid")); } else { Object[] aryGoodRegion = null; RegionCatlog region1 = regionKeyMap.get(catlog.get("regionid")); RegionCatlog region2 = regionKeyMap.get(catlog.get("regionextid")); if (region1 != null && region2 != null) { aryGoodRegion = new Object[3]; aryGoodRegion[0] = region1.getRegion_enname(); aryGoodRegion[1] = region2.getRegion_enname(); aryGoodRegion[2] = region2.getCatlogName(); } if (tmpGoodsRegionId.indexOf(String.valueOf(catlog.get("regionextid"))) < 0) { if (iNextRegionCount <= 1) { if (aryGoodRegion != null) { lstGoodsRegion.remove(0); lstGoodsRegion.add(aryGoodRegion); } tmpGoodsRegionId = tmpGoodsRegionId + "," + catlog.get("regionextid"); } iNextRegionCount++; if (iNextRegionCount > 2) { tmpGoodsRegionId = null; break; } } } } } List<Long> lstTuijian1 = goodsService.getSaleWithGoodsIds((Long) mapRegionIds.get("regionid"), tmpGoodsRegionId, (Long) mapRegionIds.get("tagid"), cityid, 11L, ""); // 剔除最后商品ID,查询推荐商品 if (lstTuijian1 != null) { if (lstTuijian1.size() > 10) { lstTuijian1.remove(lstTuijian1.size() - 1); } if (lstTuijian1.size() > 0) { List<GoodsForm> lstTuijian1GoodsForm = goodsService.getGoodsFormByChildId(lstTuijian1); request.setAttribute("lstTuijian1GoodsForm", lstTuijian1GoodsForm); } } request.setAttribute("lstGoodsTag", lstGoodsTag); request.setAttribute("lstGoodsRegion", lstGoodsRegion); } } catch (Exception ex) { ex.printStackTrace(); } /* * Goods topGoods = null; // 置顶的商品 topGoods = * goodsService.getGoodsByBrandId(Long.parseLong(merchantForm.getId())); * * // 右侧推荐 List<GoodsForm> listForm = goodsService.getTopGoodsForm(); * * request.setAttribute("listForm", listForm); * * request.setAttribute("topGoods", topGoods); * request.setAttribute("merchantForm", merchantForm); */ return "/coupon/showCouponsDetail"; } @RequestMapping("/coupon/getMerchantMapList.do") public String getMerchantMapList(ModelMap model, HttpServletRequest request, HttpServletResponse response) { String couponid = request.getParameter("couponid"); if (couponid == null || "".equals(couponid)) { try { print(response, "PARAM_ERROR"); return null; } catch (IOException e) { e.printStackTrace(); } } String result = ""; Integer mid = Integer.parseInt(couponid); List<MerchantForm> listForm = null; String currentPage = request.getParameter("mpage"); if (currentPage == null || "".equals(currentPage)) { currentPage = "1"; } // 所有优惠券支持的商家总数 int size = merchantService.getMerchantFormByCouponCount(mid); Pager pager = PagerHelper.getPager(Integer.valueOf(currentPage), size, 5); try { listForm = merchantService.getMerchantFormByCouponId(couponid, pager); } catch (Exception e) { e.printStackTrace(); result = "PARAM_ERROR"; try { print(response, result); } catch (IOException e1) { e1.printStackTrace(); } return null; } if (listForm == null || listForm.size() == 0) { // 此种返回不符合常理 try { print(response, "NO_MERCHANT"); return null; } catch (IOException e) { e.printStackTrace(); } } List<Map> list = new ArrayList<Map>(); for (MerchantForm merchantForm : listForm) { Map<String, String> map = new HashMap<String, String>(); map.put("merchantName", merchantForm.getMerchantname()); map.put("addr", merchantForm.getAddr()); map.put("buinesstime", merchantForm.getBuinesstime()); map.put("tel", merchantForm.getTel()); map.put("latitude", merchantForm.getLatitude()); map.put("city", merchantForm.getCity()); list.add(map); } Map<String, String> mpage = new HashMap<String, String>(); mpage.put("currentPage", pager.getCurrentPage() + ""); mpage.put("totalPage", pager.getTotalPages() + ""); list.add(mpage); String jsonResult = JsonUtil.listToJson(list); try { print(response, jsonResult); } catch (IOException e) { e.printStackTrace(); } return null; } private void print(HttpServletResponse response, String content) throws IOException { response.setCharacterEncoding("utf-8"); response.getWriter().write(content); } @SuppressWarnings("unchecked") @RequestMapping("/coupon/searchCouponByProperty.do") public Object searchCouponByProperty(ModelMap model, HttpServletRequest request, HttpServletResponse response) { // 设置urlcookie super.setCookieUrl(request, response); // //////////////////////////////////////////////////////////////////////////// /** * 补充说明:by zx.liu 这里 获取值修改为了对应的 tagEnname(标签值) */ String regionTag = request.getParameter("region"); if (StringUtils.isNumber(regionTag)) { regionTag = seoService.getRegionENName(regionTag); } String region = seoService.getRegionId(regionTag); String region_extTag = request.getParameter("regionext"); if (StringUtils.isNumber(region_extTag)) { region_extTag = seoService.getRegionENName(region_extTag); } String region_ext = seoService.getRegionId(region_extTag); String catlogTag = request.getParameter("catlog"); if (StringUtils.isNumber(catlogTag)) { catlogTag = seoService.getTagENName(catlogTag); } String catlog = seoService.getTagId(catlogTag); String catlog_extTag = request.getParameter("catlogext"); if (StringUtils.isNumber(catlog_extTag)) { catlog_extTag = seoService.getTagENName(catlog_extTag); } String catlog_ext = seoService.getTagId(catlog_extTag); // ////////////////////////////////////////////////////////////////////////////////////////////// // 排序 String orderbydate = request.getParameter("orderbydate"); String orderbysort = request.getParameter("orderbysort"); Map<String, Long> mapCity = (Map<String, Long>) memCacheService.get(CITY_CATLOG); if (mapCity == null) { mapCity = BeanUtils.getCity(request, "regionCatlogDao"); memCacheService.set(CITY_CATLOG, mapCity); } String city = CityUtils.getCity(request, response); if (city == null || "".equals(city)) { city = "beijing"; } Long cityid = null; if (mapCity != null) { cityid = mapCity.get(city); } CouponCatlog couponCatlog = new CouponCatlog(); couponCatlog.setCityid(cityid); try { if (region != null && !"".equals(region)) { couponCatlog.setRegionid(Long.parseLong(region)); } if (region_ext != null && !"".equals(region_ext)) { couponCatlog.setRegionextid(Long.parseLong(region_ext)); } if (catlog != null && !"".equals(catlog)) { couponCatlog.setTagid(Long.parseLong(catlog)); } if (catlog_ext != null && !"".equals(catlog_ext)) { couponCatlog.setTagextid(Long.parseLong(catlog_ext)); } // 排序 if (orderbydate != null && !"".equals(orderbydate)) { couponCatlog.setOrderbydate(orderbydate); } else if (orderbysort != null && !"".equals(orderbysort)) { couponCatlog.setOrderbysort(orderbysort); } } catch (Exception e) { e.printStackTrace(); request.setAttribute("ERRMSG", "查询条件输入有误!"); return new ModelAndView("redirect:../500.html"); } searchStrategy.setService(request, SERVICE_NAME); // 当前页 String currentPage = request.getParameter("cpage"); if (currentPage == null || "".equals(currentPage)) { currentPage = "1"; } // 计算分页 int totalCount = 0; totalCount = couponCatlogService.getCatlogCount(couponCatlog); Pager pager = PagerHelper.getPager(Integer.parseInt(currentPage), totalCount, pageSize); List<Long> searchListids = searchStrategy.getCatlog(couponCatlog, pager); // 当前页 request.setAttribute("pager", pager); List<CouponForm> listCoupon = null; if (searchListids == null || searchListids.size() == 0) { // 假如没有查出数据的默认列表 couponCatlog.setRegionextid(null); couponCatlog.setTagextid(null); totalCount = couponCatlogService.getCatlogCount(couponCatlog); pager = PagerHelper.getPager(Integer.parseInt(currentPage), totalCount, pageSize); List<Long> seIds = searchStrategy.getCatlog(couponCatlog, pager); request.setAttribute("goodsNull", "true"); if (seIds == null || seIds.size() == 0) { couponCatlog.setTagid(null); totalCount = couponCatlogService.getCatlogCount(couponCatlog); pager = PagerHelper.getPager(Integer.parseInt(currentPage), totalCount, pageSize); if (seIds == null || seIds.size() == 0) { couponCatlog.setRegionextid(null); couponCatlog.setRegionid(null); couponCatlog.setTagextid(null); couponCatlog.setTagid(null); totalCount = couponCatlogService.getCatlogCount(couponCatlog); pager = PagerHelper.getPager(Integer.parseInt(currentPage), totalCount, pageSize); seIds = searchStrategy.getCatlog(couponCatlog, pager); } } listCoupon = couponCatlogService.getCouponFormByIds(seIds); } else { listCoupon = couponCatlogService.getCouponFormByIds(searchListids); } request.setAttribute("listCoupon", listCoupon); Map<String, Map<Long, List<RegionCatlog>>> regionMap = (Map<String, Map<Long, List<RegionCatlog>>>) memCacheService.get(REGION_CATLOG); Map<Long, Map<Long, List<RegionCatlog>>> propertCatlogMap = (Map<Long, Map<Long, List<RegionCatlog>>>) memCacheService.get(CatlogListener.PROPERTY_CATLOG); Map<Long, List<RegionCatlog>> property_catlog = null; // 假如memcache里没有就从数据库里查 if (regionMap == null) { regionMap = BeanUtils.getCityCatlog(request, "regionCatlogDao"); memCacheService.set(REGION_CATLOG, regionMap); } if (propertCatlogMap == null) { propertCatlogMap = BeanUtils.getCatlog(request, "propertyCatlogDao"); property_catlog = propertCatlogMap.get(cityid); memCacheService.set(CatlogListener.PROPERTY_CATLOG, propertCatlogMap, 60 * 60 * 24 * 360); } else { property_catlog = propertCatlogMap.get(cityid); } Map<Long, List<RegionCatlog>> map = regionMap.get(city); if (region != null && !"".equals(region)) { List<RegionCatlog> listRegion = map.get(Long.parseLong(region)); CatlogUtils.setCatlogUrl(true, listRegion, catlogTag, catlog_extTag, regionTag, region_extTag, null, COUPON_URL); request.setAttribute("listRegion", listRegion); } if (catlog != null && !"".equals(catlog)) { List<RegionCatlog> listProperty = property_catlog.get(Long.parseLong(catlog)); CatlogUtils.setCatlogUrl(false, listProperty, catlogTag, catlog_extTag, regionTag, region_extTag, null, COUPON_URL); request.setAttribute("listProperty", listProperty); } List<RegionCatlog> listParentProperty = property_catlog.get(0L); List<RegionCatlog> listParentRegion = map.get(0L); if (couponCatlog.isNull()) { if (listParentRegion != null && listParentRegion.size() > 0) { for (RegionCatlog regionCatlog : listParentRegion) { CatlogUtils.setInitUrl(true, regionCatlog, COUPON_URL); } } if (listParentProperty != null && listParentProperty.size() > 0) { for (RegionCatlog regionCatlog : listParentProperty) { CatlogUtils.setInitUrl(false, regionCatlog, COUPON_URL); } } } else { CatlogUtils.setCatlogUrl(true, listParentRegion, catlogTag, catlog_extTag, regionTag, region_extTag, null, COUPON_URL); CatlogUtils.setCatlogUrl(false, listParentProperty, catlogTag, catlog_extTag, regionTag, region_extTag, null, COUPON_URL); } request.setAttribute("propertyMap", property_catlog); request.setAttribute("regionMap", map); memCacheService.set(REGION_CATLOG, regionMap); return "/coupon/listCoupon"; } @RequestMapping("/coupon/mainSearchCouponByProperty.do") public String mainSearchCouponByProperty(ModelMap model, HttpServletRequest request) { String pageParam = request.getParameter("param"); String ids = request.getParameter("ids"); List<Long> listIds = new LinkedList<Long>(); String idStrings[] = ids.split(","); for (String string : idStrings) { listIds.add(Long.parseLong(string)); } List<CouponForm> listCoupon = couponCatlogService.getCouponFormByIds(listIds); request.setAttribute("listCouponForm", listCoupon); return "index/list/" + pageParam; } @RequestMapping("/coupon/downloadCoupon.do") public String downloadCoupon(ModelMap model, HttpServletRequest request, HttpServletResponse response) { String couponnumber = request.getParameter("couponnumber"); String downmobile = request.getParameter("downmobile"); String couponid = request.getParameter("cid"); String formCode = request.getParameter("formCode"); String cookieCode = WebUtils.getCookieValue("RANDOM_VALIDATE_CODE", request); String validateCode = (String) memCacheService.get("validCode_" + cookieCode); // String validateCode=(String) // request.getSession().getAttribute("validCode"); String content = ""; if (formCode == null || validateCode == null || !formCode.equalsIgnoreCase(validateCode)) { content = "validate_code_error"; try { print(response, content); } catch (IOException e) { e.printStackTrace(); } return null; } User user = getMemcacheUser(request); String key = "COUPON_" + downmobile; String downMobileValue = (String) memCacheService.get(key); // 用户假如未登录或者未验证手机的话 同一个手机只能下载5次 if (user == null || user.getMobile_isavalible() == 0 || !downmobile.equals(user.getMobile())) { Date date = new Date(); String nowDate = DateUtils.dateToStr(date); // 判断假如同一天已经download 5次了不能再下载了 if (downMobileValue != null) { String svalue[] = downMobileValue.split("\\|"); if (svalue != null && svalue.length == 2) { String vs = svalue[1]; int count = Integer.parseInt(vs); if (count >= 5 && nowDate.equals(svalue[0])) { content = "download_coupon_error"; try { print(response, content); } catch (IOException e) { e.printStackTrace(); } return null; } } } } // 发送短信 CouponForm couponForm = couponDao.getCouponDetailById(Integer.parseInt(couponid)); String message = "千品网优惠券编号为:" + couponnumber + "," + couponForm.getSmstemplate() + "有效期:" + couponForm.getCreateDate() + "至" + couponForm.getEndDate(); SmsInfo sourceBean = new SmsInfo(downmobile, message, SMS_TYPE, "1"); smsService.sendSms(sourceBean); // 记录memcache Date date = new Date(); String nowDate = DateUtils.dateToStr(date); // 非第一次记录 取出次数加1 if (downMobileValue != null) { String svalue[] = downMobileValue.split("\\|"); String count = svalue[1]; int scount = Integer.parseInt(count) + 1; if (nowDate.equals(svalue[0])) { memCacheService.set(key, svalue[0] + "|" + scount); } else { memCacheService.set(key, nowDate + "|" + scount); } } else { memCacheService.set(key, nowDate + "|" + 1); } // 下载记数 Long downcount = (Long) memCacheService.get(Constant.MEM_COUPON_DOWNCOUNT + couponForm.getCouponid()); if (downcount == null) { downcount = couponForm.getDowncount(); } memCacheService.set(Constant.MEM_COUPON_DOWNCOUNT + couponForm.getCouponid(), downcount + 1); content = "ok"; // 记录下载日志 Map<String, String> logMap = LogAction.getLogMap(request, response); logMap.put("action", "QuanSMS"); logMap.put("mobile", downmobile); logMap.put("quanid", couponid); LogAction.printLog(logMap); try { print(response, content); } catch (IOException e) { e.printStackTrace(); } return null; } public CouponCatlogService getCouponCatlogService() { return couponCatlogService; } public void setCouponCatlogService(CouponCatlogService couponCatlogService) { this.couponCatlogService = couponCatlogService; } public CouponDao getCouponDao() { return couponDao; } public void setCouponDao(CouponDao couponDao) { this.couponDao = couponDao; } public MerchantService getMerchantService() { return merchantService; } public void setMerchantService(MerchantService merchantService) { this.merchantService = merchantService; } public SeoService getSeoService() { return seoService; } public void setSeoService(SeoService seoService) { this.seoService = seoService; } }
package io.nuls.provider.rpctools; import io.nuls.base.api.provider.Result; import io.nuls.core.core.annotation.Component; import io.nuls.core.exception.NulsRuntimeException; import java.util.Map; import java.util.function.Function; @Component public class CommonTools implements CallRpc { public Result commonRequest(String module, String cmd, Map params) { try { return callRpc(module, cmd, params, (Function<Object, Result<Object>>) res -> { if(res == null){ return new Result(); } return new Result(res); }); } catch (NulsRuntimeException e) { return Result.fail(e.getCode(), e.getMessage()); } } }
package com.wx.dubbo.api.service; import com.wx.dubbo.api.domain.User; import java.util.List; public interface UserService { User findUser(int id); List<User> listUsers(); User findUserByName(String name); }
package yblast; public class CreateRandomArray { }
package com.openfarmanager.android.adapters; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import com.openfarmanager.android.App; import com.openfarmanager.android.model.TextBuffer; import com.openfarmanager.android.view.SearchableEditText; import com.openfarmanager.android.view.SearchableTextView; import com.openfarmanager.android.view.SearchableView; import org.apache.commons.io.IOCase; import java.util.ArrayList; public class LinesAdapter extends BaseAdapter { public static final int MODE_VIEW = 0; public static final int MODE_EDIT = 1; private TextBuffer mText; private String mSearchPattern; private IOCase mCaseSensitive; private boolean mWholeWords; private boolean mRegularExpression; private boolean mDoSearch; private int mAdapterMode; public LinesAdapter(TextBuffer text) { mText = text; mAdapterMode = MODE_VIEW; } public void stopSearch() { mDoSearch = false; notifyDataSetChanged(); } public void search(String pattern, boolean caseSensitive, boolean wholeWords, boolean regularExpression) { initSearchParams(pattern, caseSensitive, wholeWords, regularExpression); mDoSearch = true; notifyDataSetChanged(); } private void initSearchParams(String pattern, boolean caseSensitive, boolean wholeWords, boolean regularExpression) { mSearchPattern = pattern; mCaseSensitive = caseSensitive ? IOCase.SENSITIVE : IOCase.INSENSITIVE; mWholeWords = wholeWords; mRegularExpression = regularExpression; } public void setMode(int mode) { mAdapterMode = mode; if (mAdapterMode == MODE_EDIT && mText.size() == 0) { mText.appendEmptyLine(); } } public int getMode() { return mAdapterMode; } @Override public int getCount() { return mText.size(); } @Override public Object getItem(int i) { return mText.getLine(i); } @Override public long getItemId(int i) { return i; } @Override public View getView(int lineNumber, View view, ViewGroup viewGroup) { String text = (String) getItem(lineNumber); if (view == null || ((SearchableView) view).getMode() != mAdapterMode) { view = newInstance(text, lineNumber); } else { ((SearchableView) view).setupText(text); } SearchableView textView = (SearchableView) view; if (mDoSearch) { textView.search(mSearchPattern, mCaseSensitive, mWholeWords); } else { textView.setText(); } return (View) textView; } public void swapData(ArrayList<String> strings) { mText.swapData(strings); notifyDataSetChanged(); } public ArrayList<String> getText() { return mText.getTextLines(); } private View newInstance(final String initText, final int lineNumber) { if (mAdapterMode == MODE_EDIT) { final SearchableEditText editText = new SearchableEditText(App.sInstance.getApplicationContext(), initText); editText.setOnFocusChangeListener(new View.OnFocusChangeListener() { @Override public void onFocusChange(View view, boolean b) { mText.setLine(lineNumber, editText.getText().toString()); } }); editText.setTag(lineNumber); return editText; } return new SearchableTextView(App.sInstance.getApplicationContext(), initText); } /** * Save value from current edit line to buffer. * * @param focusedView current focued view */ public void saveCurrentEditLine(View focusedView) { if (focusedView instanceof SearchableEditText) { SearchableEditText view = (SearchableEditText) focusedView; mText.setLine((Integer) view.getTag(), view.getText().toString()); } } }
package innerclasses; public class Externa { public void method() { } }
package com.spring.service; import java.util.List; import com.news.pojo.Topic; /** * 新闻主题的服务接口 * @author yin * */ public interface TopicServices { /** * 获取全部的新闻主题列表 * @return * @throws Exception */ public List<Topic> getAllTopic(); }
package com.scc.jellyfish6.atm; import android.content.SharedPreferences; import android.os.Bundle; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.EditText; import android.widget.Toast; public class LoginActivity extends AppCompatActivity { private String id; private String pwd; private EditText userid; private EditText password; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_login); findViews(); SharedPreferences setting=getSharedPreferences("atm",MODE_PRIVATE); userid.setText(setting.getString("Pref_User","").toString()); } public void login(View v ){ findViews(); id = userid.getText().toString(); pwd = password.getText().toString(); if(id.equals("Jelly")&& pwd.equals("1234")){//登入成功 SharedPreferences setting= getSharedPreferences("atm",MODE_PRIVATE); setting.edit() .putString("Pref_User", id) .commit(); Toast.makeText(this,"登入成功",Toast.LENGTH_LONG).show(); getIntent().putExtra("LOGIN_USERID", id); getIntent().putExtra("LOGIN_PWD", pwd); setResult(RESULT_OK,getIntent()); finish(); }else{//登入失敗 new AlertDialog.Builder(this) .setTitle("Atm") .setMessage("登入失敗") .setPositiveButton("ok",null) .show(); } } private void findViews() { userid = findViewById(R.id.userid); password = findViewById(R.id.pwd); } public void cancel(View v){ } }
package org.carpark.transaction; /** A Car Park Transaction. @author Ross Huggett */ public class TransactionFactory { /** The ThreadGroup for Transaction Factory. */ private static ThreadGroup tGroup; /** Transaction counter.Counting Threads in a ThreadGroup is only an estimate. */ private static int counter = 0; /** Returns the Transaction ThreadGroup. @return the Transaction ThreadGroup. */ public static ThreadGroup getThreadGroup() { if (tGroup == null) { tGroup = new ThreadGroup("Transactions"); } return tGroup; } /** Creates a new instance of Transaction in the Factory ThreadGroup, and returns it. @return a new instance of Transaction. */ public static Transaction getNewTransaction() { counter++; Transaction t = new Transaction(getThreadGroup(), "Transaction " + counter); t.start(); return t; } /** Method for accessing a count of active Transaction. @return an estimate of the number of active Transaction threads. */ public static int getTransactionCount() { return counter; } }
package com.chenqk.springmvc.util; import java.util.List; public class StationEntity { private String colltime; private List<Station> stationList; private List<List<String>> apList; private List<List<Double>> rssiList; private List<String> collTimeList; public List<List<String>> getApList() { return apList; } public void setApList(List<List<String>> apList) { this.apList = apList; } public List<List<Double>> getRssiList() { return rssiList; } public void setRssiList(List<List<Double>> rssiList) { this.rssiList = rssiList; } public List<String> getCollTimeList() { return collTimeList; } public void setCollTimeList(List<String> collTimeList) { this.collTimeList = collTimeList; } public String getColltime() { return colltime; } public void setColltime(String colltime) { this.colltime = colltime; } public List<Station> getStationList() { return stationList; } public void setStationList(List<Station> stationList) { this.stationList = stationList; } }
package com.mindstatus.phy; public class PhysiologyCycle { private double physical; private double feeling; private double intelligence; private long lifeDays; public long getLifeDays() { return lifeDays; } public void setLifeDays(long lifeDays) { this.lifeDays = lifeDays; } public double getAverage() { return (physical+feeling+intelligence)/3.0; } public double getPhysical() { return physical; } public void setPhysical(double physical) { this.physical = physical; } public double getFeeling() { return feeling; } public void setFeeling(double feeling) { this.feeling = feeling; } public double getIntelligence() { return intelligence; } public void setIntelligence(double intelligence) { this.intelligence = intelligence; } }
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; import java.math.RoundingMode; import java.text.DecimalFormat; public class fairShare { private static DecimalFormat df = new DecimalFormat("0.00"); static int w; static int count=0; static int checkpoint=0; static int n; static String strCopy; public static int e; static double a[][] = new double[10][2]; public static double report(int e){ if(a[e][0]==0){ return 0; } else{ double sum=0; double rep; for(int y=0;y<10;y++){ sum = sum + a[y][1]; } sum = sum/(n); rep = a[e][1] - sum; return rep; } } public static void expense(int w, double value){ if(a[w][0] != 0) a[w][1] = a[w][1] + value; else System.out.println("Error"); } public static void register(int i){ a[i][0] = 1; } public static void main(String[] args) throws IOException{ for(int i=0;i<10;i++){ a[i][0] = 0; } List<String> text = new ArrayList<>(); try(BufferedReader reader = new BufferedReader(new InputStreamReader(System.in))){ String line; for( ; ; ){ line = reader.readLine(); if(line.equals("end")) break; text.add(line); } } text.stream().forEach((String str)->{ String[] part = str.split("\\s+"); if(part[0].equals("register")){ n = part.length-1; for(count=0;count<part.length;count++){ if(part[count].equals("f1")){ int a = 0; register(a); } if(part[count].equals("f2")){ int a = 1; register(a); } if(part[count].equals("f3")){ int a = 2; register(a); } if(part[count].equals("f4")){ int a = 3; register(a); } if(part[count].equals("f5")){ int a = 4; register(a); } if(part[count].equals("f6")){ int a = 5; register(a); } if(part[count].equals("f7")){ int a = 6; register(a); } if(part[count].equals("f8")){ int a = 7; register(a); } if(part[count].equals("f9")){ int a = 8; register(a); } if(part[count].equals("f10")){ int a = 9; register(a); } } } else if((part[0].equals("expense"))){ if(part[1].equals("f1")){ w = 0; } if(part[1].equals("f2")){ w = 1; } if(part[1].equals("f3")){ w = 2; } if(part[1].equals("f4")){ w = 3; } if(part[1].equals("f5")){ w = 4; } if(part[1].equals("f6")){ w = 5; } if(part[1].equals("f7")){ w = 6; } if(part[1].equals("f8")){ w = 7; } if(part[1].equals("f9")){ w = 8; } if(part[1].equals("f10")){ w = 9; } double value = Double.parseDouble(part[2]); expense(w, value); } else if(part[0].equals("report")){ if(part[1].equals("f1")){ e = 0; } if(part[1].equals("f2")){ e = 1; } if(part[1].equals("f3")){ e = 2; } if(part[1].equals("f4")){ e = 3; } if(part[1].equals("f5")){ e = 4; } if(part[1].equals("f6")){ e = 5; } if(part[1].equals("f7")){ e = 6; } if(part[1].equals("f8")){ e = 7; } if(part[1].equals("f9")){ e = 8; } if(part[1].equals("f10")){ e = 9; } double p = report(e); if(p!=0) System.out.println(df.format(p)); else System.out.println("Error"); } }); } }
package com.foodaholic.asyncTask; import android.os.AsyncTask; import com.foodaholic.interfaces.OfferAndPromotionListener; import com.foodaholic.items.ItemOfferAndPromotion; import com.foodaholic.items.ItemRestaurant; import com.foodaholic.utils.Constant; import com.foodaholic.utils.JsonUtils; import org.json.JSONArray; import org.json.JSONObject; import java.util.ArrayList; public class LoadOfferAndPromotions extends AsyncTask<String, String, Boolean> { private OfferAndPromotionListener offerAndPromotionListener; private ArrayList<ItemOfferAndPromotion> offerAndPromotionsList; public LoadOfferAndPromotions(OfferAndPromotionListener offerAndPromotionListener) { this.offerAndPromotionListener = offerAndPromotionListener; offerAndPromotionsList = new ArrayList<>(); } @Override protected void onPreExecute() { super.onPreExecute(); offerAndPromotionListener.onStart(); } @Override protected Boolean doInBackground(String... strings) { String url = strings[0]; String json = JsonUtils.okhttpGET(url); try { JSONObject jOb = new JSONObject(json); JSONArray jsonArray = jOb.getJSONArray(Constant.TAG_ROOT); for (int j = 0; j < jsonArray.length(); j++) { JSONObject c = jsonArray.getJSONObject(j); String id = c.getString(Constant.TAG_OFFER_ID); String offer_heading = c.getString(Constant.TAG_OFFER_HEADING); String offer_description = c.getString(Constant.TAG_OFFER_DESCRIPTION); String image_link = c.getString(Constant.TAG_OFFER_IMAGE_LINK); String post_date = c.getString(Constant.TAG_OFFER_POST_DATE); ItemOfferAndPromotion currentOffer = new ItemOfferAndPromotion(id, offer_heading, offer_description, image_link, post_date); //Parse If offer associated with any restaurant if(c.has(Constant.TAG_REST_ROOT)) { JSONObject rest_obj = c.getJSONObject(Constant.TAG_REST_ROOT); String rest_id = rest_obj.getString(Constant.TAG_ID); String name = rest_obj.getString(Constant.TAG_REST_NAME); String address = rest_obj.getString(Constant.TAG_REST_ADDRESS); String image = rest_obj.getString(Constant.TAG_REST_IMAGE); String type = rest_obj.getString(Constant.TAG_REST_TYPE); float avg_Rate = Float.parseFloat(rest_obj.getString(Constant.TAG_REST_AVG_RATE)); int total_rate = Integer.parseInt(rest_obj.getString(Constant.TAG_REST_TOTAL_RATE)); String cat_name = ""; if(rest_obj.has(Constant.TAG_CAT_NAME)) { cat_name = c.getString(Constant.TAG_CAT_NAME); } String open = rest_obj.getString(Constant.TAG_REST_OPEN); ItemRestaurant itemRestaurant = new ItemRestaurant(rest_id,name,image,type,address,avg_Rate,total_rate, cat_name, open); currentOffer.setAssocidatedRestaurant(itemRestaurant); } offerAndPromotionsList.add(currentOffer); } return true; } catch (Exception e) { e.printStackTrace(); return false; } } @Override protected void onPostExecute(Boolean aBoolean) { super.onPostExecute(aBoolean); offerAndPromotionListener.onEnd(String.valueOf(aBoolean), offerAndPromotionsList); } }
package com.alibaba.dubbo.config.spring.schema; import com.alibaba.dubbo.common.Version; import com.alibaba.dubbo.config.*; import com.alibaba.dubbo.config.spring.ReferenceBean; import com.alibaba.dubbo.config.spring.ServiceBean; import org.springframework.beans.factory.xml.NamespaceHandlerSupport; public class DubboNamespaceHandler extends NamespaceHandlerSupport { static { Version.checkDuplicate(DubboNamespaceHandler.class); } @Override public void init() { registerBeanDefinitionParser("application", new DubboBeanDefinitionParser(ApplicationConfig.class, true)); registerBeanDefinitionParser("module", new DubboBeanDefinitionParser(ModuleConfig.class, true)); registerBeanDefinitionParser("registry", new DubboBeanDefinitionParser(RegistryConfig.class, true)); registerBeanDefinitionParser("monitor", new DubboBeanDefinitionParser(MonitorConfig.class, true)); registerBeanDefinitionParser("provider", new DubboBeanDefinitionParser(ProviderConfig.class, true)); registerBeanDefinitionParser("consumer", new DubboBeanDefinitionParser(ConsumerConfig.class, true)); registerBeanDefinitionParser("protocol", new DubboBeanDefinitionParser(ProtocolConfig.class, true)); registerBeanDefinitionParser("service", new DubboBeanDefinitionParser(ServiceBean.class, true)); registerBeanDefinitionParser("reference", new DubboBeanDefinitionParser(ReferenceBean.class, false)); registerBeanDefinitionParser("annotation", new AnnotationBeanDefinitionParser()); // 废弃 } }
package com.daexsys.automata.gui; import com.daexsys.automata.gui.listeners.KeyboardHandler; import java.awt.event.KeyEvent; public class Offsets { private int offsetX = 0; private int offsetY = 0; private GUI gui; public Offsets(GUI gui) { this.gui = gui; } public int getOffsetX() { return offsetX; } public int getOffsetY() { return offsetY; } private double speed = .25; public double getSpeed() { return KeyboardHandler.isDown(KeyEvent.VK_SHIFT) ? speed * 4 : speed; } public void moveUp(double delta) { delta /= 20; offsetY+=gui.getZoomLevel() * getSpeed() * delta; if(offsetY > 0) offsetY = 0; } public void moveDown(double delta) { delta /= 20; offsetY-=gui.getZoomLevel() * getSpeed() * delta; } public void moveLeft(double delta) { delta /= 20; offsetX += gui.getZoomLevel() * getSpeed() * delta; if(offsetX > 0) offsetX = 0; } public void moveRight(double delta) { delta /= 20; offsetX -= gui.getZoomLevel() * getSpeed() * delta; } @Override public String toString() { return offsetX + " " + offsetY; } }
package com.lenovohit.ssm.payment.model; import java.util.Date; import javax.persistence.Entity; import javax.persistence.Table; import com.lenovohit.core.model.BaseIdModel; @Entity @Table(name="SSM_PAY_CHANNEL") public class PayChannel extends BaseIdModel{ private static final long serialVersionUID = -6376593015883279618L; public static final String STATUS_NO = "0";//暂停 public static final String STATUS_OK = "1";//正常 private String name; private String code; private String mchId; private String mchName; private String appId; private String accNo; private String accName; private String privateKey; private String publicKey; private String signCertPath; private String signCertUser; private String signCertPwd; private String encryptCertPath; private String encryptCertUser; private String encryptCertPwd; private String validateCertPath; private String validateCertUser; private String validateCertPwd; private String charset; private String payUrl; private String refundUrl; private String cancelUrl; private String queryUrl; private String checkUrl;//[ftp:ip:port:user:password];[http:url];[https:url];[socket:ip:port];[query] private String checkTime; private String refCheckUrl;//[ftp:ip:port:user:password];[http:url];[https:url];[socket:ip:port];[query] private String refCheckTime; private String retCheckUrl;//[ftp:ip:port:user:password];[http:url];[https:url];[socket:ip:port];[query] private String retCheckTime; private String frontIp; private String frontPort; private String contacts; private String phone; private String email; private String qq; private String status; //0-暂停| 1-正常 private String memo; private Date updateTime;//更新时间 private String updateUser;//更新人 private Date regTime;//注册时间 private String regUser;//注册人 public String getName() { return name; } public void setName(String name) { this.name = name; } public String getCode() { return code; } public void setCode(String code) { this.code = code; } public String getMchId() { return mchId; } public void setMchId(String mchId) { this.mchId = mchId; } public String getMchName() { return mchName; } public void setMchName(String mchName) { this.mchName = mchName; } public String getAppId() { return appId; } public void setAppId(String appId) { this.appId = appId; } public String getAccNo() { return accNo; } public void setAccNo(String accNo) { this.accNo = accNo; } public String getAccName() { return accName; } public void setAccName(String accName) { this.accName = accName; } public String getPrivateKey() { return privateKey; } public void setPrivateKey(String privateKey) { this.privateKey = privateKey; } public String getPublicKey() { return publicKey; } public void setPublicKey(String publicKey) { this.publicKey = publicKey; } public String getSignCertPath() { return signCertPath; } public void setSignCertPath(String signCertPath) { this.signCertPath = signCertPath; } public String getSignCertUser() { return signCertUser; } public void setSignCertUser(String signCertUser) { this.signCertUser = signCertUser; } public String getSignCertPwd() { return signCertPwd; } public void setSignCertPwd(String signCertPwd) { this.signCertPwd = signCertPwd; } public String getEncryptCertPath() { return encryptCertPath; } public void setEncryptCertPath(String encryptCertPath) { this.encryptCertPath = encryptCertPath; } public String getEncryptCertUser() { return encryptCertUser; } public void setEncryptCertUser(String encryptCertUser) { this.encryptCertUser = encryptCertUser; } public String getEncryptCertPwd() { return encryptCertPwd; } public void setEncryptCertPwd(String encryptCertPwd) { this.encryptCertPwd = encryptCertPwd; } public String getValidateCertPath() { return validateCertPath; } public void setValidateCertPath(String validateCertPath) { this.validateCertPath = validateCertPath; } public String getValidateCertUser() { return validateCertUser; } public void setValidateCertUser(String validateCertUser) { this.validateCertUser = validateCertUser; } public String getValidateCertPwd() { return validateCertPwd; } public void setValidateCertPwd(String validateCertPwd) { this.validateCertPwd = validateCertPwd; } public String getCharset() { return charset; } public void setCharset(String charset) { this.charset = charset; } public String getPayUrl() { return payUrl; } public void setPayUrl(String payUrl) { this.payUrl = payUrl; } public String getRefundUrl() { return refundUrl; } public void setRefundUrl(String refundUrl) { this.refundUrl = refundUrl; } public String getCancelUrl() { return cancelUrl; } public void setCancelUrl(String cancelUrl) { this.cancelUrl = cancelUrl; } public String getQueryUrl() { return queryUrl; } public void setQueryUrl(String queryUrl) { this.queryUrl = queryUrl; } public String getCheckUrl() { return checkUrl; } public void setCheckUrl(String checkUrl) { this.checkUrl = checkUrl; } public String getCheckTime() { return checkTime; } public void setCheckTime(String checkTime) { this.checkTime = checkTime; } public String getRefCheckUrl() { return refCheckUrl; } public void setRefCheckUrl(String refCheckUrl) { this.refCheckUrl = refCheckUrl; } public String getRefCheckTime() { return refCheckTime; } public void setRefCheckTime(String refCheckTime) { this.refCheckTime = refCheckTime; } public String getRetCheckUrl() { return retCheckUrl; } public void setRetCheckUrl(String retCheckUrl) { this.retCheckUrl = retCheckUrl; } public String getRetCheckTime() { return retCheckTime; } public void setRetCheckTime(String retCheckTime) { this.retCheckTime = retCheckTime; } public String getFrontIp() { return frontIp; } public void setFrontIp(String frontIp) { this.frontIp = frontIp; } public String getFrontPort() { return frontPort; } public void setFrontPort(String frontPort) { this.frontPort = frontPort; } public String getContacts() { return contacts; } public void setContacts(String contacts) { this.contacts = contacts; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getQq() { return qq; } public void setQq(String qq) { this.qq = qq; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public String getMemo() { return memo; } public void setMemo(String memo) { this.memo = memo; } public Date getUpdateTime() { return updateTime; } public void setUpdateTime(Date updateTime) { this.updateTime = updateTime; } public String getUpdateUser() { return updateUser; } public void setUpdateUser(String updateUser) { this.updateUser = updateUser; } public Date getRegTime() { return regTime; } public void setRegTime(Date regTime) { this.regTime = regTime; } public String getRegUser() { return regUser; } public void setRegUser(String regUser) { this.regUser = regUser; } }
package com.metoo.modul.app.game.manager.tree; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.nutz.json.Json; import org.springframework.beans.BeanUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import com.metoo.core.tools.CommUtil; import com.metoo.core.tools.WebForm; import com.metoo.foundation.domain.GameAward; import com.metoo.foundation.domain.GameTask; import com.metoo.foundation.domain.Goods; import com.metoo.foundation.domain.GoodsVoucher; import com.metoo.foundation.domain.SubTrees; import com.metoo.foundation.service.IGameAwardService; import com.metoo.foundation.service.IGameTaskService; import com.metoo.foundation.service.IGoodsService; import com.metoo.foundation.service.IGoodsVoucherService; import com.metoo.foundation.service.ISubTreesService; import com.metoo.modul.app.game.tree.dto.GameAwardDto; import com.metoo.module.app.buyer.domain.Result; /** * 定义每个环节的奖品 * <p> * Title: AppGameAwardViewAction.java * </p> * * <p> * Description: 设置活动奖品 * </p> * * @author 46075 * */ @Controller @RequestMapping("/php/game/award") public class GameAwardManager { @Autowired private IGameAwardService gameAwardService; @Autowired private IGameTaskService gameTaskService; @Autowired private ISubTreesService subTreeService; @Autowired private IGoodsService goodsService; @Autowired private IGoodsVoucherService goodsVoucherService; @RequestMapping("query.json") @ResponseBody public Object query(HttpServletRequest request, HttpServletResponse response) { Map params = new HashMap(); params.put("type", 0); List<GameAward> gameAwards = this.gameAwardService.query("SELECT obj FROM GameAward obj WHERE obj.type=:type", params, -1, -1); return new Result(5200, "Successfully", gameAwards); } /** * 种树游戏 奖品 保存/更新 * @param request * @param response * @param id * @param tree_id * @return */ @RequestMapping("/save.json") @ResponseBody public Object save(HttpServletRequest request, HttpServletResponse response, String id, String tree_id, String voucher_id, String goods_info) { GameAward gameAward = null; WebForm wf = new WebForm(); if (id.equals("")) { gameAward = wf.toPo(request, GameAward.class); gameAward.setAddTime(new Date()); } else { GameAward obj = this.gameAwardService.getObjById(CommUtil.null2Long(id)); gameAward = (GameAward) wf.toPo(request, obj); } SubTrees subTree = this.subTreeService.getObjById(CommUtil.null2Long(tree_id)); if(subTree != null && subTree.getTree() != null){ gameAward.setSubTree(subTree); } if(voucher_id != null && !voucher_id.equals("")){ List<GoodsVoucher> goodsVouchers = new ArrayList<GoodsVoucher>(); String[] voucher_ids = voucher_id.split(","); for(String v_id : voucher_ids){ GoodsVoucher goodsVoucher = this.goodsVoucherService.getObjById(Long.parseLong(v_id)); if(goodsVoucher != null){ goodsVouchers.add(goodsVoucher); } } gameAward.setGoodsVouchers(goodsVouchers); } /* if(goods_info != null && !goods_info.equals("")){ Map goods_map = Json.fromJson(Map.class, goods_info); List<Map> list = resolver(goods_info); for(Map map : list){ if(map.get("goods_id") != null){ Goods goods = this.goodsService.getObjById(CommUtil.null2Long(map.get("goods_id"))); if(goods != null){ } } } }*/ if (id.equals("")) { this.gameAwardService.save(gameAward); } else { this.gameAwardService.update(gameAward); } return new Result(5200, "Successfully"); } public List<Map> resolver(String json) { List<Map> map_list = new ArrayList<Map>(); if (json != null && !json.equals("")) { map_list = Json.fromJson(ArrayList.class, json); } return map_list; } @RequestMapping("/save1.json") @ResponseBody public Object save1(GameAwardDto dto) { GameAward gameAward = null; WebForm wf = new WebForm(); if (dto.getId() == null || dto.getId().equals("")) { /*gameAward = wf.toPo(request, GameAward.class);*/ gameAward = new GameAward(); BeanUtils.copyProperties(dto, gameAward); gameAward.setAddTime(new Date()); } else { gameAward = this.gameAwardService.getObjById(CommUtil.null2Long(dto.getId())); /*gameAward = (GameAward) wf.toPo(request, obj);*/ BeanUtils.copyProperties(dto, gameAward); } SubTrees subTree = this.subTreeService.getObjById(dto.getSubTree_id()); if(subTree != null && subTree.getTree() != null){ gameAward.setSubTree(subTree); } Goods goods = this.goodsService.getObjById(dto.getGoods_id()); if(goods != null){ gameAward.setGoods(goods); } if (dto.getId() == null || dto.getId().equals("")) { this.gameAwardService.save(gameAward); } else { this.gameAwardService.update(gameAward); } return new Result(5200, "Successfully"); } /** * 删除奖品 * * @param request * @param response * @param id * @return */ @RequestMapping("delete.json") @ResponseBody public Object remove(HttpServletRequest request, HttpServletResponse response, String id) { GameAward gameAward = this.gameAwardService.getObjById(CommUtil.null2Long(id)); if (gameAward != null) { this.gameAwardService.delete(gameAward.getId()); } return new Result(5200, "Successfully"); } }
package com.bike_rental_style.model; import java.sql.*; import java.util.ArrayList; import java.util.List; import com.util.JNDI_DataSource; public class Bike_rental_styleJNDIDAO implements Bike_rental_styleDAO_interface { private static final String FIND_BY_PK = "SELECT bk_rt_no, bike_sty_no FROM BIKE_RENTAL_STYLE WHERE bk_rt_no = ? AND bike_sty_no=?"; private static final String FIND_BY_BK_RT_NO = "SELECT bk_rt_no, bike_sty_no FROM BIKE_RENTAL_STYLE WHERE bk_rt_no = ?"; private static final String FIND_BY_BIKE_STY_NO = "SELECT bk_rt_no, bike_sty_no FROM BIKE_RENTAL_STYLE WHERE bike_sty_no=?"; private static final String FIND_BY_BK_RT_STY = "SELECT bk_rt_no, bike_sty_no FROM BIKE_RENTAL_STYLE WHERE bk_rt_no = ? AND bike_sty_no=?"; private static final String GET_ALL_SQL = "SELECT bk_rt_no, bike_sty_no FROM BIKE_RENTAL_STYLE"; // private static final String ADD_Rental = "INSERT INTO Rental (BK_RT_NO) VALUES ('BK'||TO_CHAR(BIKE_RENTAL_NO.NEXTVAL,'FM000'))"; private static final String INSERT = "INSERT INTO BIKE_RENTAL_STYLE(BK_RT_NO, BIKE_STY_NO) VALUES ( ? , ? )"; private static final String DELETE_Rental = "DELETE FROM BIKE_RENTAL_STYLE WHERE BK_RT_NO = ?"; private static final String DELETE_Style = "DELETE FROM BIKE_RENTAL_STYLE WHERE BK_RT_NO = ? AND BIKE_STY_NO = ?"; // private static final String DELETE = "DELETE FROM BIKE_RENTAL_STYLE WHERE bk_rt_no = ?"; // private static final String UPDATE = "UPDATE BIKE_RENTAL set ename=?, job=?, hiredate=?, sal=?, comm=?, deptno=? where empno = ?"; @Override public List<Bike_rental_styleVO> findByBike_Rental(String bk_rt_no) { Bike_rental_styleVO bike_rental_styleVO = null; Connection con = null; PreparedStatement pstmt = null; ResultSet rs = null; List<Bike_rental_styleVO> list = new ArrayList<Bike_rental_styleVO>(); try { con = JNDI_DataSource.getDataSource().getConnection(); pstmt = con.prepareStatement(FIND_BY_BK_RT_NO); pstmt.setString(1, bk_rt_no); rs = pstmt.executeQuery(); while (rs.next()) { bike_rental_styleVO = new Bike_rental_styleVO(); bike_rental_styleVO.setBk_rt_no(rs.getString("bk_rt_no")); bike_rental_styleVO.setBk_sty_no(rs.getString("bike_sty_no")); list.add(bike_rental_styleVO); } } catch (SQLException e) { e.printStackTrace(); } finally { if (pstmt != null) { try { pstmt.close(); } catch (SQLException e) { e.printStackTrace(); } } if (con != null) { try { con.close(); } catch (SQLException e) { e.printStackTrace(); } } } return list; } @Override public List<Bike_rental_styleVO> findByBike_Style(String bike_sty_no) { Bike_rental_styleVO bike_rental_styleVO = null; Connection con = null; PreparedStatement pstmt = null; ResultSet rs = null; List<Bike_rental_styleVO> list = new ArrayList<Bike_rental_styleVO>(); try { con = JNDI_DataSource.getDataSource().getConnection(); pstmt = con.prepareStatement(FIND_BY_BIKE_STY_NO); pstmt.setString(1, bike_sty_no); rs = pstmt.executeQuery(); while (rs.next()) { bike_rental_styleVO = new Bike_rental_styleVO(); bike_rental_styleVO.setBk_rt_no(rs.getString("bk_rt_no")); bike_rental_styleVO.setBk_sty_no(rs.getString("bike_sty_no")); list.add(bike_rental_styleVO); } } catch (SQLException e) { e.printStackTrace(); } finally { if (pstmt != null) { try { pstmt.close(); } catch (SQLException e) { e.printStackTrace(); } } if (con != null) { try { con.close(); } catch (SQLException e) { e.printStackTrace(); } } } return list; } @Override public List<Bike_rental_styleVO> findByBike_Rental_Sty(String bk_rt_no, String bike_sty_no) { Bike_rental_styleVO bike_rental_styleVO = null; Connection con = null; PreparedStatement pstmt = null; ResultSet rs = null; List<Bike_rental_styleVO> list = new ArrayList<Bike_rental_styleVO>(); try { con = JNDI_DataSource.getDataSource().getConnection(); pstmt = con.prepareStatement(FIND_BY_BK_RT_STY); pstmt.setString(1, bk_rt_no); pstmt.setString(2, bike_sty_no); rs = pstmt.executeQuery(); while (rs.next()) { bike_rental_styleVO = new Bike_rental_styleVO(); bike_rental_styleVO.setBk_rt_no(rs.getString("bk_rt_no")); bike_rental_styleVO.setBk_sty_no(rs.getString("bike_sty_no")); list.add(bike_rental_styleVO); } } catch (SQLException e) { e.printStackTrace(); } finally { if (pstmt != null) { try { pstmt.close(); } catch (SQLException e) { e.printStackTrace(); } } if (con != null) { try { con.close(); } catch (SQLException e) { e.printStackTrace(); } } } return list; } @Override public List<Bike_rental_styleVO> getAll() { List<Bike_rental_styleVO> list = new ArrayList<Bike_rental_styleVO>(); Bike_rental_styleVO bike_rental_styleVO = null; Connection con = null; PreparedStatement pstmt = null; ResultSet rs = null; try { con = JNDI_DataSource.getDataSource().getConnection(); pstmt = con.prepareStatement(GET_ALL_SQL); rs = pstmt.executeQuery(); while (rs.next()) { bike_rental_styleVO = new Bike_rental_styleVO(); bike_rental_styleVO.setBk_rt_no(rs.getString("bk_rt_no")); bike_rental_styleVO.setBk_sty_no(rs.getString("bike_sty_no")); list.add(bike_rental_styleVO); } } catch (SQLException e) { e.printStackTrace(); } finally { if (pstmt != null) { try { pstmt.close(); } catch (SQLException e) { e.printStackTrace(); } } if (con != null) { try { con.close(); } catch (SQLException e) { e.printStackTrace(); } } } return list; } //刪除店 @Override public void delete_Rental(String bk_rt_no) { Connection con = null; PreparedStatement pstmt = null; try { con = JNDI_DataSource.getDataSource().getConnection(); pstmt = con.prepareStatement(DELETE_Rental); pstmt.setString(1, bk_rt_no); pstmt.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); } finally { if (pstmt != null) { try { pstmt.close(); } catch (SQLException e) { e.printStackTrace(); } } if (con != null) { try { con.close(); } catch (SQLException e) { e.printStackTrace(); } } } } //刪除店+車 @Override public void delete_Style(String bk_rt_no, String bike_sty_no) { Connection con = null; PreparedStatement pstmt = null; try { con = JNDI_DataSource.getDataSource().getConnection(); pstmt = con.prepareStatement(DELETE_Style); pstmt.setString(1, bk_rt_no); pstmt.setString(2, bike_sty_no); pstmt.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); } finally { if (pstmt != null) { try { pstmt.close(); } catch (SQLException e) { e.printStackTrace(); } } if (con != null) { try { con.close(); } catch (SQLException e) { e.printStackTrace(); } } } } //*增加方法一筆資料 @Override public void insert(String bk_rt_no, String bike_sty_no) { Connection con = null; PreparedStatement pstmt = null; try { con = JNDI_DataSource.getDataSource().getConnection(); pstmt = con.prepareStatement(INSERT); pstmt.setString(1, bk_rt_no); pstmt.setString(2, bike_sty_no); pstmt.executeUpdate(); // Handle any driver errors } catch (SQLException se) { throw new RuntimeException("A database error occured. " + se.getMessage()); } finally { if (pstmt != null) { try { pstmt.close(); } catch (SQLException se) { se.printStackTrace(System.err); } } if (con != null) { try { con.close(); } catch (Exception e) { e.printStackTrace(System.err); } } } } public static void main(String[] args) { Bike_rental_styleJDBCDAO dao = new Bike_rental_styleJDBCDAO(); List<Bike_rental_styleVO> list = dao.getAll(); for(Bike_rental_styleVO vo : list) { System.out.println(vo); } } }
package com.gxtc.huchuan.ui.circle.home; import android.Manifest; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.support.v7.app.AlertDialog; import android.text.Editable; import android.text.TextUtils; import android.text.TextWatcher; import android.view.View; import android.widget.EditText; import android.widget.ImageView; import android.widget.RelativeLayout; import com.gxtc.commlibrary.base.BaseTitleActivity; import com.gxtc.commlibrary.helper.ImageHelper; import com.gxtc.commlibrary.utils.FileUtil; import com.gxtc.commlibrary.utils.GotoUtil; import com.gxtc.commlibrary.utils.ToastUtil; import com.gxtc.huchuan.Constant; import com.gxtc.huchuan.MyApplication; import com.gxtc.huchuan.R; import com.gxtc.huchuan.bean.CreateCircleBean; import com.gxtc.huchuan.bean.MineCircleBean; import com.gxtc.huchuan.bean.UploadFileBean; import com.gxtc.huchuan.bean.UploadResult; import com.gxtc.huchuan.data.UserManager; import com.gxtc.huchuan.helper.RxTaskHelper; import com.gxtc.huchuan.http.ApiCallBack; import com.gxtc.huchuan.http.ApiObserver; import com.gxtc.huchuan.http.ApiResponseBean; import com.gxtc.huchuan.http.LoadHelper; import com.gxtc.huchuan.http.service.AllApi; import com.gxtc.huchuan.http.service.MineApi; import com.gxtc.huchuan.ui.mine.circle.EditCircleInfoActivity; import com.gxtc.huchuan.ui.mine.loginandregister.LoginAndRegisteActivity; import com.gxtc.huchuan.utils.AndroidBug5497Workaround; import com.gxtc.huchuan.utils.DialogUtil; import com.gxtc.huchuan.utils.JumpPermissionManagement; import com.gxtc.huchuan.utils.LoginErrorCodeUtil; import com.luck.picture.lib.entity.LocalMedia; import com.luck.picture.lib.model.FunctionConfig; import com.luck.picture.lib.model.FunctionOptions; import com.luck.picture.lib.model.PictureConfig; import java.io.File; import java.util.List; import butterknife.BindView; import butterknife.OnClick; import io.rong.common.FileUtils; import okhttp3.MediaType; import okhttp3.MultipartBody; import okhttp3.RequestBody; import rx.Subscription; import rx.android.schedulers.AndroidSchedulers; import rx.schedulers.Schedulers; import top.zibin.luban.Luban; import top.zibin.luban.OnCompressListener; /** * Created by sjr on 2017/4/26. * 创建免费圈子 */ public class CreateFreeCircleActivity extends BaseTitleActivity implements PictureConfig.OnSelectResultCallback { @BindView(R.id.iv_create_free_circle_selectimg) ImageView ivCreateFreeCircleSelectimg; @BindView(R.id.rl_create_free_circle) RelativeLayout rlCreateFreeCircle; @BindView(R.id.et_create_free_circle_name) EditText etCreateFreeCircleName; @BindView(R.id.et_create_free_circle_content) EditText etCreateFreeCircleContent; @BindView(R.id.iv_create_free_name) ImageView ivCreateFreeName; String circleId = "";//默认创建圈子时为空 private String imgUrl; AlertDialog alertDialog; MineCircleBean mineCircleBean; private int isPubluc; private int groupType; private AlertDialog mAlertDialog; public int createGroupChat; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_create_free_circle); AndroidBug5497Workaround.assistActivity(this); } @Override public void initView() { getBaseHeadView().showBackButton(new View.OnClickListener() { @Override public void onClick(View v) { CreateFreeCircleActivity.this.finish(); } }); getBaseHeadView().showTitle(getString(R.string.title_create_free_circle)); getBaseHeadView().showHeadRightButton("审核", new View.OnClickListener() { @Override public void onClick(View v) { if (TextUtils.isEmpty(etCreateFreeCircleName.getText())) { ToastUtil.showShort(CreateFreeCircleActivity.this, "圈子名称不能为空"); return; } if (etCreateFreeCircleName.getText().toString().length() > 8) { ToastUtil.showShort(CreateFreeCircleActivity.this, "圈子名称不能超过8个字"); return; } if (TextUtils.isEmpty(imgUrl)) { ToastUtil.showShort(CreateFreeCircleActivity.this, "请上传封面"); return; } alertDialog = DialogUtil.showCircleDialog(CreateFreeCircleActivity.this, new View.OnClickListener() { @Override public void onClick(View v) { //这里先创建融云讨论组,然后在创建圈子 createChatroom(); } }); } }); } @Override public void initData() { mineCircleBean = getIntent().getParcelableExtra("data"); isPubluc = getIntent().getIntExtra("isPubluc",-1); groupType = getIntent().getIntExtra("groupType",-1); createGroupChat = getIntent().getIntExtra("createGroupChat",0); // etCreateFreeCircleName.addTextChangedListener(new CircleNameWatcher()); if(mineCircleBean != null){ circleId = mineCircleBean.getId() + "" ; setData(); }else { circleId = ""; etCreateFreeCircleName.addTextChangedListener(new CircleNameWatcher()); } } /** * 创建讨论组 */ private void createChatroom() { saveCircle(""); } /** * 获取默认用户数据 */ private void saveCircle(String chatId) { if (UserManager.getInstance().isLogin()) { getBaseLoadingView().showLoading(); Subscription sub = AllApi.getInstance().saveCircle(UserManager.getInstance().getToken(),circleId,isPubluc,groupType, etCreateFreeCircleName.getText().toString(), etCreateFreeCircleContent.getText().toString(), imgUrl, 0, 0.00, "0", chatId,createGroupChat).subscribeOn(Schedulers.io()).observeOn( AndroidSchedulers.mainThread()).subscribe( new ApiObserver<ApiResponseBean<CreateCircleBean>>(new ApiCallBack() { @Override public void onSuccess(Object data) { if(alertDialog == null) return; CreateCircleBean bean = (CreateCircleBean) data; alertDialog.dismiss(); getBaseLoadingView().hideLoading(); Intent inten = new Intent(CreateFreeCircleActivity.this, EditCircleInfoActivity.class); inten.putExtra("groupId", bean.getGroupId()); inten.putExtra("isMy", 1); inten.putExtra("flag", true); startActivity(inten); CreateFreeCircleActivity.this.finish(); } @Override public void onError(String errorCode, String message) { if(alertDialog == null) return; LoginErrorCodeUtil.showHaveTokenError(CreateFreeCircleActivity.this, errorCode, message); alertDialog.dismiss(); getBaseLoadingView().hideLoading(); } })); RxTaskHelper.getInstance().addTask(this,sub); } else GotoUtil.goToActivity(this, LoginAndRegisteActivity.class); } @OnClick(R.id.rl_create_free_circle) public void onClick() { chooseImg(); } //选择照片 private void chooseImg() { String[] pers = new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE}; performRequestPermissions(getString(R.string.txt_permission), pers, 10010, new PermissionsResultListener() { @Override public void onPermissionGranted() { FunctionOptions options = new FunctionOptions.Builder() .setType(FunctionConfig.TYPE_IMAGE) .setSelectMode(FunctionConfig.MODE_SINGLE) .setImageSpanCount(3) .setEnableQualityCompress(false) //是否启质量压缩 .setEnablePixelCompress(false) //是否启用像素压缩 .setEnablePreview(true) // 是否打开预览选项 .setShowCamera(true) .setPreviewVideo(true) .setIsCrop(true) .setAspectRatio(1, 1) .create(); PictureConfig.getInstance().init(options).openPhoto(CreateFreeCircleActivity.this, CreateFreeCircleActivity.this); } @Override public void onPermissionDenied() { mAlertDialog = DialogUtil.showDeportDialog(CreateFreeCircleActivity.this, false, null, getString(R.string.pre_scan_notice_msg), new View.OnClickListener() { @Override public void onClick(View v) { if(v.getId() == R.id.tv_dialog_confirm){ JumpPermissionManagement.GoToSetting(CreateFreeCircleActivity.this); } mAlertDialog.dismiss(); } }); } }); } public void compression(String path) { //将图片进行压缩 final File file = new File(path); Luban.get(MyApplication.getInstance()).load(file) //传人要压缩的图片 .putGear(Luban.THIRD_GEAR) //设定压缩档次,默认三挡 .setCompressListener(new OnCompressListener() { // 压缩开始前调用,可以在方法内启动 loading UI @Override public void onStart() {} // 压缩成功后调用,返回压缩后的图片文件 @Override public void onSuccess(final File compressFile) { if (UserManager.getInstance().isLogin()) { File uploadFile = FileUtils.getFileSize(file) > Constant.COMPRESS_VALUE ? compressFile : file; LoadHelper.uploadFile(LoadHelper.UP_TYPE_IMAGE, new LoadHelper.UploadCallback() { @Override public void onUploadSuccess(UploadResult result) { if(getBaseLoadingView() == null) return; Uri uri = Uri.fromFile(file); ivCreateFreeName.setImageURI(uri); imgUrl = result.getUrl(); getBaseLoadingView().hideLoading(); } @Override public void onUploadFailed(String errorCode, String msg) { if(getBaseLoadingView() == null) return; LoginErrorCodeUtil.showHaveTokenError(CreateFreeCircleActivity.this, errorCode, msg); getBaseLoadingView().hideLoading(); } }, null, uploadFile); } else { GotoUtil.goToActivity(CreateFreeCircleActivity.this, LoginAndRegisteActivity.class); getBaseLoadingView().hideLoading(); } } // 当压缩过去出现问题时调用 @Override public void onError(Throwable e) { getBaseLoadingView().hideLoading(); ToastUtil.showShort(CreateFreeCircleActivity.this, e.toString()); } }).launch(); } public void setData(){ etCreateFreeCircleName.setText(mineCircleBean.getGroupName()); etCreateFreeCircleContent.setText(mineCircleBean.getContent()); imgUrl = mineCircleBean.getCover(); ImageHelper.loadImage(this,ivCreateFreeName,imgUrl); } @Override public void onSelectSuccess(List<LocalMedia> resultList) { } @Override public void onSelectSuccess(LocalMedia media) { getBaseLoadingView().showLoading(); compression(media.getPath()); } /** * 圈子名称监听 */ class CircleNameWatcher implements TextWatcher { @Override public void beforeTextChanged(CharSequence charSequence, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { } @Override public void afterTextChanged(Editable s) { checkOutCircleName(s); } } private void checkOutCircleName(final Editable s) { Subscription sub = AllApi.getInstance().checkOutCircleName(s.toString()).subscribeOn( Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe( new ApiObserver<ApiResponseBean<Void>>(new ApiCallBack() { @Override public void onSuccess(Object data) { } @Override public void onError(String errorCode, String message) { if ("10138".equals(errorCode)) { ToastUtil.showLong(CreateFreeCircleActivity.this, "\"" + s.toString() + "\"" + "已经存在"); return; } else { ToastUtil.showShort(CreateFreeCircleActivity.this, message); } } })); RxTaskHelper.getInstance().addTask(this,sub); } @Override protected void onDestroy() { super.onDestroy(); RxTaskHelper.getInstance().cancelTask(this); mAlertDialog = null; } }
package com.wd.news; public class textone { }
package com.eegeo.mapapi.services.tag; import androidx.annotation.UiThread; import com.eegeo.mapapi.util.Promise; /** * A service which allows you to resolve PoiSearchResult.tags to matching icons and descriptions. * * The search tag data is defined in https://github.com/wrld3d/wrld-icon-tools/blob/master/data/search_tags.json, * and this Service will load and internally process that manifest to create a table that lets you resolve tags * to icons and descriptors. */ public class TagService { private TagApi m_tagApi; /** * @eegeo.internal */ public TagService(TagApi tagApi) { this.m_tagApi = tagApi; } /** * Notify the API to load the Search Tags data. Until this completes, most methods on this service * will just return defaults. You'll be notified when the load completes via the OnTagsLoadCompletedListener, * after which time you can start calling the other methods to resolve Tags * @param listener an optional listener that will be called when the load is completed */ @UiThread public void loadTags(OnTagsLoadCompletedListener listener) { m_tagApi.loadTags(listener); } /** * Have we successfully finished loading the Search Tags data? * @return true on successful load of Search Tags data. This should be true after a successful * call to the OnTagsLoadCompletedListener */ @UiThread public Boolean hasLoadedTags() { return m_tagApi.hasLoadedTags(); } /** * Resolve a set of tags from a Poi result to an Icon Key. Icon Keys can then be used by the * Markers API or used to resolve an Icon Image URL. * @param tags the set of tags i.e. from a PoiSearchResult.tags to find a matching icon for * @return a Promise of a resolved Icon Key */ @UiThread public Promise<String> getIconKeyForTags(String tags) { return m_tagApi.getIconKeyForTags(tags); } /** * Resolve a set of tags from a Poi result to an Icon Image URL. * @param tags the set of tags i.e. from a PoiSearchResult.tags to find a matching icon for * @return a Promise of a url matching the resolved Icon Key for an image */ @UiThread public Promise<String> getIconUrlForTags(String tags) { return m_tagApi.getIconUrlForTags(tags); } /** * Resolve an Icon Key to an Icon Image URL directly. * @param iconKey the Icon Key to find a matching Icon Image URL for. * @return a Promise of a URL matching the resolved Icon Key for an image */ @UiThread public Promise<String> getIconUrlForIconKey(String iconKey) { return m_tagApi.getIconUrlByKey(iconKey); } /** * Resolve a set of tags to a collection of Human Readable tag descriptions. i.e. "sports" converts to * "Sports and Leisure". * @param tags the set of tags i.e. from a PoiSearchResult.tags to find matching tag descriptions for. * @return a Promise of a set of human readable descriptions in a String array, matching the input order. */ @UiThread public Promise<String[]> getReadableTagsForTags(String tags) { return m_tagApi.getReadableTagsForTags(tags); } }
package org.wso2.carbon.identity.user.endpoint.dto; import io.swagger.annotations.*; import com.fasterxml.jackson.annotation.*; import javax.validation.constraints.NotNull; @ApiModel(description = "") public class UserSearchEntryDTO { private String username = null; private String userId = null; /** **/ @ApiModelProperty(value = "") @JsonProperty("username") public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } /** **/ @ApiModelProperty(value = "") @JsonProperty("userId") public String getUserId() { return userId; } public void setUserId(String userId) { this.userId = userId; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class UserSearchEntryDTO {\n"); sb.append(" username: ").append(username).append("\n"); sb.append(" userId: ").append(userId).append("\n"); sb.append("}\n"); return sb.toString(); } }
package f.star.iota.milk.ui.gamersky.gamer; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.ViewGroup; import f.star.iota.milk.R; import f.star.iota.milk.base.BaseAdapter; public class GamerSkyAdapter extends BaseAdapter<GamerSkyViewHolder, GamerSkyBean> { @Override public GamerSkyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { return new GamerSkyViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.item_description, parent, false)); } @Override public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) { ((GamerSkyViewHolder) holder).bindView(mBeans.get(position)); } }
package com.ubuntu4u.ubuntu4u.ubuntu4u_client.fragments; import android.Manifest; import android.app.ProgressDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.pm.PackageManager; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Matrix; import android.graphics.Typeface; import android.location.Location; import android.location.LocationManager; import android.os.AsyncTask; import android.os.Bundle; import android.provider.ContactsContract; import android.provider.Settings; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v4.app.ActivityCompat; import android.support.v4.app.DialogFragment; import android.support.v4.app.Fragment; import android.support.v4.content.ContextCompat; import android.support.v7.app.AlertDialog; import android.text.Html; import android.util.Base64; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.ImageView; import android.widget.Toast; import com.ubuntu4u.ubuntu4u.ubuntu4u_client.R; import com.ubuntu4u.ubuntu4u.ubuntu4u_client.activities.ContactsActivity; import com.ubuntu4u.ubuntu4u.ubuntu4u_client.activities.MyRecipientsActivity; import com.ubuntu4u.ubuntu4u.ubuntu4u_client.activities.TopicsActivity; import com.ubuntu4u.ubuntu4u.ubuntu4u_client.activities.VIPListActivity; import com.ubuntu4u.ubuntu4u.ubuntu4u_client.models.ActivityLogModel; import com.ubuntu4u.ubuntu4u.ubuntu4u_client.models.Contact; import com.ubuntu4u.ubuntu4u.ubuntu4u_client.models.MapMarker; import com.ubuntu4u.ubuntu4u.ubuntu4u_client.services.DataManager; import com.google.android.gms.common.ConnectionResult; import com.google.android.gms.common.api.GoogleApiClient; import com.google.android.gms.location.LocationServices; import com.google.android.gms.maps.CameraUpdateFactory; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.OnMapReadyCallback; import com.google.android.gms.maps.SupportMapFragment; import com.google.android.gms.maps.model.BitmapDescriptorFactory; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.Marker; import com.google.android.gms.maps.model.MarkerOptions; import org.json.JSONArray; import org.json.JSONObject; import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileOutputStream; import java.io.InputStream; import java.net.URLEncoder; import java.util.ArrayList; import java.util.HashMap; /** * Created by Q. Engelbrecht on 2017-06-19. */ public class HomeFragment extends Fragment implements PanicSquadDialogFragment.PanicSquadDialogListener, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, OnMapReadyCallback { private SQLiteDatabase db; private ArrayList<Contact> recipients; private ArrayList<Contact> selectedContacts; private ArrayList<MapMarker> markers; private static final int REQUEST_PERMISSIONS_LOCATION = 20; private static final int REQUEST_PERMISSIONS_CONTACTS = 21; private static final int REQUEST_PERMISSIONS_CURRENT_LOCATION = 22; private LocationManager locationManager; private GoogleApiClient mGoogleApiClient; private Location mLastLocation; private String[] latlongs; private String locationAction; private GoogleMap googleMap; private int userId; private String displayName; private boolean goAhead; private static final int profilePicSize = 100; private static final int mapMarkerSize = 200; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.home, container, false); latlongs = new String[2]; displayName = new DataManager().getConfiguration(getActivity()).DisplayName; userId = new DataManager().getConfiguration(getActivity()).UserID; markers = new ArrayList<>(); SupportMapFragment mapFragment = (SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.map); mapFragment.getMapAsync(this); PostContactLeadsRunner runner = new PostContactLeadsRunner(getActivity()); runner.execute(); final ImageView panicButton = (ImageView)view.findViewById(R.id.btnPanic); panicButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { try { db = getActivity().openOrCreateDatabase("law4sho_db", Context.MODE_PRIVATE, null); final Cursor cursor = db.rawQuery("SELECT * FROM Recipients WHERE UserID ='" + new DataManager().getConfiguration(getActivity()).UserID + "'", null); if (cursor.getCount() > 0) { AlertDialog.Builder adb = new AlertDialog.Builder(getActivity()); adb.setTitle("Send Panic?"); adb.setMessage("A panic with your location will now be sent to all contacts in your Panic Squad."); adb.setNegativeButton("Cancel", null); adb.setPositiveButton("Continue", new AlertDialog.OnClickListener() { public void onClick(DialogInterface dialog, int which) { recipients = new ArrayList<Contact>(); cursor.moveToFirst(); while (cursor.isAfterLast() == false) { recipients.add(new Contact(Integer.parseInt(cursor.getString(0)), cursor.getString(1), cursor.getString(2))); cursor.moveToNext(); } if ((ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION) + ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED)) { requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION}, REQUEST_PERMISSIONS_LOCATION); } else { locationAction = "Panic"; InitialiseGoogleApiClient(); } }}); adb.show(); } else { Intent intent = new Intent(getActivity(), MyRecipientsActivity.class); startActivity(intent); } } catch(Exception e) { String test = e.toString(); } } }); final ImageView findMeButton = (ImageView)view.findViewById(R.id.btnFindMe); findMeButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if ((ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.READ_CONTACTS) != PackageManager.PERMISSION_GRANTED)) { ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.READ_CONTACTS}, REQUEST_PERMISSIONS_CONTACTS); } else { Intent intent = new Intent(getActivity(), ContactsActivity.class); intent.putExtra("State", "FindMe"); startActivity(intent); } } }); final ImageView findYouButton = (ImageView)view.findViewById(R.id.btnFindYou); findYouButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(getActivity(), VIPListActivity.class); startActivity(intent); } }); Button refreshButton = (Button)view.findViewById(R.id.btnRefresh); Typeface fontFamily = Typeface.createFromAsset(getActivity().getAssets(), "fonts/fontawesome-webfont.ttf"); refreshButton.setTypeface(fontFamily); refreshButton.setText(Html.fromHtml("&#xf021;")); refreshButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { AllLocationsRunnable runnable = new AllLocationsRunnable(getContext()); runnable.execute(); Toast.makeText(getActivity(), "Refreshing...", Toast.LENGTH_LONG).show(); } }); Button wikiButton = (Button)view.findViewById(R.id.btnWiki); wikiButton.setTypeface(fontFamily); wikiButton.setText(Html.fromHtml("&#xf02d;")); wikiButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(getActivity(), TopicsActivity.class); startActivity(intent); } }); return view; } private void InitialiseGoogleApiClient() { locationManager = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE); if (!isLocationEnabled()) { showAlert(); } else { if (mGoogleApiClient == null) { mGoogleApiClient = new GoogleApiClient.Builder(getActivity()) .addConnectionCallbacks(this) .addOnConnectionFailedListener(this) .addApi(LocationServices.API) .build(); } mGoogleApiClient.connect(); } } private boolean isLocationEnabled() { return locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) || locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER); } private void showAlert() { final AlertDialog.Builder dialog = new AlertDialog.Builder(getActivity()); dialog.setTitle("Enable Location") .setMessage("Your Locations Settings is set to 'Off'.\nPlease Enable Location to " + "use this app") .setPositiveButton("Location Settings", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface paramDialogInterface, int paramInt) { Intent myIntent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS); startActivity(myIntent); } }) .setNegativeButton("Cancel", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface paramDialogInterface, int paramInt) { } }); dialog.show(); } @Override public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) { switch (requestCode) { case REQUEST_PERMISSIONS_LOCATION: if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { locationAction = "Panic"; InitialiseGoogleApiClient(); } else { Toast.makeText(getActivity(), "To send a panic you need to allow us to use your location service :-)", Toast.LENGTH_LONG).show(); } break; case REQUEST_PERMISSIONS_CONTACTS: if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { Intent intent = new Intent(getActivity(), ContactsActivity.class); intent.putExtra("State", "FindMe"); startActivity(intent); } else { Toast.makeText(getActivity(), "You have to allow us to show your phonebook first :-)", Toast.LENGTH_LONG).show(); } break; case REQUEST_PERMISSIONS_CURRENT_LOCATION: if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { locationAction = "CurrentLocation"; InitialiseGoogleApiClient(); } break; } } @Override public void onDialogPositiveClick(DialogFragment dialog, ArrayList mSelectedItems) { /*selectedContacts = new ArrayList<>(); int i = 0; while (i < mSelectedItems.size()) { int j = (int)mSelectedItems.get(i); selectedContacts.add(contacts.get(j)); i++; } if ((ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION) + ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED)) { ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION}, REQUEST_PERMISSIONS_LOCATION); } else { InitialiseGoogleApiClient(); }*/ } @Override public void onDialogNegativeClick(DialogFragment dialog) { } public void ChangeMarkerIcon(long userID, String profilePicture) { try { for (MapMarker marker : markers) { if (marker.UserID.equals(String.valueOf(userID))) { Bitmap bitmap = BitmapFactory.decodeFile(getActivity().getFilesDir().getPath() + "/" + profilePicture); Bitmap smallMarker = Bitmap.createScaledBitmap(bitmap, profilePicSize, profilePicSize, false); Bitmap pin = BitmapFactory.decodeResource(getActivity().getResources(), R.drawable.marker_pin); Bitmap smallpin = Bitmap.createScaledBitmap(pin, mapMarkerSize, mapMarkerSize, false); Bitmap mask = BitmapFactory.decodeResource(getActivity().getResources(), R.drawable.profile_pic_overlay); Bitmap map_pin = overlay(smallMarker, smallpin, mask); marker.marker.setIcon(BitmapDescriptorFactory.fromBitmap(map_pin)); break; } } } catch (Exception e) { String test = e.toString(); } } public static Bitmap overlay(Bitmap bmp1, Bitmap bmp2, Bitmap bmp3) { try { Bitmap bmOverlay = Bitmap.createBitmap(mapMarkerSize, mapMarkerSize, bmp1.getConfig()); Canvas canvas = new Canvas(bmOverlay); canvas.drawBitmap(bmp3, 51, 25, null); canvas.drawBitmap(bmp1, 51, 25, null); canvas.drawBitmap(bmp2, new Matrix(), null); return bmOverlay; } catch (Exception e) { // TODO: handle exception e.printStackTrace(); return null; } } public void SetMarkers(final String DisplayName, final String Latitude, final String Longitude, final String UserID, final String ProfilePicture) { getActivity().runOnUiThread(new Runnable() { @Override public void run() { try { LatLng current = new LatLng(Float.valueOf(Latitude), Float.valueOf(Longitude)); File file = new File(getActivity().getFilesDir().getPath() + "/" + ProfilePicture); if ((file.exists()) && (ProfilePicture != null)) { Bitmap bitmap = BitmapFactory.decodeFile(getActivity().getFilesDir().getPath() + "/" + ProfilePicture); Bitmap smallMarker = Bitmap.createScaledBitmap(bitmap, profilePicSize, profilePicSize, false); Bitmap pin = BitmapFactory.decodeResource(getActivity().getResources(), R.drawable.marker_pin); Bitmap smallpin = Bitmap.createScaledBitmap(pin, mapMarkerSize, mapMarkerSize, false); Bitmap mask = BitmapFactory.decodeResource(getActivity().getResources(), R.drawable.profile_pic_overlay); Bitmap map_pin = overlay(smallMarker, smallpin, mask); for (MapMarker _marker : markers) { if (_marker.UserID.equals(String.valueOf(UserID))) { markers.remove(_marker); } } Marker marker = googleMap.addMarker(new MarkerOptions() .icon(BitmapDescriptorFactory.fromBitmap(map_pin)) .position(current) .title(DisplayName)); markers.add(new MapMarker(UserID, marker)); } else { Bitmap bitmap = BitmapFactory.decodeResource(getActivity().getResources(), R.drawable.ic_account_circle_white_48dp); Bitmap smallMarker = Bitmap.createScaledBitmap(bitmap, profilePicSize, profilePicSize, false); Bitmap pin = BitmapFactory.decodeResource(getActivity().getResources(), R.drawable.marker_pin); Bitmap smallpin = Bitmap.createScaledBitmap(pin, mapMarkerSize, mapMarkerSize, false); Bitmap mask = BitmapFactory.decodeResource(getActivity().getResources(), R.drawable.profile_pic_overlay); Bitmap map_pin = overlay(smallMarker, smallpin, mask); for (MapMarker _marker : markers) { if (_marker.UserID.equals(String.valueOf(UserID))) { markers.remove(_marker); } } Marker marker = googleMap.addMarker(new MarkerOptions() .icon(BitmapDescriptorFactory.fromBitmap(map_pin)) .position(current) .title(DisplayName)); markers.add(new MapMarker(UserID, marker)); } } catch (Exception e) { String test = e.toString(); } } }); } @Override public void onConnected(@Nullable Bundle bundle) { try { try { if (ActivityCompat.checkSelfPermission(getActivity(), android.Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getActivity(), android.Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) { mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient); if (mLastLocation != null) { latlongs[0] = String.valueOf(mLastLocation.getLatitude()); latlongs[1] = String.valueOf(mLastLocation.getLongitude()); switch (locationAction) { case "CurrentLocation": String path = getActivity().getFilesDir().getPath() + "/" + new DataManager().getConfiguration(getActivity()).ProfilePicture; Bitmap bitmap = BitmapFactory.decodeFile(getActivity().getFilesDir().getPath() + "/" + new DataManager().getConfiguration(getActivity()).ProfilePicture); if (bitmap != null) { Bitmap smallMarker = Bitmap.createScaledBitmap(bitmap, profilePicSize, profilePicSize, false); Bitmap pin = BitmapFactory.decodeResource(getActivity().getResources(), R.drawable.marker_pin); Bitmap smallpin = Bitmap.createScaledBitmap(pin, mapMarkerSize, mapMarkerSize, false); Bitmap mask = BitmapFactory.decodeResource(getActivity().getResources(), R.drawable.profile_pic_overlay); Bitmap map_pin = overlay(smallMarker, smallpin, mask); LatLng current = new LatLng(Float.valueOf(latlongs[0]), Float.valueOf(latlongs[1])); Marker marker = googleMap.addMarker(new MarkerOptions() .icon(BitmapDescriptorFactory.fromBitmap(map_pin)) .position(current) .title(displayName)); markers.add(new MapMarker(String.valueOf(userId), marker)); googleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(current, 8.0f)); //googleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(Float.valueOf("-33.270057"), Float.valueOf("22.9971846")), 5.0f)); } else { bitmap = BitmapFactory.decodeResource(getActivity().getResources(), R.drawable.ic_account_circle_white_48dp); Bitmap smallMarker = Bitmap.createScaledBitmap(bitmap, profilePicSize, profilePicSize, false); Bitmap pin = BitmapFactory.decodeResource(getActivity().getResources(), R.drawable.marker_pin); Bitmap smallpin = Bitmap.createScaledBitmap(pin, mapMarkerSize, mapMarkerSize, false); Bitmap mask = BitmapFactory.decodeResource(getActivity().getResources(), R.drawable.profile_pic_overlay); Bitmap map_pin = overlay(smallMarker, smallpin, mask); LatLng current = new LatLng(Float.valueOf(latlongs[0]), Float.valueOf(latlongs[1])); Marker marker = googleMap.addMarker(new MarkerOptions() .icon(BitmapDescriptorFactory.fromBitmap(map_pin)) .position(current) .title(displayName)); markers.add(new MapMarker(String.valueOf(userId), marker)); googleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(current, 8.0f)); } AllLocationsRunnable runnable = new AllLocationsRunnable(getContext()); runnable.execute(); break; case "Panic": PanicRunnable runner = new PanicRunnable(getActivity()); runner.execute(); break; case "AllVIPs": break; } } } } finally { goAhead = true; mGoogleApiClient.disconnect(); } } catch (Exception e) { String test = e.toString(); } } @Override public void onConnectionSuspended(int i) { } @Override public void onConnectionFailed(@NonNull ConnectionResult connectionResult) { } @Override public void onMapReady(GoogleMap googleMap) { this.googleMap = googleMap; this.googleMap.setPadding(0,0,0,490); locationAction = "CurrentLocation"; InitialiseGoogleApiClient(); } private class AllLocationsRunnable extends AsyncTask<String, String, String> { private Contact[] contactsArray; private Context context; public AllLocationsRunnable(Context context) { this.context = context; } @Override protected String doInBackground(String... strings) { try { contactsArray = new DataManager().getData("/VIPContactsService/Get?id=" + userId, Contact[].class); for (Contact contact : contactsArray) { SQLiteDatabase db = getActivity().openOrCreateDatabase("law4sho_db", Context.MODE_PRIVATE, null); Cursor cursor = db.rawQuery("SELECT * FROM ProfilePictures WHERE UserID = " + contact.UserID, null); cursor.moveToFirst(); String uploadDate = null; if (cursor.getCount() > 0) uploadDate = cursor.getString(3).replace('T', ' '); else uploadDate = ""; DataManager dataManager = new DataManager(); JSONObject jsonObject = new JSONObject(); jsonObject.put("TargetCellNumber", contact.Number.replace(" ", "")); jsonObject.put("UserID", userId); if (!uploadDate.isEmpty()) jsonObject.put("UploadDate", uploadDate); jsonObject.put("Type", "AllLocationsRequest"); String jsonString = (String)dataManager.postData(jsonObject, "/LocationRequestService/SendRequest"); jsonObject = new JSONObject(jsonString); String base64String = jsonObject.getString("ProfilePicture"); if (!base64String.isEmpty()) { byte[] imageBytes= Base64.decode(base64String, Base64.DEFAULT); InputStream is = new ByteArrayInputStream(imageBytes); Bitmap image = BitmapFactory.decodeStream(is); File file = new File(getActivity().getFilesDir().getPath() + "/" + contact.ProfilePicture); FileOutputStream stream = new FileOutputStream(file); file.createNewFile(); image.compress(Bitmap.CompressFormat.JPEG, 100, stream); is.close(); image.recycle(); if (cursor.getCount() > 0) { db.execSQL("UPDATE ProfilePictures SET ProfilePicture = '"+ contact.ProfilePicture +"', UploadDate = '"+ contact.UploadDate.replace('T', ' ') +"', MobileNumber = '"+ contact.Number +"' WHERE UserID = " + contact.UserID); } else { db.execSQL("INSERT INTO ProfilePictures (UserID, ProfilePicture, UploadDate, MobileNumber) VALUES ("+ contact.UserID +", '"+ contact.ProfilePicture +"', '"+ contact.UploadDate.replace('T', ' ') +"', '"+ contact.Number +"')"); } } } } catch (Exception e) { e.printStackTrace(); } return null; } } private class PanicRunnable extends AsyncTask<String, String, String> { private ProgressDialog asyncDialog; private String resp; private Context context; public PanicRunnable(Context context) { this.context = context; asyncDialog = new ProgressDialog(getActivity()); asyncDialog.setCanceledOnTouchOutside(false); } @Override protected String doInBackground(String... params) { try { DataManager dataManager = new DataManager(); for (int i = 0; i < recipients.size(); i++) { JSONObject jsonObject = new JSONObject(); jsonObject.put("TargetCellNumber", recipients.get(i).Number.replace(" ", "")); jsonObject.put("Latitude", latlongs[0]); jsonObject.put("Longitude", latlongs[1]); jsonObject.put("DisplayName", new DataManager().getConfiguration(context).DisplayName); jsonObject.put("UserID", new DataManager().getConfiguration(context).UserID); jsonObject.put("Type", "Panic"); dataManager.postData(jsonObject, "/NotificationsService/SendNotification"); new ActivityLogModel("Panic").LogModuleActiviy(); } resp = "Success"; } catch (Exception e) { e.printStackTrace(); resp = e.getMessage(); } return resp; } @Override protected void onPreExecute() { asyncDialog.setMessage(getString(R.string.loading_type)); asyncDialog.show(); } @Override protected void onPostExecute(String result) { if (result == "Success") Toast.makeText(getActivity(), "Panic sent...", Toast.LENGTH_LONG).show(); asyncDialog.dismiss(); } } private class PostContactLeadsRunner extends AsyncTask<String, String, String> { private Context context; public PostContactLeadsRunner(Context context) { this.context = context; } @Override protected String doInBackground(String... strings) { try { JSONObject jobject = new JSONObject(); jobject.put("Latitude", latlongs[0]); jobject.put("Longitude", latlongs[1]); jobject.put("UserID", userId); new DataManager().postData(jobject, "/LogLocationService/LogLocation"); ArrayList<Contact> contacts = new ArrayList<Contact>(); Cursor _contacts = getActivity().getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null); while (_contacts.moveToNext()) { String name = _contacts.getString(_contacts.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME)); String phoneNumber = _contacts.getString(_contacts.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)); if (phoneNumber.length() >= 10) { phoneNumber = phoneNumber.substring(phoneNumber.replace(" ", "").length() - 9).replace(" ", ""); Cursor cursor = null; SQLiteDatabase db = getActivity().openOrCreateDatabase("law4sho_db", Context.MODE_PRIVATE, null); cursor = db.rawQuery("SELECT * FROM SentLeads WHERE Number = '"+ phoneNumber +"'", null); cursor.moveToFirst(); if (cursor.getCount() == 0) { if (IsCellphoneNumberValid("0" + phoneNumber)) { db.execSQL("INSERT INTO SentLeads (Number) VALUES ('"+ phoneNumber +"')"); Contact contact = new Contact(name, phoneNumber); contacts.add(contact); } } cursor.close(); db.close(); } } _contacts.close(); if (!contacts.isEmpty()) { jobject = new JSONObject(); JSONArray jarray = new JSONArray(); int intervalCount = 0; for (Contact _contact : contacts) { intervalCount++; jobject.put("Name" + intervalCount, _contact.Name); jobject.put("Number" + intervalCount, _contact.Number); jarray.put(jobject); if (intervalCount == 20) { new DataManager().postData(null, "/PostLeadsService/PostContacts?"+ "number1=" + jobject.getString("Number1") + "&" + "number2=" + jobject.getString("Number2") + "&" + "number3=" + jobject.getString("Number3") + "&" + "number4=" + jobject.getString("Number4") + "&" + "number5=" + jobject.getString("Number5") + "&" + "number6=" + jobject.getString("Number6") + "&" + "number7=" + jobject.getString("Number7") + "&" + "number8=" + jobject.getString("Number8") + "&" + "number9=" + jobject.getString("Number9") + "&" + "number10=" + jobject.getString("Number10") + "&" + "number11=" + jobject.getString("Number11") + "&" + "number12=" + jobject.getString("Number12") + "&" + "number13=" + jobject.getString("Number13") + "&" + "number14=" + jobject.getString("Number14") + "&" + "number15=" + jobject.getString("Number15") + "&" + "number16=" + jobject.getString("Number16") + "&" + "number17=" + jobject.getString("Number17") + "&" + "number18=" + jobject.getString("Number18") + "&" + "number19=" + jobject.getString("Number19") + "&" + "number20=" + jobject.getString("Number20")); intervalCount = 0; } } } } catch (Exception e) { String test = e.toString(); } return null; } } private boolean IsCellphoneNumberValid(String number) { String regexStr = "^0((60[3-9]|64[0-5])\\d{6}|(7[1-4689]|6[1-3]|8[1-4])\\d{7})$"; boolean valid; if (!number.matches(regexStr)) valid = false; else valid = true; return valid; } }
/* * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.util.xml; import javax.xml.namespace.QName; import javax.xml.stream.Location; import javax.xml.stream.XMLStreamConstants; import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamReader; import org.xml.sax.Attributes; import org.xml.sax.ContentHandler; import org.xml.sax.SAXException; import org.xml.sax.ext.Locator2; import org.xml.sax.helpers.AttributesImpl; import org.springframework.lang.Nullable; import org.springframework.util.StringUtils; /** * SAX {@code XMLReader} that reads from a StAX {@code XMLStreamReader}. Reads from an * {@code XMLStreamReader}, and calls the corresponding methods on the SAX callback interfaces. * * @author Arjen Poutsma * @since 3.0 * @see XMLStreamReader * @see #setContentHandler(org.xml.sax.ContentHandler) * @see #setDTDHandler(org.xml.sax.DTDHandler) * @see #setEntityResolver(org.xml.sax.EntityResolver) * @see #setErrorHandler(org.xml.sax.ErrorHandler) */ class StaxStreamXMLReader extends AbstractStaxXMLReader { private static final String DEFAULT_XML_VERSION = "1.0"; private final XMLStreamReader reader; private String xmlVersion = DEFAULT_XML_VERSION; @Nullable private String encoding; /** * Construct a new instance of the {@code StaxStreamXmlReader} that reads from the given * {@code XMLStreamReader}. The supplied stream reader must be in {@code XMLStreamConstants.START_DOCUMENT} * or {@code XMLStreamConstants.START_ELEMENT} state. * @param reader the {@code XMLEventReader} to read from * @throws IllegalStateException if the reader is not at the start of a document or element */ StaxStreamXMLReader(XMLStreamReader reader) { int event = reader.getEventType(); if (!(event == XMLStreamConstants.START_DOCUMENT || event == XMLStreamConstants.START_ELEMENT)) { throw new IllegalStateException("XMLEventReader not at start of document or element"); } this.reader = reader; } @Override protected void parseInternal() throws SAXException, XMLStreamException { boolean documentStarted = false; boolean documentEnded = false; int elementDepth = 0; int eventType = this.reader.getEventType(); while (true) { if (eventType != XMLStreamConstants.START_DOCUMENT && eventType != XMLStreamConstants.END_DOCUMENT && !documentStarted) { handleStartDocument(); documentStarted = true; } switch (eventType) { case XMLStreamConstants.START_ELEMENT -> { elementDepth++; handleStartElement(); } case XMLStreamConstants.END_ELEMENT -> { elementDepth--; if (elementDepth >= 0) { handleEndElement(); } } case XMLStreamConstants.PROCESSING_INSTRUCTION -> handleProcessingInstruction(); case XMLStreamConstants.CHARACTERS, XMLStreamConstants.SPACE, XMLStreamConstants.CDATA -> handleCharacters(); case XMLStreamConstants.START_DOCUMENT -> { handleStartDocument(); documentStarted = true; } case XMLStreamConstants.END_DOCUMENT -> { handleEndDocument(); documentEnded = true; } case XMLStreamConstants.COMMENT -> handleComment(); case XMLStreamConstants.DTD -> handleDtd(); case XMLStreamConstants.ENTITY_REFERENCE -> handleEntityReference(); } if (this.reader.hasNext() && elementDepth >= 0) { eventType = this.reader.next(); } else { break; } } if (!documentEnded) { handleEndDocument(); } } private void handleStartDocument() throws SAXException { if (XMLStreamConstants.START_DOCUMENT == this.reader.getEventType()) { String xmlVersion = this.reader.getVersion(); if (StringUtils.hasLength(xmlVersion)) { this.xmlVersion = xmlVersion; } this.encoding = this.reader.getCharacterEncodingScheme(); } ContentHandler contentHandler = getContentHandler(); if (contentHandler != null) { final Location location = this.reader.getLocation(); contentHandler.setDocumentLocator(new Locator2() { @Override public int getColumnNumber() { return (location != null ? location.getColumnNumber() : -1); } @Override public int getLineNumber() { return (location != null ? location.getLineNumber() : -1); } @Override @Nullable public String getPublicId() { return (location != null ? location.getPublicId() : null); } @Override @Nullable public String getSystemId() { return (location != null ? location.getSystemId() : null); } @Override public String getXMLVersion() { return xmlVersion; } @Override @Nullable public String getEncoding() { return encoding; } }); contentHandler.startDocument(); if (this.reader.standaloneSet()) { setStandalone(this.reader.isStandalone()); } } } private void handleStartElement() throws SAXException { if (getContentHandler() != null) { QName qName = this.reader.getName(); if (hasNamespacesFeature()) { for (int i = 0; i < this.reader.getNamespaceCount(); i++) { startPrefixMapping(this.reader.getNamespacePrefix(i), this.reader.getNamespaceURI(i)); } for (int i = 0; i < this.reader.getAttributeCount(); i++) { String prefix = this.reader.getAttributePrefix(i); String namespace = this.reader.getAttributeNamespace(i); if (StringUtils.hasLength(namespace)) { startPrefixMapping(prefix, namespace); } } getContentHandler().startElement(qName.getNamespaceURI(), qName.getLocalPart(), toQualifiedName(qName), getAttributes()); } else { getContentHandler().startElement("", "", toQualifiedName(qName), getAttributes()); } } } private void handleEndElement() throws SAXException { if (getContentHandler() != null) { QName qName = this.reader.getName(); if (hasNamespacesFeature()) { getContentHandler().endElement(qName.getNamespaceURI(), qName.getLocalPart(), toQualifiedName(qName)); for (int i = 0; i < this.reader.getNamespaceCount(); i++) { String prefix = this.reader.getNamespacePrefix(i); if (prefix == null) { prefix = ""; } endPrefixMapping(prefix); } } else { getContentHandler().endElement("", "", toQualifiedName(qName)); } } } private void handleCharacters() throws SAXException { if (XMLStreamConstants.CDATA == this.reader.getEventType() && getLexicalHandler() != null) { getLexicalHandler().startCDATA(); } if (getContentHandler() != null) { getContentHandler().characters(this.reader.getTextCharacters(), this.reader.getTextStart(), this.reader.getTextLength()); } if (XMLStreamConstants.CDATA == this.reader.getEventType() && getLexicalHandler() != null) { getLexicalHandler().endCDATA(); } } private void handleComment() throws SAXException { if (getLexicalHandler() != null) { getLexicalHandler().comment(this.reader.getTextCharacters(), this.reader.getTextStart(), this.reader.getTextLength()); } } private void handleDtd() throws SAXException { if (getLexicalHandler() != null) { Location location = this.reader.getLocation(); getLexicalHandler().startDTD(null, location.getPublicId(), location.getSystemId()); } if (getLexicalHandler() != null) { getLexicalHandler().endDTD(); } } private void handleEntityReference() throws SAXException { if (getLexicalHandler() != null) { getLexicalHandler().startEntity(this.reader.getLocalName()); } if (getLexicalHandler() != null) { getLexicalHandler().endEntity(this.reader.getLocalName()); } } private void handleEndDocument() throws SAXException { if (getContentHandler() != null) { getContentHandler().endDocument(); } } private void handleProcessingInstruction() throws SAXException { if (getContentHandler() != null) { getContentHandler().processingInstruction(this.reader.getPITarget(), this.reader.getPIData()); } } private Attributes getAttributes() { AttributesImpl attributes = new AttributesImpl(); for (int i = 0; i < this.reader.getAttributeCount(); i++) { String namespace = this.reader.getAttributeNamespace(i); if (namespace == null || !hasNamespacesFeature()) { namespace = ""; } String type = this.reader.getAttributeType(i); if (type == null) { type = "CDATA"; } attributes.addAttribute(namespace, this.reader.getAttributeLocalName(i), toQualifiedName(this.reader.getAttributeName(i)), type, this.reader.getAttributeValue(i)); } if (hasNamespacePrefixesFeature()) { for (int i = 0; i < this.reader.getNamespaceCount(); i++) { String prefix = this.reader.getNamespacePrefix(i); String namespaceUri = this.reader.getNamespaceURI(i); String qName; if (StringUtils.hasLength(prefix)) { qName = "xmlns:" + prefix; } else { qName = "xmlns"; } attributes.addAttribute("", "", qName, "CDATA", namespaceUri); } } return attributes; } }
package com.example.navigator; import android.os.Bundle; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.fragment.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.google.android.gms.maps.CameraUpdateFactory; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.MapView; import com.google.android.gms.maps.OnMapReadyCallback; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.MarkerOptions; /** * A simple {@link Fragment} subclass. */ public class BlankFragment extends Fragment implements OnMapReadyCallback { private GoogleMap mMap; MapView mMapView; View mView; public BlankFragment() { // Required empty public constructor } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment mView = inflater.inflate(R.layout.fragment_blank, container, false); return mView; } @Override public void onViewCreated(@NonNull View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); mMapView = (MapView) mView.findViewById(R.id.map); if(mMapView != null){ mMapView.onCreate(null); mMapView.onResume(); mMapView.getMapAsync(this); } } @Override public void onMapReady(GoogleMap googleMap) { mMap = googleMap; // Add a marker in Sydney and move the camera LatLng sydney = new LatLng(-34, 151); mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney")); mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney)); } }
package model; import java.util.Date; public class Aluguel { private Integer idAluguel; private Date dataRetirada; private Date dataDevolucao; private double valorPagar; private Date dataEntrega; private int diasAtrasados; private double valorPago; private EnumTipoPagamento tipoPagamento; private Funcionario funcionario; private Cliente cliente; private Game game; public Aluguel() { } public Aluguel(Integer idAluguel, Funcionario funcionario, Cliente cliente, Game game, Date dataRetirada, Date dataDevolucao, double valorPagar, Date dataEntrega, int diasAtrasados, double valorPago, EnumTipoPagamento tipoPagamento) { this.idAluguel = idAluguel; this.funcionario = funcionario; this.cliente = cliente; this.game = game; this.dataRetirada = dataRetirada; this.dataDevolucao = dataDevolucao; this.valorPagar = valorPagar; this.dataEntrega = dataEntrega; this.diasAtrasados = diasAtrasados; this.valorPago = valorPago; this.tipoPagamento = tipoPagamento; } public Integer getIdAluguel() { return idAluguel; } public void setIdAluguel(Integer idAluguel) { this.idAluguel = idAluguel; } public Date getDataRetirada() { return dataRetirada; } public void setDataRetirada(Date dataRetirada) { this.dataRetirada = dataRetirada; } public Date getDataDevolucao() { return dataDevolucao; } public void setDataDevolucao(Date dataDevolucao) { this.dataDevolucao = dataDevolucao; } public double getValorPagar() { return valorPagar; } public void setValorPagar(double valorPagar) { this.valorPagar = valorPagar; } public Date getDataEntrega() { return dataEntrega; } public void setDataEntrega(Date dataEntrega) { this.dataEntrega = dataEntrega; } public int getDiasAtrasados() { return diasAtrasados; } public void setDiasAtrasados(int diasAtrasados) { this.diasAtrasados = diasAtrasados; } public double getValorPago() { return valorPago; } public void setValorPago(double valorPago) { this.valorPago = valorPago; } public EnumTipoPagamento getTipoPagamento() { return tipoPagamento; } public void setTipoPagamento(EnumTipoPagamento tipoPagamento) { this.tipoPagamento = tipoPagamento; } public Funcionario getFuncionario() { return funcionario; } public void setFuncionario(Funcionario funcionario) { this.funcionario = funcionario; } public Cliente getCliente() { return cliente; } public void setCliente(Cliente cliente) { this.cliente = cliente; } public Game getGame() { return game; } public void setGame(Game game) { this.game = game; } }
package com.cigc.limit.domain; import org.springframework.jdbc.core.RowMapper; import org.springframework.lang.Nullable; import java.sql.ResultSet; import java.sql.SQLException; /** * Created by Administrator on 2018/7/2 0002. */ public class LocationMapper implements RowMapper<Location> { @Nullable @Override public Location mapRow(ResultSet resultSet, int i) throws SQLException { Location location=new Location(); location.setLat(resultSet.getDouble(1)); location.setLng(resultSet.getDouble(2)); return location; } }
// https://leetcode.com/problems/divisor-game/ // #math #dynamic-programming class Solution { public boolean divisorGame(int n) { /* dp[n] = true/false true: start with n, the first player always wins false: start with n, always loses dp[1] = false dp[2] = true dp[3] = false A: dp[n] -> x, n % x == 0 dp[n-x]. => for (1 -> n) { x => n % x == 0 && dp[n-x] == false ? => break => true; } bottom up */ boolean[] dp = new boolean[n + 1]; dp[1] = false; for (int i = 2; i <= n; i++) { // int limit = i / 2; for (int j = 1; j <= limit; j++) { if (i % j == 0 && dp[i - j] == false) { dp[i] = true; break; } } } return dp[n]; } }
package com.jstf.tests; import org.junit.AfterClass; import org.junit.BeforeClass; import com.jstf.main.JSTF; import com.jstf.selenium.JAssert; import com.jstf.selenium.JDriver; public abstract class BaseTest { protected final static String homepageUrl = "https://github.com/"; protected JDriver jDriver; protected JAssert jAssert; @BeforeClass public static void setUpBeforeClass() throws Exception { JSTF.setup(); } @AfterClass public static void tearDownAfterClass() throws Exception { JSTF.teardown(); } }
package com.memory.platform.modules.system.base.dao; import com.memory.platform.hibernate4.dao.IBaseDao; import com.memory.platform.modules.system.base.model.SystemDept; /** * @author * * @param <T> * 模型 */ public interface ISystemDeptDao extends IBaseDao<SystemDept> { }
/* * @(#)ConsoleChatClient.java 1.01 09/06/99 * */ package org.google.code.netapps.chat; import java.io.*; import org.google.code.netapps.chat.primitive.*; import org.google.code.netapps.chat.basic.*; import org.google.code.netapps.chat.event.*; import org.google.code.servant.net.Client; import org.google.code.servant.net.Interactor; /** * Class for presenting chat client that work with a console. * * @version 1.01 09/06/99 * @author Alexander Shvets */ public class ConsoleChatInteractor extends ChatInteractor { /** * Constructs console client with the specified type and name. It will * connect with a chat server that run on specified internet address * and listening on specified port. * */ public ConsoleChatInteractor(Client client, int pollingTime) { super(client, pollingTime); } /** * Sends the request from the client * * @param request the request from the client * @exception IOException if an I/O error occurs. */ public void request(Object request) throws IOException { try { if(request.equals(Command.POLL)) { if(!txQueue.contains(Command.POLL)) { super.request(request); } } else { super.request(request); } } catch(IOException e) { e.printStackTrace(); } } /** * Implementation of ChatActionListener prototype method. * * @param event event that carries out information-notification */ public void chatPerformed(ChatEvent event) { String message = event.getMessage(); if(message != null) { System.out.println(message); } byte[] body = event.getBody(); if(body != null && body.length > 0) { System.out.println(new String(body)); } } public static void main(String args[]) throws Exception { String host = "localhost"; int port = 4646; int pollingTime = 1000; String name = ParticipantType.CSR + " " + "alex1"; String password = "aaa"; if(args.length > 0) host = args[0]; if(args.length > 1) port = Integer.parseInt(args[1]); if(args.length > 2) pollingTime = Integer.parseInt(args[2]); if(args.length > 4) name = args[3] + " " + args[4]; if(args.length > 5) password = args[5]; ChatDirectClient client = new ChatDirectClient(host, port); client.register(name, password); Interactor interactor = new ConsoleChatInteractor(client, pollingTime); interactor.start(); System.out.println(name + " has connected to " + host + ":" + port); System.out.println("Type \'" + Command.EXIT + "\' to exit"); while(true) { String request = null; try { request = (new BufferedReader(new InputStreamReader(System.in))).readLine().trim(); interactor.request(request); if(request.equals(Command.EXIT)) { break; } } catch(IOException e) { e.printStackTrace(); request = null; } } interactor.stop(); } }
package com.operacloud.pages; import java.io.IOException; import java.util.concurrent.TimeUnit; import org.openqa.selenium.By; import org.openqa.selenium.JavascriptExecutor; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.interactions.Actions; import org.openqa.selenium.remote.RemoteWebDriver; import org.openqa.selenium.support.FindBy; import org.openqa.selenium.support.ui.ExpectedConditions; import com.aventstack.extentreports.ExtentTest; import com.operacloud.selenium.actions.extensions.OperaCloudSeleniumActions; public class OperaCloud_ShiftReportsPage extends OperaCloudSeleniumActions { public OperaCloud_ShiftReportsPage(ChromeDriver driver, ExtentTest node) { //to do, verify title of the home page this.driver=driver; this.node=node; initPage(); } public OperaCloud_HomePage goBackToHomePage() throws InterruptedException, IOException { try { reportStep("you are on shift reports page", "pass"); } catch(Exception e) { reportStep("you are not on shift reports page", "fail"); } return new OperaCloud_HomePage(driver, node); } @FindBy(xpath="//a//span[text()='New']") private WebElement newButton; public OperaCloud_ManageShiftReport clickOnNewButton() throws IOException { try { System.out.println("about to click new button"); Thread.sleep(5000); //wait.until(ExpectedConditions.presenceOfElementLocated((By) newButton)); newButton.click(); System.out.println("new button clicked"); Thread.sleep(5000); reportStep("successfully clicked on new button", "PASS"); } catch(Exception e) { reportStep("clicking on new Button is unsuccessful", "FAIL"); } return new OperaCloud_ManageShiftReport(driver, node); } @FindBy(xpath="//span[text()='Search']") private WebElement searchButton; public OperaCloud_ShiftReportsPage clickSearchButton() throws InterruptedException, IOException { try { searchButton.click(); Thread.sleep(5000); reportStep("click on search button successful", "pass"); } catch(Exception e) { reportStep("click on search button unsuccessful", "fail"); } return this; } public OperaCloud_ShiftReportsPage scrollShiftReportsPage() { try { Thread.sleep(5000); scrollPage(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } return this; } String xpath = "//span[text()='replacethisvalue']"; public OperaCloud_ShiftReportsPage clickOnReportName(String reportName) throws IOException { try { Thread.sleep(5000); WebElement rprtnme = findElement("xpath", generateDynamicXpath(xpath, reportName)); rprtnme.click(); Thread.sleep(5000); reportStep("click on report is successful", "pass"); } catch(Exception e) { reportStep("click on report is unsuccessful", "fail"); } return this; } public OperaCloud_ShiftReportsPage clickOnActions() throws IOException { try { Thread.sleep(5000); WebElement clickActions= driver.findElement(By.xpath("//span[text()='rep_"+OperaCloud_ManageShiftReport.repname+"']//parent::td//following::td//span//a[@title='Actions']")); System.out.println(clickActions +"is the xpath of clickActions"); clickActions.click(); Thread.sleep(5000); reportStep("click on Actions is successful", "pass"); } catch(Exception e) { reportStep("click on Actions is unsuccessful", "fail"); } return this; } @FindBy(xpath="//a[@title='Actions']") private WebElement clickReportsAction; public OperaCloud_ShiftReportsPage clickOnReportsAction() throws InterruptedException, IOException { try { wait.until(ExpectedConditions.elementToBeClickable(clickReportsAction)); clickReportsAction.click(); Thread.sleep(5000); reportStep("click on reports actions successful", "pass"); } catch(Exception e) { reportStep("click on reports actions unsuccessful", "fail"); } return this; } @FindBy(xpath="//label[text()='Report']//following::input[contains(@id,'ReportName')]") private WebElement ReportSearch; public OperaCloud_ShiftReportsPage searchCreatedReport(String reportName) throws IOException { try { System.out.println(reportName); Thread.sleep(5000); ReportSearch.sendKeys(reportName); Thread.sleep(5000); reportStep("successfully entered the newly created report in search field", "pass"); } catch (InterruptedException e) { e.printStackTrace(); reportStep("something wrong in entering newly created report in search field" , "fail"); } return this; } @FindBy(xpath = "//span[text()='View']") private WebElement clickViewOption; public OperaCloud_ViewReportsPage clickOnViewOption() throws InterruptedException, IOException { try { //wait.until(ExpectedConditions.elementToBeClickable(clickViewOption)); clickViewOption.click(); Thread.sleep(5000); scrollPage(); reportStep("click on view options successful", "pass"); } catch(Exception e) { reportStep("click on view options unsuccessful", "fail"); } return new OperaCloud_ViewReportsPage(driver,node); } }
/** * 多数元素 https://leetcode-cn.com/problems/majority-element/description/ */ public class 多数元素 { public int majorityElementVote(int[] nums) { int count=0; int candidate=0; for (int i:nums){ if(count==0){ candidate=i; } count+=candidate==i?1:-1; } return candidate; } public int majorityElement(int[] nums) {//分治 return _recursion(nums,0,nums.length-1); } private int _recursion(int[] nums, int l, int h) { if(l==h){ return nums[l]; } int mid=(l+h)/2; int left=_recursion(nums,l,mid); int right=_recursion(nums,mid+1,h); if(left==right){ return left; } int lc=count(nums,left); int hc=count(nums,right); return lc>hc?left:right; } private int count(int[] nums, int left) { int count=0; for(int i:nums){ if(i==left){ count++; } } return count; } }
package com.test.search2; import java.util.ArrayList; import java.util.List; import com.test.base.TreeNode; /** * . 二叉树,插入,允许重复数据 * @author YLine * * 2019年3月14日 上午11:30:01 */ public class SolutionSearch2Insert { public static final int LEFT = 0; public static final int RIGHT = 1; /** * .如果数据相同,则当做大的处理 * .如果数据小于,当前节点,若无左节点,则变成子节点;若有左子节点,继续判断 * .如果数据大于,当前节点,若无右节点,则变成子节点;若有右子节点,急需判断 * @return 插入肯定是成功的;所以返回查询路径 + 最后选择的节点(左0,右1) */ public List<Integer> insert(TreeNode<Integer> root, int data) { List<Integer> pathList = new ArrayList<>(); dfs(root, data, pathList); return pathList; } private void dfs(TreeNode<Integer> root, int data, List<Integer> path) { if (data >= root.getData()) { if (null == root.getRightNode()) { path.add(root.getData()); path.add(RIGHT); return; } else { path.add(root.getData()); dfs(root.getRightNode(), data, path); } } else { if (null == root.getLeftNode()) { path.add(root.getData()); path.add(LEFT); return; } else { path.add(root.getData()); dfs(root.getLeftNode(), data, path); } } } }
package render; import java.awt.Rectangle; import java.util.ArrayList; import java.util.Collections; import world.Map; import world.Worldhandler; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.Texture; import com.badlogic.gdx.graphics.Texture.TextureFilter; import com.badlogic.gdx.graphics.g2d.BitmapFont; import com.badlogic.gdx.graphics.g2d.Sprite; import com.badlogic.gdx.graphics.g2d.SpriteBatch; import com.badlogic.gdx.graphics.g2d.TextureRegion; import com.badlogic.gdx.scenes.scene2d.ui.Label; import com.badlogic.gdx.scenes.scene2d.ui.Label.LabelStyle; import com.rapplebob.ArmsAndArmorChampions.*; import containers.Activator; import containers.ActivatorType; import containers.Alignment; import containers.ConHand; import containers.Container; import containers.ContainerType; import containers.Content; import static containers.ContentType.*; import containers.Menu; public abstract class Renderer { public Renderer() { loadFonts(); } public String ID = "DEFAULT"; public State state = null; public Sprite sprite = new Sprite(); public Texture grid; public Texture background; public Texture conBack; public Texture conFill; public Texture conCon; public Texture actBack; public BitmapFont com64; public BitmapFont com32; public BitmapFont com16; public BitmapFont com10; public BitmapFont com32_BI; public BitmapFont com16_BI; public BitmapFont com10_BI; public abstract void mobileRender(SpriteBatch batch); public abstract void staticRender(SpriteBatch batch); public abstract void specificUpdate(); public void generalUpdate() { if(active){ specificUpdate(); } } public boolean active = false; public abstract void loadSpecificResources() throws Exception; public void loadResources(){ grid = new Texture(Gdx.files.internal("data/images/grid.png")); background = new Texture(Gdx.files.internal("data/images/defaultBackground.png")); conBack = new Texture(Gdx.files.internal("data/images/conBack.png")); conFill = new Texture(Gdx.files.internal("data/images/conFill.png")); conCon = new Texture(Gdx.files.internal("data/images/conCon.png")); actBack = new Texture(Gdx.files.internal("data/images/actBack.png")); } public void drawImage(SpriteBatch batch, Texture img, float x, float y, float scale, int rotation, boolean smooth, Color tint, float opacity, boolean centered) { if(smooth){ img.setFilter(TextureFilter.Linear, TextureFilter.Linear); }else{ img.setFilter(TextureFilter.Nearest, TextureFilter.Nearest); } if(!centered){ x += img.getWidth() / 2; y += img.getHeight() / 2; } sprite = new Sprite(img); sprite.setSize(sprite.getWidth(), sprite.getHeight()); sprite.setScale(scale); sprite.setOrigin(sprite.getWidth() / 2, sprite.getHeight() / 2); sprite.setPosition(x - (sprite.getWidth() / 2), y - (sprite.getHeight() / 2)); sprite.setRotation(rotation); sprite.setColor(tint.r, tint.g, tint.b, opacity); actualDrawImage(batch); } public void drawImage(SpriteBatch batch, Texture img, float x, float y, float width, float height, int rotation, boolean smooth, Color tint, float opacity, boolean centered) { if(smooth){ img.setFilter(TextureFilter.Linear, TextureFilter.Linear); }else{ img.setFilter(TextureFilter.Nearest, TextureFilter.Nearest); } if(!centered){ x += width / 2; y += height / 2; } sprite = new Sprite(img); sprite.setSize(1, 1); sprite.setScale(width, height); sprite.setOrigin(sprite.getWidth() / 2, sprite.getHeight() / 2); sprite.setPosition(x - (sprite.getWidth() / 2), y - (sprite.getHeight() / 2)); sprite.setRotation(rotation); sprite.setColor(tint.r, tint.g, tint.b, opacity); actualDrawImage(batch); } public void drawImage(SpriteBatch batch, TextureRegion img, float x, float y, float scale, int rotation, boolean smooth, Color tint, float opacity, boolean centered) { if(smooth){ img.getTexture().setFilter(TextureFilter.Linear, TextureFilter.Linear); }else{ img.getTexture().setFilter(TextureFilter.Nearest, TextureFilter.Nearest); } if(!centered){ x += img.getRegionWidth() / 2; y += img.getRegionHeight() / 2; } sprite = new Sprite(img); sprite.setSize(sprite.getWidth(), sprite.getHeight()); sprite.setScale(scale); sprite.setOrigin(sprite.getWidth() / 2, sprite.getHeight() / 2); sprite.setPosition(x - (sprite.getWidth() / 2), y - (sprite.getHeight() / 2)); sprite.setRotation(rotation); sprite.setColor(tint.r, tint.g, tint.b, opacity); actualDrawImage(batch); } public void drawImage(SpriteBatch batch, TextureRegion img, float x, float y, float width, float height, int rotation, boolean smooth, Color tint, float opacity, boolean centered) { if(smooth){ img.getTexture().setFilter(TextureFilter.Linear, TextureFilter.Linear); }else{ img.getTexture().setFilter(TextureFilter.Nearest, TextureFilter.Nearest); } if(!centered){ x += width / 2; y += height / 2; } sprite = new Sprite(img); sprite.setSize(1, 1); sprite.setScale(width, height); sprite.setOrigin(sprite.getWidth() / 2, sprite.getHeight() / 2); sprite.setPosition(x - (sprite.getWidth() / 2), y - (sprite.getHeight() / 2)); sprite.setRotation(rotation); sprite.setColor(tint.r, tint.g, tint.b, opacity); actualDrawImage(batch); } private void actualDrawImage(SpriteBatch batch){ //if(onScreen(sprite)){ sprite.draw(batch); //} } public boolean onScreen(Sprite spr){ boolean temp = false; if(AAA_C.screenRect.intersects(new Rectangle((int) spr.getX(), (int) spr.getY(), (int) spr.getWidth(), (int) spr.getHeight()))){ temp = true; } return temp; } public void loadFonts() { com64 = new BitmapFont(Gdx.files.internal("data/fonts/com64.fnt"), Gdx.files.internal("data/fonts/com64.png"), false, false); com32 = new BitmapFont(Gdx.files.internal("data/fonts/com32.fnt"), Gdx.files.internal("data/fonts/com32.png"), false, false); com16 = new BitmapFont(Gdx.files.internal("data/fonts/com16.fnt"), Gdx.files.internal("data/fonts/com16.png"), false, false); com10 = new BitmapFont(Gdx.files.internal("data/fonts/com10.fnt"), Gdx.files.internal("data/fonts/com10.png"), false, false); com32_BI = new BitmapFont(Gdx.files.internal("data/fonts/com32_BI.fnt"), Gdx.files.internal("data/fonts/com32_BI.png"), false, false); com16_BI = new BitmapFont(Gdx.files.internal("data/fonts/com16_BI.fnt"), Gdx.files.internal("data/fonts/com16_BI.png"), false, false); com10_BI = new BitmapFont(Gdx.files.internal("data/fonts/com10_BI.fnt"), Gdx.files.internal("data/fonts/com10_BI.png"), false, false); } public float getScreenX() { return -(AAA_C.w / 2); } public float getScreenY() { return -(AAA_C.h / 2); } public void drawString(SpriteBatch batch, String string, float x, float y, BitmapFont font, Color col, float opacity) { y -= font.getCapHeight(); LabelStyle style = new LabelStyle(font, col); Label lab = new Label(string, style); lab.setPosition(x, y); lab.draw(batch, opacity); } public void drawMenu(SpriteBatch batch, Content c, int x, int y, BitmapFont font, boolean useMarker, boolean title) { Menu m = (Menu) c; x = x + m.X; y = y + m.Y; if(title){ drawString(batch, m.menuTitle, x, y, font, Color.WHITE, 1.0f); drawString(batch, "______________________", x, y - 8, font, Color.WHITE, 1.0f); } if (m.acts.size() > 0) { for (int i = 0; i < m.acts.size(); i++) { Activator a = m.acts.get(i); Color col = getActColor(a.AT); String print = a.title; if(AAA_C.debug){ print += " - " + a.script + " - " + a.AT.toString(); } //drawString(batch, print, x, y - 50 - (i * 40), com32, col, 1.0f); drawActivator(batch, a, x + a.BOX.x, y + a.BOX.y, false, font, col, Color.WHITE, 1.0f); if(useMarker){ if(i == m.activeAct){ String marker; switch(a.AT){ case BUTTON:marker = "*"; break; case INPUT:marker = ">"; break; case TEXT:marker = "-"; break; default:marker = ""; } drawString(batch, marker, x + a.BOX.x - 32, y + a.BOX.y + (font.getCapHeight()), font, Color.WHITE, 1.0f); } } } } else { drawString(batch, "EMPTY MENU", x, y - 50, font, Color.WHITE, 1.0f); } } public Color getActColor(ActivatorType type) { Color col; switch (type) { case BUTTON: col = Color.WHITE; break; case INPUT: col = Color.YELLOW; break; case TEXT: col = Color.CYAN; break; default: col = Color.WHITE; } return col; } public void drawMap(SpriteBatch batch, Map map, int mx, int my, boolean central){ if(map.LOADED && map.CELLS.length > 0){ for(int x = 0; x < map.CELLS.length; x++){ for(int y = 0; y < map.CELLS[x].length; y++){ drawCell(batch, map, mx, my, x, y); } } }else{ drawString(batch, "Map empty or not yet loaded.", -200, 50, com32, Color.RED, 1.0f); } drawString(batch, mx + ", " + my, getScreenX(), getScreenY(), com10, Color.RED, 1.0f); } public void drawCell(SpriteBatch batch, Map map, int mx, int my, int x, int y){ drawImage(batch, Worldhandler.getClimateImage(map.CELLS[x][y].CLIMATE), map.CELLS[x][y].X + mx, map.CELLS[x][y].Y + my, 1.0f, 0, false, Color.WHITE, 1.0f, false); drawImage(batch, Worldhandler.getTerrainImage(map.CELLS[x][y].TERRAIN), map.CELLS[x][y].X + mx, map.CELLS[x][y].Y + my, 1.0f, 0, false, Color.WHITE, 1.0f, false); if(AAA_C.showGrid){ drawImage(batch, grid, map.CELLS[x][y].X + mx, map.CELLS[x][y].Y + my, 1.0f, 0, false, Color.WHITE, 1.0f, false); } if(AAA_C.debug){ drawString(batch, x + "," + y, map.CELLS[x][y].X + mx, map.CELLS[x][y].Y + my, com10, Color.RED, 1.0f); drawString(batch, map.CELLS[x][y].CLIMATE + "", map.CELLS[x][y].X + mx, map.CELLS[x][y].Y + my - 12, com10, Color.RED, 1.0f); drawString(batch, "+", map.CELLS[x][y].getRealPolygon().xpoints[0], map.CELLS[x][y].getRealPolygon().ypoints[0], com10, Color.RED, 1.0f); } } /* public void drawPolygon(ShapeRenderer triangleBatch, Polygon pol[], int x, int y, Color col){ triangleBatch.setColor(col); for(int i = 0; i < pol.length; i++){ triangleBatch.triangle(pol[i].getVertices()[0] + x, pol[i].getVertices()[1] + y, pol[i].getVertices()[2] + x, pol[i].getVertices()[3] + y, pol[i].getVertices()[4] + x, pol[i].getVertices()[5] + y); } } public void drawPolygon(ShapeRenderer triangleBatch, float[] verts, int x, int y, Color col){ triangleBatch.setColor(col); triangleBatch.triangle(verts[0] + x, verts[1] + y, verts[2] + x, verts[3] + y, verts[4] + x, verts[5] + y); }*/ public int getCentralMapX(Map map){ float x = - map.getWidth() / 2; return (int) x; } public int getCentralMapY(Map map){ float y = map.getHeight() / 2; return (int) y; } public void drawContainers(SpriteBatch batch, ContainerType type){ Container[] CA = ConHand.getCons(type); for(int i = CA.length - 1; i >= 0; i--){ drawContainer(batch, CA[i]); } } public void drawContainer(SpriteBatch batch, Container con){ int x = con.getBox().x; int y = con.getBox().y; if(con.ACTIVE){ if(con.MOVING){ drawImage(batch, conBack, x - 1, y - 1, con.getBox().width + 2, con.getBox().height + 2, 0, false, Color.WHITE, con.TRANSPARENCY, false); } if(con.BACKGROUND){ drawImage(batch, conFill, x, y, con.getBox().width, con.getBox().height, 0, false, Color.WHITE, con.TRANSPARENCY, false); } for(int i = 0; i < con.CONTENT.size(); i++){ drawContent(batch, con.CONTENT.get(i), x, y); } if(con.DECORATED){ drawImage(batch, conCon, x + con.conSurf.x, y + con.conSurf.y, con.conSurf.width, con.conSurf.height, 0, true, Color.WHITE, con.TRANSPARENCY, false); drawString(batch, con.TITLE, x + con.conSurf.x, y + con.conSurf.y + con.conSurf.height - 12, com10, Color.RED, con.TRANSPARENCY); drawActivator(batch, con.EXIT, x + con.EXIT.BOX.x, y + con.EXIT.BOX.y, false, com10, Color.RED, Color.WHITE, con.TRANSPARENCY); } } } public void drawActivator(SpriteBatch batch, Activator AC, int x, int y, boolean centered, BitmapFont font, Color col, Color tint, float opacity){ //If not centered: draw from upper left corner. if(!centered){ x += AC.BOX.width / 2; y += AC.BOX.height / 2; } if(AC.textured){ drawImage(batch, AC.TEX, x, y, AC.BOX.width, AC.BOX.height, 0, false, tint, opacity, true); }else{ drawImage(batch, actBack, x, y, AC.BOX.width, AC.BOX.height, 0, false, tint, opacity, true); } drawString(batch, AC.title, x - AC.BOX.width / 4, y + (AC.BOX.height / 4), font, col, opacity); } public void drawContent(SpriteBatch batch, Content content, int x, int y){ switch(content.TYPE){ case MENU: drawMenu(batch, content, x, y, com10, false, false); break; case DEFAULT: break; case MENUHOLDER: break; } } public boolean getOnScreen(Rectangle r){ if(r.intersects(new Rectangle((int) getScreenX(), (int) getScreenY(), (int) AAA_C.w, (int) AAA_C.h))){ return true; }else{ return false; } } }
package com.example.CSVLoader; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.sql.SQLException; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.LinkedHashSet; import java.util.Set; import java.util.StringTokenizer; import javax.xml.bind.annotation.adapters.HexBinaryAdapter; import com.example.Entities.Group; import com.example.Entities.Student; import com.example.Entities.Teacher; import com.example.Entities.Tutor; import com.example.Entities.User; import com.example.Logic.CurrentCourse; import com.example.Logic.GroupJPAManager; import com.example.Logic.StudentsJPAManager; import com.example.Logic.TeachersJPAManager; import com.example.Logic.TutorJPAManager; import com.example.Logic.UserJPAManager; import com.vaadin.server.Page; import com.vaadin.shared.Position; import com.vaadin.ui.Notification; /******************************************************************************* * * Gestió d'Amonestacions v1.0 * * Esta obra está sujeta a la licencia * Reconocimiento-NoComercial-SinObraDerivada 4.0 Internacional de Creative * Commons. Para ver una copia de esta licencia, visite * http://creativecommons.org/licenses/by-nc-nd/4.0/. * * @author Francisco Javier Casado Moreno - fcasado@elpuig.xeill.net * @author Daniel Pérez Palacino - dperez@elpuig.xeill.net * @author Gerard Enrique Paulino Decena - gpaulino@elpuig.xeill.net * @author Xavier Murcia Gámez - xmurcia@elpuig.xeill.net * * * * Esta clase se encarga de cargar masivamente alumnos, grupos, * docentes, usuarios y tutores mediante un fichero csv * *******************************************************************************/ public class CSVLoader { private final static String FORMAT = "ISO-8859-3"; private final static String DATEFORMAT = "dd/MM/yyyy"; private final static String ALGORITHM = "SHA-1"; private final static String ROLTUTOR = "Tutor"; private final static String ROLPROFESSOR = "Professor"; private final static String NOTIF = "Dades carregades correctament"; private int id; private String surname, name, group, country, nacionality, phone; private String email, password, user, tutoring; private Date born, date; private StudentsJPAManager studentsJPA; private UserJPAManager userJPA; private TutorJPAManager tutorJPA; private TeachersJPAManager teachersJPA; private GroupJPAManager groupsJPA; private MessageDigest messageDigest; private HexBinaryAdapter hBinaryAdapter; private BufferedReader bReader; private DateFormat dateFormat; private ArrayList<String> lGroups; private ArrayList<Student> lStudents; private Set<String> linkedHashSet; private String line = ""; private String passwordHash; private CurrentCourse course; /** * Este es el método main en el que se inician las conexiones con la base de * datos para cada entidad. * */ public CSVLoader() { course = new CurrentCourse(); studentsJPA = new StudentsJPAManager(); userJPA = new UserJPAManager(); teachersJPA = new TeachersJPAManager(); groupsJPA = new GroupJPAManager(); tutorJPA = new TutorJPAManager(); } /** * Este es el método en el que se cargan los alumnos en la base de datos * además de los grupos. * * @param file * Este parámetro es el fichero que se descarga el programa a * partir del fichero elejido por el usuario para posteriormente * cargarlo en la base de datos * */ public void loadStudents(File file) throws IOException, SQLException, ParseException { bReader = new BufferedReader(new InputStreamReader(new FileInputStream(file.getAbsolutePath()), FORMAT)); dateFormat = new SimpleDateFormat(DATEFORMAT); // Skip first line bReader.skip(bReader.readLine().indexOf("")); lGroups = new ArrayList<String>(); lStudents = new ArrayList<Student>(); String linea = ""; while ((linea = bReader.readLine()) != null) { StringTokenizer str = new StringTokenizer(linea, ",\"\""); id = Integer.parseInt(str.nextToken()); surname = str.nextToken(); name = str.nextToken(); group = str.nextToken(); date = dateFormat.parse(str.nextToken()); born = new java.sql.Date(date.getTime()); country = str.nextToken(); nacionality = str.nextToken(); phone = str.nextToken(); lGroups.add(group); // Value null is a email of parents lStudents.add(new Student(name, surname, null, phone, born, course.currentCourse(), group)); } linkedHashSet = new LinkedHashSet<String>(); linkedHashSet.addAll(lGroups); lGroups.clear(); lGroups.addAll(linkedHashSet); // Add all groups in database for (int i = 0; i < lGroups.size(); i++) { groupsJPA.addGroup(new Group(lGroups.get(i))); } groupsJPA.closeTransaction(); // Add all students in databaseF for (int i = 0; i < lStudents.size(); i++) { studentsJPA.addStudent(lStudents.get(i)); } studentsJPA.closeTransaction(); bReader.close(); // Notification is loaded everything correctly notif(NOTIF); } /** * Este es el método en el que se cargan los docentes en la base de datos * además de los tutores y usuarios. * * @param file * Este parámetro es el fichero que se descarga el programa a * partir del fichero elejido por el usuario para posteriormente * cargarlo en la base de datos * */ public void loadTeachers(File file) throws IOException, SQLException, ParseException, NoSuchAlgorithmException { messageDigest = MessageDigest.getInstance(ALGORITHM); hBinaryAdapter = new HexBinaryAdapter(); bReader = new BufferedReader(new InputStreamReader(new FileInputStream(file.getAbsolutePath()), FORMAT)); while ((line = bReader.readLine()) != null) { StringTokenizer str = new StringTokenizer(line, ","); name = str.nextToken(); surname = str.nextToken(); email = str.nextToken(); user = str.nextToken(); password = str.nextToken(); tutoring = str.nextToken(); teachersJPA.addTeacher(new Teacher(name, surname, email)); passwordHash = hBinaryAdapter.marshal(messageDigest.digest(password.getBytes())).toLowerCase(); if (!tutoring.equals("null")) { tutorJPA.addTutor(new Tutor(teachersJPA.getIdDocent(email), tutoring)); userJPA.addUser(new User(teachersJPA.getIdDocent(email), passwordHash, user, ROLTUTOR)); } else userJPA.addUser(new User(teachersJPA.getIdDocent(email), passwordHash, user, ROLPROFESSOR)); } userJPA.closeTransaction(); bReader.close(); notif("Dades carregades correctament"); } /** * Este es el método en el que se declaran las notificaciones que el usuario * verá en pantalla * * @param mensaje * Este parámetro es la String que se mostrará por pantalla al * usuario * * */ public static void notif(String mensaje) { Notification notif = new Notification(mensaje, null, Notification.Type.HUMANIZED_MESSAGE, true); // Contains // Customize it notif.show(Page.getCurrent()); notif.setDelayMsec(500); notif.setPosition(Position.TOP_CENTER); } }
/* * Copyright 2002-2022 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.web.socket.server.standard; import java.lang.reflect.Method; import java.util.Map; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import jakarta.websocket.server.ServerContainer; import jakarta.websocket.server.ServerEndpointConfig; /** * WebSphere support for upgrading an {@link HttpServletRequest} during a * WebSocket handshake. To modify properties of the underlying * {@link jakarta.websocket.server.ServerContainer} you can use * {@link ServletServerContainerFactoryBean} in XML configuration or, when using * Java configuration, access the container instance through the * "javax.websocket.server.ServerContainer" ServletContext attribute. * * @author Rossen Stoyanchev * @author Juergen Hoeller * @since 4.2.1 */ public class WebSphereRequestUpgradeStrategy extends StandardWebSocketUpgradeStrategy { private static final Method upgradeMethod; static { ClassLoader loader = WebSphereRequestUpgradeStrategy.class.getClassLoader(); try { Class<?> type = loader.loadClass("com.ibm.websphere.wsoc.WsWsocServerContainer"); upgradeMethod = type.getMethod("doUpgrade", HttpServletRequest.class, HttpServletResponse.class, ServerEndpointConfig.class, Map.class); } catch (Exception ex) { throw new IllegalStateException("No compatible WebSphere version found", ex); } } @Override protected void upgradeHttpToWebSocket(HttpServletRequest request, HttpServletResponse response, ServerEndpointConfig endpointConfig, Map<String, String> pathParams) throws Exception { ServerContainer container = getContainer(request); upgradeMethod.invoke(container, request, response, endpointConfig, pathParams); } }
package com.example.mathpractice; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; public class LaunchActivity extends AppCompatActivity { private Button additionBtn; private Button subtractionBtn; private Button multiplicationBtn; private Button divisionBtn; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_launch); additionBtn = (Button) findViewById(R.id.addition); subtractionBtn = (Button) findViewById(R.id.subtraction); multiplicationBtn = (Button) findViewById(R.id.multiplication); divisionBtn = (Button) findViewById(R.id.division); additionBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startActivity(new Intent(LaunchActivity.this, AdditionActivity.class)); } }); subtractionBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startActivity(new Intent(LaunchActivity.this, SubtractionActivity.class)); } }); multiplicationBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startActivity(new Intent(LaunchActivity.this, MultiplicationActivity.class)); } }); divisionBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startActivity(new Intent(LaunchActivity.this, DivisionActivity.class)); } }); } }
package org.obiz.sdtd.tool.rgwmap; import javax.swing.*; import java.awt.*; import java.awt.image.BufferedImage; import java.io.IOException; import java.io.PrintWriter; import java.net.URISyntaxException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Map; public class IconsListBuilder { public static void main(String[] args) { StringBuilder objectsHtml = new StringBuilder(); try { Map<String, Path> stringPathMap = MapBuilder.loadIcons(); int tableSize = Math.round(Math.round(Math.sqrt(stringPathMap.size())))+1; int cellSize = 40; BufferedImage icons = new BufferedImage(cellSize *tableSize, cellSize *tableSize, BufferedImage.TYPE_INT_ARGB); Graphics2D g = icons.createGraphics(); int count = 0; for (String name : stringPathMap.keySet()) { Files.readAllLines(stringPathMap.get(name)).forEach(s -> objectsHtml.append(s).append("\n")); int x = count % tableSize; int y = count / tableSize; MapBuilder.drawIcon(g, name, cellSize/2, x* cellSize, y* cellSize, true, stringPathMap,2, false); count++; } Path destinationPath = Paths.get("allIcons.html"); PrintWriter printWriter = new PrintWriter(Files.newBufferedWriter(destinationPath)); Files.lines(MapBuilder.getPathForResource("/allIconsTemplate.html")) .map(s -> { if (s.equals("$objects$")) return objectsHtml.toString(); return s; }).forEach(printWriter::println); printWriter.close(); // Desktop.getDesktop().browse(destinationPath.toUri()); Thread.sleep(500); JFrame frame = new PreviewFrame(icons, stringPathMap, "TEST ICONS"); frame.setAutoRequestFocus(true); frame.setVisible(true); } catch (IOException | URISyntaxException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } } }
package com.arthur.leetcode; /** * @title: No1734 * @Author ArthurJi * @Date: 2021/5/11 11:47 * @Version 1.0 */ public class No1734 { public static void main(String[] args) { } public int[] decode(int[] encoded) { int n = encoded.length; int[] ans = new int[n + 1]; int a = 0; for (int i = 0; i < n; i+=2) { a ^= encoded[i]; } int b = 0; for (int i = 1; i <= n + 1; i++) { b ^= i; } ans[n] = a ^ b; for (int i = n - 1; i >= 0; i--) { ans[i] = ans[i + 1] ^ encoded[i]; } return ans; } } /*1734. 解码异或后的排列 给你一个整数数组 perm ,它是前 n 个正整数的排列,且 n 是个 奇数 。 它被加密成另一个长度为 n - 1 的整数数组 encoded ,满足 encoded[i] = perm[i] XOR perm[i + 1] 。比方说,如果 perm = [1,3,2] ,那么 encoded = [2,1] 。 给你 encoded 数组,请你返回原始数组 perm 。题目保证答案存在且唯一。 示例 1: 输入:encoded = [3,1] 输出:[1,2,3] 解释:如果 perm = [1,2,3] ,那么 encoded = [1 XOR 2,2 XOR 3] = [3,1] 示例 2: 输入:encoded = [6,5,4,6] 输出:[2,4,1,5,3] 提示: 3 <= n < 105 n 是奇数。 encoded.length == n - 1*/ /* 基本分析 我们知道异或运算有如下性质: 相同数值异或,结果为 00 任意数值与 00 进行异或,结果为数值本身 异或本身满足交换律 本题与 1720. 解码异或后的数组 的唯一区别是没有给出首位元素。 因此,求得答案数组的「首位元素」或者「结尾元素」可作为本题切入点。 数学 & 模拟 我们定义答案数组为 ans[],ans[] 数组的长度为 n,且 n 为奇数。 即有 [ans[0], ans[1], ans[2], ... , ans[n - 1]][ans[0],ans[1],ans[2],...,ans[n−1]]。 给定的数组 encoded[] 其实是 [ans[0] ⊕ ans[1], ans[1] ⊕ ans[2], ... , ans[n - 3] ⊕ ans[n - 2], ans[n - 2] ⊕ ans[n - 1]][ans[0]⊕ans[1],ans[1]⊕ans[2],...,ans[n−3]⊕ans[n−2],ans[n−2]⊕ans[n−1]],长度为 n - 1。 由于每相邻一位会出现相同的数组成员 ans[x],考虑“每隔一位”进行异或: 从 encoded[] 的第 00 位开始,每隔一位进行异或:可得 ans[0] ⊕ ans[1] ⊕ ... ⊕ ans[n - 2]ans[0]⊕ans[1]⊕...⊕ans[n−2],即除了 ans[] 数组中的 ans[n - 1]ans[n−1] 以外的所有异或结果。 利用 ans[] 数组是 n 个正整数的排列,我们可得 ans[0] ⊕ ans[1] ⊕ ... ⊕ ans[n - 2] ⊕ ans[n - 1]ans[0]⊕ans[1]⊕...⊕ans[n−2]⊕ans[n−1],即 ans[] 数组中所有元素的异或结果。 将两式进行「异或」,可得 ans[n - 1]ans[n−1]。 有了结尾元素后,问题变为与 1720. 解码异或后的数组 类似的模拟题。 代码: Java class Solution { public int[] decode(int[] encoded) { int n = encoded.length + 1; int[] ans = new int[n]; // 求得除了 ans[n - 1] 的所有异或结果 int a = 0; for (int i = 0; i < n - 1; i += 2) a ^= encoded[i]; // 求得 ans 的所有异或结果 int b = 0; for (int i = 1; i <= n; i++) b ^= i; // 求得 ans[n - 1] 后,从后往前做 ans[n - 1] = a ^ b; for (int i = n - 2; i >= 0; i--) { ans[i] = encoded[i] ^ ans[i + 1]; } return ans; } } 时间复杂度:O(n)O(n) 空间复杂度:构建同等数量级的答案数组。复杂度为 O(n)O(n) 作者:AC_OIer 链接:https://leetcode-cn.com/problems/decode-xored-permutation/solution/gong-shui-san-xie-note-bie-pian-li-yong-zeh6o/ 来源:力扣(LeetCode) 著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。*/
package com.sinoway.sinowayCrawer.mapper; import java.util.List; import java.util.Map; import org.springframework.stereotype.Component; import com.sinoway.sinowayCrawer.entitys.UserInfo; @Component("userInfoMapper") public interface UserInfoMapper { List<UserInfo> selectUserByCondition(Map<String, Object> pramMap); }
/* * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.beans; import java.beans.PropertyChangeEvent; import java.lang.reflect.Array; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Modifier; import java.lang.reflect.UndeclaredThrowableException; import java.security.PrivilegedActionException; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Optional; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.core.CollectionFactory; import org.springframework.core.ResolvableType; import org.springframework.core.convert.ConversionException; import org.springframework.core.convert.ConverterNotFoundException; import org.springframework.core.convert.TypeDescriptor; import org.springframework.lang.Nullable; import org.springframework.util.Assert; import org.springframework.util.ObjectUtils; import org.springframework.util.StringUtils; /** * A basic {@link ConfigurablePropertyAccessor} that provides the necessary * infrastructure for all typical use cases. * * <p>This accessor will convert collection and array values to the corresponding * target collections or arrays, if necessary. Custom property editors that deal * with collections or arrays can either be written via PropertyEditor's * {@code setValue}, or against a comma-delimited String via {@code setAsText}, * as String arrays are converted in such a format if the array itself is not * assignable. * * @author Juergen Hoeller * @author Stephane Nicoll * @author Rod Johnson * @author Rob Harrop * @author Sam Brannen * @since 4.2 * @see #registerCustomEditor * @see #setPropertyValues * @see #setPropertyValue * @see #getPropertyValue * @see #getPropertyType * @see BeanWrapper * @see PropertyEditorRegistrySupport */ public abstract class AbstractNestablePropertyAccessor extends AbstractPropertyAccessor { /** * We'll create a lot of these objects, so we don't want a new logger every time. */ private static final Log logger = LogFactory.getLog(AbstractNestablePropertyAccessor.class); private int autoGrowCollectionLimit = Integer.MAX_VALUE; @Nullable Object wrappedObject; private String nestedPath = ""; @Nullable Object rootObject; /** Map with cached nested Accessors: nested path -> Accessor instance. */ @Nullable private Map<String, AbstractNestablePropertyAccessor> nestedPropertyAccessors; /** * Create a new empty accessor. Wrapped instance needs to be set afterwards. * Registers default editors. * @see #setWrappedInstance */ protected AbstractNestablePropertyAccessor() { this(true); } /** * Create a new empty accessor. Wrapped instance needs to be set afterwards. * @param registerDefaultEditors whether to register default editors * (can be suppressed if the accessor won't need any type conversion) * @see #setWrappedInstance */ protected AbstractNestablePropertyAccessor(boolean registerDefaultEditors) { if (registerDefaultEditors) { registerDefaultEditors(); } this.typeConverterDelegate = new TypeConverterDelegate(this); } /** * Create a new accessor for the given object. * @param object the object wrapped by this accessor */ protected AbstractNestablePropertyAccessor(Object object) { registerDefaultEditors(); setWrappedInstance(object); } /** * Create a new accessor, wrapping a new instance of the specified class. * @param clazz class to instantiate and wrap */ protected AbstractNestablePropertyAccessor(Class<?> clazz) { registerDefaultEditors(); setWrappedInstance(BeanUtils.instantiateClass(clazz)); } /** * Create a new accessor for the given object, * registering a nested path that the object is in. * @param object the object wrapped by this accessor * @param nestedPath the nested path of the object * @param rootObject the root object at the top of the path */ protected AbstractNestablePropertyAccessor(Object object, String nestedPath, Object rootObject) { registerDefaultEditors(); setWrappedInstance(object, nestedPath, rootObject); } /** * Create a new accessor for the given object, * registering a nested path that the object is in. * @param object the object wrapped by this accessor * @param nestedPath the nested path of the object * @param parent the containing accessor (must not be {@code null}) */ protected AbstractNestablePropertyAccessor(Object object, String nestedPath, AbstractNestablePropertyAccessor parent) { setWrappedInstance(object, nestedPath, parent.getWrappedInstance()); setExtractOldValueForEditor(parent.isExtractOldValueForEditor()); setAutoGrowNestedPaths(parent.isAutoGrowNestedPaths()); setAutoGrowCollectionLimit(parent.getAutoGrowCollectionLimit()); setConversionService(parent.getConversionService()); } /** * Specify a limit for array and collection auto-growing. * <p>Default is unlimited on a plain accessor. */ public void setAutoGrowCollectionLimit(int autoGrowCollectionLimit) { this.autoGrowCollectionLimit = autoGrowCollectionLimit; } /** * Return the limit for array and collection auto-growing. */ public int getAutoGrowCollectionLimit() { return this.autoGrowCollectionLimit; } /** * Switch the target object, replacing the cached introspection results only * if the class of the new object is different to that of the replaced object. * @param object the new target object */ public void setWrappedInstance(Object object) { setWrappedInstance(object, "", null); } /** * Switch the target object, replacing the cached introspection results only * if the class of the new object is different to that of the replaced object. * @param object the new target object * @param nestedPath the nested path of the object * @param rootObject the root object at the top of the path */ public void setWrappedInstance(Object object, @Nullable String nestedPath, @Nullable Object rootObject) { this.wrappedObject = ObjectUtils.unwrapOptional(object); Assert.notNull(this.wrappedObject, "Target object must not be null"); this.nestedPath = (nestedPath != null ? nestedPath : ""); this.rootObject = (!this.nestedPath.isEmpty() ? rootObject : this.wrappedObject); this.nestedPropertyAccessors = null; this.typeConverterDelegate = new TypeConverterDelegate(this, this.wrappedObject); } public final Object getWrappedInstance() { Assert.state(this.wrappedObject != null, "No wrapped object"); return this.wrappedObject; } public final Class<?> getWrappedClass() { return getWrappedInstance().getClass(); } /** * Return the nested path of the object wrapped by this accessor. */ public final String getNestedPath() { return this.nestedPath; } /** * Return the root object at the top of the path of this accessor. * @see #getNestedPath */ public final Object getRootInstance() { Assert.state(this.rootObject != null, "No root object"); return this.rootObject; } /** * Return the class of the root object at the top of the path of this accessor. * @see #getNestedPath */ public final Class<?> getRootClass() { return getRootInstance().getClass(); } @Override public void setPropertyValue(String propertyName, @Nullable Object value) throws BeansException { AbstractNestablePropertyAccessor nestedPa; try { nestedPa = getPropertyAccessorForPropertyPath(propertyName); } catch (NotReadablePropertyException ex) { throw new NotWritablePropertyException(getRootClass(), this.nestedPath + propertyName, "Nested property in path '" + propertyName + "' does not exist", ex); } PropertyTokenHolder tokens = getPropertyNameTokens(getFinalPath(nestedPa, propertyName)); nestedPa.setPropertyValue(tokens, new PropertyValue(propertyName, value)); } @Override public void setPropertyValue(PropertyValue pv) throws BeansException { PropertyTokenHolder tokens = (PropertyTokenHolder) pv.resolvedTokens; if (tokens == null) { String propertyName = pv.getName(); AbstractNestablePropertyAccessor nestedPa; try { nestedPa = getPropertyAccessorForPropertyPath(propertyName); } catch (NotReadablePropertyException ex) { throw new NotWritablePropertyException(getRootClass(), this.nestedPath + propertyName, "Nested property in path '" + propertyName + "' does not exist", ex); } tokens = getPropertyNameTokens(getFinalPath(nestedPa, propertyName)); if (nestedPa == this) { pv.getOriginalPropertyValue().resolvedTokens = tokens; } nestedPa.setPropertyValue(tokens, pv); } else { setPropertyValue(tokens, pv); } } protected void setPropertyValue(PropertyTokenHolder tokens, PropertyValue pv) throws BeansException { if (tokens.keys != null) { processKeyedProperty(tokens, pv); } else { processLocalProperty(tokens, pv); } } @SuppressWarnings({"rawtypes", "unchecked"}) private void processKeyedProperty(PropertyTokenHolder tokens, PropertyValue pv) { Object propValue = getPropertyHoldingValue(tokens); PropertyHandler ph = getLocalPropertyHandler(tokens.actualName); if (ph == null) { throw new InvalidPropertyException( getRootClass(), this.nestedPath + tokens.actualName, "No property handler found"); } Assert.state(tokens.keys != null, "No token keys"); String lastKey = tokens.keys[tokens.keys.length - 1]; if (propValue.getClass().isArray()) { Class<?> requiredType = propValue.getClass().componentType(); int arrayIndex = Integer.parseInt(lastKey); Object oldValue = null; try { if (isExtractOldValueForEditor() && arrayIndex < Array.getLength(propValue)) { oldValue = Array.get(propValue, arrayIndex); } Object convertedValue = convertIfNecessary(tokens.canonicalName, oldValue, pv.getValue(), requiredType, ph.nested(tokens.keys.length)); int length = Array.getLength(propValue); if (arrayIndex >= length && arrayIndex < this.autoGrowCollectionLimit) { Class<?> componentType = propValue.getClass().componentType(); Object newArray = Array.newInstance(componentType, arrayIndex + 1); System.arraycopy(propValue, 0, newArray, 0, length); int lastKeyIndex = tokens.canonicalName.lastIndexOf('['); String propName = tokens.canonicalName.substring(0, lastKeyIndex); setPropertyValue(propName, newArray); propValue = getPropertyValue(propName); } Array.set(propValue, arrayIndex, convertedValue); } catch (IndexOutOfBoundsException ex) { throw new InvalidPropertyException(getRootClass(), this.nestedPath + tokens.canonicalName, "Invalid array index in property path '" + tokens.canonicalName + "'", ex); } } else if (propValue instanceof List list) { TypeDescriptor requiredType = ph.getCollectionType(tokens.keys.length); int index = Integer.parseInt(lastKey); Object oldValue = null; if (isExtractOldValueForEditor() && index < list.size()) { oldValue = list.get(index); } Object convertedValue = convertIfNecessary(tokens.canonicalName, oldValue, pv.getValue(), requiredType.getResolvableType().resolve(), requiredType); int size = list.size(); if (index >= size && index < this.autoGrowCollectionLimit) { for (int i = size; i < index; i++) { try { list.add(null); } catch (NullPointerException ex) { throw new InvalidPropertyException(getRootClass(), this.nestedPath + tokens.canonicalName, "Cannot set element with index " + index + " in List of size " + size + ", accessed using property path '" + tokens.canonicalName + "': List does not support filling up gaps with null elements"); } } list.add(convertedValue); } else { try { list.set(index, convertedValue); } catch (IndexOutOfBoundsException ex) { throw new InvalidPropertyException(getRootClass(), this.nestedPath + tokens.canonicalName, "Invalid list index in property path '" + tokens.canonicalName + "'", ex); } } } else if (propValue instanceof Map map) { TypeDescriptor mapKeyType = ph.getMapKeyType(tokens.keys.length); TypeDescriptor mapValueType = ph.getMapValueType(tokens.keys.length); // IMPORTANT: Do not pass full property name in here - property editors // must not kick in for map keys but rather only for map values. Object convertedMapKey = convertIfNecessary(null, null, lastKey, mapKeyType.getResolvableType().resolve(), mapKeyType); Object oldValue = null; if (isExtractOldValueForEditor()) { oldValue = map.get(convertedMapKey); } // Pass full property name and old value in here, since we want full // conversion ability for map values. Object convertedMapValue = convertIfNecessary(tokens.canonicalName, oldValue, pv.getValue(), mapValueType.getResolvableType().resolve(), mapValueType); map.put(convertedMapKey, convertedMapValue); } else { throw new InvalidPropertyException(getRootClass(), this.nestedPath + tokens.canonicalName, "Property referenced in indexed property path '" + tokens.canonicalName + "' is neither an array nor a List nor a Map; returned value was [" + propValue + "]"); } } private Object getPropertyHoldingValue(PropertyTokenHolder tokens) { // Apply indexes and map keys: fetch value for all keys but the last one. Assert.state(tokens.keys != null, "No token keys"); PropertyTokenHolder getterTokens = new PropertyTokenHolder(tokens.actualName); getterTokens.canonicalName = tokens.canonicalName; getterTokens.keys = new String[tokens.keys.length - 1]; System.arraycopy(tokens.keys, 0, getterTokens.keys, 0, tokens.keys.length - 1); Object propValue; try { propValue = getPropertyValue(getterTokens); } catch (NotReadablePropertyException ex) { throw new NotWritablePropertyException(getRootClass(), this.nestedPath + tokens.canonicalName, "Cannot access indexed value in property referenced " + "in indexed property path '" + tokens.canonicalName + "'", ex); } if (propValue == null) { // null map value case if (isAutoGrowNestedPaths()) { int lastKeyIndex = tokens.canonicalName.lastIndexOf('['); getterTokens.canonicalName = tokens.canonicalName.substring(0, lastKeyIndex); propValue = setDefaultValue(getterTokens); } else { throw new NullValueInNestedPathException(getRootClass(), this.nestedPath + tokens.canonicalName, "Cannot access indexed value in property referenced " + "in indexed property path '" + tokens.canonicalName + "': returned null"); } } return propValue; } private void processLocalProperty(PropertyTokenHolder tokens, PropertyValue pv) { PropertyHandler ph = getLocalPropertyHandler(tokens.actualName); if (ph == null || !ph.isWritable()) { if (pv.isOptional()) { if (logger.isDebugEnabled()) { logger.debug("Ignoring optional value for property '" + tokens.actualName + "' - property not found on bean class [" + getRootClass().getName() + "]"); } return; } if (this.suppressNotWritablePropertyException) { // Optimization for common ignoreUnknown=true scenario since the // exception would be caught and swallowed higher up anyway... return; } throw createNotWritablePropertyException(tokens.canonicalName); } Object oldValue = null; try { Object originalValue = pv.getValue(); Object valueToApply = originalValue; if (!Boolean.FALSE.equals(pv.conversionNecessary)) { if (pv.isConverted()) { valueToApply = pv.getConvertedValue(); } else { if (isExtractOldValueForEditor() && ph.isReadable()) { try { oldValue = ph.getValue(); } catch (Exception ex) { if (ex instanceof PrivilegedActionException pae) { ex = pae.getException(); } if (logger.isDebugEnabled()) { logger.debug("Could not read previous value of property '" + this.nestedPath + tokens.canonicalName + "'", ex); } } } valueToApply = convertForProperty( tokens.canonicalName, oldValue, originalValue, ph.toTypeDescriptor()); } pv.getOriginalPropertyValue().conversionNecessary = (valueToApply != originalValue); } ph.setValue(valueToApply); } catch (TypeMismatchException ex) { throw ex; } catch (InvocationTargetException ex) { PropertyChangeEvent propertyChangeEvent = new PropertyChangeEvent( getRootInstance(), this.nestedPath + tokens.canonicalName, oldValue, pv.getValue()); if (ex.getTargetException() instanceof ClassCastException) { throw new TypeMismatchException(propertyChangeEvent, ph.getPropertyType(), ex.getTargetException()); } else { Throwable cause = ex.getTargetException(); if (cause instanceof UndeclaredThrowableException) { // May happen e.g. with Groovy-generated methods cause = cause.getCause(); } throw new MethodInvocationException(propertyChangeEvent, cause); } } catch (Exception ex) { PropertyChangeEvent pce = new PropertyChangeEvent( getRootInstance(), this.nestedPath + tokens.canonicalName, oldValue, pv.getValue()); throw new MethodInvocationException(pce, ex); } } @Override @Nullable public Class<?> getPropertyType(String propertyName) throws BeansException { try { PropertyHandler ph = getPropertyHandler(propertyName); if (ph != null) { return ph.getPropertyType(); } else { // Maybe an indexed/mapped property... Object value = getPropertyValue(propertyName); if (value != null) { return value.getClass(); } // Check to see if there is a custom editor, // which might give an indication on the desired target type. Class<?> editorType = guessPropertyTypeFromEditors(propertyName); if (editorType != null) { return editorType; } } } catch (InvalidPropertyException ex) { // Consider as not determinable. } return null; } @Override @Nullable public TypeDescriptor getPropertyTypeDescriptor(String propertyName) throws BeansException { try { AbstractNestablePropertyAccessor nestedPa = getPropertyAccessorForPropertyPath(propertyName); String finalPath = getFinalPath(nestedPa, propertyName); PropertyTokenHolder tokens = getPropertyNameTokens(finalPath); PropertyHandler ph = nestedPa.getLocalPropertyHandler(tokens.actualName); if (ph != null) { if (tokens.keys != null) { if (ph.isReadable() || ph.isWritable()) { return ph.nested(tokens.keys.length); } } else { if (ph.isReadable() || ph.isWritable()) { return ph.toTypeDescriptor(); } } } } catch (InvalidPropertyException ex) { // Consider as not determinable. } return null; } @Override public boolean isReadableProperty(String propertyName) { try { PropertyHandler ph = getPropertyHandler(propertyName); if (ph != null) { return ph.isReadable(); } else { // Maybe an indexed/mapped property... getPropertyValue(propertyName); return true; } } catch (InvalidPropertyException ex) { // Cannot be evaluated, so can't be readable. } return false; } @Override public boolean isWritableProperty(String propertyName) { try { PropertyHandler ph = getPropertyHandler(propertyName); if (ph != null) { return ph.isWritable(); } else { // Maybe an indexed/mapped property... getPropertyValue(propertyName); return true; } } catch (InvalidPropertyException ex) { // Cannot be evaluated, so can't be writable. } return false; } @Nullable private Object convertIfNecessary(@Nullable String propertyName, @Nullable Object oldValue, @Nullable Object newValue, @Nullable Class<?> requiredType, @Nullable TypeDescriptor td) throws TypeMismatchException { Assert.state(this.typeConverterDelegate != null, "No TypeConverterDelegate"); try { return this.typeConverterDelegate.convertIfNecessary(propertyName, oldValue, newValue, requiredType, td); } catch (ConverterNotFoundException | IllegalStateException ex) { PropertyChangeEvent pce = new PropertyChangeEvent(getRootInstance(), this.nestedPath + propertyName, oldValue, newValue); throw new ConversionNotSupportedException(pce, requiredType, ex); } catch (ConversionException | IllegalArgumentException ex) { PropertyChangeEvent pce = new PropertyChangeEvent(getRootInstance(), this.nestedPath + propertyName, oldValue, newValue); throw new TypeMismatchException(pce, requiredType, ex); } } @Nullable protected Object convertForProperty( String propertyName, @Nullable Object oldValue, @Nullable Object newValue, TypeDescriptor td) throws TypeMismatchException { return convertIfNecessary(propertyName, oldValue, newValue, td.getType(), td); } @Override @Nullable public Object getPropertyValue(String propertyName) throws BeansException { AbstractNestablePropertyAccessor nestedPa = getPropertyAccessorForPropertyPath(propertyName); PropertyTokenHolder tokens = getPropertyNameTokens(getFinalPath(nestedPa, propertyName)); return nestedPa.getPropertyValue(tokens); } @SuppressWarnings({"rawtypes", "unchecked"}) @Nullable protected Object getPropertyValue(PropertyTokenHolder tokens) throws BeansException { String propertyName = tokens.canonicalName; String actualName = tokens.actualName; PropertyHandler ph = getLocalPropertyHandler(actualName); if (ph == null || !ph.isReadable()) { throw new NotReadablePropertyException(getRootClass(), this.nestedPath + propertyName); } try { Object value = ph.getValue(); if (tokens.keys != null) { if (value == null) { if (isAutoGrowNestedPaths()) { value = setDefaultValue(new PropertyTokenHolder(tokens.actualName)); } else { throw new NullValueInNestedPathException(getRootClass(), this.nestedPath + propertyName, "Cannot access indexed value of property referenced in indexed " + "property path '" + propertyName + "': returned null"); } } StringBuilder indexedPropertyName = new StringBuilder(tokens.actualName); // apply indexes and map keys for (int i = 0; i < tokens.keys.length; i++) { String key = tokens.keys[i]; if (value == null) { throw new NullValueInNestedPathException(getRootClass(), this.nestedPath + propertyName, "Cannot access indexed value of property referenced in indexed " + "property path '" + propertyName + "': returned null"); } else if (value.getClass().isArray()) { int index = Integer.parseInt(key); value = growArrayIfNecessary(value, index, indexedPropertyName.toString()); value = Array.get(value, index); } else if (value instanceof List list) { int index = Integer.parseInt(key); growCollectionIfNecessary(list, index, indexedPropertyName.toString(), ph, i + 1); value = list.get(index); } else if (value instanceof Iterable iterable) { // Apply index to Iterator in case of a Set/Collection/Iterable. int index = Integer.parseInt(key); if (value instanceof Collection<?> coll) { if (index < 0 || index >= coll.size()) { throw new InvalidPropertyException(getRootClass(), this.nestedPath + propertyName, "Cannot get element with index " + index + " from Collection of size " + coll.size() + ", accessed using property path '" + propertyName + "'"); } } Iterator<Object> it = iterable.iterator(); boolean found = false; int currIndex = 0; for (; it.hasNext(); currIndex++) { Object elem = it.next(); if (currIndex == index) { value = elem; found = true; break; } } if (!found) { throw new InvalidPropertyException(getRootClass(), this.nestedPath + propertyName, "Cannot get element with index " + index + " from Iterable of size " + currIndex + ", accessed using property path '" + propertyName + "'"); } } else if (value instanceof Map map) { Class<?> mapKeyType = ph.getResolvableType().getNested(i + 1).asMap().resolveGeneric(0); // IMPORTANT: Do not pass full property name in here - property editors // must not kick in for map keys but rather only for map values. TypeDescriptor typeDescriptor = TypeDescriptor.valueOf(mapKeyType); Object convertedMapKey = convertIfNecessary(null, null, key, mapKeyType, typeDescriptor); value = map.get(convertedMapKey); } else { throw new InvalidPropertyException(getRootClass(), this.nestedPath + propertyName, "Property referenced in indexed property path '" + propertyName + "' is neither an array nor a List/Set/Collection/Iterable nor a Map; " + "returned value was [" + value + "]"); } indexedPropertyName.append(PROPERTY_KEY_PREFIX).append(key).append(PROPERTY_KEY_SUFFIX); } } return value; } catch (InvalidPropertyException ex) { throw ex; } catch (IndexOutOfBoundsException ex) { throw new InvalidPropertyException(getRootClass(), this.nestedPath + propertyName, "Index of out of bounds in property path '" + propertyName + "'", ex); } catch (NumberFormatException | TypeMismatchException ex) { throw new InvalidPropertyException(getRootClass(), this.nestedPath + propertyName, "Invalid index in property path '" + propertyName + "'", ex); } catch (InvocationTargetException ex) { throw new InvalidPropertyException(getRootClass(), this.nestedPath + propertyName, "Getter for property '" + actualName + "' threw exception", ex); } catch (Exception ex) { throw new InvalidPropertyException(getRootClass(), this.nestedPath + propertyName, "Illegal attempt to get property '" + actualName + "' threw exception", ex); } } /** * Return the {@link PropertyHandler} for the specified {@code propertyName}, navigating * if necessary. Return {@code null} if not found rather than throwing an exception. * @param propertyName the property to obtain the descriptor for * @return the property descriptor for the specified property, * or {@code null} if not found * @throws BeansException in case of introspection failure */ @Nullable protected PropertyHandler getPropertyHandler(String propertyName) throws BeansException { Assert.notNull(propertyName, "Property name must not be null"); AbstractNestablePropertyAccessor nestedPa = getPropertyAccessorForPropertyPath(propertyName); return nestedPa.getLocalPropertyHandler(getFinalPath(nestedPa, propertyName)); } /** * Return a {@link PropertyHandler} for the specified local {@code propertyName}. * Only used to reach a property available in the current context. * @param propertyName the name of a local property * @return the handler for that property, or {@code null} if it has not been found */ @Nullable protected abstract PropertyHandler getLocalPropertyHandler(String propertyName); /** * Create a new nested property accessor instance. * Can be overridden in subclasses to create a PropertyAccessor subclass. * @param object the object wrapped by this PropertyAccessor * @param nestedPath the nested path of the object * @return the nested PropertyAccessor instance */ protected abstract AbstractNestablePropertyAccessor newNestedPropertyAccessor(Object object, String nestedPath); /** * Create a {@link NotWritablePropertyException} for the specified property. */ protected abstract NotWritablePropertyException createNotWritablePropertyException(String propertyName); private Object growArrayIfNecessary(Object array, int index, String name) { if (!isAutoGrowNestedPaths()) { return array; } int length = Array.getLength(array); if (index >= length && index < this.autoGrowCollectionLimit) { Class<?> componentType = array.getClass().componentType(); Object newArray = Array.newInstance(componentType, index + 1); System.arraycopy(array, 0, newArray, 0, length); for (int i = length; i < Array.getLength(newArray); i++) { Array.set(newArray, i, newValue(componentType, null, name)); } setPropertyValue(name, newArray); Object defaultValue = getPropertyValue(name); Assert.state(defaultValue != null, "Default value must not be null"); return defaultValue; } else { return array; } } private void growCollectionIfNecessary(Collection<Object> collection, int index, String name, PropertyHandler ph, int nestingLevel) { if (!isAutoGrowNestedPaths()) { return; } int size = collection.size(); if (index >= size && index < this.autoGrowCollectionLimit) { Class<?> elementType = ph.getResolvableType().getNested(nestingLevel).asCollection().resolveGeneric(); if (elementType != null) { for (int i = collection.size(); i < index + 1; i++) { collection.add(newValue(elementType, null, name)); } } } } /** * Get the last component of the path. Also works if not nested. * @param pa property accessor to work on * @param nestedPath property path we know is nested * @return last component of the path (the property on the target bean) */ protected String getFinalPath(AbstractNestablePropertyAccessor pa, String nestedPath) { if (pa == this) { return nestedPath; } return nestedPath.substring(PropertyAccessorUtils.getLastNestedPropertySeparatorIndex(nestedPath) + 1); } /** * Recursively navigate to return a property accessor for the nested property path. * @param propertyPath property path, which may be nested * @return a property accessor for the target bean */ protected AbstractNestablePropertyAccessor getPropertyAccessorForPropertyPath(String propertyPath) { int pos = PropertyAccessorUtils.getFirstNestedPropertySeparatorIndex(propertyPath); // Handle nested properties recursively. if (pos > -1) { String nestedProperty = propertyPath.substring(0, pos); String nestedPath = propertyPath.substring(pos + 1); AbstractNestablePropertyAccessor nestedPa = getNestedPropertyAccessor(nestedProperty); return nestedPa.getPropertyAccessorForPropertyPath(nestedPath); } else { return this; } } /** * Retrieve a Property accessor for the given nested property. * Create a new one if not found in the cache. * <p>Note: Caching nested PropertyAccessors is necessary now, * to keep registered custom editors for nested properties. * @param nestedProperty property to create the PropertyAccessor for * @return the PropertyAccessor instance, either cached or newly created */ private AbstractNestablePropertyAccessor getNestedPropertyAccessor(String nestedProperty) { if (this.nestedPropertyAccessors == null) { this.nestedPropertyAccessors = new HashMap<>(); } // Get value of bean property. PropertyTokenHolder tokens = getPropertyNameTokens(nestedProperty); String canonicalName = tokens.canonicalName; Object value = getPropertyValue(tokens); if (value == null || (value instanceof Optional<?> optional && optional.isEmpty())) { if (isAutoGrowNestedPaths()) { value = setDefaultValue(tokens); } else { throw new NullValueInNestedPathException(getRootClass(), this.nestedPath + canonicalName); } } // Lookup cached sub-PropertyAccessor, create new one if not found. AbstractNestablePropertyAccessor nestedPa = this.nestedPropertyAccessors.get(canonicalName); if (nestedPa == null || nestedPa.getWrappedInstance() != ObjectUtils.unwrapOptional(value)) { if (logger.isTraceEnabled()) { logger.trace("Creating new nested " + getClass().getSimpleName() + " for property '" + canonicalName + "'"); } nestedPa = newNestedPropertyAccessor(value, this.nestedPath + canonicalName + NESTED_PROPERTY_SEPARATOR); // Inherit all type-specific PropertyEditors. copyDefaultEditorsTo(nestedPa); copyCustomEditorsTo(nestedPa, canonicalName); this.nestedPropertyAccessors.put(canonicalName, nestedPa); } else { if (logger.isTraceEnabled()) { logger.trace("Using cached nested property accessor for property '" + canonicalName + "'"); } } return nestedPa; } private Object setDefaultValue(PropertyTokenHolder tokens) { PropertyValue pv = createDefaultPropertyValue(tokens); setPropertyValue(tokens, pv); Object defaultValue = getPropertyValue(tokens); Assert.state(defaultValue != null, "Default value must not be null"); return defaultValue; } private PropertyValue createDefaultPropertyValue(PropertyTokenHolder tokens) { TypeDescriptor desc = getPropertyTypeDescriptor(tokens.canonicalName); if (desc == null) { throw new NullValueInNestedPathException(getRootClass(), this.nestedPath + tokens.canonicalName, "Could not determine property type for auto-growing a default value"); } Object defaultValue = newValue(desc.getType(), desc, tokens.canonicalName); return new PropertyValue(tokens.canonicalName, defaultValue); } private Object newValue(Class<?> type, @Nullable TypeDescriptor desc, String name) { try { if (type.isArray()) { Class<?> componentType = type.componentType(); // TODO - only handles 2-dimensional arrays if (componentType.isArray()) { Object array = Array.newInstance(componentType, 1); Array.set(array, 0, Array.newInstance(componentType.componentType(), 0)); return array; } else { return Array.newInstance(componentType, 0); } } else if (Collection.class.isAssignableFrom(type)) { TypeDescriptor elementDesc = (desc != null ? desc.getElementTypeDescriptor() : null); return CollectionFactory.createCollection(type, (elementDesc != null ? elementDesc.getType() : null), 16); } else if (Map.class.isAssignableFrom(type)) { TypeDescriptor keyDesc = (desc != null ? desc.getMapKeyTypeDescriptor() : null); return CollectionFactory.createMap(type, (keyDesc != null ? keyDesc.getType() : null), 16); } else { Constructor<?> ctor = type.getDeclaredConstructor(); if (Modifier.isPrivate(ctor.getModifiers())) { throw new IllegalAccessException("Auto-growing not allowed with private constructor: " + ctor); } return BeanUtils.instantiateClass(ctor); } } catch (Throwable ex) { throw new NullValueInNestedPathException(getRootClass(), this.nestedPath + name, "Could not instantiate property type [" + type.getName() + "] to auto-grow nested property path", ex); } } /** * Parse the given property name into the corresponding property name tokens. * @param propertyName the property name to parse * @return representation of the parsed property tokens */ private PropertyTokenHolder getPropertyNameTokens(String propertyName) { String actualName = null; List<String> keys = new ArrayList<>(2); int searchIndex = 0; while (searchIndex != -1) { int keyStart = propertyName.indexOf(PROPERTY_KEY_PREFIX, searchIndex); searchIndex = -1; if (keyStart != -1) { int keyEnd = getPropertyNameKeyEnd(propertyName, keyStart + PROPERTY_KEY_PREFIX.length()); if (keyEnd != -1) { if (actualName == null) { actualName = propertyName.substring(0, keyStart); } String key = propertyName.substring(keyStart + PROPERTY_KEY_PREFIX.length(), keyEnd); if (key.length() > 1 && (key.startsWith("'") && key.endsWith("'")) || (key.startsWith("\"") && key.endsWith("\""))) { key = key.substring(1, key.length() - 1); } keys.add(key); searchIndex = keyEnd + PROPERTY_KEY_SUFFIX.length(); } } } PropertyTokenHolder tokens = new PropertyTokenHolder(actualName != null ? actualName : propertyName); if (!keys.isEmpty()) { tokens.canonicalName += PROPERTY_KEY_PREFIX + StringUtils.collectionToDelimitedString(keys, PROPERTY_KEY_SUFFIX + PROPERTY_KEY_PREFIX) + PROPERTY_KEY_SUFFIX; tokens.keys = StringUtils.toStringArray(keys); } return tokens; } private int getPropertyNameKeyEnd(String propertyName, int startIndex) { int unclosedPrefixes = 0; int length = propertyName.length(); for (int i = startIndex; i < length; i++) { switch (propertyName.charAt(i)) { case PropertyAccessor.PROPERTY_KEY_PREFIX_CHAR: // The property name contains opening prefix(es)... unclosedPrefixes++; break; case PropertyAccessor.PROPERTY_KEY_SUFFIX_CHAR: if (unclosedPrefixes == 0) { // No unclosed prefix(es) in the property name (left) -> // this is the suffix we are looking for. return i; } else { // This suffix does not close the initial prefix but rather // just one that occurred within the property name. unclosedPrefixes--; } break; } } return -1; } @Override public String toString() { String className = getClass().getName(); if (this.wrappedObject == null) { return className + ": no wrapped object set"; } return className + ": wrapping object [" + ObjectUtils.identityToString(this.wrappedObject) + ']'; } /** * A handler for a specific property. */ protected abstract static class PropertyHandler { private final Class<?> propertyType; private final boolean readable; private final boolean writable; public PropertyHandler(Class<?> propertyType, boolean readable, boolean writable) { this.propertyType = propertyType; this.readable = readable; this.writable = writable; } public Class<?> getPropertyType() { return this.propertyType; } public boolean isReadable() { return this.readable; } public boolean isWritable() { return this.writable; } public abstract TypeDescriptor toTypeDescriptor(); public abstract ResolvableType getResolvableType(); public TypeDescriptor getMapKeyType(int nestingLevel) { return TypeDescriptor.valueOf(getResolvableType().getNested(nestingLevel).asMap().resolveGeneric(0)); } public TypeDescriptor getMapValueType(int nestingLevel) { return TypeDescriptor.valueOf(getResolvableType().getNested(nestingLevel).asMap().resolveGeneric(1)); } public TypeDescriptor getCollectionType(int nestingLevel) { return TypeDescriptor.valueOf(getResolvableType().getNested(nestingLevel).asCollection().resolveGeneric()); } @Nullable public abstract TypeDescriptor nested(int level); @Nullable public abstract Object getValue() throws Exception; public abstract void setValue(@Nullable Object value) throws Exception; } /** * Holder class used to store property tokens. */ protected static class PropertyTokenHolder { public PropertyTokenHolder(String name) { this.actualName = name; this.canonicalName = name; } public String actualName; public String canonicalName; @Nullable public String[] keys; } }
package com.student.registration.entity; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import lombok.*; import javax.persistence.*; import java.io.Serializable; import java.util.HashSet; import java.util.Set; @Entity @Table(name = "STUDENT") @AllArgsConstructor @NoArgsConstructor @EqualsAndHashCode @Getter @Setter @NamedQueries({ @NamedQuery(name = "Student.findStudentByCourseNameOrderByStudentNameAsc", query = "SELECT DISTINCT s FROM Student s JOIN FETCH s.courseRegistrations cr where cr.course.courseName IN (:courseName) order by s.studentName ASC") , @NamedQuery(name = "Student.findStudentByStudentNameAndCourseNameIn", query = "SELECT DISTINCT s FROM Student s JOIN FETCH s.courseRegistrations cr where s.studentName=:studentName AND cr.course.courseName IN (:courseNames) order by s.studentName ASC") , @NamedQuery(name = "Student.findStudentByNotOptingCourseNameOrderByStudentNameAsc", query = "SELECT DISTINCT s FROM Student s LEFT JOIN FETCH s.courseRegistrations cr LEFT JOIN FETCH cr.course crs where s.courseRegistrations IS EMPTY OR :courseName NOT IN(SELECT DISTINCT crs.courseName FROM cr.course crs) order by s.studentName ASC") }) public class Student implements Serializable { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "STUDENT_ID", unique = true, nullable = false) private Long studentId; @Column(name = "STUDENT_NAME", nullable = false) private String studentName; @JsonIgnoreProperties(value = {"student"}) @OneToMany(cascade = CascadeType.ALL, targetEntity = CourseRegistration.class) @JoinColumn(name = "STUDENT_ID", referencedColumnName = "STUDENT_ID") private Set<CourseRegistration> courseRegistrations = new HashSet<>(); }
public class ImplementStackUsingArrays { int size; int arr[]; int top; ImplementStackUsingArrays(int size) { this.size = size; this.arr = new int[size]; this.top = -1; } // push function public void push(int x) { if(!isFull()) { top++; arr[top] = x; System.out.println("pushed element: " + x); } else { System.out.println("stack overflow"); } } // pop function public int pop() { if(!isEmpty()) { int returnedTop = top; top--; System.out.println("popped element: " + arr[returnedTop]); return arr[returnedTop]; } else { System.out.println("stack is empty"); return -1; } } public int peek() { if(!isEmpty()) { return arr[top]; } else { System.out.println("stack is empty"); return -1; } } public boolean isEmpty() { return top == -1; } public boolean isFull() { return (size - 1 == top); } // main method public static void main(String args[]) { ImplementStackUsingArrays StackCustom = new ImplementStackUsingArrays(10); StackCustom.pop(); System.out.println("================="); StackCustom.push(10); StackCustom.push(30); StackCustom.push(50); StackCustom.push(40); System.out.println("================="); StackCustom.pop(); StackCustom.pop(); StackCustom.pop(); System.out.println("================="); } }
import org.cruise.model.Position; import org.cruise.model.User; import org.cruise.repositories.UserRepository; import org.cruise.service.PositionService; import org.cruise.service.PreachService; import org.cruise.service.UserService; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import java.util.List; /** * Created by Cruise on 4/29/15. */ @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations={"classpath:applicationContext.xml"}) public class RepositoryTest { // @Autowired // UserRepository userRepository; // // @Autowired // UserService userService; @Autowired PositionService positionService; @Autowired PreachService preachService; @Test public void testPageRequest(){ Page p = positionService.search("","","北京","","","0"); System.out.println(p.getNumberOfElements()); System.out.println(p.getTotalPages()); System.out.println("test output:" + p.getContent().get(1) ); } // @Test // public void testLogin(){ // User u = new User(); // u.setUsername("admin"); // u.setPassword("admin"); // System.out.println(userService.login(u)); // } }
package com.fmi.decorator; public abstract class AShapeDecorator implements IShape { public final IShape shape; public AShapeDecorator(final IShape shapeArg) { this.shape = shapeArg; } }
package com.alura.dto; import lombok.AllArgsConstructor; import lombok.Data; @Data @AllArgsConstructor public class ErroDeFormularioDto { private String campo; private String erro; }
package pipline; import org.junit.Test; import pipeline.filter.EqualPredicate; import pipeline.filter.PipelineFilter; import pipeline.messages.SimpleMessage; import pipeline.processing.PipelineProcessor; import pipeline.processing.PipelineSum; public class PipelineTests { PipelineProcessor _filter; PipelineProcessor _sum; @Test public void simpleTest() { _filter = new PipelineFilter(new PipelineSum(4, 6, null), new EqualPredicate(2,2)); _filter.accept(new SimpleMessage("Moooe")); } }
package com.example.basicCalculator; import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; public class MainActivity extends AppCompatActivity { Button b1; int op= 1; EditText v1,v2,r; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } public void buttonClickOption(View v){ b1=findViewById(R.id.button1); String temp = b1.getText().toString(); if(temp.equals("Mode\nAddition")) { b1.setText(R.string.str1); op=-1; } else { b1.setText(R.string.str2); op=1; } } public void buttonCalculate(View v) { v1=(EditText)findViewById(R.id.input1); v2=(EditText)findViewById(R.id.input2); r=(EditText)findViewById(R.id.result); int i,j,result; i=Integer.parseInt(v1.getText().toString()); j=Integer.parseInt(v2.getText().toString()); result=i+(op*j); r.setText(String.format("%d",result)); } }
package com.example.ayuth.androidpresentationremoteclient; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import com.github.nkzawa.emitter.Emitter; import java.net.URISyntaxException; public class MainActivity extends AppCompatActivity implements View.OnClickListener { private RemoteSocket remoteSocket; private Button btnConnectToRemoteServer, btnDisconnectFromRemoteServer, btnStartPresentation, btnStopPresentation, btnGotoFirstSlide, btnGotoPreviousSlide, btnGotoNextSlide, btnGotoLastSlide; private EditText etUri; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); initInstances(); enableControls(false); // set everything disabled before we're connected } private void initInstances() { remoteSocket = RemoteSocket.getInstance(); etUri = findViewById(R.id.etUri); btnConnectToRemoteServer = findViewById(R.id.btnConnectToRemoteServer); btnConnectToRemoteServer.setOnClickListener(this); btnDisconnectFromRemoteServer = findViewById(R.id.btnDisconnectFromRemoteServer); btnDisconnectFromRemoteServer.setOnClickListener(this); btnStartPresentation = findViewById(R.id.btnStartPresentation); btnStartPresentation.setOnClickListener(this); btnStopPresentation = findViewById(R.id.btnStopPresentation); btnStopPresentation.setOnClickListener(this); btnGotoFirstSlide = findViewById(R.id.btnGotoFirstSlide); btnGotoFirstSlide.setOnClickListener(this); btnGotoPreviousSlide = findViewById(R.id.btnGotoPreviousSlide); btnGotoPreviousSlide.setOnClickListener(this); btnGotoNextSlide = findViewById(R.id.btnGotoNextSlide); btnGotoNextSlide.setOnClickListener(this); btnGotoLastSlide = findViewById(R.id.btnGotoLastSlide); btnGotoLastSlide.setOnClickListener(this); } @Override public void onClick(View v) { if (v == btnConnectToRemoteServer) { String uri = etUri.getText().toString(); // append http:// if not exists if (!(uri.indexOf("http://") >= 0)) { uri = "http://" + uri; } try { remoteSocket.connect(uri); if (remoteSocket.getSocket().connected()) { enableControls(true); Toast.makeText(this, "Connected", Toast.LENGTH_SHORT).show(); } else { enableControls(false); Toast.makeText(this, "Unable to connect " + uri, Toast.LENGTH_SHORT).show(); } } catch (URISyntaxException ex) { enableControls(false); Toast.makeText(this, ex.getMessage(), Toast.LENGTH_SHORT).show(); Log.e("MainActivity", ex.getMessage()); } } else if (v == btnDisconnectFromRemoteServer) { try { remoteSocket.getSocket().disconnect(); enableControls(false); Toast.makeText(this, "Disconnected", Toast.LENGTH_SHORT).show(); } catch (Exception ex) { Toast.makeText(this, ex.getMessage(), Toast.LENGTH_SHORT).show(); } } else if (v == btnStartPresentation) { remoteSocket.sendCommand(RemoteCommand.START_PRESENTATION); } else if (v == btnStopPresentation) { remoteSocket.sendCommand(RemoteCommand.STOP_PRESENTATION); } else if (v == btnGotoFirstSlide) { remoteSocket.sendCommand(RemoteCommand.GOTO_FIRST_SLIDE); } else if (v == btnGotoPreviousSlide) { remoteSocket.sendCommand(RemoteCommand.GOTO_PREVIOUS_SLIDE); } else if (v == btnGotoNextSlide) { remoteSocket.sendCommand(RemoteCommand.GOTO_NEXT_SLIDE); } else if (v == btnGotoLastSlide) { remoteSocket.sendCommand(RemoteCommand.GOTO_LAST_SLIDE); } } private void enableControls(boolean enable) { if (enable) { etUri.setEnabled(false); btnConnectToRemoteServer.setEnabled(false); btnDisconnectFromRemoteServer.setEnabled(true); btnStartPresentation.setEnabled(true); btnStopPresentation.setEnabled(true); btnGotoFirstSlide.setEnabled(true); btnGotoPreviousSlide.setEnabled(true); btnGotoNextSlide.setEnabled(true); btnGotoLastSlide.setEnabled(true); } else { etUri.setEnabled(true); btnConnectToRemoteServer.setEnabled(true); btnDisconnectFromRemoteServer.setEnabled(false); btnStartPresentation.setEnabled(false); btnStopPresentation.setEnabled(false); btnGotoFirstSlide.setEnabled(false); btnGotoPreviousSlide.setEnabled(false); btnGotoNextSlide.setEnabled(false); btnGotoLastSlide.setEnabled(false); } } @Override protected void onDestroy() { super.onDestroy(); remoteSocket.getSocket().disconnect(); } }
package org.viqueen.java.datastream; import java.io.DataInputStream; import java.io.IOException; import java.lang.annotation.Annotation; import java.util.Collection; import java.util.Optional; import java.util.Set; public class PrimitiveDataStreamCodec implements DataStreamCodec { private final Set<Class<?>> types = Set.of( boolean.class, Boolean.class, byte.class, Byte.class, char.class, Character.class, double.class, Double.class, float.class, Float.class, int.class, Integer.class, long.class, Long.class, short.class, Short.class ); @Override public <TYPE> boolean supports(Class<TYPE> type) { return types.contains(type); } @Override public <TYPE> TYPE decode( final DataInputStream stream, final Class<TYPE> type, final Collection<Annotation> annotations) throws IOException { if (type == int.class || type == Integer.class) { Optional<Unsigned> unsigned = annotations.stream() .filter(a -> a.annotationType().equals(Unsigned.class)) .map(Unsigned.class::cast) .findFirst(); final int value; if (unsigned.isPresent()) { value = switch (unsigned.get().type()) { case ONE -> stream.readUnsignedByte(); case TWO -> stream.readUnsignedShort(); case FOUR -> stream.readInt(); }; } else { value = stream.readInt(); } //noinspection unchecked return (TYPE) Integer.valueOf(value); } if (type == long.class || type == Long.class) { //noinspection unchecked return (TYPE) Long.valueOf(stream.readLong()); } if (type == short.class || type == Short.class) { //noinspection unchecked return (TYPE) Short.valueOf(stream.readShort()); } if (type == double.class || type == Double.class) { //noinspection unchecked return (TYPE) Double.valueOf(stream.readDouble()); } if (type == float.class || type == Float.class) { //noinspection unchecked return (TYPE) Float.valueOf(stream.readFloat()); } if (type == boolean.class || type == Boolean.class) { //noinspection unchecked return (TYPE) Boolean.valueOf(stream.readBoolean()); } if (type == char.class || type == Character.class) { //noinspection unchecked return (TYPE) Character.valueOf(stream.readChar()); } if (type == byte.class || type == Byte.class) { //noinspection unchecked return (TYPE) Byte.valueOf(stream.readByte()); } throw new IOException("decodePrimitive failed : " + type); } }
package de.varylab.discreteconformal.convergence; import static de.varylab.discreteconformal.util.DiscreteEllipticUtility.generateEllipticImage; import java.io.FileOutputStream; import java.util.HashSet; import java.util.Map; import java.util.Set; import java.util.logging.Level; import java.util.logging.Logger; import joptsimple.OptionParser; import joptsimple.OptionSet; import joptsimple.OptionSpec; import joptsimple.OptionSpecBuilder; import de.jreality.math.Pn; import de.jtem.halfedgetools.adapter.TypedAdapterSet; import de.jtem.halfedgetools.adapter.type.generic.Position4d; import de.jtem.halfedgetools.adapter.type.generic.TexturePosition4d; import de.jtem.halfedgetools.algorithm.computationalgeometry.ConvexHull; import de.jtem.halfedgetools.algorithm.subdivision.LoopLinear; import de.jtem.mfc.field.Complex; import de.varylab.conformallab.data.DataIO; import de.varylab.conformallab.data.DataUtility; import de.varylab.conformallab.data.types.ConformalDataList; import de.varylab.conformallab.data.types.HalfedgeEmbedding; import de.varylab.conformallab.data.types.HalfedgeMap; import de.varylab.conformallab.data.types.ObjectFactory; import de.varylab.discreteconformal.ConformalAdapterSet; import de.varylab.discreteconformal.heds.CoEdge; import de.varylab.discreteconformal.heds.CoFace; import de.varylab.discreteconformal.heds.CoHDS; import de.varylab.discreteconformal.heds.CoVertex; import de.varylab.discreteconformal.unwrapper.EuclideanUnwrapperPETSc; import de.varylab.discreteconformal.util.CuttingUtility.CuttingInfo; import de.varylab.discreteconformal.util.DiscreteEllipticUtility; public class ConvergenceSubdivision extends ConvergenceSeries { private static Logger log = Logger.getLogger(ConvergenceSubdivision.class.getName()); private int maxSubdivision = 0, numExtraPoints = 0; private boolean useConvexHull = true; private LoopLinear loop = new LoopLinear(); public ConvergenceSubdivision() { } @Override protected OptionSet configureAndParseOptions(OptionParser p, String... args) { OptionSpec<Integer> mixSubdivisionSpec = p.accepts("max", "Maxmum number of subdivision steps").withRequiredArg().ofType(Integer.class).defaultsTo(0); OptionSpec<Integer> numExtraPointsSpec = p.accepts("extra", "Number of extra points").withRequiredArg().ofType(Integer.class).defaultsTo(0); OptionSpecBuilder noConvexHullSpec = p.accepts("noConvexHull", "Skip creating convex hull"); OptionSet result = p.parse(args); maxSubdivision = mixSubdivisionSpec.value(result); numExtraPoints = numExtraPointsSpec.value(result); useConvexHull = !result.has(noConvexHullSpec); return result; } @Override protected void perform() throws Exception { writeComment("numVertex[1], absDifErr[2], absErr[3], argErr[4], reErr[5], imErr[6], re[7], im[8], gradNormSq[9]"); ConformalDataList dataList = new ObjectFactory().createConformalDataList(); ConformalAdapterSet a = new ConformalAdapterSet(); TypedAdapterSet<double[]> da = a.querySet(double[].class); for (int i = 0; i < maxSubdivision; i ++) { CoHDS hds = new CoHDS(); // predefined vertices for (int vi = 0; vi < vertices.length; vi++) { CoVertex v = hds.addNewVertex(); v.P = new double[] {vertices[vi][0], vertices[vi][1], vertices[vi][2], 1.0}; Pn.setToLength(v.P, v.P, 1, Pn.EUCLIDEAN); } // extra points for (int j = 0; j < numExtraPoints; j++) { CoVertex v = hds.addNewVertex(); v.P = new double[] {rnd.nextGaussian(), rnd.nextGaussian(), rnd.nextGaussian(), 1.0}; Pn.setToLength(v.P, v.P, 1, Pn.EUCLIDEAN); } ConvexHull.convexHull(hds, da, 1E-8); // subdivision for (int si = 0; si < i; si++) { CoHDS subdivided = new CoHDS(); loop.subdivide(hds, subdivided, da); hds = subdivided; // reset branch data for (int vi = 0; vi < vertices.length; vi++) { CoVertex v = hds.getVertex(vi); v.P = new double[] {vertices[vi][0], vertices[vi][1], vertices[vi][2], 1.0}; Pn.setToLength(v.P, v.P, 1, Pn.EUCLIDEAN); } // project to the sphere in every step for (CoVertex v : hds.getVertices()) { Pn.setToLength(v.P, v.P, 1, Pn.EUCLIDEAN); } } HalfedgeEmbedding input = DataUtility.toHalfedgeEmbedding("input " + i, hds, a, Position4d.class, null); dataList.getData().add(input); int numVerts = hds.numVertices(); Complex tau = null; CoVertex cutRoot = hds.getVertex(branchIndices[0]); CuttingInfo<CoVertex, CoEdge, CoFace> cutInfo = new CuttingInfo<>(); try { Set<CoEdge> glueSet = new HashSet<CoEdge>(); Map<CoVertex, CoVertex> involution = generateEllipticImage(hds, 0, true, useConvexHull, glueSet, branchIndices); if (!cutRoot.isValid()) cutRoot = involution.get(cutRoot); tau = DiscreteEllipticUtility.calculateHalfPeriodRatio(hds, cutRoot, 1E-9, cutInfo); } catch (Exception e) { log.log(Level.WARNING, e.getMessage(), e); continue; } double absErr = tau.abs() - getExpectedTau().abs(); double absDifErr = tau.minus(getExpectedTau()).abs(); double argErr = tau.arg() - getExpectedTau().arg(); double reErr = tau.re - getExpectedTau().re; double imErr = tau.im - getExpectedTau().im; writeData(numVerts + "\t" + absDifErr + "\t" + absErr + "\t" + argErr + "\t" + reErr + "\t" + imErr + "\t" + tau.re + "\t" + tau.im + "\t" + EuclideanUnwrapperPETSc.lastGNorm); HalfedgeMap map = DataUtility.toHalfedgeMap("map " + i, hds, a, TexturePosition4d.class, Position4d.class, cutInfo); dataList.getData().add(map); } try { FileOutputStream fout = new FileOutputStream(fileName + ".xml"); DataIO.writeConformalDataList(dataList, fout); } catch (Exception e) { log.log(Level.WARNING, e.getMessage(), e); } } }
package com.igs.qhrzlc.utils; /** * 类描述: * 创建人:heliang * 创建时间:2015/12/3 16:39 * 修改人:8153 * 修改时间:2015/12/3 16:39 * 修改备注: */ public final class ActivityCode { public static final String FROM_PAGE = "fromPage"; public static final int DEFAULT_RESULT_PAGE = -1; }
package sonar.minimodem; import java.io.*; import org.apache.commons.codec.binary.Base32InputStream; public class BufferedReceiver extends InputStream { private Base32InputStream innerReader; private Process rxHandle; public BufferedReceiver(MinimodemReceiver rx) throws IOException { this.rxHandle = rx.initProcess(); InputStream stdout = this.rxHandle.getInputStream(); this.innerReader = new Base32InputStream(stdout); } @Override public int read() throws IOException { // System.out.println("reading..."); int ret = this.innerReader.read(); return ret; } @Override public void close() { this.rxHandle.destroy(); } }
package Players.Engines; public class Boogeyman extends BattleshipEngine { @Override public void placeShip(int shipIndex) { } @Override public String fireASalvo() { return null; } }//end of class
package jnouse; import jalgo.StudentTest; import java.util.ArrayList; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.JOptionPane; import jclient.VideoFile; import jmckoi.MatrixRetrieve; import Jama.Matrix; public class ChiSquareTest { /** * Significant level of the two-sided test of statistics */ static final double alpha = 0.1; /** * p.values for every column of mat match with corresponding * columns of matrices videoMat. The probability values are * obtained using the student distribution; * dim=[#videosToTest][256] * */ double[]pvalues; boolean showtest = true; List<String> thevideos = new ArrayList<String>(); static int totest = 0; //Results of test after completing test private static StringBuffer res[]= new StringBuffer[3] ; private static Logger mLog = Logger.getLogger(StudentTest.class.getName()); private boolean debug = true; public static double getAlpha(){ return alpha; } //it will exclude the video to test or index totest public List<String> getThevideos(){ return thevideos; } public void setThevideos(List<String> vt){ thevideos=vt; } public static StringBuffer[] getRes(){ return res; } public ChiSquareTest(String args[]){ if(!debug) mLog.setLevel(Level.WARNING); //true is for the mean otherwise it is the median MatrixRetrieve vstore = new MatrixRetrieve("TbVideoColt", true, true); List<String> similar = new ArrayList<String>(); //videos are input as arguments of main if(args.length > 1) { vstore.retreiveMat(args); for(int a=0; a < args.length; ++a) thevideos.add(args[a]); } int cnt = args.length; //videos are input in a file if (args.length == 1){ //reading from file args[0].trim(); thevideos = VideoFile.readFile(args[0]); String [] argsf = thevideos.toArray(new String[thevideos.size()]); vstore.retreiveMat(argsf); cnt = argsf.length; } // int sz = thevideos.size(); String testvid = thevideos.get(totest); List<String> pass = new ArrayList<String>(); pass.addAll(thevideos); StringBuffer r[] = meanDifTest(vstore, totest); for(int k=0; k<3; ++k) this.res[k]=r[k]; String toprint="\n\nTest video: "+ testvid + "\nStudent test at significant level= " + ChiSquareTest.alpha; StringBuffer sim =new StringBuffer(toprint); mLog.info(toprint); } public StringBuffer[] meanDifTest(MatrixRetrieve vstore,int totest){ String testvid = thevideos.get(totest); if(!showtest) thevideos.remove(totest); StringBuffer res0 = new StringBuffer("Test video "+ testvid); StringBuffer[] res = new StringBuffer[3]; String mess1 = "Testing video: " + testvid; JOptionPane.showMessageDialog(null, mess1, "Test videos", JOptionPane.INFORMATION_MESSAGE); Matrix [] matG = MatrixRetrieve.studentMats(vstore.getMeangreenCnt()); Matrix [] matR = MatrixRetrieve.studentMats(vstore.getMeanredCnt()); Matrix [] matB = MatrixRetrieve.studentMats(vstore.getMeanblueCnt()); Matrix Rtest = matR[totest]; Matrix Gtest = matG[totest]; Matrix Btest = matB[totest]; Matrix [] Rbase = matR; StringBuffer rtest = chitest(Rbase,Rtest, thevideos, "RED"); res[0] = new StringBuffer("\n"+res0); res[0].append(rtest); Matrix [] Gbase = matG; StringBuffer gtest = chitest(Gbase,Gtest, thevideos,"GREEN"); res[1] = new StringBuffer("\n"+res0); res[1].append(gtest); Matrix [] Bbase = matB; StringBuffer btest = chitest(Bbase,Btest, thevideos,"BLUE"); res[2] = new StringBuffer("\n"+res0); res[2].append( btest); return res; } public StringBuffer chitest(Matrix[]base, Matrix test, List<String> thevid, String col ){ double[] tfrm = test.transpose().getArrayCopy()[0]; double rowtestotal = 0d; for(double d: tfrm) rowtestotal +=d; pvalues = new double[base.length]; StringBuffer res = new StringBuffer(); res.append("\nChiSquare test at significant level= "+ ChiSquareTest.alpha); res.append("\nColor component "+ col + ": "); for(int videoInd=0; videoInd < base.length; ++videoInd){ Matrix mm= base[videoInd]; String str = thevideos.get(videoInd); double[] coltotal = new double[tfrm.length]; double [] exptest = new double[tfrm.length]; double df =0; double [] bfrm = mm.transpose().getArrayCopy()[0]; double [] expbase = new double[bfrm.length]; double rowbasetotal = 0d; for(double d: bfrm) rowbasetotal +=d; double N = rowtestotal + rowbasetotal; double x2=0; for(int c=0; c < coltotal.length; ++c){ coltotal[c] = bfrm[c] + tfrm[c]; exptest[c]=coltotal[c]*rowtestotal/N; expbase[c] = coltotal[c]*rowbasetotal/N; if((bfrm[c]+tfrm[c]) >1.e-5){ df++; x2 += (bfrm[c]-expbase[c])*(bfrm[c]-expbase[c])/(expbase[c]+1.e-10); x2 += (tfrm[c]-exptest[c])*(tfrm[c]-exptest[c])/(exptest[c]+1.e-10); } } pvalues[videoInd]=cern.jet.stat.Probability.chiSquareComplemented(2, x2); res.append("\nVideo "+ str+ " x2="+ x2+" df="+ df+"\npvalue= " +pvalues[videoInd]); if ( pvalues[videoInd] <= alpha) { res.append("\t"+col+ "...Different videos.\n"); }else{ res.append("\t"+ col+"...Same videos.\n"); ; } } return res; } public static void main(String[]args){ ChiSquareTest chi = new ChiSquareTest(args); StringBuffer[] res = chi.getRes(); for(StringBuffer buf:res) mLog.info(buf.toString()); } }
package top.aldrinLake.Service; public interface ExcelServe { /** * 文件下载次数自增 */ public void addDownloadNum(int id); /** * @view 把文件名存入数据库 */ public void storeFilePath(String filePath); /** * @view 获取excel表的所有数据 */ public String getExcelInfo(int page); }
package basePage; import pageObjects.RandomDateGenerator; public class BasePage { public RandomDateGenerator rdgPgObj = new RandomDateGenerator(); }
/****************************************************************************** * __ * * <-----/@@\-----> * * <-< < \\// > >-> * * <-<-\ __ /->-> * * Data / \ Crow * * ^ ^ * * info@datacrow.net * * * * This file is part of Data Crow. * * Data Crow is free software; you can redistribute it and/or * * modify it under the terms of the GNU General Public * * License as published by the Free Software Foundation; either * * version 3 of the License, or any later version. * * * * Data Crow is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * * See the GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public * * License along with this program. If not, see http://www.gnu.org/licenses * * * ******************************************************************************/ package net.datacrow.console.windows.onlinesearch; import java.awt.Dimension; import java.awt.GridBagConstraints; import java.awt.Insets; import javax.swing.JProgressBar; import net.datacrow.console.Layout; import net.datacrow.console.windows.DcDialog; import net.datacrow.util.DcSwingUtilities; public class ProgressDialog extends DcDialog { private JProgressBar bar = new JProgressBar(); public ProgressDialog(String title) { super(DcSwingUtilities.getRootFrame()); bar.setMinimum(0); bar.setMaximum(100); getContentPane().setLayout(Layout.getGBL()); getContentPane().add(bar, Layout.getGBC( 0, 0, 1, 1, 50.0, 50.0 ,GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, new Insets(5, 5, 5, 5), 0, 0)); pack(); setSize(new Dimension(500, 100)); setCenteredLocation(); setResizable(false); setTitle(title); setModal(false); setVisible(true); } public void update() { if (bar != null) { int value = bar.getValue(); value = value < bar.getMaximum() ? value + 1 : 0; bar.setValue(value); } } @Override public void close() { bar = null; super.close(); } }
package org.legital.roommanagement.domain; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; @Entity public class Course { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; private String fieldOfStudy; private int number; private String lecturer; private String title; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getFieldOfStudy() { return fieldOfStudy; } public void setFieldOfStudy(String fieldOfStudy) { this.fieldOfStudy = fieldOfStudy; } public int getNumber() { return number; } public void setNumber(int number) { this.number = number; } public String getLecturer() { return lecturer; } public void setLecturer(String lecturer) { this.lecturer = lecturer; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } }
/* * Copyright © 2020-2022 ForgeRock AS (obst@forgerock.com) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.forgerock.sapi.gateway.ob.uk.common.datamodel.testsupport.account; import com.forgerock.sapi.gateway.ob.uk.common.datamodel.account.FRAccountAccessConsent; import com.forgerock.sapi.gateway.ob.uk.common.datamodel.account.FRAccountAccessConsent.FRAccountAccessConsentBuilder; import com.forgerock.sapi.gateway.ob.uk.common.datamodel.account.FRExternalPermissionsCode; import com.forgerock.sapi.gateway.ob.uk.common.datamodel.account.FRExternalRequestStatusCode; import org.joda.time.DateTime; import java.util.List; import java.util.UUID; /** * Test data factory for {@link FRAccountAccessConsent}. */ public class FRAccountAccessConsentTestDataFactory { public static FRAccountAccessConsent aValidFRAccountAccessConsent() { return aValidFRAccountAccessConsentBuilder().build(); } public static FRAccountAccessConsentBuilder aValidFRAccountAccessConsentBuilder() { return FRAccountAccessConsent.builder() .id(UUID.randomUUID().toString()) .clientId(UUID.randomUUID().toString()) .userId(UUID.randomUUID().toString()) .aispId(UUID.randomUUID().toString()) .aispName("AISP Name") .status(FRExternalRequestStatusCode.AWAITINGAUTHORISATION) .accountIds(List.of(UUID.randomUUID().toString())) .permissions(List.of( FRExternalPermissionsCode.READACCOUNTSDETAIL, FRExternalPermissionsCode.READBENEFICIARIESDETAIL, FRExternalPermissionsCode.READSCHEDULEDPAYMENTSDETAIL, FRExternalPermissionsCode.READSTANDINGORDERSDETAIL, FRExternalPermissionsCode.READSTATEMENTSDETAIL, FRExternalPermissionsCode.READTRANSACTIONSDETAIL)) .expirationDateTime(DateTime.now().plusDays(1)) .transactionFromDateTime(DateTime.now().minusDays(1)) .transactionToDateTime(DateTime.now()); } }
package tw.iii.ed.mydatastorage; import android.Manifest; import android.content.SharedPreferences; import android.content.pm.PackageManager; import android.os.Environment; import android.support.annotation.NonNull; import android.support.v4.app.ActivityCompat; import android.support.v4.content.ContextCompat; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Toast; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.FileReader; import java.io.InputStreamReader; public class MainActivity extends AppCompatActivity { private SharedPreferences sp; private SharedPreferences.Editor editor; private File sdRoot, appRoot; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED){ ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 123); }else init(); //Log.i("brad", sdRoot.getAbsolutePath()); } private void init(){ sp = getSharedPreferences("gamedata", MODE_PRIVATE); //gamedata.xml editor = sp.edit(); sdRoot = Environment.getExternalStorageDirectory(); appRoot = new File(sdRoot, "Android/data/" + getPackageName() + "/"); if(!appRoot.exists()){ appRoot.mkdirs(); } } @Override public void onRequestPermissionsResult( int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); if (requestCode == 123){ if (grantResults[0] == PackageManager.PERMISSION_GRANTED){ init(); }else finish(); } } public void test1(View view){ editor.putString("username", "Ed"); editor.putInt("stage", 2); editor.putBoolean("sound", false); editor.commit(); Toast.makeText(this, "Save OK", Toast.LENGTH_SHORT).show(); } public void test2(View view){ boolean sound = sp.getBoolean("sound", true); String username = sp.getString("username", "guest"); Log.i("brad", ""+sound + ":" + username); } public void test3 (View view){ try (FileOutputStream fout = openFileOutput("data.txt", MODE_PRIVATE)){ fout.write("Hello, World\nHello, Ed\n1234567\n".getBytes()); fout.flush(); Toast.makeText(this, "Save OK", Toast.LENGTH_SHORT).show(); } catch (Exception e){ Log.i("brad" , e.toString()); } } public void test4 (View view){ try(FileInputStream fin = openFileInput("data.txt"); BufferedReader br = new BufferedReader(new InputStreamReader(fin))){ String tmp; StringBuilder builder = new StringBuilder(); while((tmp = br.readLine()) != null){ builder.append(tmp + "\n"); } Toast.makeText(this, builder.toString(), Toast.LENGTH_SHORT).show(); }catch (Exception e){ Log.i("brad" , e.toString()); } } public void test5(View view){ try{ File file = new File(sdRoot, "file.txt"); FileOutputStream fout = new FileOutputStream(file); fout.write("OK".getBytes()); fout.flush(); fout.close(); }catch (Exception e){ Log.i("brad" , e.toString()); } } public void test6(View view){ try{ File file = new File(appRoot, "file.txt"); FileOutputStream fout = new FileOutputStream(file); fout.write("OK".getBytes()); fout.flush(); fout.close(); }catch (Exception e){ Log.i("brad" , e.toString()); } } }
package de.wiltherr.ws2812fx; import java.util.List; import java.util.Set; public interface WS2812FX { int SPEED_MIN = 10; int SPEED_MAX = 65535; int BRIGHTNESS_MIN = 0; int BRIGHTNESS_MAX = 255; int MAX_NUM_SEGMENTS = 10; int COLORS_PER_SEGMENT = 3; void setBrightness(int brightness) throws WS2812FXException; // public void setPixelColor(int pixelIdx, Color color) throws WS2812FXException; // public void setMultiPixelColor(Map<Integer,Color> pixelColorMap) throws WS2812FXException; void updateSegment(int segmentIndex, SegmentConfig segmentConfig) throws WS2812FXException; void updateSegmentMulti(Set<Integer> segmentIndices, SegmentConfig segmentConfig) throws WS2812FXException; public void updateSegmentAll(SegmentConfig segment) throws WS2812FXException; public void resetSegments(List<Segment> segments) throws WS2812FXException; public Integer getLength() throws WS2812FXException; public void setLength(int pixelCount) throws WS2812FXException; public Segment getSegment(int segmentIdx) throws WS2812FXException; public List<Segment> getSegments() throws WS2812FXException; public void pause() throws WS2812FXException; public void resume() throws WS2812FXException; public void start() throws WS2812FXException; public void stop() throws WS2812FXException; /* TODO: Das hier auch?? public void setSegmentMode(int segmentIndex, Mode mode); public void setSegmentColors(int segmentIndex, List<Color> colors); public void setSegmentSpeed(int segmentIndex, int speed); */ }
package circuits; import java.lang.StringBuilder; public abstract class Gate { protected Gate[] inGates; public Gate(Gate[] inGates) { this.inGates = inGates; } public boolean calc() throws CircuitException{ boolean []inValues = null; if(inGates != null) { inValues= new boolean[inGates.length]; for(int i=0; i <inGates.length; i++ ) { inValues[i] = inGates[i].calc(); } } return func(inValues); } protected abstract boolean func(boolean[] inValues) throws CircuitException; public abstract String getName(); public abstract Gate simplify(); public String toString() { StringBuilder res = new StringBuilder(); res.append(getName()); if(inGates != null) { res.append("["); for (Gate g: inGates) { res.append(g.toString() + ", "); } res.delete(res.length() -2, res.length()); res.append("]"); } return res.toString(); } }
package utilidades.annotations; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; @Retention(RetentionPolicy.RUNTIME) public @interface Sort { public boolean value() default true; }
import java.io.IOException; import java.nio.ByteBuffer; import java.nio.channels.SocketChannel; import java.util.HashSet; import java.util.Iterator; import java.util.Set; /** * Created by Yohann on 2016/10/8. */ public class ConnPool { //保存需要维护的通道 private Set<SocketChannel> channelSet; private Iterator<SocketChannel> ite; public ConnPool() { channelSet = new HashSet<>(); } /** * 添加套接字通道 * * @param sc */ public void add(SocketChannel sc) { channelSet.add(sc); } /** * 发送心跳包 */ public void startHeart() throws IOException, InterruptedException { ByteBuffer buf = ByteBuffer.allocate(10); while (true) { ite = channelSet.iterator(); while (ite.hasNext()) { System.out.println("集合中有连接"); SocketChannel sc = ite.next(); buf.put("heart".getBytes()); buf.flip(); sc.write(buf); buf.clear(); } //发送心跳包间隔为5s Thread.sleep(5 * 1000); System.out.println("发送心跳包"); } } }
package com.sunjob.yudioj_springboot_framemark.vo; public class ComplieProcess { public enum result{ CompileError , CompileSucess , CompileTimeout //编译成功 编译失败 编译超时 } private result type; public result getType() { return type; } public void setType(result type) { this.type = type; } private String msg; //编译过程中产生的信息 private Long time; //编译使用的时间 public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } public Long getTime() { return time; } public void setTime(Long time) { this.time = time; } }
package cn.xuetang.common.config; import cn.xuetang.common.action.BaseAction; import cn.xuetang.modules.app.bean.App_info; import cn.xuetang.modules.sys.bean.Sys_config; import org.nutz.dao.Cnd; import org.nutz.dao.Dao; import org.nutz.dao.Sqls; import org.nutz.filepool.FilePool; import org.nutz.log.Log; import org.nutz.log.Logs; import org.nutz.mvc.Mvcs; import org.quartz.Scheduler; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; /** * @author Wizzer.cn * @time 2012-9-13 上午10:54:04 */ public class Globals extends BaseAction { private final static Log log = Logs.get(); //虚拟目录路径 public static String APP_BASE_PATH = ""; //虚拟目录名称 public static String APP_BASE_NAME = ""; //应用中文名 public static String APP_NAME = ""; //系统配置 public static Map<String, String> SYS_CONFIG; //数据字典,根据ID分别初始化 public static Map<String, Object> DATA_DICT; //应用信息,用于通过mykey验证来源,放在内存里为了提高响应速度 public static Map<String, Object> APP_INFO; //定时任务实例 public static Scheduler SCHEDULER; //文件池 public static FilePool FILE_POOL; public static void InitAppInfo(Dao dao) { try { if (APP_INFO == null) { APP_INFO = new HashMap<String, Object>(); } APP_INFO.clear(); List<App_info> appInfoList = dao.query(App_info.class, Cnd.orderBy().asc("ID")); for (App_info appInfo : appInfoList) { Globals.APP_INFO.put(appInfo.getMykey(), appInfo); } } catch (Exception e) { e.printStackTrace(); log.error(e); } } public static void InitSysConfig(Dao dao) { try { if (SYS_CONFIG == null) { SYS_CONFIG = new HashMap<String, String>(); } List<Sys_config> configList = dao.query(Sys_config.class, Cnd.orderBy().asc("ID")); for (Sys_config sysConfig : configList) { Globals.SYS_CONFIG.put(sysConfig.getCname(), sysConfig.getCvalue()); } } catch (Exception e) { e.printStackTrace(); log.error(e); } } public static void InitDataDict(Dao dao) { try { if (DATA_DICT == null) { DATA_DICT = new HashMap<String, Object>(); } DATA_DICT.put(Dict.APP_TYPE, daoCtl.getHashMap(dao, Sqls.create("SELECT dkey,dval FROM sys_dict WHERE id LIKE '" + Dict.APP_TYPE + "____'"))); DATA_DICT.put(Dict.DIVSION, daoCtl.getHashMap(dao, Sqls.create("SELECT dkey,dval FROM sys_dict WHERE id LIKE '" + Dict.DIVSION + "_%'"))); DATA_DICT.put(Dict.FORM_TYPE, daoCtl.getHashMap(dao, Sqls.create("SELECT dkey,dval FROM sys_dict WHERE id LIKE '" + Dict.FORM_TYPE + "_%' order by location asc,id asc"))); } catch (Exception e) { e.printStackTrace(); log.error(e); } } }
package ru.itmo.ctlab.sgmwcs; import ru.itmo.ctlab.sgmwcs.graph.Edge; import ru.itmo.ctlab.sgmwcs.graph.Graph; import ru.itmo.ctlab.sgmwcs.graph.Node; import ru.itmo.ctlab.sgmwcs.graph.Unit; import ru.itmo.ctlab.sgmwcs.solver.Solver; import ru.itmo.ctlab.sgmwcs.solver.SolverException; import java.util.*; import static ru.itmo.ctlab.sgmwcs.solver.Utils.sum; public class ReferenceSolver implements Solver { public List<Unit> solve(Graph graph, Signals signals, List<Node> roots) { for (Node root : roots) { if (!graph.containsVertex(root)) { throw new IllegalArgumentException(); } } if (graph.edgeSet().size() > 31) { throw new IllegalArgumentException(); } List<Unit> maxSet = Collections.emptyList(); double max = roots.isEmpty() ? 0 : -Double.MAX_VALUE; // Isolated vertices for (Node node : graph.vertexSet()) { if ((roots.isEmpty() || (roots.size() == 1 && roots.get(0) == node)) && signals.weight(node) > max) { max = signals.weight(node); maxSet = new ArrayList<>(); maxSet.add(node); } } Edge[] edges = graph.edgeSet().stream().toArray(Edge[]::new); int m = edges.length; for (int i = 0; i < (1 << m); i++) { Set<Edge> currEdges = new LinkedHashSet<>(); for (int j = 0; j < m; j++) { if ((i & (1 << j)) != 0) { currEdges.add(edges[j]); } } Graph subgraph = graph.subgraph(graph.vertexSet(), currEdges); for (Set<Node> component : subgraph.connectedSets()) { if (component.size() == 1) { subgraph.removeVertex(component.iterator().next()); } } List<Set<Node>> connectedSets = subgraph.connectedSets(); if (connectedSets.size() == 1) { Set<Node> res = connectedSets.iterator().next(); boolean containsRoots = true; for (Node root : roots) { if (!res.contains(root)) { containsRoots = false; break; } } Set<Unit> units = new HashSet<>(res); units.addAll(currEdges); double candidate = sum(units, signals); if (containsRoots && candidate > max) { max = candidate; maxSet = new ArrayList<>(); maxSet.addAll(res); maxSet.addAll(currEdges); } } } return maxSet; } @Override public List<Unit> solve(Graph graph, Signals signals) throws SolverException { return solve(graph, signals, Collections.emptyList()); } @Override public boolean isSolvedToOptimality() { return true; } @Override public TimeLimit getTimeLimit() { throw new UnsupportedOperationException(); } @Override public void setTimeLimit(TimeLimit tl) { throw new UnsupportedOperationException(); } @Override public void setLogLevel(int logLevel) { throw new UnsupportedOperationException(); } @Override public void setLB(double lb) { throw new UnsupportedOperationException(); } @Override public double getLB() { return 0; } }
package com.github.andrelugomes.v2.domain; import com.github.andrelugomes.v2.domain.usecase.indexing.gateway.EventParserGateway; import com.github.andrelugomes.v2.domain.usecase.indexing.entity.Event; import com.github.andrelugomes.v2.infrastructure.adapter.GsonEventParserAdapter; import com.github.andrelugomes.v2.infrastructure.adapter.exception.ResponseException; import com.github.andrelugomes.v2.domain.usecase.indexing.gateway.MerchantGateway; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import java.io.IOException; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.*; @RunWith(JUnit4.class) public class IndexerTest { @Test public void shouldSkipMessageBecauseHasNoData() throws IOException, InterruptedException { var gateway = mock(MerchantGateway.class); var parser = mock(EventParserGateway.class); Event event = new Event(); event.setMessageId("ID"); event.setPublishTime("TIMESTAMP"); Indexer indexer = new Indexer(gateway, parser); indexer.handle(event); verify(gateway, never()).upsert(anyString(), anyString()); verify(gateway, never()).delete(anyString()); verify(parser, never()).parse(any(Event.class)); } @Test public void shouldHandleMessageThatUpsertMerchant() throws IOException, InterruptedException { var gateway = mock(MerchantGateway.class); var parser = new GsonEventParserAdapter(); Event event = new Event(); event.setMessageId("ID"); event.setPublishTime("TIMESTAMP"); event.setData("ewogICJpZCI6IjEiLAogICJvcCI6IlVQU0VSVCIsCiAgImRhdGEiOiB7CiAgICAibmFtZSI6ICJTdGVha2hvdXNlIiwKICAg" +"ICJsb2NhdGlvbiI6IHsKICAgICAgImxhdCI6IC0yMS45NTg0MDA3MjYzMTgzNiwKICAgICAgImxvbiI6IC00Ny45ODgyMDExNDEzN" +"Tc0MgogICAgfSwKICAgICJwYXltZW50 X29wdGlvbnMiOiBbCiAgICAgICJDQVNIIiwgIkNSRURJVF9DQVJEIgogICAgXSwKICAgI" +"CJjYXRlZ29yeSI6ICJTVEVBS0hPVVNFIiwKICAgICJjcmVhdGVkX2F0IjogMTU4NTYwNjY1NjU2OAogIH0KfQ=="); Indexer handler = new Indexer(gateway, parser); handler.handle(event); verify(gateway, atLeastOnce()).upsert(anyString(), anyString()); } @Test public void shouldHandleMessageThatDeleteMerchant() throws IOException, InterruptedException { var gateway = mock(MerchantGateway.class); var parser = new GsonEventParserAdapter(); Event event = new Event(); event.setMessageId("ID"); event.setPublishTime("TIMESTAMP"); event.setData("eyJpZCI6IjMyMSIsIm9wIjoiREVMRVRFIn0="); //{"id":"321","op":"DELETE"} Indexer indexer = new Indexer(gateway, parser); indexer.handle(event); verify(gateway, atLeastOnce()).delete(anyString()); } @Test(expected = ResponseException.class) public void shouldThrowResponseException() throws IOException, InterruptedException { var gateway = mock(MerchantGateway.class); var parser = new GsonEventParserAdapter(); doThrow(ResponseException.class).when(gateway).upsert(anyString(), anyString()); Event event = new Event(); event.setMessageId("ID"); event.setPublishTime("TIMESTAMP"); event.setData("eyJpZCI6IjMyMSIsIm9wIjoiVVBTRVJUIn0="); //{"id":"321","op":"UPSERT"} Indexer indexer = new Indexer(gateway, parser); indexer.handle(event); } }