text stringlengths 10 2.72M |
|---|
package netistrar.clientapi.objects.domain.descriptor;
import netistrar.clientapi.objects.domain.DomainNameContact;
import java.util.Map;
/**
* Descriptor for a domain name update operation. This should be passed to the update operation on the Domains API.
*/
public class DomainNameUpdateDescriptor {
/**
* the array of domain names to be updated.
*/
private String[] domainNames;
/**
* A new owner contact to apply to all supplied domains. If this is supplied as null, no owner contact update will be performed.<br><br><b>NB: </b> Key changes to owner details for GTLDs will trigger a verification email to the owner of the domain before these changes will be applied. Once approved by the owner a 60 day transfer lock will be placed on the domain. If a verification has been triggered, it will be noted in the Transaction Element operation data for the update. Please see extra documentation in the <a href="object:Netistrar/WebServices/Common/Objects/Domain/DomainNameContact">DomainNameContact</a> object definition.
*/
private DomainNameContact ownerContact;
/**
* A new admin contact to apply to all supplied domains. If this is supplied as null, no admin contact update will be performed.
*/
private DomainNameContact adminContact;
/**
* A new admin contact to apply to all supplied domains. If this is supplied as null, no billing contact update will be performed.
*/
private DomainNameContact billingContact;
/**
* A new admin contact to apply to all supplied domains. If this is supplied as null, no technical contact update will be performed.
*/
private DomainNameContact technicalContact;
/**
* The array of nameservers to apply to the supplied domain names. If this is supplied as null, no nameserver update will be performed.
*/
private String[] nameservers;
/**
* When set to 1 or 0 this will set / unset respectively the locked status for all passed domains. If left unset no change will be made to the locked status for the domains.<br><br><b>NB:</b>It may not always be possible to unlock a domain if a mandatory lock has been applied such as after a create / transfer operation.
*/
private Boolean locked;
/**
* This should be set to one of the following values: <br><br><b>0</b> If limited details are to be published via the WHOIS system for all supplied domains according to Registry policy.<br><b>1</b> if the free Netistrar Privacy Proxy service will be used for all supplied domains.
*/
private Integer privacyProxy;
/**
* A boolean indicator as to whether the an attempt will be made to auto renew this domain using account payment methods (defaults to 0)
*/
private Boolean autoRenew;
/**
* An array of tags to add to the supplied domain names for organisational purposes.
*/
private String[] addTags;
/**
* An array of tags to remove from the supplied domain names for organisational purposes.
*/
private String[] removeTags;
/**
* Blank Constructor
*
*/
public DomainNameUpdateDescriptor(){
}
/**
* Updatable Constructor
*
* @param domainNames the domainNames
* @param ownerContact the ownerContact
* @param adminContact the adminContact
* @param billingContact the billingContact
* @param technicalContact the technicalContact
* @param nameservers the nameservers
* @param locked the locked
* @param privacyProxy the privacyProxy
* @param autoRenew the autoRenew
* @param addTags the addTags
* @param removeTags the removeTags
*/
public DomainNameUpdateDescriptor(String[] domainNames, DomainNameContact ownerContact, DomainNameContact adminContact, DomainNameContact billingContact, DomainNameContact technicalContact, String[] nameservers, Boolean locked, Integer privacyProxy, Boolean autoRenew, String[] addTags, String[] removeTags){
this.domainNames = domainNames;
this.ownerContact = ownerContact;
this.adminContact = adminContact;
this.billingContact = billingContact;
this.technicalContact = technicalContact;
this.nameservers = nameservers;
this.locked = locked;
this.privacyProxy = privacyProxy;
this.autoRenew = autoRenew;
this.addTags = addTags;
this.removeTags = removeTags;
}
/**
* Get the domainNames
*
* @return domainNames
*/
public String[] getDomainNames(){
return this.domainNames;
}
/**
* Set the domainNames
*
* @param domainNames the domainNames
* @return DomainNameUpdateDescriptor
*/
public DomainNameUpdateDescriptor setDomainNames(String[] domainNames){
this.domainNames = domainNames;
return this;
}
/**
* Get the ownerContact
*
* @return ownerContact
*/
public DomainNameContact getOwnerContact(){
return this.ownerContact;
}
/**
* Set the ownerContact
*
* @param ownerContact the ownerContact
* @return DomainNameUpdateDescriptor
*/
public DomainNameUpdateDescriptor setOwnerContact(DomainNameContact ownerContact){
this.ownerContact = ownerContact;
return this;
}
/**
* Get the adminContact
*
* @return adminContact
*/
public DomainNameContact getAdminContact(){
return this.adminContact;
}
/**
* Set the adminContact
*
* @param adminContact the adminContact
* @return DomainNameUpdateDescriptor
*/
public DomainNameUpdateDescriptor setAdminContact(DomainNameContact adminContact){
this.adminContact = adminContact;
return this;
}
/**
* Get the billingContact
*
* @return billingContact
*/
public DomainNameContact getBillingContact(){
return this.billingContact;
}
/**
* Set the billingContact
*
* @param billingContact the billingContact
* @return DomainNameUpdateDescriptor
*/
public DomainNameUpdateDescriptor setBillingContact(DomainNameContact billingContact){
this.billingContact = billingContact;
return this;
}
/**
* Get the technicalContact
*
* @return technicalContact
*/
public DomainNameContact getTechnicalContact(){
return this.technicalContact;
}
/**
* Set the technicalContact
*
* @param technicalContact the technicalContact
* @return DomainNameUpdateDescriptor
*/
public DomainNameUpdateDescriptor setTechnicalContact(DomainNameContact technicalContact){
this.technicalContact = technicalContact;
return this;
}
/**
* Get the nameservers
*
* @return nameservers
*/
public String[] getNameservers(){
return this.nameservers;
}
/**
* Set the nameservers
*
* @param nameservers the nameservers
* @return DomainNameUpdateDescriptor
*/
public DomainNameUpdateDescriptor setNameservers(String[] nameservers){
this.nameservers = nameservers;
return this;
}
/**
* Get the locked
*
* @return locked
*/
public Boolean getLocked(){
return this.locked;
}
/**
* Set the locked
*
* @param locked the locked
* @return DomainNameUpdateDescriptor
*/
public DomainNameUpdateDescriptor setLocked(Boolean locked){
this.locked = locked;
return this;
}
/**
* Get the privacyProxy
*
* @return privacyProxy
*/
public Integer getPrivacyProxy(){
return this.privacyProxy;
}
/**
* Set the privacyProxy
*
* @param privacyProxy the privacyProxy
* @return DomainNameUpdateDescriptor
*/
public DomainNameUpdateDescriptor setPrivacyProxy(Integer privacyProxy){
this.privacyProxy = privacyProxy;
return this;
}
/**
* Get the autoRenew
*
* @return autoRenew
*/
public Boolean getAutoRenew(){
return this.autoRenew;
}
/**
* Set the autoRenew
*
* @param autoRenew the autoRenew
* @return DomainNameUpdateDescriptor
*/
public DomainNameUpdateDescriptor setAutoRenew(Boolean autoRenew){
this.autoRenew = autoRenew;
return this;
}
/**
* Get the addTags
*
* @return addTags
*/
public String[] getAddTags(){
return this.addTags;
}
/**
* Set the addTags
*
* @param addTags the addTags
* @return DomainNameUpdateDescriptor
*/
public DomainNameUpdateDescriptor setAddTags(String[] addTags){
this.addTags = addTags;
return this;
}
/**
* Get the removeTags
*
* @return removeTags
*/
public String[] getRemoveTags(){
return this.removeTags;
}
/**
* Set the removeTags
*
* @param removeTags the removeTags
* @return DomainNameUpdateDescriptor
*/
public DomainNameUpdateDescriptor setRemoveTags(String[] removeTags){
this.removeTags = removeTags;
return this;
}
/**
* Overridden equals method for doing field based equals comparison.
*/
public boolean equals(Object otherObject) {
if (otherObject == this)
return true;
if (!(otherObject instanceof DomainNameUpdateDescriptor))
return false;
DomainNameUpdateDescriptor castObject = (DomainNameUpdateDescriptor)otherObject;
boolean equals = true;
equals = equals && ( (this.getDomainNames() == null && castObject.getDomainNames() == null) ||
(this.getDomainNames() != null && this.getDomainNames().equals(castObject.getDomainNames())));
equals = equals && ( (this.getOwnerContact() == null && castObject.getOwnerContact() == null) ||
(this.getOwnerContact() != null && this.getOwnerContact().equals(castObject.getOwnerContact())));
equals = equals && ( (this.getAdminContact() == null && castObject.getAdminContact() == null) ||
(this.getAdminContact() != null && this.getAdminContact().equals(castObject.getAdminContact())));
equals = equals && ( (this.getBillingContact() == null && castObject.getBillingContact() == null) ||
(this.getBillingContact() != null && this.getBillingContact().equals(castObject.getBillingContact())));
equals = equals && ( (this.getTechnicalContact() == null && castObject.getTechnicalContact() == null) ||
(this.getTechnicalContact() != null && this.getTechnicalContact().equals(castObject.getTechnicalContact())));
equals = equals && ( (this.getNameservers() == null && castObject.getNameservers() == null) ||
(this.getNameservers() != null && this.getNameservers().equals(castObject.getNameservers())));
equals = equals && ( (this.getLocked() == null && castObject.getLocked() == null) ||
(this.getLocked() != null && this.getLocked().equals(castObject.getLocked())));
equals = equals && ( (this.getPrivacyProxy() == null && castObject.getPrivacyProxy() == null) ||
(this.getPrivacyProxy() != null && this.getPrivacyProxy().equals(castObject.getPrivacyProxy())));
equals = equals && ( (this.getAutoRenew() == null && castObject.getAutoRenew() == null) ||
(this.getAutoRenew() != null && this.getAutoRenew().equals(castObject.getAutoRenew())));
equals = equals && ( (this.getAddTags() == null && castObject.getAddTags() == null) ||
(this.getAddTags() != null && this.getAddTags().equals(castObject.getAddTags())));
equals = equals && ( (this.getRemoveTags() == null && castObject.getRemoveTags() == null) ||
(this.getRemoveTags() != null && this.getRemoveTags().equals(castObject.getRemoveTags())));
return equals;
}
} |
package com.example.hante.newprojectsum.broadcast;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
/**
* 监测屏幕广播
* 接收系统广播事件,
* 屏幕在三种状态(开屏、锁屏、解锁)之间变换的时候,系统都会发送广播
*/
public class ScreenBroadcastReceiver extends BroadcastReceiver{
private static final String TAG = "ScreenBroadcastReceiver";
private String mAction = null;
@Override
public void onReceive (Context context, Intent intent) {
mAction = intent.getAction();
if(Intent.ACTION_SCREEN_ON.equals(mAction)){
// 开屏
} else if (Intent.ACTION_SCREEN_OFF.equals(mAction)){
// 锁屏
} else if (Intent.ACTION_USER_PRESENT.equals(mAction)){
// 解锁
}
}
}
|
package view;
import java.io.IOException;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.image.Image;
import javafx.scene.layout.AnchorPane;
import javafx.stage.Stage;
public class GUI extends Application {
private Stage primaryStage;
@Override
public void start(Stage primaryStage) {
// connect primary stage
this.primaryStage = primaryStage;
mainWindow();
}
// main window
public void mainWindow() {
try {
// view
FXMLLoader loader = new FXMLLoader(getClass().getResource("/view/login.fxml"));
AnchorPane pane = loader.load();
// scene on stage
Scene scene = new Scene(pane);
primaryStage.setScene(scene);
primaryStage.show();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
launch(args);
}
} |
package 数据结构.线性结构.堆栈;
/**
* Created by Yingjie.Lu on 2018/8/30.
*/
/**
* @Title: 链式存储_堆栈
* @Date: 2018/8/30 11:22
*/
public class MyLinkedStack{
private Node top=new Node(null);
private int size=0;
/**
* @Title: 定义一个节点
* @Date: 2018/8/30 13:29
*/
private class Node{
private Object data;
private Node last;//上一个节点
private Node next;//下一个节点
Node(Object o){
this.data=o;
}
}
public void push(Object o){
Node node=new Node(o);
if(size==0){
top=node;
}else {
node.last=top;//新来的元素的last要指向上一个元素
top=node;//然后将top指向新来的元素
}
size++;
}
public Object pop(){
if(size==0){
return null;
}
Node node=top;
top=top.last;//将top的last指向上一个节点
size--;
return node.data;
}
public boolean isEmpty(){
if(size==0){
return true;
}else{
return false;
}
}
public static void main(String[] args) {
MyLinkedStack myLinkedStack=new MyLinkedStack();
//压入10个元素
for(int i=0;i<10;i++){
myLinkedStack.push(i);
}
//弹出5个元素
for(int i=0;i<5;i++){
myLinkedStack.pop();
}
//再压入5个元素
for(int i=10;i<15;i++){
myLinkedStack.push(i);
}
//最后弹出所有元素
while(!myLinkedStack.isEmpty()){
System.out.println(myLinkedStack.pop());
}
}
}
|
package com.api.impl;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.persistence.TypedQuery;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import org.springframework.stereotype.Repository;
import com.api.domain.Metrics;
import com.api.domain.Pois;
import com.api.interf.MetricsCustomMethods;
@Repository
public class MetricsRepositoryImpl implements MetricsCustomMethods{
@PersistenceContext
private EntityManager em;
@Override
public Metrics getAllMetricsByPage(Integer page) {
Metrics retorno = new Metrics();
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<Metrics> criteriaQuery = cb.createQuery(Metrics.class);
Root<Metrics> ptable = criteriaQuery.from(Metrics.class);
criteriaQuery.select(ptable);
criteriaQuery.orderBy(cb.asc(ptable.get("id")));
TypedQuery<Metrics> query = em.createQuery(criteriaQuery);
int totalRows = query.getResultList().size();
retorno.setPageTotalLines(totalRows);
retorno.setPageNumber(page);
query.setFirstResult(page * 50 - 50);
query.setMaxResults(50);
List<Metrics> list = query.getResultList();
retorno.getListMetrics().addAll(list);
return retorno;
}
@Override
public Metrics getMetricsBySearch(String name, Double valmin, Double valmax, Integer page) {
Metrics retorno = new Metrics();
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<Metrics> criteriaQuery = cb.createQuery(Metrics.class);
Root<Metrics> ptable = criteriaQuery.from(Metrics.class);
criteriaQuery.select(ptable);
List<Predicate> predicates = new ArrayList<>();
if (name != null && !name.equals("null")) {
predicates.add(cb.like(ptable.get("metrics"), name));
if(valmin!= null && valmax != null) {
if (valmin > -1 && valmax > -1) {
predicates.add(cb.between(ptable.get("placa"), valmin, valmax));
}
}
criteriaQuery.select(ptable).where(predicates.toArray(new Predicate[predicates.size()]));
criteriaQuery.orderBy(cb.asc(ptable.get("id")));
TypedQuery<Metrics> query = em.createQuery(criteriaQuery);
List<Metrics> list = query.getResultList();
int totalRows = query.getResultList().size();
retorno.setPageTotalLines(totalRows);
retorno.setPageNumber(page);
query.setFirstResult(page * 50 - 50);
query.setMaxResults(50);
//List<Product> list = em.createQuery(criteriaQuery).getResultList();
retorno.getListMetrics().addAll(list);
return retorno;
}else {
if(valmin!= null &&valmax != null) {
if (valmin > -1 && valmax > -1) {
criteriaQuery.select(ptable).where(cb.between(ptable.get("data"), valmin, valmax));
criteriaQuery.orderBy(cb.asc(ptable.get("id")));
}
}
TypedQuery<Metrics> query = em.createQuery(criteriaQuery);
int totalRows = query.getResultList().size();
retorno.setPageTotalLines(totalRows);
retorno.setPageNumber(page);
query.setFirstResult(page * 50 - 50);
query.setMaxResults(50);
List<Metrics> list = query.getResultList();
retorno.getListMetrics().addAll(list);
return retorno;
}
}
@Override
public Metrics getMetricByList(String placa, Date valmin, Date valmax, Integer page) {
List<Metrics> metricsList = new ArrayList<Metrics>();
Metrics retorno = new Metrics();
StringBuilder sb = new StringBuilder();
sb.append("SELECT metrics FROM Metrics metrics WHERE 1=1 ");
if(placa !=null && !placa.equals("null")) {
sb.append(" AND placa = :placa ");
}
if(valmin !=null && !valmin.equals("null")) {
sb.append(" AND metrics.dataPosicao >= :valmin ");
}
if(valmax !=null && !valmax.equals("null")) {
sb.append(" AND metrics.dataPosicao <= :valmax ");
}
sb.append(" ORDER BY metrics.dataPosicao ");
TypedQuery<Metrics> query = em.createQuery(sb.toString(), Metrics.class);
if(placa !=null && !placa.equals("null")) {
query.setParameter("placa", placa);
}
if(valmin !=null && !valmin.equals("null")) {
query.setParameter("valmin", valmin);
}
if(valmax !=null && !valmax.equals("null")) {
query.setParameter("valmax", valmax);
}
int totalRows = query.getResultList().size();
retorno.setPageTotalLines(totalRows);
retorno.setPageNumber(page);
query.setFirstResult(page * 50 - 50);
query.setMaxResults(50);
metricsList = query.getResultList();
retorno.getListMetrics().addAll(metricsList);
return retorno;
}
}
|
package com.savvycom.gametank.Entity;
import com.savvycom.gametank.Common.Item;
import com.savvycom.gametank.Common.TypeItem;
import java.awt.*;
public class Bullet extends Item {
private Orientation orientation;
public Bullet(TypeItem typeItem, int x, int y, int size, Orientation orientation) {
super(typeItem, x, y, size);
this.orientation = orientation;
}
public void moveBullet() {
switch (orientation) {
case UP:
y -= 2;
break;
case LEFT:
x -= 2;
break;
case RIGHT:
x += 2;
break;
default:
y += 2;
break;
}
}
}
|
package com.tu.rocketmq.config;
import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.apache.rocketmq.spring.core.RocketMQPushConsumerLifecycleListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import java.util.List;
/**
* @Auther: tuyongjian
* @Date: 2020/4/21 16:26
* @Description:事务消费者
*
* 当实现 RocketMQPushConsumerLifecycleListener的prepareStart方法之后
* RocketMQListener 的onMessage方法就不会执行
*
*/
@Component
@RocketMQMessageListener(topic="testTrans",consumerGroup="testTrans" )
public class ConsumerTrans implements RocketMQListener<String> , RocketMQPushConsumerLifecycleListener {
private static final Logger logger = LoggerFactory.getLogger(ConsumerTrans.class);
@Override
public void onMessage(String s) {
logger.info("onMessage 开始消费事务消息---"+s);
}
@Override
public void prepareStart(DefaultMQPushConsumer defaultMQPushConsumer) {
logger.info("prepareStart 开始消费事务消息---");
defaultMQPushConsumer.registerMessageListener(new MessageListenerConcurrently() {
@Override
public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> msgs, ConsumeConcurrentlyContext context) {
try {
MessageExt messageExt = msgs.get(0);
logger.info("重试次数:" + messageExt.getReconsumeTimes());
// 注意可以在此处判断重试次数,实现入库插入,记录相关消息,进行下面的业务逻辑处理
if (messageExt.getReconsumeTimes() >= 3) {
return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
}
int i=1/0;
logger.info("接受到的消息:" + new String(messageExt.getBody()));
return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
} catch (Exception e) {
logger.info("消费出现异常:" + e.getMessage());
return ConsumeConcurrentlyStatus.RECONSUME_LATER;
}
}
});
}
}
|
package com.stk123.model.projection;
public interface IndustryProjection {
Integer getId();
String getName();
String getCode();
String getSource();
String getBkCode();
}
|
package com.amundi.tech.onsite.rest;
import com.amundi.tech.onsite.db.WorkingDayRepository;
import com.amundi.tech.onsite.model.usage.ParkingUsageImpl;
import com.amundi.tech.onsite.model.usage.RestaurantUsageImpl;
import com.amundi.tech.onsite.model.usage.SiteUsageImpl;
import com.amundi.tech.onsite.service.UsageService;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import java.time.LocalDate;
import java.util.List;
@Slf4j
@RestController
@RequestMapping("/api/usage")
@AllArgsConstructor
@Tag(name = "usage", description = "get sites & restaurants usages")
public class UsageResource {
private final UsageService usageService;
private final WorkingDayRepository workingDayRepository;
@GetMapping(path = "/site/{id}", produces = MediaType.APPLICATION_JSON_VALUE)
public List<SiteUsageImpl> usagesBySite(@PathVariable("id") long siteId,
@RequestParam(value = "startDate", required = false)
@DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate startDate,
@RequestParam(value = "limit", required = false) Integer limit) {
return (startDate!=null && limit !=null)?
usageService.getSiteUsages(startDate, LocalDate.from(startDate).plusDays(limit), siteId):
usageService.getSiteUsages(siteId);
}
@GetMapping(path = "/restaurant/{id}", produces = MediaType.APPLICATION_JSON_VALUE)
public List<RestaurantUsageImpl> usagesByRestaurant(@PathVariable("id") long restaurantId,
@RequestParam(value = "startDate", required = false)
@DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate startDate,
@RequestParam(value = "limit", required = false) Integer limit) {
return (startDate!=null && limit !=null)?
usageService.getRestaurantUsages(startDate, LocalDate.from(startDate).plusDays(limit), restaurantId):
usageService.getRestaurantUsages(restaurantId);
}
@GetMapping(path = "/parking/{id}", produces = MediaType.APPLICATION_JSON_VALUE)
public List<ParkingUsageImpl> usagesByParking(@PathVariable("id") long parkingId,
@RequestParam(value = "startDate", required = false)
@DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate startDate,
@RequestParam(value = "limit", required = false) Integer limit) {
return (startDate!=null && limit !=null)?
usageService.getParkingUsages(startDate, LocalDate.from(startDate).plusDays(limit), parkingId):
usageService.getParkingUsages(parkingId);
}
}
|
package com.example.instilingo;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Window;
public class Splash2 extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.splash2);
Thread timer2 = new Thread(){
public void run(){
try{
sleep(500);
}catch(InterruptedException e){
e.printStackTrace();
}finally{
try{
Class ourClass = Class.forName("com.example.instilingo.MainActivity");
Intent openMain = new Intent(Splash2.this , ourClass);
startActivity(openMain);
}catch(ClassNotFoundException e){
e.printStackTrace();
}
}
}
};
timer2.start();
}
@Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
finish();
}
}
|
package serve.serveup.views.search;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import java.util.ArrayList;
import java.util.List;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import serve.serveup.R;
import serve.serveup.dataholder.RestaurantInfo;
import serve.serveup.utils.Utils;
import serve.serveup.utils.adapters.DiscoveryRecyclerAdapter;
import serve.serveup.webservices.RestManagement;
public class SearchedRestaurantsActivity extends AppCompatActivity {
private RecyclerView searchRecyclerView;
private LinearLayoutManager layoutManager;
private DiscoveryRecyclerAdapter myAdapter;
private ImageView backToSearchIcon;
private ArrayList<RestaurantInfo> filteredRestaurants;
private LinearLayout progressBarLayout;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_searched_restaurants);
if(getIntent() != null) {
String lokacija = getIntent().getStringExtra("lokacija_text");
final String tipRestavracije = getIntent().getStringExtra("tip_restavracije_text");
filteredRestaurants = new ArrayList<>();
searchRecyclerView = findViewById(R.id.searchedRestaurantsRecycler);
backToSearchIcon = findViewById(R.id.backToSearchIcon);
layoutManager = new LinearLayoutManager(getApplicationContext());
progressBarLayout = findViewById(R.id.loadingSearchRestauransProgressBar);
progressBarLayout.setVisibility(View.VISIBLE);
RestManagement.getAllRestaurants(lokacija).
enqueue(new Callback<List<RestaurantInfo>>() {
@Override
public void onResponse(Call<List<RestaurantInfo>> call, Response<List<RestaurantInfo>> response) {
if (response.code() == 200) {
progressBarLayout.setVisibility(View.GONE);
for (RestaurantInfo restaurant : response.body()) {
if (restaurant.getTip().equalsIgnoreCase(tipRestavracije)) {
filteredRestaurants.add(restaurant);
}
}
myAdapter = new DiscoveryRecyclerAdapter(filteredRestaurants);
searchRecyclerView.setAdapter(myAdapter);
searchRecyclerView.setLayoutManager(layoutManager);
}
}
@Override
public void onFailure(Call<List<RestaurantInfo>> call, Throwable t) {
Utils.logInfo("api 'restaurant/home/' failed");
}
}
);
}
backToSearchIcon.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
finish();
}
});
}
}
|
package com.fznsys.xiyou_full_platform.controller.order;
import com.alibaba.fastjson.JSONObject;
import com.fznsys.xiyou_full_platform.pojo.Food;
import com.fznsys.xiyou_full_platform.pojo.Order;
import com.fznsys.xiyou_full_platform.pojo.User;
import com.fznsys.xiyou_full_platform.service.OrderService;
import com.fznsys.xiyou_full_platform.util.LayuiJSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;
@RestController
public class OrderController {
@Autowired
OrderService orderService;
@RequestMapping("/getorderlist")
public JSONObject getlist(){
List<Order> orders= orderService.getlistAll();
String a=null;
Double money = 0.0;
for (int i=0;i<orders.size();i++){
a=a+"+"+orders.get(i).getId();
}
System.out.println(a);
String date = orders.get(0).getDate();
String mark = orders.get(0).getMark();
JSONObject jsonObject=LayuiJSON.layuiJSON( orderService.getlistAll());
jsonObject.put("data",a);
jsonObject.put("money",money);
jsonObject.put("date",date);
jsonObject.put("mark",mark);
System.out.println(jsonObject);
return LayuiJSON.layuiJSON( orderService.getlistAll());
}
@RequestMapping("/getorderById")
public Order getlist(String id){
return orderService.getOrderById(id);
}
@RequestMapping("/insertorder")
public void insertorder(HttpServletRequest request,String data){
HttpSession session=request.getSession();
User user=(User)session.getAttribute("user");
System.out.println("sessonuser"+user);
//String orderid=orderService.insertorder(user.getId(),sum,mark);
String a[]=data.split("-");
for (int i=0;i<a.length;i++){
System.out.println(a[i]);
//orderService.insertorder(a[i]);
//orderService.insertorder();
}
}
@RequestMapping("/deleteorderById")
public List<Order> deleteorder(String id){
return orderService.deleteorder(id);
}
}
|
package lsinf1225.uclove;
/**
* Classe qui lie deux amis et leur chat ou juste une request d'ami si le chat vaut null
* Created by cariamole on 29.04.16.
*/
public class Friendship {
private String login1;
private String login2;
private String chat;
public Friendship(String login1, String login2, String chat){
this.login1=login1;
this.login2=login2;
this.chat=chat;
}
public Friendship(){}
public String getLogin1(){
return this.login1;
}
public String getLogin2(){
return this.login2;
}
public String getChat(){
return this.chat;
}
public void setLogin1(String s) {
this.login1 =s;
}
public void setLogin2(String s) {
this.login2 =s;
}
public void setChat(String s) {
this.chat=s;
}
}
|
/* $Id$ */
package djudge.acmcontester.server.interfaces;
import djudge.acmcontester.structures.SubmissionData;
public interface TeamSubmissionsNativeInterface
{
public SubmissionData[] getTeamSubmissions(String username, String password);
public boolean submitSolution(String username, String password, String problemID, String languageID, String sourceCode);
public boolean testSolution(String username, String password, String problemID, String languageID, String sourceCode);
}
|
/*
* Copyright 2002-2019 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.test.context.testng;
import jakarta.annotation.Resource;
import org.testng.annotations.AfterClass;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import org.springframework.beans.factory.BeanNameAware;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.testfixture.beans.Employee;
import org.springframework.beans.testfixture.beans.Pet;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.transaction.AfterTransaction;
import org.springframework.test.context.transaction.BeforeTransaction;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import static org.assertj.core.api.Assertions.assertThat;
import static org.springframework.test.transaction.TransactionAssert.assertThatTransaction;
import static org.springframework.transaction.support.TransactionSynchronizationManager.isActualTransactionActive;
/**
* Combined integration test for {@link AbstractTestNGSpringContextTests} and
* {@link AbstractTransactionalTestNGSpringContextTests}.
*
* @author Sam Brannen
* @since 2.5
*/
@ContextConfiguration
public class ConcreteTransactionalTestNGSpringContextTests extends AbstractTransactionalTestNGSpringContextTests
implements BeanNameAware, InitializingBean {
private static final String JANE = "jane";
private static final String SUE = "sue";
private static final String YODA = "yoda";
private static final int NUM_TESTS = 8;
private static final int NUM_TX_TESTS = 1;
private static int numSetUpCalls = 0;
private static int numSetUpCallsInTransaction = 0;
private static int numTearDownCalls = 0;
private static int numTearDownCallsInTransaction = 0;
private Employee employee;
@Autowired
private Pet pet;
@Autowired(required = false)
private Long nonrequiredLong;
@Resource
private String foo;
private String bar;
private String beanName;
private boolean beanInitialized = false;
@Autowired
private void setEmployee(Employee employee) {
this.employee = employee;
}
@Resource
private void setBar(String bar) {
this.bar = bar;
}
@Override
public void setBeanName(String beanName) {
this.beanName = beanName;
}
@Override
public void afterPropertiesSet() {
this.beanInitialized = true;
}
@BeforeClass
void beforeClass() {
numSetUpCalls = 0;
numSetUpCallsInTransaction = 0;
numTearDownCalls = 0;
numTearDownCallsInTransaction = 0;
}
@AfterClass
void afterClass() {
assertThat(numSetUpCalls).as("number of calls to setUp().").isEqualTo(NUM_TESTS);
assertThat(numSetUpCallsInTransaction).as("number of calls to setUp() within a transaction.").isEqualTo(NUM_TX_TESTS);
assertThat(numTearDownCalls).as("number of calls to tearDown().").isEqualTo(NUM_TESTS);
assertThat(numTearDownCallsInTransaction).as("number of calls to tearDown() within a transaction.").isEqualTo(NUM_TX_TESTS);
}
@BeforeMethod
void setUp() {
numSetUpCalls++;
if (isActualTransactionActive()) {
numSetUpCallsInTransaction++;
}
assertNumRowsInPersonTable((isActualTransactionActive() ? 2 : 1), "before a test method");
}
@AfterMethod
void tearDown() {
numTearDownCalls++;
if (isActualTransactionActive()) {
numTearDownCallsInTransaction++;
}
assertNumRowsInPersonTable((isActualTransactionActive() ? 4 : 1), "after a test method");
}
@BeforeTransaction
void beforeTransaction() {
assertNumRowsInPersonTable(1, "before a transactional test method");
assertAddPerson(YODA);
}
@AfterTransaction
void afterTransaction() {
assertThat(deletePerson(YODA)).as("Deleting yoda").isEqualTo(1);
assertNumRowsInPersonTable(1, "after a transactional test method");
}
@Test
@Transactional(propagation = Propagation.NOT_SUPPORTED)
public void verifyBeanNameSet() {
assertThatTransaction().isNotActive();
assertThat(this.beanName)
.as("The bean name of this test instance should have been set to the fully qualified class name due to BeanNameAware semantics.")
.startsWith(getClass().getName());
}
@Test
@Transactional(propagation = Propagation.NOT_SUPPORTED)
public void verifyApplicationContextSet() {
assertThatTransaction().isNotActive();
assertThat(super.applicationContext)
.as("The application context should have been set due to ApplicationContextAware semantics.")
.isNotNull();
Employee employeeBean = (Employee) super.applicationContext.getBean("employee");
assertThat(employeeBean.getName()).as("employee's name.").isEqualTo("John Smith");
}
@Test
@Transactional(propagation = Propagation.NOT_SUPPORTED)
public void verifyBeanInitialized() {
assertThatTransaction().isNotActive();
assertThat(beanInitialized)
.as("This test instance should have been initialized due to InitializingBean semantics.")
.isTrue();
}
@Test
@Transactional(propagation = Propagation.NOT_SUPPORTED)
public void verifyAnnotationAutowiredFields() {
assertThatTransaction().isNotActive();
assertThat(nonrequiredLong).as("The nonrequiredLong field should NOT have been autowired.").isNull();
assertThat(pet).as("The pet field should have been autowired.").isNotNull();
assertThat(pet.getName()).as("pet's name.").isEqualTo("Fido");
}
@Test
@Transactional(propagation = Propagation.NOT_SUPPORTED)
public void verifyAnnotationAutowiredMethods() {
assertThatTransaction().isNotActive();
assertThat(employee).as("The setEmployee() method should have been autowired.").isNotNull();
assertThat(employee.getName()).as("employee's name.").isEqualTo("John Smith");
}
@Test
@Transactional(propagation = Propagation.NOT_SUPPORTED)
public void verifyResourceAnnotationInjectedFields() {
assertThatTransaction().isNotActive();
assertThat(foo).as("The foo field should have been injected via @Resource.").isEqualTo("Foo");
}
@Test
@Transactional(propagation = Propagation.NOT_SUPPORTED)
public void verifyResourceAnnotationInjectedMethods() {
assertThatTransaction().isNotActive();
assertThat(bar).as("The setBar() method should have been injected via @Resource.").isEqualTo("Bar");
}
@Test
public void modifyTestDataWithinTransaction() {
assertThatTransaction().isActive();
assertAddPerson(JANE);
assertAddPerson(SUE);
assertNumRowsInPersonTable(4, "in modifyTestDataWithinTransaction()");
}
private int createPerson(String name) {
return jdbcTemplate.update("INSERT INTO person VALUES(?)", name);
}
private int deletePerson(String name) {
return jdbcTemplate.update("DELETE FROM person WHERE name=?", name);
}
private void assertNumRowsInPersonTable(int expectedNumRows, String testState) {
assertThat(countRowsInTable("person"))
.as("the number of rows in the person table (" + testState + ").")
.isEqualTo(expectedNumRows);
}
private void assertAddPerson(String name) {
assertThat(createPerson(name)).as("Adding '" + name + "'").isEqualTo(1);
}
}
|
/*
* ################################################################
*
* ProActive Parallel Suite(TM): The Java(TM) library for
* Parallel, Distributed, Multi-Core Computing for
* Enterprise Grids & Clouds
*
* Copyright (C) 1997-2011 INRIA/University of
* Nice-Sophia Antipolis/ActiveEon
* Contact: proactive@ow2.org or contact@activeeon.com
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License
* as published by the Free Software Foundation; version 3 of
* the License.
*
* This library 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
* Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
* USA
*
* If needed, contact us to obtain a release under GPL Version 2 or 3
* or a different license than the AGPL.
*
* Initial developer(s): The ProActive Team
* http://proactive.inria.fr/team_members.htm
* Contributor(s):
*
* ################################################################
* $$PROACTIVE_INITIAL_DEV$$
*/
package org.ow2.proactive.scheduler.util;
import java.io.File;
import java.net.URI;
import java.rmi.AlreadyBoundException;
import org.apache.commons.cli.AlreadySelectedException;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.GnuParser;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.MissingArgumentException;
import org.apache.commons.cli.MissingOptionException;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
import org.apache.commons.cli.Parser;
import org.apache.commons.cli.UnrecognizedOptionException;
import org.apache.log4j.Logger;
import org.objectweb.proactive.ActiveObjectCreationException;
import org.objectweb.proactive.core.remoteobject.AbstractRemoteObjectFactory;
import org.objectweb.proactive.core.remoteobject.exception.UnknownProtocolException;
import org.objectweb.proactive.core.util.log.ProActiveLogger;
import org.ow2.proactive.authentication.crypto.Credentials;
import org.ow2.proactive.resourcemanager.RMFactory;
import org.ow2.proactive.resourcemanager.authentication.RMAuthentication;
import org.ow2.proactive.resourcemanager.core.properties.PAResourceManagerProperties;
import org.ow2.proactive.resourcemanager.frontend.ResourceManager;
import org.ow2.proactive.resourcemanager.nodesource.NodeSource;
import org.ow2.proactive.resourcemanager.nodesource.infrastructure.LocalInfrastructure;
import org.ow2.proactive.resourcemanager.nodesource.policy.StaticPolicy;
import org.ow2.proactive.scheduler.SchedulerFactory;
import org.ow2.proactive.scheduler.common.SchedulerAuthenticationInterface;
import org.ow2.proactive.scheduler.common.util.SchedulerLoggers;
import org.ow2.proactive.scheduler.core.properties.PASchedulerProperties;
import org.ow2.proactive.scheduler.exception.AdminSchedulerException;
import org.ow2.proactive.utils.FileToBytesConverter;
import org.ow2.proactive.utils.Tools;
import org.ow2.proactive.utils.console.JVMPropertiesPreloader;
/**
* SchedulerStarter will start a new Scheduler on the local host connected to the given Resource Manager.<br>
* If no Resource Manager is specified, it will try first to connect a local one. If not succeed, it will create one on
* the localHost started with 4 local nodes.<br>
* The scheduling policy can be specified at startup. If not given, it will use the default one.<br>
* Start with -h option for more help.<br>
*
* @author The ProActive Team
* @since ProActive Scheduling 0.9
*/
public class SchedulerStarter {
//shows how to run the scheduler
private static Logger logger = ProActiveLogger.getLogger(SchedulerLoggers.CONSOLE);
private static Logger logger_dev = ProActiveLogger.getLogger(SchedulerDevLoggers.SCHEDULER);
public static final String defaultPolicy = PASchedulerProperties.SCHEDULER_DEFAULT_POLICY
.getValueAsString();
public static final int defaulNodesNumber = 4;
public static final int defaultNodesTimemout = 30 * 1000;
/**
* Start the scheduler creation process.
*
* @param args
*/
public static void main(String[] args) {
args = JVMPropertiesPreloader.overrideJVMProperties(args);
Options options = new Options();
Option help = new Option("h", "help", false, "to display this help");
help.setArgName("help");
help.setRequired(false);
options.addOption(help);
Option rmURL = new Option("u", "rmURL", true, "the resource manager URL (default localhost)");
rmURL.setArgName("rmURL");
rmURL.setRequired(false);
options.addOption(rmURL);
Option policy = new Option(
"p",
"policy",
true,
"the complete name of the scheduling policy to use (default org.ow2.proactive.scheduler.policy.PriorityPolicy)");
policy.setArgName("policy");
policy.setRequired(false);
options.addOption(policy);
boolean displayHelp = false;
try {
RMAuthentication rmAuth = null;
//get the path of the file
String rm = null;
String policyFullName = defaultPolicy;
Parser parser = new GnuParser();
CommandLine cmd = parser.parse(options, args);
if (cmd.hasOption("h"))
displayHelp = true;
else {
if (cmd.hasOption("p")) {
policyFullName = cmd.getOptionValue("p");
logger_dev.info("Used policy : " + policyFullName);
}
if (cmd.hasOption("u")) {
rm = cmd.getOptionValue("u");
logger_dev.info("RM URL : " + rm);
}
logger.info("Starting Scheduler, Please wait...");
boolean onlySched = false;
if (rm != null) {
try {
logger_dev.info("Trying to connect to Resource Manager on " + rm);
SchedulerFactory.tryJoinRM(new URI(rm));
onlySched = true;
} catch (Exception e) {
logger.error("ERROR while connecting the RM on " + rm + ", no RM found !");
System.exit(2);
}
} else {
rm = getLocalAdress();
URI uri = new URI(rm);
//trying to connect to a started local RM
logger_dev.info("Trying to connect to a started Resource Manager on " + uri);
try {
SchedulerFactory.tryJoinRM(uri);
logger
.info("Resource Manager URL was not specified, connection made to the local Resource Manager at " +
uri);
} catch (Exception e) {
logger.info("Resource Manager doesn't exist on the local host");
try {
//Starting a local RM using default deployment descriptor
RMFactory.setOsJavaProperty();
logger.info("Trying to start a local Resource Manager");
rmAuth = RMFactory.startLocal();
logger_dev
.info("Trying to connect the local Resource Manager using Scheduler identity");
//creating default node source
ResourceManager rman = rmAuth.login(Credentials
.getCredentials(PAResourceManagerProperties
.getAbsolutePath(PAResourceManagerProperties.RM_CREDS
.getValueAsString())));
//first im parameter is default rm url
byte[] creds = FileToBytesConverter.convertFileToByteArray(new File(
PAResourceManagerProperties
.getAbsolutePath(PAResourceManagerProperties.RM_CREDS
.getValueAsString())));
rman.createNodeSource(NodeSource.LOCAL_INFRASTRUCTURE_NAME,
LocalInfrastructure.class.getName(), new Object[] { "", creds,
defaulNodesNumber, defaultNodesTimemout, "" }, StaticPolicy.class
.getName(), null);
logger.info("Resource Manager created on " + rmAuth.getHostURL());
} catch (AlreadyBoundException abe) {
logger.error("Resource Manager already exists on local host", abe);
System.exit(4);
} catch (ActiveObjectCreationException aoce) {
logger.error("Unable to create local Resource Manager", aoce);
System.exit(5);
}
}
}
try {
if (!onlySched) {
logger.info("Starting scheduler...");
}
SchedulerAuthenticationInterface sai = SchedulerFactory.startLocal(new URI(rm),
policyFullName);
logger.info("Scheduler successfully created on " + sai.getHostURL());
} catch (AdminSchedulerException e) {
logger.warn("", e);
}
}
} catch (MissingArgumentException e) {
logger_dev.error("", e);
displayHelp = true;
} catch (MissingOptionException e) {
logger_dev.error("", e);
displayHelp = true;
} catch (UnrecognizedOptionException e) {
logger_dev.error("", e);
logger_dev.error("", e);
displayHelp = true;
} catch (AlreadySelectedException e) {
logger_dev.error("", e);
displayHelp = true;
} catch (ParseException e) {
logger_dev.error("", e);
displayHelp = true;
} catch (Exception e) {
logger.error("", e);
System.exit(6);
}
if (displayHelp) {
logger.info("");
HelpFormatter hf = new HelpFormatter();
hf.setWidth(120);
hf.printHelp("scheduler-start" + Tools.shellExtension(), options, true);
System.exit(10);
}
}
private static String getLocalAdress() {
try {
return AbstractRemoteObjectFactory.getDefaultRemoteObjectFactory().getBaseURI().toString();
} catch (UnknownProtocolException e) {
return "rmi://localhost/";
}
}
}
|
package com.fanfte.effectivejava.chapter2;
import java.math.BigDecimal;
public class MyCar implements Cloneable{
private String brand;
private long length;
private long weight;
private BigDecimal price;
@Override
protected MyCar clone() throws CloneNotSupportedException {
return (MyCar)super.clone();
}
public MyCar(String brand, long length, long weight, BigDecimal price) {
this.brand = brand;
this.length = length;
this.weight = weight;
this.price = price;
}
@Override
public String toString() {
return "brand " + this.brand + " length " + this.length
+" weight " + this.weight + " price " + this.price;
}
public static void main(String[] args) {
try {
MyCar clone = new MyCar("Ford", 2, (long) 33.40, BigDecimal.valueOf(20.01)).clone();
System.out.println(clone);
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
}
}
|
package interfaceex2;
public class DaoExample {
public static void dbWork(DataAccessObject dao) {
dao.select();
dao.insert();
dao.update();
dao.delete();
}
public static void main(String[] args) {
dbWork(new OracleData());
dbWork(new MySqlData());
}
}
|
package com.hyokeun.org.sessionmanager;
import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import com.hyokeun.org.model.Repository;
public class RepositoryManager extends HibernateUtils {
private static SessionFactory factory;
private static RepositoryManager instance = new RepositoryManager();
private static int count = 0;
public RepositoryManager() {
factory = HibernateUtils.createSessionFactory();
}
public static RepositoryManager getInstance() {
return instance;
}
public Session getSession() {
return factory.openSession();
}
public static void close() {
factory.close();
}
public Repository add(Repository repo) {
Session session = getSession();
session.beginTransaction();
session.saveOrUpdate(repo);
session.getTransaction().commit();
return repo;
}
public List<Repository> search(int start, int count) {
Session session = getSession();
session.beginTransaction();
List list = null;
try {
Query query = getSession().createQuery("from Repository");
if (start > 0)
query.setFirstResult(start);
if (count > 0)
query.setMaxResults(count);
list = query.list();
} catch (Exception e) {
System.out.println("Exception: " + e);
} finally {
session.close();
}
return list;
}
public int count() {
Session session = getSession();
int count = 0;
try {
count = ((Long) session.createQuery("select count(*) from Repository").uniqueResult()).intValue();
} catch (Exception e) {
System.out.println("Count Exception: " + e);
} finally {
session.close();
}
return count;
}
}
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package tableModel;
import java.util.ArrayList;
import java.util.List;
import javax.swing.table.AbstractTableModel;
/**
*
* @author Team Foufou
*/
public abstract class TableModel extends AbstractTableModel {
protected List<?> objects = new ArrayList();
protected String[] columnNames;
/**
* Data Constructor
* @param objects
* @param columnNames
*/
public TableModel(List<?> objects, String[] columnNames) {
this.objects = objects;
this.columnNames = columnNames;
}
@Override
public String getColumnName(int columnIndex) {
return columnNames[columnIndex];
}
@Override
public int getRowCount() {
return objects.size();
}
@Override
public int getColumnCount() {
return this.columnNames.length;
}
/**
* Retrieve the object that corresponds of a specific row
* @param rowIndex
* @return the object
*/
public Object getObjectAt(int rowIndex){
return this.objects.get(rowIndex);
}
/**
* Retrieve the value that corresponds to the given row and column
* @param rowIndex
* @param columnIndex
* @return the value
*/
public abstract Object getValueAt(int rowIndex, int columnIndex);
/**
* Retrieve the class that corresponds to the given column
* @param columnIndex
* @return the class
*/
public abstract Class<?> getColumnClass(int columnIndex);
}
|
package com.example.demo.service.impl;
import com.example.demo.dto.Data3DTO;
import com.example.demo.dto.PlayerDTO;
import com.example.demo.entity.Player;
import com.example.demo.mapper.PlayerMapper;
import com.example.demo.repository.CharacterRepository;
import com.example.demo.repository.PlayerRepository;
import com.example.demo.service.PlayerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.transaction.Transactional;
import java.util.ArrayList;
import java.util.List;
@Service
@Transactional
public class PlayerServiceImpl implements PlayerService {
private PlayerRepository playerRepository;
//private CharacterRepository characterRepository;
@Autowired
public PlayerServiceImpl(PlayerRepository playerRepository) {
this.playerRepository = playerRepository;
//this.characterRepository = characterRepository;
}
@Override
public void save(PlayerDTO playerDTO) {
Player player = PlayerMapper.getplayer(playerDTO);
player = playerRepository.save(player);
}
@Override
public List<PlayerDTO> findAll() {
List<PlayerDTO> playerDTOList = new ArrayList<>();
List<Player> playerList = playerRepository.findAll();
for (Player player : playerList) {
playerDTOList.add(PlayerMapper.getPlayerDTO(player));
}
return playerDTOList;
}
@Override
public PlayerDTO findById(Integer id) {
Player player = playerRepository.findById(id);
return PlayerMapper.getPlayerDTO(player);
}
@Override
public PlayerDTO findByName(String name) {
Player player = playerRepository.findByName(name);
return PlayerMapper.getPlayerDTO(player);
}
@Override
public void update(PlayerDTO playerDTO) {
Player player = PlayerMapper.getplayer(playerDTO);
player = playerRepository.update(player);
}
@Override
public void deleteById(Integer id) {
playerRepository.deleteById(id);
}
// @Override
// public List<Data3DTO> fetchData() {
// List<Data3DTO> playerDTOList = new ArrayList<>();
// playerDTOList = playerRepository.fetchData();
// return playerDTOList;
// }
}
|
package sample;
import javafx.animation.*;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.geometry.Point3D;
import javafx.scene.Group;
import javafx.scene.Node;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.AnchorPane;
import javafx.scene.shape.Arc;
import javafx.scene.transform.Rotate;
import javafx.stage.Stage;
import javafx.util.Duration;
import java.io.*;
import java.net.URL;
import java.sql.Time;
import java.util.*;
public class Controller implements Initializable {
@FXML
public Arc arc1, arc2, arc3, arc4, arc5, arc6, arc7, arc8;
@FXML
public Group circle1;
static GameData toBeLoaded;
static boolean isLoaded;
public void rotateArc(KeyEvent keyEvent) {
}
public void rotate(Node node) {
RotateTransition rotate1 = new RotateTransition();
rotate1.setAxis(Rotate.Z_AXIS);
rotate1.setByAngle(360);
rotate1.setCycleCount(Integer.MAX_VALUE);
rotate1.setDuration(Duration.millis(1200));
rotate1.setNode(node);
rotate1.play();
}
@Override
public void initialize(URL url, ResourceBundle resourceBundle) {
rotate(arc1);
rotate(arc2);
rotate(arc3);
rotate(arc4);
rotate(arc5);
rotate(arc6);
rotate(arc7);
rotate(arc8);
rotate(circle1);
// AnimationTimer a = new AnimationTimer() {
// @Override
// public void handle(long l) {
// if(isSaved.isSavedGame) {
// try {
// toBeSaved = (HashMap) ois.readObject();
// } catch (IOException e) {
// e.printStackTrace();
// } catch (ClassNotFoundException e) {
// e.printStackTrace();
// }
// toBeSaved.put(isSaved.nameOfSavedGame, newGame);
// isSaved.isSavedGame = false;
// try {
// oos.writeObject(toBeSaved);
// } catch (IOException e) {
// e.printStackTrace();
// }
// }
// }
// };
// a.start();
}
public void newGame(MouseEvent mouseEvent) {
isLoaded = false;
try {
Game newGame = new Game();
newGame.start(new Stage());
} catch (Exception e) {
e.printStackTrace();
}
}
public void exitGame(MouseEvent mouseEvent) throws IOException {
SavedGames.serialize();
System.exit(0);
}
public void loadGame(MouseEvent mouseEvent) {
// isLoaded = true;
// toBeLoaded = SavedGames.getGame("F");
// try {
// Game newGame = new Game();
// newGame.start(new Stage());
// } catch (Exception e) {
// e.printStackTrace();
// }
try {
Select_Game sg = new Select_Game();
sg.start(new Stage());
} catch (Exception e) {
e.printStackTrace();
}
}
}
class GameData implements Serializable {
int ballColor, score, posColorSwitcher;
ArrayList<Point_2D> ObstacleCoordinates;
ArrayList<Boolean> isVisible;
double angle;
Point_2D ballCoordinates;
GameData(double angle, int ballColor, int score, Point_2D ballCoordinates) {
this.angle = angle;
this.ballColor = ballColor;
this.score = score;
this.ballCoordinates = ballCoordinates;
ObstacleCoordinates = new ArrayList<>();
isVisible = new ArrayList<>();
}
public void addCoordinates(Point_2D coordinates) {
ObstacleCoordinates.add(coordinates);
}
public void addVisibility(boolean vis) {
isVisible.add(vis);
}
public int getBallColor() {
return ballColor;
}
public int getScore() {
return score;
}
public Point_2D getBallCoordinates() {
return ballCoordinates;
}
public int getPosColorSwitcher() {
return posColorSwitcher;
}
public Point_2D getObstacleCoordinates(int i) {
return ObstacleCoordinates.get(i);
}
public boolean getVisibility(int i) {
return isVisible.get(i);
}
public double getAngle() {
return angle;
}
}
class SavedGames {
private Map<String, GameData> savedGames;
private static SavedGames games;
static File file = new File("SavedGames.txt");
static FileOutputStream fos;
static ObjectOutputStream oos;
static {
try {
games = new SavedGames();
} catch (IOException e) {
e.printStackTrace();
}
try {
fos = new FileOutputStream(file);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
try {
oos = new ObjectOutputStream(fos);
} catch (IOException e) {
e.printStackTrace();
}
}
FileInputStream fis = new FileInputStream(file);
ObjectInputStream ois = new ObjectInputStream(fis);
private SavedGames() throws IOException {
try {
savedGames = (HashMap) ois.readObject();
}
catch (Exception e) {
savedGames = new HashMap<>();
}
}
public static void insert(String name, GameData gameData) {
games.savedGames.put(name, gameData);
}
public static GameData getGame(String name) {
return games.savedGames.get(name);
}
public static Map<String, GameData> getObject() {return games.savedGames;}
public static void serialize() throws IOException {
oos.writeObject(games.savedGames);
}
}
class sortByY implements Comparator<Group> {
@Override
public int compare(Group g, Group g1) {
return (int) (g1.getTranslateY() - g.getTranslateY());
}
} |
package com.xwolf.eop.common.pojo;
import com.alibaba.fastjson.JSONArray;
import com.github.pagehelper.*;
import com.xwolf.eop.common.pojo.easyui.PageRequest;
import com.xwolf.eop.common.pojo.easyui.PageResult;
import org.apache.commons.lang3.StringUtils;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
/**
* 分页
*/
public class PageHelper{
public static PageRequest getPage (HttpServletRequest request){
String size=request.getParameter("rows");
String start=request.getParameter("page");
PageRequest pageRequest =new PageRequest();
int s=pageRequest.getRows();
if(StringUtils.isNoneBlank(size)){
s=Integer.valueOf(size);
pageRequest.setRows(s);
}
int ps=pageRequest.getPage();
if(StringUtils.isNoneBlank(start)){
ps=Integer.valueOf(start);
pageRequest.setPage(ps);
}
int p=pageRequest.getPage();
int st=(p-1)*s;
com.github.pagehelper.PageHelper.startPage(st,pageRequest.getRows(),true);
return pageRequest;
}
public static <T> PageResult getListResult(List<T> list){
PageInfo page = new PageInfo(list);
JSONArray ary = new JSONArray();
for(T t :list){
ary.add(t);
}
PageResult result=new PageResult();
int size=list.size();
result.setTotal(0);
if ( size != 0){
result.setTotal(page.getTotal());
}
result.setRows(ary);
return result;
}
}
|
package com.pointinside.android.api.dao;
import android.database.Cursor;
import android.net.Uri;
import com.pointinside.android.api.content.Files;
import java.io.File;
public class PIFileDataCursor
extends AbstractDataCursor
{
private static final AbstractDataCursor.Creator<PIFileDataCursor> CREATOR = new AbstractDataCursor.Creator()
{
public PIFileDataCursor init(Cursor paramAnonymousCursor)
{
return new PIFileDataCursor(paramAnonymousCursor);
}
};
private int mColumnDateAdded;
private int mColumnDateModified;
private int mColumnDateToken;
private int mColumnDownloadId;
private int mColumnFileName;
private int mColumnFileScanned;
private int mColumnFileUri;
private int mColumnVenueUUID;
private PIFileDataCursor(Cursor paramCursor)
{
super(paramCursor);
this.mColumnVenueUUID = paramCursor.getColumnIndex("venue_uuid");
this.mColumnFileName = paramCursor.getColumnIndex("file_name");
this.mColumnDownloadId = paramCursor.getColumnIndex("download_id");
this.mColumnFileUri = paramCursor.getColumnIndex("file_uri");
this.mColumnDateAdded = paramCursor.getColumnIndex("date_added");
this.mColumnDateModified = paramCursor.getColumnIndex("date_modified");
this.mColumnDateToken = paramCursor.getColumnIndex("datetoken");
this.mColumnFileScanned = paramCursor.getColumnIndex("scanned");
}
public static PIFileDataCursor getInstance(Cursor paramCursor)
{
return (PIFileDataCursor)CREATOR.newInstance(paramCursor);
}
public static PIFileDataCursor getInstance(PIMapDataset paramPIMapDataset, Uri paramUri)
{
return (PIFileDataCursor)CREATOR.newInstance(paramPIMapDataset, paramUri);
}
public long getDateAdded()
{
return this.mCursor.getLong(this.mColumnDateAdded);
}
public long getDateModified()
{
return this.mCursor.getLong(this.mColumnDateModified);
}
public long getDateToken()
{
return this.mCursor.getLong(this.mColumnDateToken);
}
public long getDownloadId()
{
return this.mCursor.getLong(this.mColumnDownloadId);
}
public String getFileName()
{
return this.mCursor.getString(this.mColumnFileName);
}
public File getFilePath()
{
return new File(getFileUri());
}
public String getFileUri()
{
return this.mCursor.getString(this.mColumnFileUri);
}
public Uri getUri()
{
return Files.getFileUri(getId());
}
public String getVenueUUID()
{
return this.mCursor.getString(this.mColumnVenueUUID);
}
public boolean isFileScanned()
{
return this.mCursor.getInt(this.mColumnFileScanned) == 1;
}
}
/* Location: D:\xinghai\dex2jar\classes-dex2jar.jar
* Qualified Name: com.pointinside.android.api.dao.PIFileDataCursor
* JD-Core Version: 0.7.0.1
*/ |
package com.example.nimbus.controller;
import java.util.concurrent.atomic.AtomicInteger;
/**
* @ClassName: demo
* @Description: //TODO
* @Author: yongchen
* @Date: 2021/4/28 10:08
**/
public class demo {
/**
* 最大17bit的序列号是131071
*/
public final static int MAX_ORDER_NO = 131071;
/**
* 时间戳的掩码41bit
*/
public final static long TIME_CODE = Long.MAX_VALUE >>> 22;
/**
* 2015-01-01 00:00:00
* 1420041600210
* 因为我们的生成器可以使用69年,而我们想在这些时间里面,生成出来的id是逐渐自增的。
* 所以我这里指定了从什么时候开始使用id生成器。
*/
public final static long START_TIME = 1420041600210L;
/**
* 机器码 (0-31)
*/
public final long MACHINE_CODE;
/**
* 用于生成序列号
*/
public AtomicInteger orderNo;
public demo() {
if (1L < 0 || 1L > 31) {
throw new IllegalArgumentException("请注意,1、机器码在多台机器或应用间是不允许重复的!2、机器码取值仅仅在0~31之间");
}
this.MACHINE_CODE = 1L;
orderNo = new AtomicInteger(0);
}
public Long generateLong() {
//1.与基准时间对其,得到相对时间
long timeMillis = System.currentTimeMillis();
System.out.println(Long.toBinaryString(timeMillis));
long currentTimeMillis = timeMillis - START_TIME;
System.out.println("------------------------------------------");
System.out.println(Long.toBinaryString(currentTimeMillis));
//2.保留相对时间的低41bit
currentTimeMillis = currentTimeMillis & TIME_CODE;
System.out.println(Long.toBinaryString(TIME_CODE));
System.out.println(Long.toBinaryString(currentTimeMillis));
System.out.println("------------------------------------------");
//3、将1到41bit移到高位去 就是23~63。
currentTimeMillis = currentTimeMillis << 22;
System.out.println(Long.toBinaryString(currentTimeMillis));
/*
* 序列号自增1和获取
* 注意:先增加再取值。
*/
int orderNo = this.orderNo.incrementAndGet();
do {
if (orderNo > MAX_ORDER_NO) {
//如果超过了最大序列号 则重置为0
if (this.orderNo.compareAndSet(orderNo, 0)) {
//这里使用cas操作,所以不需要加锁 1、操作失败了 则表示别的线程已经更改了数据,则直接进行自增并获取则可以了
orderNo = 0;
} else {
//注意:先增加再取值。
orderNo = this.orderNo.incrementAndGet();
}
}
} while (orderNo > MAX_ORDER_NO);
//符号位(1)bit、时间戳(2~42)bit | 序列号(43~59)bit | 机器码(60~64)bit
System.out.println(Long.toBinaryString(orderNo << 5));
System.out.println(Long.toBinaryString(MACHINE_CODE));
return currentTimeMillis | (orderNo << 5) | MACHINE_CODE;
}
public static void main(String[] args) {
demo demo = new demo();
Long aLong = demo.generateLong();
System.out.println(Long.toBinaryString(aLong));
System.out.println(Long.toBinaryString(aLong).length());
System.out.println(aLong);
System.out.println(Long.toBinaryString(-1L));
System.out.println(Long.toBinaryString(-1L << 5));
System.out.println(Long.toBinaryString(-1L ^(-1L << 5)));
}
}
|
package com.nantian.foo.web;
import com.nantian.foo.web.util.dao.BaseDaoFactoryBean;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.transaction.annotation.EnableTransactionManagement;
@EnableTransactionManagement //启注解事务管理
@EnableJpaRepositories(basePackages = {"com.nantian.foo.web"},
repositoryFactoryBeanClass = BaseDaoFactoryBean.class)
@SpringBootApplication
public class FooWebApplication {
public static void main(String[] args) {
SpringApplication.run(FooWebApplication.class, args);
}
}
|
package exception_handling;
import java.util.Scanner;
public class Test2
{
public static void main(String[] args)
{
int i=1;
do
{
try
{
Scanner sc=new Scanner(System.in);
System.out.println("enter the first number");
int x=sc.nextInt();
System.out.println("enter the second number");
int y=sc.nextInt();
if(y==0) throw new ArithmeticException("hey stupid dont divide with zero");
int z=x/y;
System.out.println("z is "+z);
i=2;
}
catch (ArithmeticException e)
{
System.out.println(e.getMessage());
}
}while(i==1);
}
}
|
package fym;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.config.IniSecurityManagerFactory;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.Factory;
import org.junit.Test;
import java.util.Arrays;
/**
* Created by lenovo on 2020/1/14.
*/
public class LoginLogoutTest {
@Test
public void test() throws Exception{
//1、创建SecurityManager工厂,IniSecurityManagerFactory可以从ini文件中初始化SecurityManager环境
IniSecurityManagerFactory factory = new IniSecurityManagerFactory("classpath:shiro.ini");
//2、创建SecurityManager
SecurityManager securityManager = factory.getInstance();
//3、将securityManager设置到运行环境中
SecurityUtils.setSecurityManager(securityManager);
//4、在运行环境下创建Subject
Subject subject = SecurityUtils.getSubject();
//5、创建token令牌,记录用户认证的身份和凭证即账号和密码
UsernamePasswordToken token = new UsernamePasswordToken("zhangsan", "666");
try {
//6、登录,即身份验证
subject.login(token);
} catch (AuthenticationException e) {
//7、身份验证失败
e.printStackTrace();
}
//8、用户认证状态
Boolean isAuthenticated = subject.isAuthenticated();
System.out.println("用户认证状态:" + isAuthenticated);
//9、用户退出
subject.logout();
isAuthenticated = subject.isAuthenticated();
System.out.println("用户认证状态:" + isAuthenticated);
}
@Test
public void testRole() throws Exception {
//1、创建SecurityManager工厂,IniSecurityManagerFactory可以从ini文件中初始化SecurityManager环境
Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro-permission.ini");
//2、创建SecurityManager
SecurityManager securityManager = factory.getInstance();
//3、将securityManager设置到运行环境中
SecurityUtils.setSecurityManager(securityManager);
//4、在运行环境下创建Subject
Subject subject = SecurityUtils.getSubject();
//5、创建token令牌,记录用户认证的身份和凭证即账号和密码
UsernamePasswordToken token = new UsernamePasswordToken("zhangsan", "666");
try {
//6、登录,即身份验证
subject.login(token);
} catch (AuthenticationException e) {
//7、身份验证失败
e.printStackTrace();
}
//8、用户认证状态
Boolean isAuthenticated = subject.isAuthenticated();
System.out.println("用户认证状态:" + isAuthenticated);
//是否有某一个角色
System.out.println("用户是否拥有一个角色:" + subject.hasRole("role2"));
//是否有多个角色
System.out.println("用户是否拥有多个角色:" + subject.hasAllRoles(Arrays.asList("role1", "role2")));
//角色检查,如果没有就跑出异常
//subject.checkRole("role1");
//subject.checkRoles(Arrays.asList("role1", "role2"));
}
@Test
public void testPermission() throws Exception {
//1、创建SecurityManager工厂,IniSecurityManagerFactory可以从ini文件中初始化SecurityManager环境
Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro-permission.ini");
//2、创建SecurityManager
SecurityManager securityManager = factory.getInstance();
//3、将securityManager设置到运行环境中
SecurityUtils.setSecurityManager(securityManager);
//4、在运行环境下创建Subject
Subject subject = SecurityUtils.getSubject();
//5、创建token令牌,记录用户认证的身份和凭证即账号和密码
UsernamePasswordToken token = new UsernamePasswordToken("zhangsan", "666");
try {
//6、登录,即身份验证
subject.login(token);
} catch (AuthenticationException e) {
//7、身份验证失败
e.printStackTrace();
}
//8、用户认证状态
Boolean isAuthenticated = subject.isAuthenticated();
System.out.println("用户认证状态:" + isAuthenticated);
//是否有某一个权限
System.out.println("用户是否拥有一个权限:" + subject.isPermitted("user:create"));
//是否有多个权限
System.out.println("用户是否拥有多个权限:" + subject.isPermittedAll("user:create","user:update"));
//权限检查,如果没有就跑出异常
//subject.checkPermission("user:delete");
//subject.checkPermissions("user:create","user:delete");
//是否具备编号为1的user资源进行delete操作
//subject.checkPermission("user:delete:1");
}
}
|
/**
* Package contenant la classe principale d'une partie
*/
package jeu; |
/*
* 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.context.request;
import java.util.Locale;
import java.util.Map;
import jakarta.servlet.ServletRequest;
import jakarta.servlet.ServletResponse;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletRequestWrapper;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpServletResponseWrapper;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.web.multipart.MultipartRequest;
import org.springframework.web.testfixture.servlet.MockHttpServletRequest;
import org.springframework.web.testfixture.servlet.MockHttpServletResponse;
import static org.assertj.core.api.Assertions.assertThat;
/**
* @author Juergen Hoeller
*/
public class ServletWebRequestTests {
private MockHttpServletRequest servletRequest;
private MockHttpServletResponse servletResponse;
private ServletWebRequest request;
@BeforeEach
public void setup() {
servletRequest = new MockHttpServletRequest();
servletResponse = new MockHttpServletResponse();
request = new ServletWebRequest(servletRequest, servletResponse);
}
@Test
public void parameters() {
servletRequest.addParameter("param1", "value1");
servletRequest.addParameter("param2", "value2");
servletRequest.addParameter("param2", "value2a");
assertThat(request.getParameter("param1")).isEqualTo("value1");
assertThat(request.getParameterValues("param1")).hasSize(1);
assertThat(request.getParameterValues("param1")[0]).isEqualTo("value1");
assertThat(request.getParameter("param2")).isEqualTo("value2");
assertThat(request.getParameterValues("param2")).hasSize(2);
assertThat(request.getParameterValues("param2")[0]).isEqualTo("value2");
assertThat(request.getParameterValues("param2")[1]).isEqualTo("value2a");
Map<String, String[]> paramMap = request.getParameterMap();
assertThat(paramMap).hasSize(2);
assertThat(paramMap.get("param1")).hasSize(1);
assertThat(paramMap.get("param1")[0]).isEqualTo("value1");
assertThat(paramMap.get("param2")).hasSize(2);
assertThat(paramMap.get("param2")[0]).isEqualTo("value2");
assertThat(paramMap.get("param2")[1]).isEqualTo("value2a");
}
@Test
public void locale() {
servletRequest.addPreferredLocale(Locale.UK);
assertThat(request.getLocale()).isEqualTo(Locale.UK);
}
@Test
public void nativeRequest() {
assertThat(request.getNativeRequest()).isSameAs(servletRequest);
assertThat(request.getNativeRequest(ServletRequest.class)).isSameAs(servletRequest);
assertThat(request.getNativeRequest(HttpServletRequest.class)).isSameAs(servletRequest);
assertThat(request.getNativeRequest(MockHttpServletRequest.class)).isSameAs(servletRequest);
assertThat(request.getNativeRequest(MultipartRequest.class)).isNull();
assertThat(request.getNativeResponse()).isSameAs(servletResponse);
assertThat(request.getNativeResponse(ServletResponse.class)).isSameAs(servletResponse);
assertThat(request.getNativeResponse(HttpServletResponse.class)).isSameAs(servletResponse);
assertThat(request.getNativeResponse(MockHttpServletResponse.class)).isSameAs(servletResponse);
assertThat(request.getNativeResponse(MultipartRequest.class)).isNull();
}
@Test
public void decoratedNativeRequest() {
HttpServletRequest decoratedRequest = new HttpServletRequestWrapper(servletRequest);
HttpServletResponse decoratedResponse = new HttpServletResponseWrapper(servletResponse);
ServletWebRequest request = new ServletWebRequest(decoratedRequest, decoratedResponse);
assertThat(request.getNativeRequest()).isSameAs(decoratedRequest);
assertThat(request.getNativeRequest(ServletRequest.class)).isSameAs(decoratedRequest);
assertThat(request.getNativeRequest(HttpServletRequest.class)).isSameAs(decoratedRequest);
assertThat(request.getNativeRequest(MockHttpServletRequest.class)).isSameAs(servletRequest);
assertThat(request.getNativeRequest(MultipartRequest.class)).isNull();
assertThat(request.getNativeResponse()).isSameAs(decoratedResponse);
assertThat(request.getNativeResponse(ServletResponse.class)).isSameAs(decoratedResponse);
assertThat(request.getNativeResponse(HttpServletResponse.class)).isSameAs(decoratedResponse);
assertThat(request.getNativeResponse(MockHttpServletResponse.class)).isSameAs(servletResponse);
assertThat(request.getNativeResponse(MultipartRequest.class)).isNull();
}
}
|
package api.facultad;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface RepositorioFacultad extends JpaRepository<EntidadFacultad, Integer> {
}
|
package com.example.haoch.wocao;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomNavigationView;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.MenuItem;
import android.widget.FrameLayout;
public class MainActivity extends AppCompatActivity {
private BottomNavigationView mMainNav;
private FrameLayout mMainFrame;
private AccountFragment accountFragment;
private NearbyDeviceFragment nearbyDeviceFragment;
private BeaconFragment beaconFragment;
private SettingFragment settingFragment;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mMainFrame = (FrameLayout)findViewById(R.id.main_frame);
mMainNav = (BottomNavigationView)findViewById(R.id.main_nav);
// beaconFragment = new BeaconFragment();
// nearbyDeviceFragment = new NearbyDeviceFragment();
// settingFragment = new SettingFragment();
// accountFragment = new AccountFragment();
shiftFragment(1);
mMainNav.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
switch (item.getItemId()){
case R.id.nav_beacon:
// mMainNav.setItemBackgroundResource(R.color.colorPrimary);
shiftFragment(1);
return true;
case R.id.nav_nearby:
// mMainNav.setItemBackgroundResource(R.color.colorAccent);
shiftFragment(2);
return true;
case R.id.nav_setting:
// mMainNav.setItemBackgroundResource(R.color.colorPrimaryDark);
shiftFragment(3);
return true;
case R.id.nav_account:
// mMainNav.setItemBackgroundResource(R.color.colorAccent);
shiftFragment(4);
return true;
default:
return false;
}
}
});
}
private void shiftFragment(int index){
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
hideFragment(fragmentTransaction);
switch (index){
case 1:
if (beaconFragment!=null)
fragmentTransaction.show(beaconFragment);
else{
beaconFragment = new BeaconFragment();
fragmentTransaction.add(R.id.main_frame, beaconFragment);
}
break;
case 2:
if (nearbyDeviceFragment!=null)
fragmentTransaction.show(nearbyDeviceFragment);
else{
nearbyDeviceFragment = new NearbyDeviceFragment();
fragmentTransaction.add(R.id.main_frame, nearbyDeviceFragment);
}
break;
case 3:
if (settingFragment!=null)
fragmentTransaction.show(settingFragment);
else{
settingFragment = new SettingFragment();
fragmentTransaction.add(R.id.main_frame, settingFragment);
}
break;
case 4:
if (accountFragment!=null)
fragmentTransaction.show(accountFragment);
else{
accountFragment = new AccountFragment();
fragmentTransaction.add(R.id.main_frame, accountFragment);
}
break;
}
fragmentTransaction.commit();
}
private void hideFragment(FragmentTransaction fragmentTransaction) {
if (beaconFragment!=null){
fragmentTransaction.hide(beaconFragment);
}
if (nearbyDeviceFragment!=null){
fragmentTransaction.hide(nearbyDeviceFragment);
}
if (settingFragment!=null){
fragmentTransaction.hide(settingFragment);
}
if (accountFragment!=null){
fragmentTransaction.hide(accountFragment);
}
}
}
|
package modul.systemu.asi.backend.dao;
import modul.systemu.asi.frontend.model.Comment;
import modul.systemu.asi.frontend.model.Notification;
import modul.systemu.asi.frontend.model.Task;
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.List;
public interface CommentRepository extends JpaRepository<Comment, Long> {
List<Comment> findAllByNotificationOrderByDateAsc(Notification notification);
List<Comment> findAllByTaskOrderByDateAsc(Task task);
}
|
package shopping;
import java.util.Scanner;
public class Application {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
ShoppingList myList = new ShoppingList();
int input = 0;
do {
System.out.println("");
System.out.println("----- Shopping List -----");
System.out.println("1) Add an item to the list.");
System.out.println("2) Display list and total number of items.");
System.out.println("3) Exit.");
if (input == 1) {
myList.addItem();
} else if (input == 2) {
myList.displayItem();
}
} while (input != 3);
}
}
|
package com.project.blackjack;
public class Dealer {
private Hand dealersHand;
public Dealer() {
}
public void setDealersHand(Hand dealersHand) {
this.dealersHand = dealersHand;
}
public Hand getDealersHand() {
return dealersHand;
}
public String handToString() {
String output ="";
for(Card card : this.dealersHand.getHand()) {
output+=card.cardToString();
if(card.equals(this.dealersHand.getHand().get(this.dealersHand.getHand().size()-1))) {
}else {
output+=", ";
}
}
return output;
}
}
|
package junit_test;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.XPath;
import org.dom4j.io.SAXReader;
public class ItcastClassPathXmlApplicationContext {
private List<BeanDefinition> beanDefines = new ArrayList<BeanDefinition>();
private Map<String ,Object> sigletons = new HashMap<String,Object>();
public ItcastClassPathXmlApplicationContext(String filename){
this.readXml(filename);
this.instanceBeans();
this.injectObject();
}
private void injectObject(){
for(BeanDefinition beanDefinition:beanDefines){
Object bean = sigletons.get(beanDefinition.getId());
if(bean!=null){
try{
PropertyDescriptor[] ps = Introspector.getBeanInfo(bean.getClass()).getPropertyDescriptors();
for(PropertyDefinition propertyDefinition:beanDefinition.getPropertys()){
for(PropertyDescriptor propertyDesc:ps){
if(propertyDefinition.getName().equals(propertyDesc.getName())){
Method setter = propertyDesc.getWriteMethod();
if(setter!=null){
Object value = sigletons.get(propertyDesc.getName());
setter.setAccessible(true);
setter.invoke(bean, value);
}
break;
}
}
}
}
catch(Exception e){
e.printStackTrace();
}
}
}
}
private void instanceBeans(){
for(BeanDefinition beanDefinition:beanDefines){
try{
if(beanDefinition.getClassname()!=null&&!"".equals(beanDefinition.getClassname().trim()))
sigletons.put(beanDefinition.getId(),Class.forName(beanDefinition.getClassname()).newInstance());
}
catch(Exception e){
e.printStackTrace();
}
}
}
private void readXml(String filename){
SAXReader saxReader = new SAXReader();
Document document = null;
try{
URL xmlpath = this.getClass().getClassLoader().getResource(filename);
System.out.println("The file path is "+xmlpath);
document = saxReader.read(xmlpath);
//System.out.println(document==null);
Map<String,String> nsMap = new HashMap<String,String>();
nsMap.put("ns", "http://www.springframework.org/schema/beans");// 加入命名空间
XPath xsub = document.createXPath("//ns:beans/ns:bean");// 创建beans/bean查询路径
xsub.setNamespaceURIs(nsMap); // 设置命名空间*/
List<Element> beans = xsub.selectNodes(document); // 获取文档下所有bean节点m
for (Element element : beans) {
String id = element.attributeValue("id"); // 获取id属性值
String clazz = element.attributeValue("class"); // 获取class属性值
BeanDefinition beanDefine = new BeanDefinition(id, clazz);
beanDefines.add(beanDefine);
XPath propertysub = element.createXPath("ns:property");
propertysub.setNamespaceURIs(nsMap);
List<Element> propertys = propertysub.selectNodes(element);
for(Element property:propertys){
String proName = property.attributeValue("name");
String proRef = property.attributeValue("ref");
System.out.println(proName +"="+proRef);
PropertyDefinition ptDefi = new PropertyDefinition(proName,proRef);
beanDefine.getPropertys().add(ptDefi);
}
beanDefines.add(beanDefine);
System.out.println(id+"####"+clazz);
}
}
catch(Exception e){
e.printStackTrace();
}
}
public Object getBean(String beanName){
System.out.println(sigletons.get(beanName));
return this.sigletons.get(beanName);
}
}
|
package com.mx.cdmx.cacho.partnersample;
//we declare this class as final, no one can extend from this class
public final class Immutable {
private String carName;
Immutable(String name) {
this.carName = name;
}
public String getName() {
return carName;
}
//no setter
public static void main(String[] args) {
Immutable obj = new Immutable("Ferrari");
System.out.println(obj.getName());
// there is no way to update the Car's name after the object is created
// because this object is immutable.
// obj.setName("new Audi");
// System.out.println(obj.getName());
}
}
|
package com.demo.lib.av;
public interface DataSourceSink {
void onMeta(MediaMeta meta);
void onData(byte []data);
void onStop();
}
|
//program based on employee
import java.awt.*;
import java.applet.*;
public class emp extends Applet
{
String ename;
long ecode;
float basic,da,hra,ma,gross,itax,net;
public void init()
{
ename=(getParameter("c"));
ecode=Long.parseLong(getParameter("num1"));
basic=Float.valueOf(getParameter("num2"));
}//close of init()
public void start()
{
da=basic*20/100;
hra=basic*15/100;
ma=basic*10/100;
gross=basic+da+hra+ma;
itax=gross*(12.5F)/100;
net=gross-itax;
}//close of start()
public void paint(Graphics g)
{
g.drawString("*****************Sallery*******************",40,20);
g.drawString("Employee name :- "+String.valueOf(ename),40,30);
g.drawString("Employee code :- "+String.valueOf(ecode),40,40);
g.drawString("Basic pay in Rs :- "+String.valueOf(basic),40,50);
g.drawString("Dearness allowance in Rs :- "+String.valueOf(da),40,60);
g.drawString("House rent allowance in Rs :- "+String.valueOf(hra),40,70);
g.drawString("madical allowance in Rs :- "+String.valueOf(ma),40,80);
g.drawString("=======================================",40,90);
g.drawString("Gross salary in Rs :- "+String.valueOf(gross),40,100);
g.drawString("Incometax deduction in Rs :- "+String.valueOf(itax),40,110);
g.drawString("=======================================",40,120);
g.drawString("Net Sallery in Rs:- "+String.valueOf(net),40,130);
}//close of paint()
}//close of class
|
import java.util.Scanner;
/*
*
*/
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String input = sc.nextLine();
//input = input.toLowerCase();
System.out.println(input.replaceAll("(?iu)\\bбяка\\b", " - вырезано цензурой!"));
}
}
|
package org.testinfected.petstore.controllers;
import org.testinfected.petstore.billing.Address;
import org.testinfected.petstore.billing.CreditCardDetails;
import org.testinfected.petstore.order.OrderNumber;
import org.testinfected.petstore.order.SalesAssistant;
import org.testinfected.molecule.Application;
import org.testinfected.molecule.Request;
import org.testinfected.molecule.Response;
import static org.testinfected.petstore.billing.CreditCardType.valueOf;
public class PlaceOrder implements Application {
private final SalesAssistant salesAssistant;
public PlaceOrder(SalesAssistant salesAssistant) {
this.salesAssistant = salesAssistant;
}
public void handle(Request request, Response response) throws Exception {
OrderNumber orderNumber = salesAssistant.placeOrder(readPaymentDetailsFrom(request));
response.redirectTo("/orders/" + orderNumber.getNumber());
}
private CreditCardDetails readPaymentDetailsFrom(Request request) {
return new CreditCardDetails(
valueOf(request.parameter("card-type")),
request.parameter("card-number"),
request.parameter("expiry-date"),
new Address(
request.parameter("first-name"),
request.parameter("last-name"),
request.parameter("email")));
}
}
|
package com.group.etoko.model;
import androidx.annotation.NonNull;
import androidx.room.Entity;
import androidx.room.PrimaryKey;
@Entity
public class Cart {
@PrimaryKey(autoGenerate = true)
@NonNull
private int id;
@NonNull
private String productId;
@NonNull
private double productCount;
@NonNull
public int getId() {
return id;
}
@NonNull
public String getProductId() {
return productId;
}
public int getProductCount() {
return (int) productCount;
}
public void setProductCount(double productCount) {
this.productCount = productCount;
}
public void setProductId(@NonNull String productId) {
this.productId = productId;
}
public void setId(@NonNull int id) {
this.id = id;
}
}
|
/*
* Watr. Android application
* Copyright (c) 2020 Linus Willner, Panu Eronen and Markus Hartikainen.
* Licensed under the MIT license.
*/
package com.watr.app.ui.pages;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import com.watr.app.R;
import com.watr.app.ui.activities.AppSettingsActivity;
import com.watr.app.ui.activities.UserProfileSettingsActivity;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import lombok.NoArgsConstructor;
import lombok.val;
/**
* Settings page. All functionality specific to the settings page goes here.
*
* @author panueronen
* @version 1.0.0
*/
@NoArgsConstructor
public class SettingsPage extends Fragment {
private List<String> settings = new ArrayList<>();
private View view;
@Override
public View onCreateView(
LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_settings, container, false);
}
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
settings.add("Application settings");
settings.add("Edit user profile");
this.view = view;
ListView settingsListView = view.findViewById(R.id.settingsList);
// TODO: Optimise items with HashMap
val adapter =
new ArrayAdapter<>(
Objects.requireNonNull(getContext()), android.R.layout.simple_list_item_1, settings);
settingsListView.setAdapter(adapter);
settingsListView.setOnItemClickListener(
(parent, view1, position, id) -> {
val context = getContext();
Intent nextActivity;
switch (settings.get(position)) {
case "Application settings":
nextActivity = new Intent(context, AppSettingsActivity.class);
break;
case "Edit user profile":
nextActivity = new Intent(context, UserProfileSettingsActivity.class);
break;
default:
throw new ActivityNotFoundException(
String.format(
"Activity for settings field %s not found", settings.get(position)));
}
startActivity(nextActivity);
});
}
}
|
package auton.scripts;
import java.util.ArrayList;
import auton.AutonCommand;
import auton.usused.PowerTurnTestCommand;
public class PowerTurnTestScript extends AutonScript { //script to run a test for turning, not currently in use
private static PowerTurnTestScript blank;
private ArrayList<AutonCommand> script = new ArrayList<AutonCommand>(){
@Override
public int indexOf(Object o){
if (o == null) {
for (int i = 0; i < script.size(); i++)
if (script.get(i) == null)
return i;
} else {
for (int i = 0; i < script.size(); i++)
if (script.get(i).equals(o))
return i;
}
return -1;
}
};
private PowerTurnTestScript(){
script.add(new PowerTurnTestCommand("name"));
}
public static PowerTurnTestScript getInstance(){
if(blank == null)
blank = new PowerTurnTestScript();
return blank;
}
@Override
public ArrayList<AutonCommand> getScript() {
return script;
}
}
|
package hmo.flightroute.domain.exception;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
public class InternalErrorException extends FlightRouteException {
public InternalErrorException() {}
public InternalErrorException(String developerMessage) {
this(developerMessage, null, null);
}
public InternalErrorException(String developerMessage, String userMessage) {
this(developerMessage, userMessage, null);
}
public InternalErrorException(String developerMessage, String userMessage, Throwable cause) {
super(developerMessage, userMessage, cause);
}
}
|
package control.rewardSystem.payJudgerAspect;
import java.awt.event.ActionEvent;
import control.DynamicSystem;
import control.rewardSystem.RewardControl;
import model.data.employeeData.rewardEmployeeData.PayJudgerData;
import view.insuranceSystemView.rewardView.payJudger.PayJudgerTaskSelectView;
import view.panel.BasicPanel;
public class PayJudgerTaskSelectControl extends RewardControl {
// Association
private PayJudgerData user;
// Constructor
public PayJudgerTaskSelectControl(PayJudgerData user) {this.user=user;}
@Override
public BasicPanel getView() {return new PayJudgerTaskSelectView (this.user, this.actionListener, this.rewardDataList);}
@Override
public DynamicSystem processEvent(ActionEvent e) {
if(e.getActionCommand().equals("")) {return null;}
return new ShowAccInvestInfoForPJControl(this.user, Integer.parseInt(e.getActionCommand()));
}
}
|
package hu.hevi.timeline.api.model;
import org.springframework.data.mongodb.core.mapping.Document;
@Document(collection = "attachment")
public class Attachment {
}
|
/*
import javafx.animation.AnimationTimer;
import javafx.concurrent.Task;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.canvas.Canvas;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextField;
import javafx.scene.layout.BorderPane;
import javafx.scene.paint.Color;
import java.net.URL;
import java.util.Random;
import java.util.ResourceBundle;
*/
/**
* Created by lqsch on 2017-10-01.
*//*
public class Controller implements Initializable {
@FXML
public TextField init;
@FXML
public TextField death;
@FXML
public TextField duration;
@FXML
public TextField infection;
@FXML
public TextField population;
@FXML
public TextArea outputBox;
@FXML
public BorderPane background;
public GraphicsContext gc;
public int maxY;
public int maxX;
public boolean Xover;
public boolean Yover;
public int initInt;
public int counter;
Task<Boolean>[][] mapping;
boolean[][] index;
Canvas display;
int[][] mouseRec;
//probability for each cell
Task<Integer[]> cell (int x, int y){
Random rand = new Random();
double test = rand.nextDouble();
if(test < Double.parseDouble(infection.getText())){
updateCanvas(x, y);
active(x, y);
return null;
}else{
cell(x,y);
}
updateCanvas(x, y);
active(x, y);
return null;//infected
}
private AnimationTimer timer;
@FXML
public void start(ActionEvent actionEvent){
int populationInt= Integer.parseInt(population.getText());
if (populationInt < 74 * 80) {
maxX = (int) Math.floor(Math.sqrt(populationInt));
maxY = populationInt / maxX;
display=new Canvas(maxX*10,maxY*10);
display.setId("display");
gc = display.getGraphicsContext2D();
background.setCenter(display);
mapping = new Task[maxX][maxY];
index =new boolean[maxX][maxY];
} else {
outputBox.setText("Population size is too big. it should be less that 70*77 ");
return;
}
int initInt= Integer.parseInt(init.getText());
mouseRec= new int[initInt][2];
display.setOnMouseClicked(event -> {
int xAxis=(int) Math.floor(event.getX());
int yAxis=(int) Math.floor(event.getY());
updateCanvas(xAxis,yAxis);
mouseRec[counter][0]=xAxis/10*10;
mouseRec[counter][1]=yAxis/10*10;
counter++;
if (counter==initInt) {
display.setOnMouseClicked(null);
for (int i = 0; i < counter; i++) {
active(mouseRec[i][0],mouseRec[i][1]);
}
};
});
//inital
}
public void active(int x,int y) {
int testCounter =0;
int loopY = y/10 - 1;
int loopX = x/10 - 1;
final int limitX=loopX+2;
final int limitY=loopY+2;
//loop though the cell (8 of them) around the current active cell
Thread myThreads[] = new Thread[8];
while (loopY <= limitY) {
loopX=limitX-2;
while (loopX <= limitX) {
if (index[loopX][loopY] != true){
Task<Integer[]> currentT = cell(loopX*10,loopY*10);
myThreads[testCounter] = new Thread(currentT);
myThreads[testCounter].start();
*/
/*currentT.valueProperty().addListener((observable, oldValue, newValue) -> {
if (newValue != null) {
if (newValue) {
updateCanvas(finalLoopX , finalLoopY );
active(finalLoopX , finalLoopY );
}
System.out.println("Result for cell "+finalLoopX+", "+finalLoopY+" at coordinate "+finalLoopX*10+", "+finalLoopY*10 +" is :"+ newValue);
}
});*//*
}
testCounter++;
loopX++;
}
loopY++;
}
for(testCounter=0;testCounter<myThreads.length;testCounter++){
try {
myThreads[testCounter].join();
}catch (Exception e){
System.out.println(e);
}
}
System.out.println("active has looped "+ testCounter+" times");
*/
/* final Boolean[] result = new Boolean[1];
int finalLoopX = loopX;
int finalLoopY = loopY;
currentT.setOnSucceeded(new EventHandler<WorkerStateEvent>() {
@Override
public void handle(WorkerStateEvent t) {
result[0] = currentT.getValue();
if (result[0]) {
updateCanvas(finalLoopX*10, finalLoopY*10);
}
}
});*//*
}
public void updateCanvas(int x,int y){
final int xReal = x ;
final int yReal = y ;
gc.setFill(Color.RED);
gc.fillRect(xReal, yReal, 10, 10);
index[x/10][y/10]=true;
}
@Override
public void initialize(URL location, ResourceBundle resources) {
counter = 0;
Xover = false;
Yover = false;
}
}*/
|
package com.pelephone_mobile.songwaiting.ui.fragments;
import android.graphics.Typeface;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import com.pelephone_mobile.R;
import com.pelephone_mobile.songwaiting.global.SWGlobal;
import com.pelephone_mobile.songwaiting.service.SWService;
import com.pelephone_mobile.songwaiting.service.interfaces.ISWServiceResponceListener;
import com.pelephone_mobile.songwaiting.service.interfaces.ISWShareSongFacebookListener;
import com.pelephone_mobile.songwaiting.service.pojos.Pojo;
import com.pelephone_mobile.songwaiting.service.pojos.Song;
import com.pelephone_mobile.songwaiting.service.pojos.Songs;
import com.pelephone_mobile.songwaiting.ui.adapters.SWEndlessAdapter;
import com.pelephone_mobile.songwaiting.ui.adapters.SWSongAdapter;
import com.pelephone_mobile.songwaiting.utils.SWLogger;
import com.pelephone_mobile.songwaiting.utils.SWMediaPlayer;
import com.facebook.Session;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import java.util.ArrayList;
import java.util.List;
public class SongsListFragment extends SWBaseWithMenu {
private int categoryId;
private int subCategoryId;
private String subCategoryName;
private static final String tag = "SongsListFragment";
private ListView mLvSongList;
private ProgressBar mListLoading;
private boolean mIsWithBackButton = false;
private ImageView mImageArtist;
public boolean ismIsWithBackButton() {
return mIsWithBackButton;
}
public void setmIsWithBackButton(boolean mIsWithBackButton) {
this.mIsWithBackButton = mIsWithBackButton;
}
public static SongsListFragment getInstance(int categoryId,
int subCategoryId, String subCategoryName) {
SongsListFragment songsListFragment = new SongsListFragment();
songsListFragment.setCategoryId(categoryId);
songsListFragment.setSubCategoryId(subCategoryId);
songsListFragment.setSubCategoryName(subCategoryName);
Log.d(tag, "categoryId:" + categoryId + "subCategoryId:"
+ subCategoryId);
return songsListFragment;
}
@Override
public void onServiceConnected(SWService service) {
super.onServiceConnected(service);
Log.d(tag, "categoryId:" + categoryId + "subCategoryId:"
+ subCategoryId);
initSongList();
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
mContentView = inflater.inflate(R.layout.songs_list_layout, container,
false);
if (mContentView != null) {
mListLoading = (ProgressBar) mContentView
.findViewById(R.id.progressBarListLoad);
mTransperent = (FrameLayout) mContentView
.findViewById(R.id.transperentView);
TextView tvTitle = (TextView) mContentView
.findViewById(R.id.tvTitle);
tvTitle.setText(subCategoryName);
Typeface fontBold = Typeface.createFromAsset(SWGlobal
.getAppResources().getAssets(), "arialbd.ttf");
tvTitle.setTypeface(fontBold);
mLvSongList = (ListView) mContentView.findViewById(R.id.lvSongs);
mImageArtist = (ImageView) mContentView
.findViewById(R.id.ivPicture);
if (!mIsWithArtistPic) {
mImageArtist.setVisibility(View.GONE);
// ImageView frame = (ImageView) mContentView
// .findViewById(R.id.frame);
// frame.setVisibility(View.GONE);
} else {
ImageButton btnMenu = (ImageButton) mContentView
.findViewById(R.id.ibMenu);
ImageButton btnSearh = (ImageButton) mContentView
.findViewById(R.id.ibSearch);
btnSearh.setImageResource(R.drawable.selector_bcak);
btnSearh.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
SWMediaPlayer.getInstance().killMediaPlayer();
getActivity().getSupportFragmentManager()
.popBackStack();
}
});
btnMenu.setVisibility(View.INVISIBLE);
}
ImageView ibBack = (ImageView) mContentView
.findViewById(R.id.ibBackGray);
if (mIsWithBackButton) {
ibBack.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
SWMediaPlayer.getInstance().killMediaPlayer();
getActivity().getSupportFragmentManager()
.popBackStack();
}
});
} else {
ibBack.setVisibility(View.GONE);
}
return mContentView;
}
return super.onCreateView(inflater, container, savedInstanceState);
}
public void setCategoryId(int categoryId) {
this.categoryId = categoryId;
}
public void setSubCategoryId(int subCategoryId) {
this.subCategoryId = subCategoryId;
}
public void setSubCategoryName(String subCategoryName) {
this.subCategoryName = subCategoryName;
}
private void initSongList() {
if (mSWService != null) {
if (getActivity() != null) {
mSWService.getSongsController().getSongsBySubCategory(
new ISWServiceResponceListener() {
@Override
public void onResponce(Pojo data) {
// TODO Auto-generated method stub
if (data instanceof Songs) {
for (Song s : ((Songs) data).allSongs) {
SWLogger.print(tag, "Song id : "
+ s.songId + ", Song name : "
+ s.songName + ", picture : "
+ s.picture);
}
final List<Pojo> list = new ArrayList<Pojo>();
list.addAll(((Songs) data).allSongs);
SWGlobal global = SWGlobal.sharedInstance();
if (getActivity() != null) {
SWSongAdapter songAdapter = new SWSongAdapter(
getActivity(),
list,
categoryId,
subCategoryId,
mSWService,
global.getmToken(),
global.getmPhone(),
new ISWShareSongFacebookListener() {
@Override
public void onShareSongFacebook(
Song song) {
Session session = Session
.getActiveSession();
if (!session.isOpened()) {
mIsFirtTimePublish = true;
}
logInFacebook(song);
}
});
final SWEndlessAdapter endlessAdapter = new SWEndlessAdapter(
getActivity(), songAdapter,
mSWService.getSongsController());
getActivity().runOnUiThread(
new Runnable() {
@Override
public void run() {
mListLoading
.setVisibility(View.INVISIBLE);
mLvSongList
.setAdapter(endlessAdapter);
if (mIsWithArtistPic) {
DisplayImageOptions options = new DisplayImageOptions.Builder()
.cacheInMemory().cacheOnDisc().build();
ImageLoader imageLoader = ImageLoader.getInstance();
imageLoader.init(ImageLoaderConfiguration.createDefault(getActivity()));
imageLoader.displayImage(
((Song) list
.get(0)).picture, (ImageView) mContentView
.findViewById(R.id.ivPicture));
//
// UrlImageViewHelper.setUrlDrawable(
// (ImageView) mContentView
// .findViewById(R.id.ivPicture),
// ((Song) list
// .getAndParse(0)).picture);
}
}
});
}
}
}
@Override
public void onError(ErrorsTypes error) {
// TODO Auto-generated method stub
if (error != null) {
switch (error) {
case CONNECTION_ERROR:
SWLogger.printError(tag,
" getSongsBySubCategory - CONNECTION_ERROR ");
break;
case DB_ERROR:
SWLogger.printError(tag,
" getSongsBySubCategory - DB_ERROR ");
break;
case JSON_PARSE_ERROR:
SWLogger.printError(tag,
" getSongsBySubCategory - JSON_PARSE_ERROR ");
break;
case IODATA_ERROR:
SWLogger.printError(tag,
" getSongsBySubCategory - IODATA_ERROR ");
break;
default:
SWLogger.printError(tag,
" getSongsBySubCategory - UNKNOWN_ERROR ");
break;
}
} else {
SWLogger.printError(tag,
" getSongsBySubCategory - UNKNOWN_ERROR ");
}
}
}, categoryId, subCategoryId);
} else {
}
}
}
@Override
public void onPause() {
SWMediaPlayer.getInstance().killMediaPlayer();
super.onPause();
}
}
|
/**
*
*/
package com.android.aid;
import java.util.ArrayList;
import org.apache.http.NameValuePair;
import android.content.Context;
/**
* @author wangpeifeng
*
*/
public class ReqAppubOpenSync extends ServiceActionDelegate {
public ReqAppubOpenSync(Context context, String requestAction) {
super(context, requestAction);
// TODO Auto-generated constructor stub
}
private class WebApi extends WebServiceApi{
public WebApi(Context context, String web_api_pref_key,
HttpPostListener listener) {
super(context, web_api_pref_key, listener);
// TODO Auto-generated constructor stub
}
@Override
public void postApi() {
// TODO Auto-generated method stub
ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();
this.postApi(params);
}
@Override
public void getApi() {
// TODO Auto-generated method stub
ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();
this.getApi(params);
}
}
private HttpPostListener lsrHttpPost = new HttpPostListener(context){
@Override
public void OnHttpPostResponse(String[] response) {
// TODO Auto-generated method stub
if(WebServiceApi.isRespSuccess(response[HttpListener.HTTP_RESP])){
new AppubPreferences(context).openAppubSwitch();
}
}
};
@Override
public void action() {
// TODO Auto-generated method stub
if(!new AppubPreferences(context).isAppubOpen()){
new WebApi(this.getContext(),
WebServicePreferences.PREF_KEY_API_APPUB_OPEN,
this.lsrHttpPost).postApi();
}
}
}
|
package com.tenjava.entries.MOMOTHEREAL.t3.timing;
import com.tenjava.entries.MOMOTHEREAL.t3.TenJava;
import org.bukkit.*;
import org.bukkit.entity.Player;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
/**
* Copyright MOMOTHEREAL (c) 2014.
*/
public class BlackIce implements Runnable {
/**
* Spawns spikes of black ice of all players that are: in a world where the difficulty is higher than Peaceful, in a snow biome and in direct contact with daylight.
*/
@Override
public void run() {
for (Player player : Bukkit.getOnlinePlayers()) {
if (player.getWorld().isThundering()) {
if (player.getWorld().getDifficulty() != Difficulty.PEACEFUL && TenJava.isAcidicWeather && TenJava.enabledFeatures && TenJava.isInSnowBiome(player) && TenJava.isAtDayLight(player)) {
for (Location l : randomLocationAroundPlayer(player)) {
l.getBlock().setType(Material.ICE);
}
player.playSound(player.getLocation(), Sound.FIZZ, 1f, 1f);
}
}
}
}
/**
* Gets a list of random places to spawn ice spikes.
*/
public List<Location> randomLocationAroundPlayer(Player player) {
List<Location> r = new ArrayList<>();
Location under = player.getLocation().subtract(0d, 1d, 0d);
r.add(under);
Random random = new Random();
int where = random.nextInt(4);
if (where == 1) {
Location p1 = player.getLocation().add(1d, 0d, 1d);
Location p2 = player.getLocation().add(1d, 1d, 1d);
r.add(p1);
r.add(p2);
}
if (where == 2) {
Location p1 = player.getLocation().add(-1d, 0d, 1d);
Location p2 = player.getLocation().add(-1d, 1d, 1d);
r.add(p1);
r.add(p2);
}
if (where == 3) {
Location p1 = player.getLocation().add(-1d, 0d, -1d);
Location p2 = player.getLocation().add(-1d, 1d, -1d);
r.add(p1);
r.add(p2);
}
if (where == 4) {
Location p1 = player.getLocation().add(1d, 0d, -1d);
Location p2 = player.getLocation().add(1d, 1d, -1d);
r.add(p1);
r.add(p2);
}
return r;
}
}
|
import java.util.Scanner;
import java.util.*;
public class pg1 {
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter String");
String s=sc.nextLine();
System.out.println("Enter regex of string");
String s1=sc.nextLine();
System.out.println("replacement String");
String s2=sc.nextLine();
s = s.replaceFirst(s1, s2);
System.out.println(s);
}
}
|
package ch.mitti.auktion;
/**
* Modellierung von Personen, die an einer
* Auktion teilnehmen.
*
* @author David J. Barnes und Michael Kölling.
* @version 31.07.2011
*/
public class Person
{
// der Name dieser Person
private final String name;
/**
* Erzeuge eine neue Person mit dem angegebenen Namen.
* @param name der Name der Person
*/
public Person(String name)
{
this.name = name;
}
/**
* @return den Namen der Person.
*/
public String gibName()
{
return name;
}
}
|
package com.example.mav_mr_fpv_osu_2020.old;
// FPV Zoomed View
public class FPVZoomViewModel {
}
|
package common.android;
import java.util.ArrayList;
import java.util.List;
public class NotificationList {
private List<GenericMessage> list = new ArrayList<GenericMessage>();
public void setList(List<GenericMessage> list) {
this.list = list;
}
public List<GenericMessage> getList() {
return list;
}
}
|
/**
* DFA敏感词过滤算法
*/
package xyz.noark.game.dfa; |
class Pratica1Carro {
String tipo;
String cor;
String placa;
int numPortas;
int cambio;
Pratica1Pessoa dono;
public Pratica1Carro(String tipo, String cor, String placa, int numPortas){
this.tipo = tipo;
this.cor = cor;
this.placa = placa;
this.numPortas = numPortas;
}
Pratica1Pessoa getDono(){
return dono;
}
void setDono(Pratica1Pessoa dono){
this.dono = dono;
}
void setCor(String c){
cor = c;
}
String getCor(){
return cor;
}
String getTipo(){
return tipo;
}
void setTipo(String tipo){
this.tipo = tipo;
}
String getPlaca(){
return placa;
}
void setPlaca(String placa){
this.placa = placa;
}
int getNumPortas(){
return numPortas;
}
void setNumPortas(int numPortas){
this.numPortas = numPortas;
}
void ligar(){
System.out.println("carro ligado.");
}
void desligar(){
System.out.println("carro desligado.");
}
void acelerar(){
System.out.println("carro acelerando");
}
void frear(){
System.out.println("carro freando.");
}
void setCambio(int marcha){
this.cambio = marcha;
}
int getCambio(){
return this.cambio;
}
} |
/*
package com.lsm.boot.shiro.config;
import com.lsm.boot.shiro.vo.ResultCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.json.MappingJackson2JsonView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;
@Configuration
@Slf4j
public class ExceptionHandler implements HandlerExceptionResolver {
public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler,
Exception ex) {
ModelAndView mv = new ModelAndView();
MappingJackson2JsonView view = new MappingJackson2JsonView();
Map<String, Object> attributes = new HashMap();
attributes.put("code", ResultCode.C500.getCode());
attributes.put("msg", ResultCode.C500.getDesc());
log.error("内部异常", ex);
view.setAttributesMap(attributes);
mv.setView(view);
return mv;
}
@Bean
public ExceptionHandler createExceptionHandler() {
return new ExceptionHandler();
}
}
*/
|
package com.org.mohammedabdullah3296.linkdevtask.view;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.org.mohammedabdullah3296.linkdevtask.R;
import com.squareup.picasso.Picasso;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import butterknife.BindView;
import butterknife.ButterKnife;
public class DetailsActivity extends AppCompatActivity {
@BindView(R.id.media_image)
ImageView articleImage;
@BindView(R.id.primary_text)
TextView articleTitle;
@BindView(R.id.sub_text)
TextView articlePublicher;
@BindView(R.id.action_button_2)
TextView articleDescribtion;
@BindView(R.id.action_button_1)
TextView articleContent;
@BindView(R.id.action_button_)
TextView articleDate;
@BindView(R.id.websitbtn)
Button websitbtn;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_details);
ButterKnife.bind(this);
final Bundle bundle = getIntent().getExtras();
articleTitle.setText(bundle.getString("currentTitle"));
articlePublicher.setText(String.format("By %s", bundle.getString("currentPublisher")));
setVisibility(articleDescribtion, bundle.getString("currentDescription"));
setVisibility(articleContent, bundle.getString("currentContent"));
articleDate.setText(dateFormate(bundle.getString("currentDate")));
Picasso.get().load(bundle.getString("currentImage"))
.placeholder(R.drawable.placeholder).into(articleImage);
websitbtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(bundle.getString("currentUrl")));
startActivity(intent);
}
});
}
public void setVisibility(TextView v, String msg) {
if (TextUtils.isEmpty(msg)) {
v.setVisibility(View.GONE);
} else {
v.setText(msg);
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.details, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
Toast.makeText(this, item.getTitle(), Toast.LENGTH_SHORT).show();
return true;
}
return super.onOptionsItemSelected(item);
}
public String dateFormate(String date1) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
String mmm = null ;
try {
Date date = sdf.parse(date1);
mmm = new SimpleDateFormat("MMM dd, yyyy").format(date) ;
} catch (ParseException e) {
e.printStackTrace();
}
return mmm;
}
}
|
package com.maxleap.demo.analytics;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.View.OnClickListener;
import com.maxleap.MLAnalytics;
public class WithFragmentActivity extends AppCompatActivity {
private int mCount = 1;
private static final String EXTRA_COUNT = "count";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_page);
findViewById(R.id.open_new_page_button).setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
mCount++;
Fragment f = SimpleFragment.newInstance(mCount,
"SimpleFragment " + mCount);
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.fragment, f)
.setTransition(
FragmentTransaction.TRANSIT_FRAGMENT_OPEN)
.addToBackStack(null).commit();
}
});
if (savedInstanceState == null) {
Fragment f = SimpleFragment.newInstance(mCount, "SimpleFragment "
+ mCount);
getSupportFragmentManager().beginTransaction()
.add(R.id.fragment, f).commit();
} else {
mCount = savedInstanceState.getInt(EXTRA_COUNT);
}
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt(EXTRA_COUNT, mCount);
}
@Override
protected void onResume() {
super.onResume();
//session
MLAnalytics.onResume(this);
}
@Override
protected void onPause() {
super.onPause();
//session
MLAnalytics.onPause(this);
}
}
|
package com.example.demo.mapper;
import com.example.demo.entity.OrderContractProject;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
/**
* <p>
* Mapper 接口
* </p>
*
* @author zjp
* @since 2020-12-03
*/
public interface OrderContractProjectMapper extends BaseMapper<OrderContractProject> {
}
|
package Lec_05_Whill_Loop_1;
import java.util.Scanner;
public class Lab_05_05_MinNumber {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Въведете броя на подаваните цели числа: ");
int numInput = Integer.parseInt(scanner.nextLine());
int minNum = Integer.MAX_VALUE;
int counter = 1;
while (counter <= numInput){
System.out.print("Въведете цяло число за сравняване: ");
int num = Integer.parseInt(scanner.nextLine());
counter++;
if (num < minNum){
minNum = num;
}
}
System.out.printf("%d", minNum);
}
}
|
package edu.mum.sonet.security;
import lombok.Data;
/**
* Created by Jonathan on 12/10/2019.
*/
@Data
public class GoogleOAuth2UserInfo {
private String id;
private String name;
private String email;
private String imageUrl;
}
|
package com.bnrc.busapp;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
import com.bnrc.util.BusTags;
import com.bnrc.util.CameraSurfaceView;
import com.bnrc.util.collectwifi.BaseActivity;
public class ArActivity extends BaseActivity implements View.OnClickListener,BusTags.IAutoFocus{
private CameraSurfaceView mCameraSurfaceView;
private BusTags mBusTags;
private boolean isClicked;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
// 全屏显示
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_main);
mCameraSurfaceView = (CameraSurfaceView) findViewById(R.id.cameraSurfaceView);
mBusTags = (BusTags) findViewById(R.id.busTags);
mBusTags.setIAutoFocus(this);
mBusTags.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()){
case R.id.busTags:
Toast.makeText(ArActivity.this,"You clicked a tag", Toast.LENGTH_LONG).show();
break;
default:
break;
}
}
@Override
public void autoFocus() {
mCameraSurfaceView.setAutoFocus();
}
}
|
package com.qfc.yft.net.chat;
import com.qfc.yft.vo.CimWSReturn;
/**
*
* @author zw.Bai
*
*/
public interface IWSCallback {
public void callback(CimWSReturn wsReturn);
}
|
package com.example.extra_menu_test.ui;
public class Test {
public static float PI = 3.14F;
}
|
package com.sipc.catalina.controller;
import org.junit.Assert;
import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest
class StudentControllerTest {
@Autowired
private StudentController controller;
@Test
void getAll() {
Assert.assertNotNull(controller.getAll());
System.out.println("通过测试!");
}
@Test
void create() {
}
@Test
void findById() {
Assert.assertNotEquals(null, controller.findById(10));
}
@Test
void update() {
}
} |
package shulei.july23;
public class GeneralRun implements Runnable {
private static boolean flag = true;
private long time;
public static String general = "";
public GeneralRun(long time) {
this.time = time;
}
public void end() {
flag = false;
}
@Override
public void run() {
GeneralManager manager = new GeneralManager();
while (flag) {
manager.getRandomGeneral();
general = manager.getRandomGeneral();
GeneralStauts.putAndSysout(this);
try {
Thread.sleep(time);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
|
package com.wangzhu.guava;
import java.util.List;
import java.util.Random;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.base.Function;
import com.google.common.base.Optional;
import com.google.common.base.Preconditions;
import com.google.common.base.Predicate;
import com.google.common.base.Predicates;
import com.google.common.collect.Collections2;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import com.google.common.collect.Ordering;
public class TestGuavaList {
private static Logger logger = LoggerFactory.getLogger(TestGuavaList.class);
/**
* 新建列表List
*
* @param arr
* @return
*/
public static <T> List<T> createArrayList(T... arr) {
List<T> list = Lists.newArrayList(arr);
return list;
}
/**
* 删除列表中的null项,是否更改源列表
*
* @param list
* @param isChange
* @return
*/
public static <T> List<T> removeNullFromList(List<T> list, boolean isChange) {
if (isChange) {
TestGuavaList.removeNullFromList(list);
return null;
}
return Lists.newArrayList(Iterables.filter(list, Predicates.notNull()));
}
/**
* 从列表List中删除null值
*
* @param list
*/
public static <T> void removeNullFromList(List<T> list) {
Iterables.removeIf(list, Predicates.isNull());
}
/**
* 反转列表
*
* @param list
* @return
*/
public static <T> List<T> reverse(List<T> list) {
List<T> reverseList = Lists.reverse(list);
TestGuavaList.logger.info("reverse from {} to{} ", list, reverseList);
return reverseList;
}
/**
* 创建不可更改的列表List
*
* @param list
* @return
*/
public static <T> List<T> createImmutableList(List<T> list) {
// ImmutableList.builder().addAll(list).build();
return ImmutableList.copyOf(list);
}
public static <T> void testClass(T... arr) {
List<T> list = TestGuavaList.createArrayList(arr);
TestGuavaList.logger.info("create list:{}", list);
List<T> notNullList = TestGuavaList.removeNullFromList(list, false);
TestGuavaList.logger.info("remove null list:{},{}", list, notNullList);
if (notNullList != null) {
list = notNullList;
}
List<T> reverseList = TestGuavaList.reverse(list);
TestGuavaList.logger.info("reverseList:dest{} source{}", reverseList,
list);
List<T> newList = TestGuavaList.createImmutableList(list);
TestGuavaList.logger.info("new immutable list:{}", newList);
}
public static void main(String[] args) {
TestGuavaList.logger.info("TestGuavaList start");
TestGuavaList.testClass('a', 'b', 'c', 'd', null);
TestGuavaList
.testClass(1, 3, 5, null, 7, 10, 111, null, 123, -11, null);
TestGuavaList.logger.info("TestGuavaList end");
List<Character> characterList = Lists.charactersOf("qingyezhu");
TestGuavaList.logger.info("characterList:{}", characterList);
Random random = new Random();
int len = 10;
Person[] personArr = new Person[len];
for (int i = 0; i < len; i++) {
personArr[i] = new Person(random.nextInt(100), "name" + i, i & 1,
random.nextInt(100));
}
List<Person> personList = Lists.newArrayList(personArr);
TestGuavaList.printList(personList);
// personList = null;
Optional<List<Person>> personListField = Optional
.fromNullable(personList);
Preconditions.checkState(personListField.isPresent(),
"presonList must not be null");
// 谓词Predicate与筛选Filter
TestGuavaList.printList(ImmutableList.copyOf(Collections2.filter(
personList, new Predicate<Person>() {
public boolean apply(Person input) {
return input.getSex() == 0;
}
})));
// 转化transform
TestGuavaList.printList(ImmutableList.copyOf(Lists.transform(
personList, new Function<Person, String>() {
public String apply(Person input) {
return input.getName();
}
})));
// 排序
TestGuavaList.printList(new Ordering<Person>() {
@Override
public int compare(Person left, Person right) {
int age = left.getAge() - right.getAge();
if (age == 0) {
return left.getId() - right.getId();
}
return age;
}
}.immutableSortedCopy(personList));
}
private static <T> void printList(List<T> list) {
for (T t : list) {
TestGuavaList.logger.info("{}", t);
}
TestGuavaList.logger.info("\n");
}
static class Person {
private int id;
private String name;
private int sex;
private int age;
public Person(int id, String name, int sex, int age) {
this.id = id;
this.name = name;
this.sex = sex;
this.age = age;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getSex() {
return sex;
}
public void setSex(int sex) {
this.sex = sex;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "{id=" + id + ", name=" + name + ", sex=" + sex + ", age="
+ age + "}";
}
}
}
|
package org.benlin.moneytransfer.service;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.benlin.moneytransfer.database.Database;
import org.benlin.moneytransfer.exception.DataNotFoundException;
import org.benlin.moneytransfer.exception.OverdraftException;
import org.benlin.moneytransfer.model.Account;
public class AccountService {
private Map<Long, Account> accounts = Database.getAccounts();
public AccountService() {
accounts.put(1L, new Account(1L, "Ben Lin", 100.0));
// accounts.put(2L, new Account(2L, "John Smith", 200.0));
}
public List<Account> getAllAccounts(){
return new ArrayList<Account>(accounts.values());
}
public Account getAccount(long accountId) {
Account account = accounts.get(accountId);
if (account == null) {
throw new DataNotFoundException("Account with id " + accountId + " not found");
}
else {
return account;
}
}
public Account addAccount(Account account) {
account.setAccountId(accounts.size()+1);
accounts.put(account.getAccountId(), account);
return account;
}
public Account updateAccount(Account account) {
if(account.getAccountId() <= 0) {
return null;
}
accounts.put(account.getAccountId(), account);
return account;
}
/*
* Handle the error better
*/
public Account withdraw(Account account, double amount) {
if(account.getAccountId() <= 0 || amount < 0) {
return null;
}
double newBalance = account.getBalance() - amount;
if(newBalance >= 0) {
account.setBalance(newBalance);
return updateAccount(account);
}
else {
throw new OverdraftException(amount + " exceeds " + account.getOwner() + "'s account balance");
}
}
public Account deposit(Account account, double amount) {
if(account.getAccountId() <= 0 || amount < 0) {
return null;
}
account.setBalance(account.getBalance() + amount);
return updateAccount(account);
}
public Account removeAccount(long accountId) {
return accounts.remove(accountId);
}
}
|
/*
* Created on Mar 14, 2007
*
*/
package com.citibank.ods.modules.product.prodriskcatprvt.functionality;
import java.math.BigInteger;
import java.text.SimpleDateFormat;
import org.apache.struts.action.ActionForm;
import com.citibank.ods.Globals.FuncionalityFormatKeys;
import com.citibank.ods.common.dataset.DataSet;
import com.citibank.ods.common.functionality.ODSListFnc;
import com.citibank.ods.common.functionality.valueobject.BaseFncVO;
import com.citibank.ods.common.functionality.valueobject.BaseODSFncVO;
import com.citibank.ods.modules.product.prodriskcatprvt.form.ProdRiskCatPrvtHistoryListForm;
import com.citibank.ods.modules.product.prodriskcatprvt.functionality.valueobject.BaseProdRiskCatPrvtListFncVO;
import com.citibank.ods.modules.product.prodriskcatprvt.functionality.valueobject.ProdRiskCatPrvtHistoryListFncVO;
import com.citibank.ods.persistence.pl.dao.TplProdRiskCatPrvtHistDAO;
import com.citibank.ods.persistence.pl.dao.factory.ODSDAOFactory;
/**
* @author leonardo.nakada
*
*/
public class ProdRiskCatPrvtHistoryListFnc extends BaseProdRiskCatPrvtListFnc
implements ODSListFnc
{
/*
* (non-Javadoc)
* @see com.citibank.ods.common.functionality.BaseFnc#createFncVO()
*/
public BaseFncVO createFncVO()
{
return new ProdRiskCatPrvtHistoryListFncVO();
}
/*
* (non-Javadoc)
* @see com.citibank.ods.common.functionality.ODSListFnc#list(com.citibank.ods.common.functionality.valueobject.BaseFncVO)
*/
public void list( BaseFncVO fncVO_ )
{
ProdRiskCatPrvtHistoryListFncVO catPrvtHistoryListFncVO = ( ProdRiskCatPrvtHistoryListFncVO ) fncVO_;
// Obtém a instância da Factory
ODSDAOFactory factory = ODSDAOFactory.getInstance();
TplProdRiskCatPrvtHistDAO tplProdRiskCatPrvtHistDAO = factory.getTplProdRiskCatPrvtHistDAO();
/** *** 20110321 ***
* As funcionalidades que utilizavam a tabela PL.TPL_PROD_RISK_CAT_PRVT devem utilizar a tabela
* PL.TPL_RISK_INVST_PROD_RDIP (apenas funcionalidades que utilizem consulta, as telas de
* inserção e alteração serão removidas)
*/
// DataSet results = tplProdRiskCatPrvtHistDAO.list(
// catPrvtHistoryListFncVO.getProdRiskCatCodeHistSrc(),
// catPrvtHistoryListFncVO.getProdRiskCatTextSrc(),
// catPrvtHistoryListFncVO.getProdRiskCatRefDateSrc() );
//
// catPrvtHistoryListFncVO.setResults( results );
//
// if ( results.size() > 0 )
// {
// catPrvtHistoryListFncVO.addMessage( BaseODSFncVO.C_MESSAGE_SUCESS );
// }
// else
// {
// catPrvtHistoryListFncVO.addMessage( BaseODSFncVO.C_NO_REGISTER_FOUND );
// }
}
/*
* (non-Javadoc)
* @see com.citibank.ods.common.functionality.ODSListFnc#load(com.citibank.ods.common.functionality.valueobject.BaseFncVO)
*/
public void load( BaseFncVO fncVO_ )
{
BaseProdRiskCatPrvtListFncVO prodRiskCatPrvtListFncVO = ( BaseProdRiskCatPrvtListFncVO ) fncVO_;
prodRiskCatPrvtListFncVO.setResults( null );
prodRiskCatPrvtListFncVO.setProdRiskCatTextSrc( null );
( ( ProdRiskCatPrvtHistoryListFncVO ) prodRiskCatPrvtListFncVO ).setProdRiskCatRefDateSrc( null );
}
/*
* (non-Javadoc)
* @see com.citibank.ods.common.functionality.ODSListFnc#validateList(com.citibank.ods.common.functionality.valueobject.BaseFncVO)
*/
public void validateList( BaseFncVO fncVO_ )
{
//
}
/*
* Atualiza o FncVO com as informacoes da Form
*
* @see com.citibank.ods.common.functionality.BaseFnc#updateFncVOFromForm(org.apache.struts.action.ActionForm,
* com.citibank.ods.common.functionality.valueobject.BaseFncVO)
*/
public void updateFncVOFromForm( ActionForm form_, BaseFncVO fncVO_ )
{
super.updateFncVOFromForm( form_, fncVO_ );
ProdRiskCatPrvtHistoryListForm prvtHistoryListForm = ( ProdRiskCatPrvtHistoryListForm ) form_;
ProdRiskCatPrvtHistoryListFncVO listFncVO = ( ProdRiskCatPrvtHistoryListFncVO ) fncVO_;
SimpleDateFormat formatter = new SimpleDateFormat(
FuncionalityFormatKeys.C_FORMAT_DATE_DDMMYYYY );
try
{
if ( prvtHistoryListForm.getProdRiskCatCodeHistSrc() != null
&& !prvtHistoryListForm.getProdRiskCatCodeHistSrc().equals( "" ) )
{
listFncVO.setProdRiskCatCodeHistSrc( new BigInteger(
prvtHistoryListForm.getProdRiskCatCodeHistSrc() ) );
}
else
{
listFncVO.setProdRiskCatCodeHistSrc( null );
}
listFncVO.setProdRiskCatRefDateSrc( formatter.parse( prvtHistoryListForm.getProdRiskCatRefDate() ) );
}
catch ( Exception e )
{
listFncVO.setProdRiskCatRefDateSrc( null );
}
}
} |
package com.njits.iot.advert.test;
public interface AnalysicDataSource
{
void analysicData(String... args);
}
|
public class BalancedBinaryTree {
/**
* Return true if the Tree is balanced, false othersie;
*/
public class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) { val = x; }
}
boolean result =true;
public boolean isBalanced(TreeNode root) {
if(root==null) return true;
height(root);
return result;
}
public int height(TreeNode root){
if(root==null) return 0;
int left = height(root.left);
int right = height(root.right);
if(Math.abs(left-right)>1) result = false;
return 1+ Math.max(left, right);
}
/**
* Thinking to go check every node previously, but the runtime is about O(n^2)
* Better to have a boolean to check when getting height of the root.
*/
}
|
package automat;
import java.util.Date;
/* En klasse der bruges til at gemme data om handel */
public class Transaktioner {
/**
* Den transarktions tekst der bilver lavet.
*/
private double beløb;
private Date udDato;
private int gyldighed;
private String fra;
private String til;
private int zoneStart;
private int zoneAntal;
private int billetType; //1: Voksen, 2: Barn, 3: To voksne, 4: To børn, 5: Voksen og barn
private int ID;
private boolean retur;
public Transaktioner(double beløb, int gyldighed, String fra, String til, int zoneStart, int zoneAntal, int billetType, boolean retur ) {
udDato = new Date();
this.gyldighed = gyldighed;
this.beløb = beløb;
this.fra = fra;
this.til = til;
this.zoneStart = zoneStart;
this.zoneAntal = zoneAntal;
this.billetType = billetType;
double random = Math.random() * 400;
ID = (gyldighed + zoneStart + zoneAntal + billetType) * (int)random ;
this.retur = retur;
}
}
|
package encapsule;
/**
* @file_name : CardMain.java
* @author : dingo44kr@gmail.com
* @date : 2015. 9. 23.
* @story : 트럼프 게임
*/
import org.omg.Messaging.SyncScopeHelper;
public class Card {
//멤버 필드
private String kind; // 카드의 무늬(스페이드, 다이아, 하트, 클럽)
private int number; // 카드의 넘버 (1 ~ 13)
private int number2;
static int WIDTH = 100; // 카드의 너비
static int HEIGHT = 180; // 카드의 높이
private int random1;
private int random2;
//get 읽다
//set 쓰다
public String getKind() {
return kind;
}
public void setKind(String kind) {
this.kind = "하트";
}
public int getNumber() {
return number;
}
public void setNumber(int number) {
this.number = random1;
}
public int getNumber2() {
return number2;
}
public void setNumber2(int number2) {
this.number2 = random2;
}
public int getRandom1() {
return random1;
}
public void setRandom1(int random1) {
this.random1 = (int) (Math.random()*13) + 1;
}
public int getRandom2() {
return random2;
}
public void setRandom2(int random2) {
this.random2 = (int) (Math.random() * 13) + 1;
}
//
// @Override
// public String toString() {
// // TODO Auto-generated method stub
// return
// }
// number1 = random1, number2 = number2
} |
package de.ing.mws.refapp.war.controller;
import de.ing.mws.refapp.moda.service.ServiceA1;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/testbo")
public class TestBoController {
@Autowired
String warTestBean;
@Autowired
ServiceA1 serviceA1;
@GetMapping("/test")
public String test() {
return warTestBean;
}
@GetMapping()
public boolean doIt() {
return serviceA1.doIt();
}
@GetMapping("/all")
public String listAll() {
return "a b c";
}
}
|
package com.hqzmss.memento.use;
public class MainClass {
public static void main(String[] args) {
Student student = new Student();
student.setName("hqz");
student.setAge(9);
student.setSex(true);
Caretaker caretaker = new Caretaker();
//创建备忘录
caretaker.setMemento(student.createMemento());
//修改原对象信息
student.setName("123");
//恢复原对象的状态信息
student.restoreMemento(caretaker.getMemento());
}
}
|
package se.xperjon.hibernate_demo.domain;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.NamedQueries;
import javax.persistence.OneToOne;
@Entity
public class Personal {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int personalID;
@Column
private String namn;
private String befattning;
private boolean isCEO;
@OneToOne
@JoinColumn(name = "avdelningID")
private Avdelning avdelning;
public int getPersonalId() {
return personalID;
}
public void setPersonalId(int personalId) {
this.personalID = personalId;
}
public String getNamn() {
return namn;
}
public void setNamn(String namn) {
this.namn = namn;
}
public String getBefattning() {
return befattning;
}
public void setBefattning(String befattning) {
this.befattning = befattning;
}
public Avdelning getAvdelning() {
return avdelning;
}
public void setAvdelning(Avdelning avdelning) {
this.avdelning = avdelning;
}
public boolean isCEO() {
return isCEO;
}
public void setCEO(boolean isCEO) {
this.isCEO = isCEO;
}
@Override
public String toString() {
return "Personal [personalID=" + personalID + ", namn=" + namn + ", befattning=" + befattning + ", avdelning="
+ avdelning + "]";
}
}
|
package com.fods.psp_bt;
import android.icu.text.DecimalFormat;
import android.icu.text.SimpleDateFormat;
import android.os.Build;
import android.support.annotation.RequiresApi;
import android.text.format.DateFormat;
import android.util.Log;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.channels.FileChannel;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import java.util.Scanner;
import java.util.TimeZone;
import static android.content.ContentValues.TAG;
import static com.fods.psp_bt.SOR.Constants.BELL_FODPARAMS_MAGIC;
import static com.fods.psp_bt.SOR.Constants.EV_CODE_EG;
import static com.fods.psp_bt.SOR.Constants.EV_CODE_EN;
import static com.fods.psp_bt.SOR.Constants.EV_CODE_GE;
import static com.fods.psp_bt.SOR.Constants.EV_CODE_GM;
import static com.fods.psp_bt.SOR.Constants.EV_CODE_GS;
import static com.fods.psp_bt.SOR.Constants.EV_CODE_MB;
import static com.fods.psp_bt.SOR.Constants.EV_CODE_MS;
import static com.fods.psp_bt.SOR.Constants.EV_CODE_SG;
import static com.fods.psp_bt.SOR.Constants.EV_CODE_SP;
import static com.fods.psp_bt.SOR.Constants.EV_CODE_ST;
import static com.fods.psp_bt.SOR.Constants.EV_CTYPEN_MSK_GR_END;
import static com.fods.psp_bt.SOR.Constants.EV_CTYPEN_MSK_GR_MIDDLE;
import static com.fods.psp_bt.SOR.Constants.EV_CTYPEN_MSK_GR_START;
import static com.fods.psp_bt.SOR.Constants.EV_CTYPEN_MSK_LINK_END;
import static com.fods.psp_bt.SOR.Constants.EV_CTYPEN_MSK_LINK_START;
import static com.fods.psp_bt.SOR.Constants.EV_CTYPEN_MSK_MACROBEND;
import static com.fods.psp_bt.SOR.Constants.EV_CTYPEN_MSK_SIMPLE;
import static com.fods.psp_bt.SOR.Constants.EV_CTYPEN_MSK_SPLITTER;
import static com.fods.psp_bt.SOR.Constants.FIBER_TYPE_SMF28E;
import static com.fods.psp_bt.SOR.Constants.FIBER_TYPE_USER1;
import static com.fods.psp_bt.SOR.Constants.FIBER_TYPE_USER2;
import static com.fods.psp_bt.SOR.Constants.LightVelocity;
import static com.fods.psp_bt.SOR.Constants.MAX_BLOCKSIZE;
import static com.fods.psp_bt.SOR.Constants.MAX_TNDP;
import static com.fods.psp_bt.SOR.Constants.MAX_TNKE;
import static com.fods.psp_bt.SOR.Constants.NETWORK_TYPE_POINT_TO_POINT;
import static com.fods.psp_bt.SOR.Constants.NETWORK_TYPE_PON;
import static com.fods.psp_bt.SOR.Constants.PASSFAIL_TYPE_ITUG671;
import static com.fods.psp_bt.SOR.Constants.PASSFAIL_TYPE_TIA568_3D;
import static com.fods.psp_bt.SOR.Constants.PASSFAIL_TYPE_USER1;
import static com.fods.psp_bt.SOR.Constants.PFT_THRESH_DFLT_EVENT_ACI;
import static com.fods.psp_bt.SOR.Constants.PFT_THRESH_DFLT_EVENT_CONN_LOSS;
import static com.fods.psp_bt.SOR.Constants.PFT_THRESH_DFLT_EVENT_CONN_REFL;
import static com.fods.psp_bt.SOR.Constants.PFT_THRESH_DFLT_EVENT_END_REFL;
import static com.fods.psp_bt.SOR.Constants.PFT_THRESH_DFLT_EVENT_SPLICE_LOSS;
import static com.fods.psp_bt.SOR.Constants.PFT_THRESH_DFLT_EVENT_SPLITTER1_LOSS_TOLERANCE;
import static com.fods.psp_bt.SOR.Constants.PFT_THRESH_DFLT_EVENT_SPLITTER1_RATIO_INDX;
import static com.fods.psp_bt.SOR.Constants.PFT_THRESH_DFLT_EVENT_SPLITTER2_LOSS_TOLERANCE;
import static com.fods.psp_bt.SOR.Constants.PFT_THRESH_DFLT_EVENT_SPLITTER2_RATIO_INDX;
import static com.fods.psp_bt.SOR.Constants.PFT_THRESH_DFLT_EVENT_SPLITTER_REFL;
import static com.fods.psp_bt.SOR.Constants.PFT_THRESH_DFLT_LINK_ACI;
import static com.fods.psp_bt.SOR.Constants.PFT_THRESH_DFLT_LINK_LENGTH;
import static com.fods.psp_bt.SOR.Constants.PFT_THRESH_DFLT_LINK_LENGTH_TOLERANCE;
import static com.fods.psp_bt.SOR.Constants.PFT_THRESH_DFLT_LINK_LOSS;
import static com.fods.psp_bt.SOR.Constants.PFT_THRESH_DFLT_LINK_ORL;
import static com.fods.psp_bt.SOR.Constants.TEST_TYPE_LOCATE_END_AND_FAULTS;
import static com.tom_roush.pdfbox.cos.COSName.DS;
import static com.tom_roush.pdfbox.pdmodel.documentinterchange.taggedpdf.StandardStructureTypes.RT;
import static org.apache.commons.net.telnet.TelnetCommand.AO;
import static org.apache.commons.net.telnet.TelnetCommand.EL;
/**
* Created by Valentinas on 2018-01-15.
*/
public class SOR {
private static FileInputStream fis;
private static long fsize;
static TestParams_T TestParamS = new TestParams_T();
public static int[] sk;
public static EvEventsS Events = new SOR.EvEventsS();
public class Constants {
public static final int TESTP_FPO = (2987);
/* max. number of possible wavelength values in Test Settings menu */
public static final int TESTSET_WL_NMAX = 7;
/* max number of configurable splitters */
public static final int TEST_TYPE_NMAX = (11);
public static final int TEST_SMART_AUTO_TEST_TYPES_NMAX = (2);
public static final int NETWORK_TYPE_NMAX = (2);
public static final int MAX_NUMBER_OF_SUPPORTED_WL = (3);
public static final int FIBER_USER_TYPES_NMAX = (2);
public static final int FIBER_TYPES_NMAX = (3);
public static final int PASSFAIL_USER_TYPES_NMAX = (1);
public static final int PASSFAIL_TYPES_NMAX = (3);
public static final int TEST_TYPE_LOCATE_END_AND_FAULTS = 10;
public static final int FIBER_TYPE_SMF28E = 0;
public static final int FIBER_TYPE_USER1 = 30;
public static final int FIBER_TYPE_USER2 = 31;
public static final int PASSFAIL_TYPE_ITUG671 = 0;
public static final int PASSFAIL_TYPE_TIA568_3D = 1;
public static final int PASSFAIL_TYPE_USER1 = 30;
public static final int NETWORK_TYPE_POINT_TO_POINT = 0;
public static final int NETWORK_TYPE_PON = 1;
public static final int PFT_THRESH_DFLT_LINK_LENGTH = (10000);
public static final int PFT_THRESH_DFLT_LINK_LENGTH_TOLERANCE =(10);
public static final int PFT_THRESH_DFLT_LINK_LOSS =(5000);
public static final int PFT_THRESH_DFLT_LINK_ACI =(500);
public static final int PFT_THRESH_DFLT_LINK_ORL =(24000);
public static final int PFT_THRESH_DFLT_EVENT_CONN_LOSS =(750);
public static final int PFT_THRESH_DFLT_EVENT_CONN_REFL =(-260);
public static final int PFT_THRESH_DFLT_EVENT_SPLICE_LOSS =(300);
public static final int PFT_THRESH_DFLT_EVENT_SPLITTER1_LOSS_TOLERANCE =(1000);
public static final int PFT_THRESH_DFLT_EVENT_SPLITTER2_LOSS_TOLERANCE =(1000);
public static final int PFT_THRESH_DFLT_EVENT_SPLITTER1_RATIO_INDX =(4);
public static final int PFT_THRESH_DFLT_EVENT_SPLITTER2_RATIO_INDX =(0);
public static final int PFT_THRESH_DFLT_EVENT_END_REFL =(-260);
public static final int PFT_THRESH_DFLT_EVENT_ACI =(500);
public static final int PFT_THRESH_DFLT_EVENT_SPLITTER_REFL =(-550);
public static final int TEST_DBUF_NMAX = (300000 + 512);
public static final int MAX_TNDP = (TEST_DBUF_NMAX);
public static final int MAX_BLOCKSIZE = (2*MAX_TNDP+22);
public static final int EV_SPL_CFG_MAX = (3);
public static final int EV_CODE_MB = 0x424D;
public static final int EV_CODE_SP = 0x5053;
public static final int EV_CODE_GS = 0x5347;
public static final int EV_CODE_GM = 0x4D47;
public static final int EV_CODE_GE = 0x4547;
public static final int EV_CODE_ST = 0x5453;
public static final int EV_CODE_SG = 0x4753; /* link start group */
public static final int EV_CODE_EG = 0x4745; /* link end group */
public static final int EV_CODE_EN = 0x4E45;
public static final int EV_CODE_SI = 0x4953;
public static final int EV_CODE_MS = 0x534D; /* macrobend at splitter */
public static final int BELL_FODPARAMS_MAGIC = 0x5fa5;
public static final int MAX_TNKE = (80);
public static final double LightVelocity = 1.49896229e4;
public static final int EV_CTYPEN_MSK_SIMPLE = 0x0000;
public static final int EV_CTYPEN_MSK_MACROBEND = 0x0001;
public static final int EV_CTYPEN_MSK_SPLITTER = 0x0002;
public static final int EV_CTYPEN_MSK_GR_START = 0x0004;
public static final int EV_CTYPEN_MSK_GR_MIDDLE = 0x0008;
public static final int EV_CTYPEN_MSK_GR_END = 0x0010;
public static final int EV_CTYPEN_MSK_IS_GROUP = 0x001C;
public static final int EV_CTYPEN_MSK_LINK_START = 0x0020;
public static final int EV_CTYPEN_MSK_LINK_END = 0x0040;
};
public SOR (){
}
enum EvSplCfgTypes_t{
EvSplCfgType_Auto,
EvSplCfgType_None,
EvSplCfgType_R1_1,
EvSplCfgType_R1_2,
}
public static class EvSplCfg_t{
int r1[] = new int[3]; /* r1:r2, -1:Auto, 0:None, 1, 2.. */
int r2[] = new int[3]; /* r1:r2 */
};
public static int C2X_FUNC(char c1, char c2){
int retval = ((c2 << 8) | c1);
return retval;
}
public static class TestComParams_T{
public int TNDP; /* Total Number of Data Points */
public int AO; /* int32_t Acquisition Offset */
public int DS; /* Data Spacing */
public int NPPW; /* Number of Data Points for Each Pulse Width */
public int AR; /* Acquisition Range */
public int TPW; /* Total Number of Pulse Widths Used */
public int PWU; /* Pulse Widths Used */
public int Test_Mode; /* FullAuto, EndLocate, Live, Expert */
public int Test_RangeIndx; /* aqcuisition */
public int Test_PwIndx;
public int Test_RangeChangedFlag;
public int Fiber_Type; /* SMF-28e, User */
public int Network_Type; /* Point-to-Point, PON */
public int PassFail_Type; /* ITU G.671, User1 */
public int Live_Fiber; /* indicates live fiber mode */
public int Event_Mode; /* Off, Auto, EndLocate */
public int TestGain;
public int TestTime; /* test time in seconds x 100 */
public int RefreshTime; /* trace refresh time in seconds * 100 */
public int Resolution;
public int marker1_val; /* marker 1 location */
public int marker2_val; /* marker 2 location */
public int Cable_Launch_cm; /* Launch cables in cm */
public int Cable_Receive_cm; /* Receive cables in cm */
public int MacrobendDetection; /* Macrobend detection on/off */
public int LQC_Result; /* 0 -off, 1 - OK, 2 - poor */
public EvSplCfg_t ev_spl_cfg = new EvSplCfg_t();
public int otdr_script_id;
public int otdr_script_state; /* 0 - idle, 1 - busy, 2 - done */
public int otdr_script_status; /* 0 - OK, >0 error */
public int[] LinkPassFailThresholdsOnOff = new int[2]; /* 0b000000000000dcba, link thresholds on/off bits 0-off,1-on: a-length, b-loss, c-ACI, d-ORL */
public int[] EventPassFailThresholdsOnOff = new int[2]; /* 0b00000000hgfedcba, event thresholds on/off bits 0-off,1-on: a-event, b-conn.loss, c-conn.refl., d-splice loss, e-splitter1 loss, f-splitter2 loss, g-end refl, h-fiber sec.*/
public int[] LinkPassThrLength = new int[2]; /* Link length pass threshold in meters */
public int[] LinkPassThrLengthTolerance = new int[2]; /* Link length tolerance pass threshold in percent */
public int[] LinkPassThrLoss = new int[2]; /* Link Loss pass threshold in dB*100 */
public int[] LinkPassThrACI = new int[2]; /* Link Loss/Distance pass threshold in dB/km*100 */
public int[] LinkPassThrORL = new int[2]; /* Link ORL pass threshold in dB*100 */
public int[] EventPassThrConnLoss = new int[2]; /* Event Connector Loss pass threshold in dB*100 */
public int[] EventPassThrConnRefl = new int[2]; /* Event Connector Reflectance pass threshold in dB*10 */
public int[] EventPassThrSpliceLoss = new int[2]; /* Event Splice Loss pass threshold in dB*100 */
public int[] EventPassThrSplitter1Ratio = new int[2]; /* Event Splitter 1 Ratio pass threshold (2, 4, 8, 16, 32, 64, 128) */
public int[] EventPassThrSplitter2Ratio = new int[2]; /* Event Splitter 2 Ratio pass threshold (2, 4, 8, 16, 32, 64, 128) */
public int[] EventPassThrSplitter1LossTolerance = new int[2]; /* Event Splitter 1 Loss Tolerance pass threshold in dB*100 */
public int[] EventPassThrSplitter2LossTolerance = new int[2]; /* Event Splitter 2 Loss Tolerance pass threshold in dB*100 */
public int[] EventPassThrEndRefl = new int[2]; /* Event End Reflectance pass threshold in dB*100 */
public int[] EventPassThrACI = new int[2]; /* Event Fiber Section (ACI) pass threshold in dB/km*100 */
public int EventPassThrSplitterRefl; /* Event Splitter Reflectance pass threshold in dB*100 */
}
public static class EvEventPS{
public int Location; //int32_t
public int End; //int32_t
public int Type; //uint16_t
public int Max; //int32_t
public int CustomType;//uint16_t
public int PassFail;//uint16_t
public int ACI;//int16_t
public int Refl;//int32_t
public int Loss;//int32_t
public int StartLevel;//int32_t
public int LocStart_mm;//int32_t
public int LocMax_mm;//int32_t
public int LocEnd_mm;//int32_t
public int PW_mm;//int32_t
public int MaxLevel;//int32_t
public int EndLevel;//int32_t
public int SegmentID;//int16_t
public int Flags;//int16_t
public int SplitterRatio; /*uint16_t 1:x, 0 - auto */
}
public static class ldiv_t
{ /* result of long divide */
long quot;
long rem;
}
public static class TestParams_T{
public int UO; /*int32_t User Offset */
public int GI; /*int32_t Group Index */
public int NAV; /*int32_t Number of Averages */
public int NW; /*int16_t Nominal Wavelength */
public int BC; /*int16_t Backscater Coefficient */
public int TNKE; /*int16_t Number of Key Events */
public int LT; /*uint16_t Loss Threshold */
public int RT; /*uint16_t Reflectance Threshold */
public int ET; /*uint16_t End-of-Fiber Threshold */
public int NF; /*uint16_t Noise Floor Level */
public int FPO; /*int32_t Front Panel Offset */
public String CID;
public String FID;
public String OL;
public String TL;
public String CCD;
public String SN;
public String MFID;
public String OTDR;
public String OMID;
public String OMSN;
public String SR;
public String OT;
public int TraceValid; //int16_t
public int EventValid; //int16_t
public int EEL; /*int32_t End to End Loss */
public int ELMP1; /*int32_t End loss marker 1 position */
public int ELMP2; /*int32_t End loss marker 2 position */
public int ORL; /*uint16_t Optical return loss */
public int RLMP1; /*int32_t ORL marker 1 position */
public int RLMP2; /*int32_t ORL marker 2 position */
public int EEACI; /*int16_t End to End ACI */
public int LinkPassFailResult; /*uint16_t 0b00000000ddccbbaa, aa - link length pf status, bb - Loss pf status, cc - ACI pf status, dd - ORL pf status */
public int TimeStamp; /*uint32_t unix time since 1970-01-01 */
public int DefaultACI; //uint16_t
public int[] EventPassThrSplitterLossMin = new int[12]; /*uint16_t Event Splitter Loss Min pass threshold in dB*100 */
public int[] EventPassThrSplitterLossMax = new int[12]; /*uint16_t Event Splitter Loss Max pass threshold in dB*100 */
TestComParams_T c = new TestComParams_T(); /* common paramters */ //Bandyk dabar.
}
static class EvEventsS{
/*int16_t */int N; /* number of events */
/*int32_t */int LocationIndx[] = new int[MAX_TNKE+2];
/*int32_t */int EndIndx[] = new int[MAX_TNKE+2];
/*int32_t */int MaxIndx[] = new int[MAX_TNKE+2];
/*uint16_t*/int Type[] = new int[MAX_TNKE+2];
/*uint16_t*/int CustomType[] = new int[MAX_TNKE+2];
/*uint16_t*/int PassFail[] = new int[MAX_TNKE+2];
/*int16_t */int ACI[] = new int[MAX_TNKE+2];
/*int32_t */int ReflectionLevel[] = new int[MAX_TNKE+2];
/*int32_t */int InsertionLoss[] = new int[MAX_TNKE+2];
/*int32_t */int StartLevel[] = new int[MAX_TNKE+2];
/*int32_t */int LocStart_mm[] = new int[MAX_TNKE+2];
/*int32_t */int LocMax_mm[] = new int[MAX_TNKE+2];
/*int32_t */int LocEnd_mm[] = new int[MAX_TNKE+2];
/*int32_t */int PW_mm[] = new int[MAX_TNKE+2];
/*int32_t */int MaxLevel[] = new int[MAX_TNKE+2];
/*int32_t */int EndLevel[] = new int[MAX_TNKE+2];
/*int16_t */int SegmentID[] = new int[MAX_TNKE+2];
/*int16_t */int Flags[] = new int[MAX_TNKE+2];
/*uint16_t*/int SplitterRatio[] = new int[MAX_TNKE+2];
};
// test types
enum TestType_t{
TEST_TYPE_NONE,
TEST_TYPE_EXPERT,
TEST_TYPE_FULLAUTO,
TEST_TYPE_FILEOPEN,
TEST_TYPE_REALTIME,
TEST_TYPE_PMOTDR,
TEST_TYPE_OTDRONLY,
TEST_TYPE_ENDLOCATE,
TEST_TYPE_PMOTDR_SPLITTER,
TEST_TYPE_CHARACTERIZE,
TEST_TYPE_LOCATE_END_AND_FAULTS
}
enum FiberType_t{
FIBER_TYPE_SMF28E,
FIBER_TYPE_USER1,
FIBER_TYPE_USER2
}
enum PassFailType_t{
PASSFAIL_TYPE_ITUG671,
PASSFAIL_TYPE_TIA568_3D,
PASSFAIL_TYPE_USER1,
}
enum NetworkType_t{
NETWORK_TYPE_POINT_TO_POINT,
NETWORK_TYPE_PON,
}
boolean IS_TEST_TYPE_VALID(int t){ return (t <= TEST_TYPE_LOCATE_END_AND_FAULTS);}
boolean IS_FIBER_TYPE_VALID(int t){ return (t == FIBER_TYPE_SMF28E || t == FIBER_TYPE_USER1 || t == FIBER_TYPE_USER2);}
boolean IS_PASSFAIL_TYPE_VALID(int t){ return (t == PASSFAIL_TYPE_ITUG671 || t == PASSFAIL_TYPE_TIA568_3D || t == PASSFAIL_TYPE_USER1);}
boolean IS_NETWORK_TYPE_VALID(int t){ return (t == NETWORK_TYPE_POINT_TO_POINT || t == NETWORK_TYPE_PON);}
/**
* @brief Sor file read and parse function
* @param fp - file pointer,
* data - unsigned 16-bit integer data buffer
* tp - TestParams structure,
* Events - structure for KeyEvents
* @retval signed 8-bit integer read operation result 0-Pass, 1-Fail
*/
//int sorReadTraceData(FIL *fp, int data[], TestParamS * tp, EvEventsS * Events, int16_t wave)
static int crc16_table[] = {
0x0000, 0x1021, 0x2042, 0x3063, 0x4084, 0x50a5, 0x60c6, 0x70e7,
0x8108, 0x9129, 0xa14a, 0xb16b, 0xc18c, 0xd1ad, 0xe1ce, 0xf1ef,
0x1231, 0x0210, 0x3273, 0x2252, 0x52b5, 0x4294, 0x72f7, 0x62d6,
0x9339, 0x8318, 0xb37b, 0xa35a, 0xd3bd, 0xc39c, 0xf3ff, 0xe3de,
0x2462, 0x3443, 0x0420, 0x1401, 0x64e6, 0x74c7, 0x44a4, 0x5485,
0xa56a, 0xb54b, 0x8528, 0x9509, 0xe5ee, 0xf5cf, 0xc5ac, 0xd58d,
0x3653, 0x2672, 0x1611, 0x0630, 0x76d7, 0x66f6, 0x5695, 0x46b4,
0xb75b, 0xa77a, 0x9719, 0x8738, 0xf7df, 0xe7fe, 0xd79d, 0xc7bc,
0x48c4, 0x58e5, 0x6886, 0x78a7, 0x0840, 0x1861, 0x2802, 0x3823,
0xc9cc, 0xd9ed, 0xe98e, 0xf9af, 0x8948, 0x9969, 0xa90a, 0xb92b,
0x5af5, 0x4ad4, 0x7ab7, 0x6a96, 0x1a71, 0x0a50, 0x3a33, 0x2a12,
0xdbfd, 0xcbdc, 0xfbbf, 0xeb9e, 0x9b79, 0x8b58, 0xbb3b, 0xab1a,
0x6ca6, 0x7c87, 0x4ce4, 0x5cc5, 0x2c22, 0x3c03, 0x0c60, 0x1c41,
0xedae, 0xfd8f, 0xcdec, 0xddcd, 0xad2a, 0xbd0b, 0x8d68, 0x9d49,
0x7e97, 0x6eb6, 0x5ed5, 0x4ef4, 0x3e13, 0x2e32, 0x1e51, 0x0e70,
0xff9f, 0xefbe, 0xdfdd, 0xcffc, 0xbf1b, 0xaf3a, 0x9f59, 0x8f78,
0x9188, 0x81a9, 0xb1ca, 0xa1eb, 0xd10c, 0xc12d, 0xf14e, 0xe16f,
0x1080, 0x00a1, 0x30c2, 0x20e3, 0x5004, 0x4025, 0x7046, 0x6067,
0x83b9, 0x9398, 0xa3fb, 0xb3da, 0xc33d, 0xd31c, 0xe37f, 0xf35e,
0x02b1, 0x1290, 0x22f3, 0x32d2, 0x4235, 0x5214, 0x6277, 0x7256,
0xb5ea, 0xa5cb, 0x95a8, 0x8589, 0xf56e, 0xe54f, 0xd52c, 0xc50d,
0x34e2, 0x24c3, 0x14a0, 0x0481, 0x7466, 0x6447, 0x5424, 0x4405,
0xa7db, 0xb7fa, 0x8799, 0x97b8, 0xe75f, 0xf77e, 0xc71d, 0xd73c,
0x26d3, 0x36f2, 0x0691, 0x16b0, 0x6657, 0x7676, 0x4615, 0x5634,
0xd94c, 0xc96d, 0xf90e, 0xe92f, 0x99c8, 0x89e9, 0xb98a, 0xa9ab,
0x5844, 0x4865, 0x7806, 0x6827, 0x18c0, 0x08e1, 0x3882, 0x28a3,
0xcb7d, 0xdb5c, 0xeb3f, 0xfb1e, 0x8bf9, 0x9bd8, 0xabbb, 0xbb9a,
0x4a75, 0x5a54, 0x6a37, 0x7a16, 0x0af1, 0x1ad0, 0x2ab3, 0x3a92,
0xfd2e, 0xed0f, 0xdd6c, 0xcd4d, 0xbdaa, 0xad8b, 0x9de8, 0x8dc9,
0x7c26, 0x6c07, 0x5c64, 0x4c45, 0x3ca2, 0x2c83, 0x1ce0, 0x0cc1,
0xef1f, 0xff3e, 0xcf5d, 0xdf7c, 0xaf9b, 0xbfba, 0x8fd9, 0x9ff8,
0x6e17, 0x7e36, 0x4e55, 0x5e74, 0x2e93, 0x3eb2, 0x0ed1, 0x1ef0
};
/**
* @brief A CRC-CCITT, 16-bit checksum calculation function.
* @param crc - already calculated CRC value, buf - new data buffer, n - word count to calculate
* @retval unsigned 16-bit integer - new crc value
*/
static int sorCalcCrc(int crc,byte buf[], int n)
{
int i;
//uint8_t hbit, ptr = ;
int hbit;
int table_idx;
for (i = 0; i < n; i++ ) {
hbit = (crc & 0xff00) >> 8;
crc <<= 8;
crc = (crc & 0xffff);
table_idx = hbit ^ (buf[i] & 0xff);
crc ^= crc16_table [table_idx];
}
return crc;
}
/**
* @brief A CRC-CCITT, 16-bit checksum check funtion, reads entire file and compares calculated CRC value with value from file.
* @retval signed 8-bit integer CRC check result 0-Pass, 1-Fail
*/
static int sorCheckCrc(File file) throws IOException {
int crc,r_crc;
long n, br;
int r_crc_idx = 0;
fis = null;
fis = new FileInputStream(file);
Log.d(TAG, "Total file size (in bytes) : " + fis.available());
fsize = fis.available();
fis.getChannel().position(0);
if(fsize < 4)
{
return 1; /* return ERROR */
}
else
{
n = fsize;
n >>= 1;
n -= 1;
r_crc_idx = (int) (fsize-2);
}
crc = 0xffff;
//byte[] buf = new byte[(int)fsize];
byte[] buf = new byte[32767];
int r_bytes = 0;
long rb_left = fsize-2;
try{
while( rb_left != 0){
r_bytes = fis.read(buf, 0, buf.length);
if(r_bytes != -1){
if(r_bytes >= rb_left) {
crc = sorCalcCrc(crc, buf, (int)rb_left);
rb_left -= rb_left;
}else {
crc = sorCalcCrc(crc, buf, r_bytes);
rb_left -= r_bytes;
}
}
}
}catch (IOException e){
Log.e(TAG, "CRC: Read error: " + e.getMessage() );
}
fis.getChannel().position(fsize-2);
fis.read(buf, 0, 2);
byte[] arr = new byte[] {buf[0],buf[1]};
//ByteBuffer wrapped = ByteBuffer.wrap(arr); // big-endian by default
//r_crc = bytesToShort(arr);//wrapped.getShort(); bytesToShort(arr);//
r_crc = toInt(bytesToShort(arr));
if(crc != r_crc)
{
return 1; /* return ERROR */
}
return 0;
}
public static short bytesToShort(byte[] bytes) {
short retval = ByteBuffer.wrap(bytes).order(ByteOrder.LITTLE_ENDIAN).getShort();
retval &= 0x0000FFFF;
return retval;
}
public byte[] shortToBytes(short value) {
return ByteBuffer.allocate(2).order(ByteOrder.LITTLE_ENDIAN).putShort(value).array();
}
// packing an array of 4 bytes to an int, big endian
public static int bytesToInt(byte[] bytes) {
return bytes[3] << 24 | (bytes[2] & 0xFF) << 16 | (bytes[1] & 0xFF) << 8 | (bytes[0] & 0xFF);
}
static int sorReadTraceData(File file) throws IOException {
int error;
int dw; //uint32_t
int w; //uint16_t
byte[] BlockName = new byte[20];
//String BlockName = new String();
byte[] BlockRev = new byte[2];
byte[] BlockSize= new byte[4];
byte[] bNumberOfBlocks = new byte[2];
int AllSize;
int flg_DataPts, flg_GenParams,flg_SupParams, flg_FxdParams, flg_FodParams,
flg_Fod02Params, flg_Fod03Params, flg_Fod04Params, flg_Fod05Params, flg_KeyEvents;
int size_DataPts = 0;
int size_GenParams = 0;
int size_SupParams = 0;
int size_FxdParams = 0;
int size_FodParams = 0;
int size_Fod02Params = 0;
int size_Fod03Params = 0;
int size_Fod04Params = 0;
int size_Fod05Params = 0;
int size_KeyEvents = 0;
int rev_DataPts = 0;
int rev_GenParams = 0;
int rev_SupParams = 0;
int rev_FxdParams= 0;
int rev_FodParams= 0;
int rev_Fod02Params= 0;
int rev_Fod03Params = 0;
int rev_Fod04Params= 0;
int rev_Fod05Params= 0;
int rev_KeyEvents= 0;
int EPT; /*int32_t Event Propagation Time */
int ER; /*int32_t Event Reflectance */
int EN; /*int16_t Event Number */
int EL; /*int16_t Event Loss */
int ACI; /*int16_t Event Attenuation Coefficient */
byte EC[] = new byte[7]; /* Event Code */
int fod_ver = 0;
fis = new FileInputStream(file);
error = sorCheckCrc(file);
//error = 0;
if(error != 0){
fis.close();
return 1; /* return ERROR */
}
fis.getChannel().position(0);
TestParamS.c.LQC_Result = 0; /* initialize LQC Result */
TestParamS.EEACI = 0;
TestParamS.DefaultACI = 0;
TestParamS.c.RefreshTime = 100; /* 1 second */
TestParamS.c.LinkPassFailThresholdsOnOff[0] = 0;
TestParamS.c.EventPassFailThresholdsOnOff[0] = 0;
TestParamS.c.LinkPassThrLength[0] = PFT_THRESH_DFLT_LINK_LENGTH;
TestParamS.c.LinkPassThrLengthTolerance[0] = PFT_THRESH_DFLT_LINK_LENGTH_TOLERANCE;
TestParamS.c.LinkPassThrLoss[0] = PFT_THRESH_DFLT_LINK_LOSS;
TestParamS.c.LinkPassThrACI[0] = PFT_THRESH_DFLT_LINK_ACI;
TestParamS.c.LinkPassThrORL[0] = PFT_THRESH_DFLT_LINK_ORL;
TestParamS.c.EventPassThrConnLoss[0] = PFT_THRESH_DFLT_EVENT_CONN_LOSS;
TestParamS.c.EventPassThrConnRefl[0] = PFT_THRESH_DFLT_EVENT_CONN_REFL;
TestParamS.c.EventPassThrSpliceLoss[0] = PFT_THRESH_DFLT_EVENT_SPLICE_LOSS;
TestParamS.c.EventPassThrSplitter1Ratio[0] = 2 << PFT_THRESH_DFLT_EVENT_SPLITTER1_RATIO_INDX;
TestParamS.c.EventPassThrSplitter2Ratio[0] = 2 << PFT_THRESH_DFLT_EVENT_SPLITTER2_RATIO_INDX;
TestParamS.c.EventPassThrSplitter1LossTolerance[0] = PFT_THRESH_DFLT_EVENT_SPLITTER1_LOSS_TOLERANCE;
TestParamS.c.EventPassThrSplitter2LossTolerance[0] = PFT_THRESH_DFLT_EVENT_SPLITTER2_LOSS_TOLERANCE;
TestParamS.c.EventPassThrEndRefl[0] = PFT_THRESH_DFLT_EVENT_END_REFL;
TestParamS.c.EventPassThrACI[0] = PFT_THRESH_DFLT_EVENT_ACI;
TestParamS.c.LinkPassFailThresholdsOnOff[1] = 0;
TestParamS.c.EventPassFailThresholdsOnOff[1] = 0;
TestParamS.c.LinkPassThrLength[1] = PFT_THRESH_DFLT_LINK_LENGTH;
TestParamS.c.LinkPassThrLengthTolerance[1] = PFT_THRESH_DFLT_LINK_LENGTH_TOLERANCE;
TestParamS.c.LinkPassThrLoss[1] = PFT_THRESH_DFLT_LINK_LOSS;
TestParamS.c.LinkPassThrACI[1] = PFT_THRESH_DFLT_LINK_ACI;
TestParamS.c.LinkPassThrORL[1] = PFT_THRESH_DFLT_LINK_ORL;
TestParamS.c.EventPassThrConnLoss[1] = PFT_THRESH_DFLT_EVENT_CONN_LOSS;
TestParamS.c.EventPassThrConnRefl[1] = PFT_THRESH_DFLT_EVENT_CONN_REFL;
TestParamS.c.EventPassThrSpliceLoss[1] = PFT_THRESH_DFLT_EVENT_SPLICE_LOSS;
TestParamS.c.EventPassThrSplitter1Ratio[1] = 2 << PFT_THRESH_DFLT_EVENT_SPLITTER1_RATIO_INDX;
TestParamS.c.EventPassThrSplitter2Ratio[1] = 2 << PFT_THRESH_DFLT_EVENT_SPLITTER2_RATIO_INDX;
TestParamS.c.EventPassThrSplitter1LossTolerance[1] = PFT_THRESH_DFLT_EVENT_SPLITTER1_LOSS_TOLERANCE;
TestParamS.c.EventPassThrSplitter2LossTolerance[1] = PFT_THRESH_DFLT_EVENT_SPLITTER2_LOSS_TOLERANCE;
TestParamS.c.EventPassThrEndRefl[1] = PFT_THRESH_DFLT_EVENT_END_REFL;
TestParamS.c.EventPassThrACI[1] = PFT_THRESH_DFLT_EVENT_ACI;
TestParamS.c.EventPassThrSplitterRefl = PFT_THRESH_DFLT_EVENT_SPLITTER_REFL;
TestParamS.LinkPassFailResult = 0;
f_gets(BlockName, 5);
if (!((BlockName[0] == 'M') && (BlockName[1] == 'a') && (BlockName[2] == 'p')))
{
fis.getChannel().position(0);/* if no 'Map\0' BLOCK ID then it's SOR1, so read from beginning */
}
fis.read(BlockRev, 0, BlockRev.length);/* Map Block revision */
fis.read(BlockSize, 0, BlockSize.length);/* Map Block size */
fis.read(bNumberOfBlocks, 0, bNumberOfBlocks.length);/* Number of Blocks */
int NumberOfBlocks = bytesToShort(bNumberOfBlocks);
if (bytesToInt(BlockSize) > MAX_BLOCKSIZE) return 1;
AllSize = bytesToInt(BlockSize);
flg_DataPts = 0;
flg_GenParams = 0;
flg_SupParams = 0;
flg_FxdParams = 0;
flg_FodParams = 0;
flg_Fod02Params = 0;
flg_Fod03Params = 0;
flg_Fod04Params = 0;
flg_Fod05Params = 0;
flg_KeyEvents = 0;
for (int i = 0; i < NumberOfBlocks - 1; i++)
{
String strBlockName = f_gets();;
fis.read(BlockRev, 0, BlockRev.length); /* Block Revision No */
fis.read(BlockSize, 0, BlockSize.length); /* Block size */
if (bytesToInt(BlockSize) > MAX_BLOCKSIZE) return 1;
if (strBlockName.compareTo("DataPts") == 0){
flg_DataPts = 1;
size_DataPts = AllSize;
rev_DataPts = bytesToShort(BlockRev);
}else if (strBlockName.compareTo("GenParams") == 0){
flg_GenParams = 1;
rev_GenParams = bytesToShort(BlockRev);
size_GenParams = AllSize;
}else if (strBlockName.compareTo("SupParams") == 0){
flg_SupParams = 1;
size_SupParams = AllSize;
rev_SupParams = bytesToShort(BlockRev);
}else if (strBlockName.compareTo("FxdParams") == 0){
flg_FxdParams = 1;
size_FxdParams = AllSize;
rev_FxdParams = bytesToShort(BlockRev);
}else if (strBlockName.compareTo("FodParams") == 0){
flg_FodParams = 1;
size_FodParams = AllSize;
rev_FodParams = bytesToShort(BlockRev);
}else if (strBlockName.compareTo("Fod02Params") == 0){
flg_Fod02Params = 1;
size_Fod02Params = AllSize;
rev_Fod02Params = bytesToShort(BlockRev);
}else if (strBlockName.compareTo("Fod03Params") == 0){
flg_Fod03Params = 1;
size_Fod03Params = AllSize;
rev_Fod03Params = bytesToShort(BlockRev);
}else if (strBlockName.compareTo("Fod04Params") == 0){
flg_Fod04Params = 1;
size_Fod04Params = AllSize;
rev_Fod04Params = bytesToShort(BlockRev);
}else if (strBlockName.compareTo("Fod05Params") == 0){
flg_Fod05Params = 1;
size_Fod05Params = AllSize;
rev_Fod05Params = bytesToShort(BlockRev);
}else if (strBlockName.compareTo("KeyEvents") == 0){
flg_KeyEvents = 1;
size_KeyEvents = AllSize;
rev_KeyEvents = bytesToShort(BlockRev);
}
AllSize = AllSize + bytesToInt(BlockSize);
}
if (flg_DataPts == 1)
{
/* read data points */
fis.getChannel().position(size_DataPts);
if (rev_DataPts >= 200){
fis.getChannel().position(fis.getChannel().position()+8);
}
TestParamS.c.TNDP = f_read_int32(); /* Total Number of Data Points */
if (TestParamS.c.TNDP > MAX_TNDP){
TestParamS.c.TNDP = MAX_TNDP;
}
fis.getChannel().position(fis.getChannel().position()+8);
int DataSize = TestParamS.c.TNDP;
int DataPointIdx = 0;
sk = new int[TestParamS.c.TNDP];
//int skIdx = 0;
while(DataSize-- != 0){
//data[DataPointIdx++] = f_read_unt16(); /* read data points */
//sk[skIdx] = toInt((short)data[skIdx]);
//skIdx++;
sk[DataPointIdx++] = toInt((short) f_read_unt16());
}
}
if (flg_GenParams == 1)
{
fis.getChannel().position(size_GenParams + 2);
if (rev_GenParams >= 0xC8) {
fis.getChannel().position(fis.getChannel().position()+10);
}
TestParamS.CID = f_gets();
TestParamS.FID = f_gets();
if (rev_GenParams >= 0xC8){
fis.getChannel().position(fis.getChannel().position()+2); /* Fiber Type */
}
TestParamS.NW = f_read_unt16(); /* Nominal Wavelength */
TestParamS.OL = f_gets();
TestParamS.TL = f_gets();
TestParamS.CCD = f_gets();
fis.getChannel().position(fis.getChannel().position()+2);
int uo = f_read_int32(); /* User Offset */
TestParamS.UO = uo; /* User Offset */
}
if (flg_SupParams == 1)
{
fis.getChannel().position(size_SupParams);
if (rev_SupParams >= 0xC8) {
fis.getChannel().position(fis.getChannel().position()+10);
}
TestParamS.SN = f_gets();
TestParamS.MFID = f_gets();
TestParamS.OTDR = f_gets();
TestParamS.OMID = f_gets();
TestParamS.OMSN = f_gets();
TestParamS.SR = f_gets();
TestParamS.OT = f_gets();
}
if (flg_FxdParams == 1)
{
int it;
if (rev_FxdParams >= 0xC8) {
fis.getChannel().position(size_FxdParams + 10);
}else {
fis.getChannel().position(size_FxdParams);
}
dw = f_read_int32();
TestParamS.TimeStamp = dw;
w = f_read_unt16(); /* Units of Distance */
w = f_read_unt16(); /* Actual Wavelength */
TestParamS.c.AO = f_read_int32(); /* Acquisition Offset */
if (rev_FxdParams >= 0xC8){
fis.getChannel().position(fis.getChannel().position() + 4);/* Acquisition Offset Distance */
}
TestParamS.c.TPW = f_read_unt16(); /* Total Number of Pulse Widths Used */
if (TestParamS.c.TPW > 1){
return 1;
}
w = f_read_unt16(); /* Pulse Widths Used */
if ((w==101)||(w==301)||(w==1001)||(w==3001)) w--;
TestParamS.c.PWU = w;
//it = hostifPwCheck(TestParamS.c.PWU);
//if(it == 0){return 1;} /* return ERROR */
//TestParamS.c.Test_PwIndx = it-1;
TestParamS.c.Test_PwIndx = 0;
if (TestParamS.c.TPW > 2)
{
fis.getChannel().position(fis.getChannel().position() + 2 * (TestParamS.c.TPW - 1));
}
TestParamS.c.DS = f_read_int32(); /* Data Spacing */
if (TestParamS.c.TPW > 2)
{
fis.getChannel().position(fis.getChannel().position() + 4 * (TestParamS.c.TPW - 1));
}
TestParamS.c.NPPW = f_read_int32(); /* Number of Data Points for Each Pulse Width */
if (TestParamS.c.TPW > 2)
{
fis.getChannel().position(fis.getChannel().position() + 4 * (TestParamS.c.TPW - 1));
}
TestParamS.GI = f_read_int32(); /* Group Index */
TestParamS.BC = f_read_unt16(); /* Backscater Coefficient */
TestParamS.NAV = f_read_int32(); /* Number of Averages */
if (rev_FxdParams >= 0xC8){
fis.getChannel().position(fis.getChannel().position() + 2); /* Acquisition Time */
}
TestParamS.c.AR = f_read_int32(); /* Acquisition Range */
if (rev_FxdParams >= 0xC8){
fis.getChannel().position(fis.getChannel().position() + 4);/* Acquisition Range Distance */
}
TestParamS.FPO = f_read_int32(); /* Front Panel Offset */
TestParamS.NF = f_read_unt16(); /* Noise Floor Level */
fis.getChannel().position(fis.getChannel().position() + 4);
TestParamS.LT = f_read_unt16(); /* Loss Threshold */
TestParamS.RT = f_read_unt16(); /* Reflectance Threshold */
TestParamS.ET = f_read_unt16(); /* End-of-Fiber Threshold */
}
if (flg_FodParams == 1) {
/* Fod Parameters Block */
fis.getChannel().position(size_FodParams);
if (rev_FodParams >= 0xC8){
fis.getChannel().position(fis.getChannel().position() + 10);
}
w = f_read_unt16(); /* Magic number */
if(w != BELL_FODPARAMS_MAGIC)
{
return 0; /* return */
}
w = f_read_unt16(); /* Block Version */
if(w >= 6) {
fod_ver = w;
//BellFodParamsVerOK = 1;
}
else{ return 1; /* return ERROR */
}
w = f_read_unt16(); /* Resolution */
if (fod_ver >= 0x0010){
TestParamS.c.Resolution = w;
}else{
TestParamS.c.Resolution = 0xffff;
}
//i = testPFilterIndxCheck(w);
//if(i==0){return 1;} /* return ERROR */
//tp->Test_FilterIndx = w;
w = f_read_unt16(); /* Average time in 100 ms */
//i = testPAvgTimeCheck(w);
//if(i==0){return 1;} /* return ERROR */
//tp->Test_AvgIndx = i-1;
TestParamS.c.TestTime = w;
w = f_read_unt16(); /* Test Range Index */
//i = testPRangeIndxCheck(w);
//if(i==0){return 1;} /* return ERROR */
TestParamS.c.Test_RangeIndx = w;
w = f_read_unt16(); /* Test Mode */
//i = testPTestModeCheck(w);
//if(i==0){return 1;} /* return ERROR */
TestParamS.c.Test_Mode = w;
w = f_read_unt16(); /* Event Mode */
//i = testPEventModeCheck(w);
//if(i==0){return 1;} /* return ERROR */
TestParamS.c.Event_Mode = w;
w = f_read_unt16(); /* Front Panel Offset */
//i = testPFrontPanelOffsetCheck(dw);
//if(i==0){return 1;} /* return ERROR */
//tp->c->FPO = dw;
//BellFodParamsFPO = dw/2;
dw = f_read_int32(); /* Launch Cable */
//i = testPLaunchCableCheck(dw);
//if(i==0){return 1;} /* return ERROR */
TestParamS.c.Cable_Launch_cm = dw;
dw = f_read_int32(); /* Receive Cable */
//i = testPReceiveCableCheck(dw);
//if(i==0){return 1;} /* return ERROR */
TestParamS.c.Cable_Receive_cm = dw;
if (fod_ver >= 7)
{
w = f_read_unt16(); /* Live Fiber */
TestParamS.c.Live_Fiber = w;
if (fod_ver >= 8)
{
int indx;
ldiv_t res;
dw = f_read_int32(); /* Marker 1 location in 100 ps */
dw += TestParamS.FPO + TestParamS.UO;
dw *= 100;
res = ldiv(dw, (TestParamS.c.DS / 100));
indx = (int) res.quot;
if(res.rem == 1){
indx++;
}
TestParamS.c.marker1_val = indx;
dw = f_read_int32(); /* Marker 2 location in 100 ps */
dw += TestParamS.FPO + TestParamS.UO;
dw *= 100;
res = ldiv(dw, (TestParamS.c.DS / 100));
indx = (int) res.quot;
if(res.rem == 1)
{
indx++;
}
TestParamS.c.marker2_val = indx;
if (fod_ver >= 17)
{
w = f_read_unt16(); /* LQC Result */
TestParamS.c.LQC_Result = w;
if (fod_ver >= 18)
{
w = f_read_unt16(); /* Network type */
TestParamS.c.Network_Type = w;
w = f_read_unt16(); /* Pass/Fail type */
TestParamS.c.PassFail_Type = w;
if (fod_ver >= 19)
{
w = f_read_unt16(); /* End to End ACI */
TestParamS.EEACI = w;
if (fod_ver >= 20){
w = f_read_unt16(); /* Default ACI */
TestParamS.DefaultACI = w;
}
}
}
else
{
TestParamS.c.Network_Type = 0;
TestParamS.c.PassFail_Type = 0;
}
}
}
else{
TestParamS.c.marker1_val = 0;
TestParamS.c.marker2_val = 0;
}
}
else
{
TestParamS.c.Live_Fiber = 0;
}
}
TestParamS.EEL = 0;
TestParamS.ELMP1 = 0;
TestParamS.ELMP2 = 0;
TestParamS.ORL = 0;
TestParamS.RLMP1 = 0;
TestParamS.RLMP2 = 0;
if ((flg_KeyEvents == 1) && (Events != null))
{
EvEventPS ev;
int indx; //int32_t
ldiv_t res;
fis.getChannel().position(size_KeyEvents);
if (rev_KeyEvents >= 0xC8){
fis.getChannel().position(fis.getChannel().position() + 10);
}
TestParamS.TNKE = f_read_unt16(); /* Number of Key Events */
if (TestParamS.TNKE > MAX_TNKE){return 1;}
Events.N = 0;
for (int i = 0; i < TestParamS.TNKE; i++)
{
EN = f_read_unt16(); /* Event Number */
EPT = f_read_int32(); /* Event Propagation Time */
ACI = f_read_unt16(); /* Event Attenuation Coefficient */
EL = f_read_unt16(); /* Event Loss */
ER = f_read_int32(); /* Event Reflectance */
fis.read(EC,0,EC.length);
fis.getChannel().position(fis.getChannel().position() + 2);
if (rev_KeyEvents >= 0xC8){
fis.getChannel().position(fis.getChannel().position() + 20); /*Marker locations*/
}
f_gets();
//EPT += tp->c->FPO + tp->UO;
//EPT *= 100;
res = ldiv(EPT, (TestParamS.c.DS / 100));
indx = (int) res.quot;
if(res.rem == 1)
{
indx++;
}
//ev.LocStart_mm = SamplesToRangemm(indx - (tp->c->FPO + tp->UO)*10000/tp->c->DS, tp->c->DS, tp->GI);
Events.LocStart_mm[i] = Time100psToRangemm(2*(EPT + TestParamS.UO), TestParamS.GI);
Events.LocEnd_mm [i] = Events.LocStart_mm[i];
Events.LocationIndx[i] = indx;
Events.InsertionLoss [i] = EL;
Events.ReflectionLevel [i] = ER;
Events.ACI [i] = ACI;
Events.Type [i] = (EC[1] << 8) + EC[0];
Events.PassFail [i] = 0;
Events.PW_mm [i] = 0;
Events.SplitterRatio [i] = 0;
if (EN == i + 1)
{
Events.N++;
}
else
{
break;
}
}
TestParamS.EEL = f_read_int32(); /* End to End loss (EEL) */
TestParamS.ELMP1 = f_read_int32(); /* EEL marker 1 */
TestParamS.ELMP2 = f_read_int32(); /* EEL marker 2 */
TestParamS.ORL = f_read_unt16(); /* optical return loss (ORL) */
TestParamS.RLMP1 = f_read_int32(); /* ORL marker 1 */
TestParamS.RLMP2 = f_read_int32(); /* ORL marker 2 */
/*FOD02Params start finish*/
if ((flg_Fod02Params==1) && (Events != null))
{
int n_ev, ev_code; //uint16_t
//int EN; //uint16_t
/* Fod Parameters Block */
fis.getChannel().position(size_Fod02Params);
if (rev_Fod02Params >= 0xC8){
fis.getChannel().position(fis.getChannel().position() + 12);
}
w = f_read_unt16(); /* Number of events */
n_ev = w;
for(int i = 0; i < n_ev; i++)
{
w = f_read_unt16(); /* Event number */
EN = w;
dw = f_read_int32(); /* Event Tail Propagation Time*/
EPT = dw;
//EPT += tp->c->FPO + tp->UO;
//EPT *= 100;
res = ldiv(EPT, (TestParamS.c.DS/100));
indx = (int) res.quot;
if(res.rem == 1){indx++;}
w = f_read_unt16(); /* Custom Event Code */
ev_code = w;
if (EN-1 < TestParamS.TNKE){
Events.EndIndx[EN-1] = indx;
Events.LocEnd_mm[EN-1] = Time100psToRangemm(2*(EPT + TestParamS.UO), TestParamS.GI);
//Events.LocEnd_mm[EN-1] = SamplesToRangemm(indx - (tp->c->FPO + tp->UO)*10000/tp->c->DS, tp->c->DS, tp->GI);
if (fod_ver < 21){
switch(ev_code){
case EV_CODE_MB:
Events.CustomType[EN-1] = EV_CTYPEN_MSK_MACROBEND;
break;
case EV_CODE_SP:
Events.CustomType[EN-1] = EV_CTYPEN_MSK_SPLITTER;
break;
case EV_CODE_GS:
Events.CustomType[EN-1] = EV_CTYPEN_MSK_GR_START;
break;
case EV_CODE_GM:
Events.CustomType[EN-1] = EV_CTYPEN_MSK_GR_MIDDLE;
break;
case EV_CODE_GE:
Events.CustomType[EN-1] = EV_CTYPEN_MSK_GR_END;
break;
case EV_CODE_ST:
Events.CustomType[EN-1] = EV_CTYPEN_MSK_LINK_START;
break;
case EV_CODE_SG:
Events.CustomType[EN-1] = EV_CTYPEN_MSK_LINK_START|EV_CTYPEN_MSK_GR_START;
break;
case EV_CODE_EG:
Events.CustomType[EN-1] = EV_CTYPEN_MSK_GR_END;
break;
case EV_CODE_EN:
Events.CustomType[EN-1] = EV_CTYPEN_MSK_LINK_END;
break;
case EV_CODE_MS:
Events.CustomType[EN-1] = EV_CTYPEN_MSK_MACROBEND|EV_CTYPEN_MSK_SPLITTER;
break;
default:
Events.CustomType[EN-1] = EV_CTYPEN_MSK_SIMPLE;
break;
}
}else{
Events.CustomType[EN-1] = ev_code;
}
}
}
}
/*FOD02Params read finish*/
if ((flg_Fod03Params == 1) && (Events != null))
{
/* Fod Parameters Block */
fis.getChannel().position(fis.getChannel().position() + size_Fod03Params);
if (rev_Fod03Params >= 0xC8){
fis.getChannel().position(fis.getChannel().position() + 12);
}
w = f_read_unt16(); /* MB Fixed Part */
w = f_read_unt16(); /* MB GIR Error */
w = f_read_unt16(); /* MB Pulse Rounding*/
w = f_read_unt16(); /* MB Digitizing Error */
w = f_read_unt16(); /* MB Variable Part */
w = f_read_unt16(); /* Splitter Detection Threshold*/
w = f_read_unt16(); /* MB Setting */
TestParamS.c.MacrobendDetection = w;
}
if ((flg_Fod05Params == 1) && (Events != null))
{
int n_ev; //uint16_t
int ev_ratio; //uint16_t
/* Fod Parameters Block */
fis.getChannel().position(size_Fod05Params);
if (rev_Fod05Params >= 0xC8) {
fis.getChannel().position(fis.getChannel().position() + 12);
}
w = f_read_unt16(); /* Magic number */
if(w != BELL_FODPARAMS_MAGIC)
{
return 0; /* return */
}
w = f_read_unt16(); /* Block Version */
if(w >= 0x0001)
{
fod_ver = w;
}
else{
return 1; /* return ERROR */
}
for (int i = 0 ; i < 12; i++){
TestParamS.EventPassThrSplitterLossMin[i] = f_read_unt16();
TestParamS.EventPassThrSplitterLossMax[i] = f_read_unt16();
}
TestParamS.c.EventPassThrSplitterRefl = f_read_unt16();
/* PON config */
for(int i = 0; i < 3; i++){
TestParamS.c.ev_spl_cfg.r1[i] = f_read_unt16();
TestParamS.c.ev_spl_cfg.r2[i] = f_read_unt16();
}
w = f_read_unt16(); /* Number of events */
n_ev = w;
for(int i = 0; i < n_ev; i++)
{
w = f_read_unt16(); /* Event number */
EN = w;
w = f_read_unt16(); /* Event Pass/Fail Status*/
ev_ratio = w;
if (EN-1 < TestParamS.TNKE){
Events.SplitterRatio[EN-1] = ev_ratio & 0x7ff;
}
}
}else{
//pf_assign_splitter_ratios(tp, Events);
//pftFillThrToTestParams(tp);
}
if ((flg_Fod04Params == 1) && (Events != null))
{
int n_ev; //uint16_t
int ev_passfail; //uint16_t
/* Fod Parameters Block */
fis.getChannel().position(size_Fod04Params);
if (rev_Fod04Params >= 0xC8){
fis.getChannel().position(fis.getChannel().position() + 12);
}
w = f_read_unt16(); /* Magic number */
if(w != BELL_FODPARAMS_MAGIC)
{
return 0; /* return */
}
w = f_read_unt16(); /* Block Version */
if(w >= 0x0001)
{
fod_ver = w;
//BellFodParamsVerOK = 1;
}else{
return 1; /* return ERROR */
}
w = f_read_unt16(); /* Link Length P/F */
TestParamS.LinkPassFailResult = w & 3;
w = f_read_unt16(); /* Link Loss P/F */
TestParamS.LinkPassFailResult |= (w << 2);
w = f_read_unt16(); /* Link Loss/Dist. P/F */
TestParamS.LinkPassFailResult |= (w << 4);
w = f_read_unt16(); /* Link ORL P/F */
TestParamS.LinkPassFailResult |= (w << 6);
if (fod_ver >= 0x0002)
{
w = f_read_unt16(); /* Link Pass Thresholds On/off */
TestParamS.c.LinkPassFailThresholdsOnOff[0] = w;
w = f_read_unt16(); /* Event Pass Fail Thresholds On/Off */
TestParamS.c.EventPassFailThresholdsOnOff[0] = w;
dw = f_read_int32(); /* Link Length Threshold */
TestParamS.c.LinkPassThrLength[0] = dw;
w = f_read_unt16(); /* Link Length Tolerance Threshold */
TestParamS.c.LinkPassThrLengthTolerance[0] = w;
w = f_read_unt16(); /* Link Loss Threshold */
TestParamS.c.LinkPassThrLoss[0] = w;
w = f_read_unt16(); /* Link Loss/Distance Threshold */
TestParamS.c.LinkPassThrACI[0] = w;
w = f_read_unt16(); /* Link ORL Threshold */
TestParamS.c.LinkPassThrORL[0] = w;
w = f_read_unt16(); /* Event Conn. Loss Threshold */
TestParamS.c.EventPassThrConnLoss[0] = w;
w = f_read_unt16(); /* Event Conn. Refl. Threshold */
TestParamS.c.EventPassThrConnRefl[0] = w;
w = f_read_unt16(); /* Event Splice Loss Threshold */
TestParamS.c.EventPassThrSpliceLoss[0] = w;
w = f_read_unt16(); /* Event Splitter 1 Ratio */
TestParamS.c.EventPassThrSplitter1Ratio[0] = w;
w = f_read_unt16(); /* Event Splitter 2 Ratio */
TestParamS.c.EventPassThrSplitter2Ratio[0] = w;
w = f_read_unt16(); /* Event Splitter 1 Loss Tolerance */
TestParamS.c.EventPassThrSplitter1LossTolerance[0] = w;
w = f_read_unt16(); /* Event Splitter 2 Loss Tolerance */
TestParamS.c.EventPassThrSplitter2LossTolerance[0] = w;
w = f_read_unt16(); /* Event End Refl. Threshold */
TestParamS.c.EventPassThrEndRefl[0] = w;
w = f_read_unt16(); /* Event Fiber Section Loss/Dist. (ACI) Threshold */
TestParamS.c.EventPassThrACI[0] = w;
if (fod_ver >= 0x0003){
w = f_read_unt16(); /* Link Fault Thresholds On/off */
TestParamS.c.LinkPassFailThresholdsOnOff[1] = w;
w = f_read_unt16(); /* Event Fault Thresholds On/Off */
TestParamS.c.EventPassFailThresholdsOnOff[1] = w;
dw = f_read_int32(); /* Link Length Fault Threshold */
TestParamS.c.LinkPassThrLength[1] = dw;
w = f_read_unt16(); /* Link Length Tolerance Fault Threshold */
TestParamS.c.LinkPassThrLengthTolerance[1] = w;
w = f_read_unt16(); /* Link Loss Fault Threshold */
TestParamS.c.LinkPassThrLoss[1] = w;
w = f_read_unt16(); /* Link Loss/Distance Fault Threshold */
TestParamS.c.LinkPassThrACI[1] = w;
w = f_read_unt16(); /* Link ORL Fault Threshold */
TestParamS.c.LinkPassThrORL[1] = w;
w = f_read_unt16(); /* Event Conn. Loss Fault Threshold */
TestParamS.c.EventPassThrConnLoss[1] = w;
w = f_read_unt16(); /* Event Conn. Refl. Fault Threshold */
TestParamS.c.EventPassThrConnRefl[1] = w;
w = f_read_unt16(); /* Event Splice Loss Fault Threshold */
TestParamS.c.EventPassThrSpliceLoss[1] = w;
w = f_read_unt16(); /* Event Splitter 1 Ratio */
TestParamS.c.EventPassThrSplitter1Ratio[1] = w;
w = f_read_unt16(); /* Event Splitter 2 Ratio */
TestParamS.c.EventPassThrSplitter2Ratio[1] = w;
w = f_read_unt16(); /* Event Splitter 1 Loss Fault Tolerance */
TestParamS.c.EventPassThrSplitter1LossTolerance[1] = w;
w = f_read_unt16(); /* Event Splitter 2 Loss Fault Tolerance */
TestParamS.c.EventPassThrSplitter2LossTolerance[1] = w;
w = f_read_unt16(); /* Event End Refl. Fault Threshold */
TestParamS.c.EventPassThrEndRefl[1] = w;
w = f_read_unt16(); /* Event Fiber Section Loss/Dist. (ACI) Fault Threshold */
TestParamS.c.EventPassThrACI[1] = w;
fis.getChannel().position(fis.getChannel().position() + 60);
}else{
fis.getChannel().position(fis.getChannel().position() + 94);
}
}else{
fis.getChannel().position(fis.getChannel().position() + 128);
}
w = f_read_unt16(); /* Number of events */
n_ev = w;
for(int i = 0; i < n_ev; i++){
w = f_read_unt16(); /* Event number */
EN = w;
w = f_read_unt16(); /* Event Pass/Fail Status*/
ev_passfail = w;
if (EN-1 < TestParamS.TNKE){
Events.PassFail[EN-1] = ev_passfail;
}
}
}
}
TestParamS.TraceValid = 1;
return 0;
}
static int f_read_unt16() throws IOException {
byte[] byteData= new byte[2];
fis.read(byteData,0, byteData.length);
return bytesToShort(byteData);
}
static int f_read_int32() throws IOException {
byte[] byteData= new byte[4];
fis.read(byteData,0, byteData.length);
return bytesToInt(byteData);
}
static void f_gets(byte str[], int len) throws IOException {
int ch = 0;
while (len != 0){
byte[] b = new byte[1];
fis.read(b);
str[ch++] = b[0];
len--;
if(b[0] == '\0'){
str[ch++] = '\n';
return;
}
}
}
int hostifPwCheck(int pw)
{
int i;
int hostif_pws[] = {3, 5, 10, 20, 25, 30, 50, 100, 200, 300, 500, 1000, 2000, 3000, 5000, 10000, 20000};
for(i = 0; i < 17; i++){
if(hostif_pws[i] == pw){
return i+1;
}
}
return 0;
}
static String f_gets() throws IOException {
String str = "";
byte[] b = new byte[1];
for(;;) {
fis.read(b);
if(b[0] == '\0'){
return str;
}
str += (char) b[0];
}
}
static ldiv_t ldiv(long numer, long denom){
ldiv_t ret_val = new ldiv_t();
ret_val.quot = numer/denom;
ret_val.rem = numer % denom;
return ret_val;
}
/* two way time -> mm */
static int Time100psToRangemm(int t, int gir)
{
double mm;
mm = ((LightVelocity * 100.0)/gir) * t;
return (int) Math.round(mm);
}
static String getEventName(int ev_nr){
String str = "";
Boolean have_type = false;
if(Events.CustomType[ev_nr] == 0){
if((Events.Type[ev_nr] & 0x00FF)== 0x30){
str = "SPLICE";
}else{
str = "CONNECTOR";
}
}else{
if((Events.CustomType[ev_nr] & EV_CTYPEN_MSK_MACROBEND) != 0){
str += "MACROBEND";
have_type = true;
}
if((Events.CustomType[ev_nr] & EV_CTYPEN_MSK_SPLITTER) != 0){
if(have_type){ str += ", "; }
str += "SPLITTER";
have_type = true;
}
if((Events.CustomType[ev_nr] & EV_CTYPEN_MSK_GR_START) != 0){
if(have_type){ str += ", "; }
str += "MACROBEND";
have_type = true;
}
if((Events.CustomType[ev_nr] & EV_CTYPEN_MSK_GR_MIDDLE) != 0){
if(have_type){ str += ", "; }
str += "GR_MIDDLE";
have_type = true;
}
if((Events.CustomType[ev_nr] & EV_CTYPEN_MSK_GR_END) != 0){
if(have_type){ str += ", "; }
str += "GR_END";
have_type = true;
}
if((Events.CustomType[ev_nr] & EV_CTYPEN_MSK_LINK_START) != 0){
if(have_type){ str += ", "; }
str += "LINK_START";
have_type = true;
}
if((Events.CustomType[ev_nr] & EV_CTYPEN_MSK_LINK_END) != 0){
if(have_type){ str += ", "; }
str += "LINK_END";
}
}
return str;
}
static String getLen_KM(int ev_nr){
String str = "";
double l = Events.LocStart_mm[ev_nr]*0.000001;
str = String.format("%.05f", l);
return str;
}
static String getSectionLen_KM(int ev_nr){
String str = "";
double l = (Events.LocStart_mm[ev_nr+1] - Events.LocStart_mm[ev_nr]) * 0.000001;
str = String.format("%.05f", l);
return str;
}
static String getLost(int ev_nr){
String str = " - ";
if(Events.InsertionLoss[ev_nr] != 0) {
double l = Events.InsertionLoss[ev_nr] * 0.001 ;
str = String.format("%.03f", l);
}
return str;
}
static String getSectiontLost(int ev_nr){
String str = " - ";
if(Events.ACI[ev_nr+1] != 0) {
double len = (Events.LocStart_mm[ev_nr+1] - Events.LocStart_mm[ev_nr]) * 0.000001;
double l = (len*Events.ACI[ev_nr+1]) * 0.001;
str = String.format("%.03f", l);
}
return str;
}
static String getRef(int ev_nr){
String str = " - ";
if(Events.ReflectionLevel[ev_nr] != 0) {
double l = Events.ReflectionLevel[ev_nr] * 0.001;
str = String.format("%.03f", l);
}
return str;
}
static String getACI(int ev_nr){
String str = " - ";
if(Events.ACI[ev_nr] != 0) {
double l = Events.ACI[ev_nr] * 0.001;
str = String.format("%.03f", l);
}
return str;
}
static String getDeviceId(){
String str = " - ";
//if(TestParamS. != 0) {
// double l = Events.ACI[ev_nr] * 0.001;
// str = String.format("%.03f", l);
//}
return str;
}
public static byte[] toBytes(short s) {
return new byte[]{0, 0, (byte) ((s & 0xFF00) >> 8), (byte) (s & 0x00FF)};
}
public static int toInt(short short_arr) {
byte[] arr = toBytes(short_arr);
//ByteBuffer buf = ByteBuffer.wrap(arr); // big-endian by default
ByteBuffer buf = ByteBuffer.wrap(arr);
return buf.getInt();
}
public static String getDateCurrentTimeZone(long timestamp) {
String date = "";
try{
Calendar cal = Calendar.getInstance(Locale.getDefault());
cal.setTimeInMillis(timestamp * 1000L);
date = DateFormat.format("yyyy-MM-dd hh:mm:ss", cal).toString();
}catch (Exception e) {
}
return date;
}
}
|
package com.ipincloud.iotbj.srv.service.impl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import java.util.List;
import java.util.ArrayList;
import java.util.Map;
import java.util.HashMap;
import com.alibaba.fastjson.JSONObject;
import com.ipincloud.iotbj.srv.domain.Fileitem;
import com.ipincloud.iotbj.srv.dao.*;
import com.ipincloud.iotbj.srv.service.FileitemService;
import com.ipincloud.iotbj.utils.ParaUtils;
//(Fileitem) 服务实现类
//generate by redcloud,2020-07-24 19:59:20
@Service("FileitemService")
public class FileitemServiceImpl implements FileitemService {
@Resource
private FileitemDao fileitemDao;
//@param id 主键
//@return 实例对象Fileitem
@Override
public Fileitem queryById(Long id){
return this.fileitemDao.queryById(id);
}
//已处理,参看统一接口/hyupload
}
|
package zj.unit;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.embedded.EmbeddedChannel;
import org.junit.Test;
import java.util.Queue;
import static org.junit.Assert.*;
/**
* Created by lzj on 2017/4/23.
*/
public class TestEmbeded {
/**
*
*/
@Test
public void test01() throws Exception {
ByteBuf b = Unpooled.buffer();
for (int i = 0; i < 9; i++) {
b.writeByte(i);
}
ByteBuf input = b.copy();
EmbeddedChannel channel = new EmbeddedChannel(new FixedLengFrameDecoder(3));
//写入9个字节
assertTrue(channel.writeInbound(input));
assertTrue(channel.finish());
//读取数据
assertEquals(b.readBytes(3), channel.readInbound());
assertEquals(b.readBytes(3), channel.readInbound());
assertEquals(b.readBytes(3), channel.readInbound());
assertNull(channel.readInbound());
}
@Test
public void testFramesDecoded2() {
ByteBuf buf = Unpooled.buffer();
for (int i = 0; i < 9; i++) {
buf.writeByte(i);
}
ByteBuf input = buf.duplicate();
EmbeddedChannel channel = new EmbeddedChannel(new
FixedLengFrameDecoder(3));
assertFalse(channel.writeInbound(input.readBytes(2)));
assertTrue(channel.writeInbound(input.readBytes(7)));
assertTrue(channel.finish());
assertEquals(buf.readBytes(3), channel.readInbound());
assertEquals(buf.readBytes(3), channel.readInbound());
assertEquals(buf.readBytes(3), channel.readInbound());
assertNull(channel.readInbound());
}
@Test
public void testEncoded() {
ByteBuf buf = Unpooled.buffer();
for (int i = 1; i < 10; i++) {
buf.writeInt(i * -1);
}
EmbeddedChannel channel = new EmbeddedChannel(
new AbsIntegerEncoder());
assertTrue(channel.writeOutbound(buf));
assertTrue(channel.finish());
// read bytes
for (int i = 1; i < 10; i++) {
//调用 queue.poll,会删掉消息
assertTrue(i == (Integer) channel.readOutbound());
}
Queue<Object> msgs = channel.outboundMessages();
int i = 1;
for (Object msg : msgs) {
assertEquals(i++, msg);
}
}
}
|
package com.ihq.capitalpool.ssoserver.Service;
import java.util.Map;
public interface PasswordTokenService {
Map<String, String> generator(String uuid, String data, String key);
}
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.alexander.mainstuff.controllers;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.transaction.annotation.EnableTransactionManagement;
/**
*
* @author user
*/
@SpringBootApplication
@EnableAutoConfiguration
@ComponentScan(basePackages={"com.alexander.mainstuff"})
@EnableJpaRepositories(basePackages="com.alexander.mainstuff.repositories")
@EnableTransactionManagement
@EntityScan(basePackages="com.alexander.mainstuff.entities")
public class MainApplication {
public static void main(String[] args) {
SpringApplication.run(MainApplication.class, args);
}
}
|
package symap.closeup.components;
import java.awt.Color;
import java.awt.Font;
import java.awt.Point;
import java.awt.Graphics;
import java.awt.Dimension;
import java.awt.Graphics2D;
import java.awt.FontMetrics;
import java.awt.geom.Dimension2D;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JComponent;
import java.util.HashMap;
import java.util.Map;
import java.util.Vector;
import java.util.Arrays;
import util.PropertiesReader;
import util.DoubleDimension;
import util.Ruler;
import symap.SyMAP;
import symap.closeup.alignment.HitAlignment;
import symap.closeup.alignment.GeneAlignment;
@SuppressWarnings("serial") // Prevent compiler warning for missing serialVersionUID
public class CloseUpComponent extends JComponent {
public static Color backgroundColor;
public static Color rulerColor;
public static Color rulerFontColor;
public static Color markerColor;
public static Color besColor;
public static Color outsideColor;
public static Color missColor;
public static Color deleteColor;
public static Color insertColor;
public static Color exonColor;
public static Color intronColor;
private static Font rulerFont;
private static Font hitFont, geneFont;
public static Color hitFontColor, geneFontColor;
public static final double LINE_HEIGHT;
public static final DoubleDimension ARROW_DIMENSION;
public static final double MISS_HEIGHT;
public static final double DELETE_HEIGHT;
public static final DoubleDimension INSERT_DIMENSION;
public static final double INSERT_OFFSET;
public static final double VERTICAL_HIT_SPACE, HORIZONTAL_HIT_SPACE;
public static final double VERTICAL_GENE_SPACE, HORIZONTAL_GENE_SPACE;
private static final int VERTICAL_BORDER, HORIZONTAL_BORDER;
public static final double EXON_HEIGHT;
public static final double INTRON_HEIGHT;
public static final double EXON_ARROW_WIDTH;
public static final double MIN_BP_PER_PIXEL;
private static final Dimension2D RULER_ARROW_DIM;
private static final Dimension2D RULER_TICK_DIM;
private static final double RULER_TICK_SPACE;
private static final double RULER_LINE_THICKNESS;
private static final double RULER_OFFSET;
static {
PropertiesReader props = new PropertiesReader(SyMAP.class.getResource("/properties/closeup.properties"));
backgroundColor = props.getColor("backgroundColor");
rulerColor = props.getColor("rulerColor");
rulerFontColor = props.getColor("rulerFontColor");
rulerFont = props.getFont("rulerFont");
markerColor = props.getColor("markerColor");
besColor = props.getColor("besColor");
outsideColor = props.getColor("outsideColor");
missColor = props.getColor("missColor");
deleteColor = props.getColor("deleteColor");
insertColor = props.getColor("insertColor");
LINE_HEIGHT = props.getDouble("lineHeight");
ARROW_DIMENSION = props.getDoubleDimension("arrowDimension");
DELETE_HEIGHT = props.getDouble("deleteHeight");
INSERT_DIMENSION = props.getDoubleDimension("insertDimension");
INSERT_OFFSET = props.getDouble("insertOffset");
MISS_HEIGHT = props.getDouble("missHeight");
VERTICAL_HIT_SPACE = props.getDouble("verticalHitSpace");
HORIZONTAL_HIT_SPACE = props.getDouble("horizontalHitSpace");
VERTICAL_GENE_SPACE = props.getDouble("verticalGeneSpace");
HORIZONTAL_GENE_SPACE = props.getDouble("horizontalGeneSpace");
HORIZONTAL_BORDER = props.getInt("horizontalBorder");
VERTICAL_BORDER = props.getInt("verticalBorder");
exonColor = props.getColor("exonColor");
intronColor = props.getColor("intronColor");
EXON_HEIGHT = props.getDouble("exonHeight");
INTRON_HEIGHT = props.getDouble("intronHeight");
EXON_ARROW_WIDTH = props.getDouble("exonArrowWidth");
MIN_BP_PER_PIXEL = props.getDouble("minBpPerPixel");
RULER_ARROW_DIM = props.getDoubleDimension("rulerArrowDimension");
RULER_TICK_DIM = props.getDoubleDimension("rulerTickDimension");
RULER_TICK_SPACE = props.getDouble("rulerTickSpace");
RULER_LINE_THICKNESS = props.getDouble("rulerLineThickness");
RULER_OFFSET = props.getDouble("rulerOffset");
hitFont = props.getFont("hitFont");
geneFont = props.getFont("geneFont");
hitFontColor = props.getColor("hitFontColor");
geneFontColor = props.getColor("geneFontColor");
}
public static final double HIT_HEIGHT;
static {
double part = Math.max(Math.max(Math.max(MISS_HEIGHT, DELETE_HEIGHT),
ARROW_DIMENSION.height), LINE_HEIGHT);
HIT_HEIGHT = Math.max(part, INSERT_DIMENSION.height + INSERT_OFFSET
+ (part / 2.0));
}
public static final double GENE_HEIGHT = Math.max(EXON_HEIGHT, INTRON_HEIGHT);
private static final double FONT_SPACE = 3;
private HitAlignment[] ha;
private GeneAlignment[] ga;
private int start, end;
private Ruler ruler;
private Vector<CloseUpListener> listeners;
public CloseUpComponent() {
super();
setBackground(backgroundColor);
listeners = new Vector<CloseUpListener>();
addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
notifyListenersOfClick(getHitAlignment(e.getPoint()));
}
});
ruler = new Ruler(RULER_ARROW_DIM, RULER_ARROW_DIM, RULER_TICK_DIM,
true, RULER_TICK_SPACE, RULER_LINE_THICKNESS);
}
public void addCloseUpListener(CloseUpListener cl) {
if (!listeners.contains(cl))
listeners.add(cl);
}
public void removeCloseUpListener(CloseUpListener cl) {
listeners.remove(cl);
}
public void set(int start, int end, GeneAlignment[] ga, HitAlignment[] ha) {
this.start = start;
this.end = end;
this.ga = ga;
this.ha = ha;
if (this.ga != null)
Arrays.sort(this.ga);
if (this.ha != null)
Arrays.sort(this.ha);
setPreferredSize(getWidth());
}
public int getNumberOfHits() { return (ha == null ? 0 : ha.length); }
public int getStart() { return start; }
public int getEnd() { return end; }
public int getLength() { return Math.abs(end - start) + 1; }
public BlastComponent[] getBlastComponents() {
BlastComponent[] bc = new BlastComponent[ha == null ? 0 : ha.length];
for (int i = 0; i < bc.length; i++)
bc[i] = new BlastComponent(ha[i]);
return bc;
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
if (ga == null || ha == null)
return;
// mdb removed 12/29/08 for pseudo-pseudo closeup - incorrectly drawing dotted line to end of window
// double bpPerPixel = getBpPerPixel();
// if (bpPerPixel <= 0)
// return;
double bpPerPixel = 1; // mdb added 12/29/08 for pseudo-pseudo closeup
Graphics2D g2 = (Graphics2D) g;
ruler.paint(g2, rulerColor, rulerFontColor, rulerFont);
FontMetrics fm = getFontMetrics(hitFont);
Vector<Long> uniqueClones = new Vector<Long>(); // ASD: kludge for printing the name and dotted line only once
for (int i = 0; i < ha.length; ++i) {
long id = ha[i].getID();
if (!uniqueClones.contains(id)) {
ha[i].paintName(g2, fm, hitFontColor, FONT_SPACE, bpPerPixel);
ha[i].paintLine(g2, bpPerPixel, getStart(), HORIZONTAL_BORDER);
uniqueClones.add(id);
}
}
uniqueClones = null;
// Paint the hit segments
for (int i = 0; i < ha.length; ++i)
ha[i].paint(g2);
// Paint the genes
fm = getFontMetrics(geneFont);
for (int i = 0; i < ga.length; ++i)
ga[i].paint(g2, fm, geneFontColor, FONT_SPACE);
}
// mdb removed 12/29/08 for pseudo-pseudo closeup
// private double getBpPerPixel() {
// if (ha == null || ga == null)
// return 0;
// double pixels = getWidth() - 2 * HORIZONTAL_BORDER;
// if (pixels <= 0)
// return 0;
// return getLength() / pixels;
// }
public void setPreferredSize(Dimension d) {
setPreferredSize(d.width);
}
public void setPreferredSize(double width) {
Dimension d = new Dimension();
if (ha != null && ga != null) {
double bpPerPixel = Math.max(MIN_BP_PER_PIXEL, getLength()
/ (width - 2 * HORIZONTAL_BORDER));
ruler.setBounds(getStart(), getEnd(), HORIZONTAL_BORDER,
VERTICAL_BORDER, bpPerPixel, getFontMetrics(rulerFont));
double h = ruler.getBounds().getX() + ruler.getBounds().getHeight()
+ RULER_OFFSET;
d.width = (int) Math.ceil(getLength() / bpPerPixel + 2
* HORIZONTAL_BORDER);
h = setHitLayers(h, bpPerPixel);
h = setGeneLayers(h, bpPerPixel);
d.height = (int) Math.ceil(h + VERTICAL_BORDER);
}
super.setPreferredSize(d);
}
private double setGeneLayers(double y, double bpPerPixel) {
int[] layers = getGeneLayers(bpPerPixel);
double layerSize = GENE_HEIGHT + VERTICAL_GENE_SPACE
+ getFontHeight(geneFont) + FONT_SPACE;
int max = -1;
int startBP = getStart();
for (int i = 0; i < ga.length; ++i) {
if (layers[i] > max)
max = layers[i];
ga[i].setBounds(startBP, HORIZONTAL_BORDER, bpPerPixel, layers[i] * layerSize + y, start, end);
}
return ((max + 1) * layerSize) + y;
}
private int[] getGeneLayers(double bpPerPixel) {
if (ga == null || ga.length == 0)
return new int[0];
int[] layers = new int[ga.length];
double[] ends = new double[ga.length];
Arrays.fill(layers, -1);
Arrays.fill(ends, Double.NEGATIVE_INFINITY);
int startBP = getStart();
for (int i = 0; i < ga.length; ++i) {
double x = ga[i].getX(startBP, 0, bpPerPixel, start);
for (int j = 0; j < ends.length; ++j) {
if (ends[j] <= x || ends[j] < 0) {
layers[i] = j;
break;
}
}
ends[layers[i]] = x + ga[i].getWidth(bpPerPixel, start, end) + HORIZONTAL_GENE_SPACE;
}
return layers;
}
private double setHitLayers(double y, double bpPerPixel) {
final double layerHeight = HIT_HEIGHT + VERTICAL_HIT_SPACE + getFontHeight(hitFont) + FONT_SPACE;
int numLayers = makeHitLayers();
for (HitAlignment h : ha)
h.setBounds(getStart(), HORIZONTAL_BORDER, bpPerPixel, h.getLayer() * layerHeight + y);
return ((numLayers + 1) * layerHeight) + y;
}
// mdb rewritten 1/6/09 for pseudo-pseudo closeup
private int makeHitLayers() {
if (ha == null || ha.length == 0 || ga == null)
return 0;
Vector<Layer> layers = new Vector<Layer>();
Map<Long,Integer> map = new HashMap<Long,Integer>(); // < hit_id, layer_num >
int layerNum;
for (HitAlignment h : ha) {
int start = h.getMinTarget();
int end = start + h.getWidthTarget() - 1;
// First check to see if part of previously layered clone
long id = h.getID();
if (map.containsKey(id)) {
layerNum = map.get(id).intValue();
h.setLayer(layerNum);
layers.get(layerNum).extend(start, end);
continue;
}
// Otherwise, new clone - see where it fits
for (layerNum = 0; layerNum < layers.size() && layers.get(layerNum).contains(start, end); layerNum++);
// It fit in an existing layer
if (layerNum < layers.size()) {
layers.get(layerNum).extend(start, end);
map.put(id, new Integer(layerNum));
h.setLayer(layerNum);
continue;
}
// Otherwise, make new layer
layers.add(new Layer(start, end));
map.put(id, new Integer(layerNum));
h.setLayer(layerNum);
}
return layers.size();
}
private HitAlignment getHitAlignment(Point p) {
if (ha != null) {
for (HitAlignment h : ha)
if (h.contains(p))
return h;
}
return null;
}
private void notifyListenersOfClick(HitAlignment h) {
if (h != null)
for (int i = 0; i < listeners.size(); ++i)
((CloseUpListener) listeners.get(i)).hitClicked(h);
}
private double getFontHeight(Font font) {
return (double) getFontMetrics(font).getHeight() + FONT_SPACE;
}
// ASD added helper class (defines a structure) for change to single layer 5/14/2006
private class Layer {
private int start, end;
public Layer(int start, int end) {
this.start = start;
this.end = end;
}
public void extend(int start, int end) {
if (start < this.start)
this.start = start;
if (end > this.end)
this.end = end;
}
public boolean contains(int start, int end) {
if ((start >= this.start && start <= this.end)
|| (end >= this.start && end <= this.end))
return true;
return false;
}
}
}
|
package com.isg.ifrend.core.service.mli;
import java.util.List;
import com.isg.ifrend.core.model.mli.customer.Address;
import com.isg.ifrend.core.model.mli.customer.Contact;
import com.isg.ifrend.core.model.mli.customer.Customer;
public class CustomerServiceImpl implements CustomerService {
@Override
public List<Customer> searchCustomer(Customer customer) {
// TODO Auto-generated method stub
return null;
}
@Override
public Customer getRelationship(String param) {
// TODO Auto-generated method stub
return null;
}
@Override
public Address getAddressDetail(String customerNum) {
// TODO Auto-generated method stub
return null;
}
@Override
public Contact getContactDetail(String customerNum) {
// TODO Auto-generated method stub
return null;
}
@Override
public String updateCustomerDetail(Customer customer) {
// TODO Auto-generated method stub
return null;
}
}
|
package com.design.pattern.proxy;
/**
* @Author: 98050
* @Time: 2019-02-17 22:04
* @Feature:
*/
public class UserServiceImpl implements UserService {
@Override
public void add() {
System.out.println("添加数据");
}
}
|
package DAO.Formatter;
/**
* Created by Catawiki on 2-2-2016.
*/
public class SqlExport {
}
|
package ca.utoronto.utm.mcs;
import static org.neo4j.driver.Values.parameters;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import org.json.*;
import org.neo4j.driver.AuthTokens;
import org.neo4j.driver.Driver;
import org.neo4j.driver.GraphDatabase;
import org.neo4j.driver.Session;
import static org.neo4j.driver.Values.parameters;
import org.neo4j.driver.AuthTokens;
import org.neo4j.driver.Driver;
import org.neo4j.driver.GraphDatabase;
import org.neo4j.driver.Result;
import org.neo4j.driver.Session;
import org.neo4j.driver.Transaction;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
public class ComputeBaconNumber implements HttpHandler {
private Driver driver;
private String uriDb;
public ComputeBaconNumber() {
uriDb = "bolt://localhost:7687";
driver = GraphDatabase.driver(uriDb, AuthTokens.basic("neo4j", "1234"));
}
public void handle(HttpExchange r) {
try {
if (r.getRequestMethod().equals("GET")) {
handleGet(r);
}
} catch (Exception e) {
e.printStackTrace();
}
}
public void handleGet(HttpExchange r) throws IOException, JSONException {
try {
String body = Utils.convert(r.getRequestBody());
JSONObject deserialized = new JSONObject(body);
String actorId = new String("");
if (deserialized.has("actorId")) {
actorId = deserialized.getString("actorId");
} else {
JSONObject obj = new JSONObject();
String response = obj.toString();
r.sendResponseHeaders(400, response.length());
OutputStream os = r.getResponseBody();
os.write(response.getBytes());
os.close();
return;
}
/*
* try (Session session = driver.session()) { try (Transaction tx =
* session.beginTransaction()) { Result checker =
* tx.run("MATCH (a:Actor {id:$x})-[:ACTED_IN]-(b:Movie)" + "RETURN b.Name",
* parameters("x", actorId)); System.out.println(checker.next()); if
* (checker.hasNext()) { System.out.println(checker.next().get("b.Name")); } } }
*/
if (actorExists(actorId) == false) {
JSONObject obj = new JSONObject();
String response = obj.toString();
r.sendResponseHeaders(400, response.length());
OutputStream os = r.getResponseBody();
os.write(response.getBytes());
os.close();
return;
}
String baconNum = "";
if(actorId.equals("nm0000102")) {
baconNum = "0";
JSONObject obj = new JSONObject();
obj.put("baconNumber", baconNum);
String response = obj.toString();
r.sendResponseHeaders(200, response.length());
OutputStream os = r.getResponseBody();
os.write(response.getBytes());
os.close();
return;
}
baconNum = findBaconNum(actorId);
if(baconNum.equals("")) {
JSONObject obj = new JSONObject();
String response = obj.toString();
r.sendResponseHeaders(404, response.length());
OutputStream os = r.getResponseBody();
os.write(response.getBytes());
os.close();
return;
}
int adjusted = Integer.parseInt(baconNum);
adjusted = (adjusted+1)/2;
String adjustedBaconNum = String.valueOf(adjusted);
JSONObject obj = new JSONObject();
obj.put("baconNumber", adjustedBaconNum);
String response = obj.toString();
r.sendResponseHeaders(200, response.length());
OutputStream os = r.getResponseBody();
os.write(response.getBytes());
os.close();
//String movieList = getMovies(actorId).toString();
//System.out.println(movieList);
//obj.put("movies","hey");
//obj.put("movies","hi");
//System.out.println(movieList);
} catch (Exception e) {
JSONObject obj = new JSONObject();
String response = obj.toString();
r.sendResponseHeaders(500, response.length());
OutputStream os = r.getResponseBody();
os.write(response.getBytes());
os.close();
}
}
public boolean actorExists(String actorId) {
try (Session session = driver.session()) {
try (Transaction tx = session.beginTransaction()) {
Result checker = tx.run("MATCH(n:Actor) WHERE EXISTS(n.id) AND n.id=$x RETURN n",
parameters("x", actorId));
if (checker.hasNext()) {
return true;
}
}
}
return false;
}
public String findBaconNum(String actorId) {
try (Session session = driver.session()) {
try (Transaction tx = session.beginTransaction()) {
Result checker = tx.run("MATCH (a:Actor { id: $x})"
+ "MATCH(b:Actor { id: 'nm0000102'}),"
+ "p = ShortestPath((a)-[*]-(b))"
+ "RETURN length(p)",
parameters("x", actorId));
if (checker.hasNext()) {
//System.out.println(checker.next());
return String.valueOf(checker.next().get("length(p)"));
}
}
}
return "";
}
}
|
package com.txxlc.SystemConfig.Service;
import org.springframework.security.access.ConfigAttribute;
import java.util.Collection;
import java.util.HashMap;
public interface menuRoleService {
/**
* 将数据库查询查询出来的数据,整理去重
* */
public HashMap<String, Collection<ConfigAttribute>> findAllmenuAndRelationRole();
}
|
package com.shangdao.phoenix.filter;
import java.io.IOException;
import java.util.HashMap;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.CacheManager;
import org.springframework.context.ApplicationContext;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.authentication.event.InteractiveAuthenticationSuccessEvent;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;
import org.springframework.security.web.authentication.NullRememberMeServices;
import org.springframework.security.web.authentication.RememberMeServices;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.shangdao.phoenix.service.WorkWeixinContactService;
import com.shangdao.phoenix.util.HTTPResponse;
import com.shangdao.phoenix.util.OutsideRuntimeException;
public class WorkWeixinAuthenticationFilter extends AbstractAuthenticationProcessingFilter {
// ~ Static fields/initializers
// =====================================================================================
private RememberMeServices rememberMeServices = new NullRememberMeServices();
@Autowired
private WorkWeixinContactService workWeixinService;
private boolean postOnly = false;
private Logger logger = LoggerFactory.getLogger(this.getClass());
// ~ Constructors
// ===================================================================================================
public WorkWeixinAuthenticationFilter(String point) {
super(new AntPathRequestMatcher(point));
}
// ~ Methods
// ========================================================================================================
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
throws AuthenticationException, IOException {
ObjectMapper mapper = new ObjectMapper();
try {
if (request.getParameter("code") == null) {
throw new RuntimeException("用户禁止授权");
}
Authentication authRequest = workWeixinService.workWeixinAuthorize(request.getParameter("code"));
return authRequest;
} catch (OutsideRuntimeException failReturnObject) {
HTTPResponse httpResponse = new HTTPResponse(((OutsideRuntimeException)failReturnObject).getCode(), "外部错误",((OutsideRuntimeException)failReturnObject).getError());
String json = mapper.writeValueAsString(httpResponse);
response.setContentType("application/json;charset=utf-8");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(json);
return null;
}
}
protected void setDetails(HttpServletRequest request, UsernamePasswordAuthenticationToken authRequest) {
authRequest.setDetails(authenticationDetailsSource.buildDetails(request));
}
/**
* Defines whether only HTTP POST requests will be allowed by this filter.
* If set to true, and an authentication request is received which is not a
* POST request, an exception will be raised immediately and authentication
* will not be attempted. The <tt>unsuccessfulAuthentication()</tt> method
* will be called as if handling a failed authentication.
* <p>
* Defaults to <tt>true</tt> but may be overridden by subclasses.
*/
public void setPostOnly(boolean postOnly) {
this.postOnly = postOnly;
}
@Override
protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain,
Authentication authResult) throws IOException, ServletException {
// TODO Auto-generated method stub
if (logger.isDebugEnabled()) {
logger.debug("Authentication success. Updating SecurityContextHolder to contain: "
+ authResult);
}
SecurityContextHolder.getContext().setAuthentication(authResult);
rememberMeServices.loginSuccess(request, response, authResult);
// Fire event
if (this.eventPublisher != null) {
eventPublisher.publishEvent(new InteractiveAuthenticationSuccessEvent(
authResult, this.getClass()));
}
getSuccessHandler().onAuthenticationSuccess(request, response, authResult);
}
}
|
/******************************************************************************
* __ *
* <-----/@@\-----> *
* <-< < \\// > >-> *
* <-<-\ __ /->-> *
* 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.components;
import java.awt.Graphics;
import javax.swing.JTextField;
import javax.swing.JToolTip;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;
import javax.swing.text.PlainDocument;
import net.datacrow.console.ComponentFactory;
import net.datacrow.core.DcRepository;
import net.datacrow.settings.DcSettings;
import net.datacrow.util.DcSwingUtilities;
import net.datacrow.util.Utilities;
public class DcDecimalField extends JTextField implements IComponent {
public DcDecimalField() {
super();
ComponentFactory.setBorder(this);
}
@Override
protected Document createDefaultModel() {
return new DecimalDocument();
}
@Override
public Object getValue() {
String text = getText();
String s = DcSettings.getString(DcRepository.Settings.stDecimalSeparatorSymbol);
char decimalSep = s != null && s.length() > 0 ? s.charAt(0) : ',';
s = DcSettings.getString(DcRepository.Settings.stDecimalGroupingSymbol);
char groupingSep = s != null && s.length() > 0 ? s.charAt(0) : '.';
text = text.replaceAll("\\" + groupingSep, "");
text = text.replaceAll("\\" + decimalSep, ".");
return text.length() == 0 ? null : Double.valueOf(text);
}
@Override
public void clear() {}
@Override
public void setValue(Object o) {
setText(Utilities.toString((Double) o));
}
private static class DecimalDocument extends PlainDocument {
@Override
public void insertString(int offs, String s, AttributeSet a) throws BadLocationException {
if (s == null || s.trim().length() == 0) return;
String sep = DcSettings.getString(DcRepository.Settings.stDecimalSeparatorSymbol);
String grp = DcSettings.getString(DcRepository.Settings.stDecimalGroupingSymbol);
if (s.length() == 1) {
String check = getText(0, getContent().length());
if (offs != 0 && s.matches("[0-9,'" + sep + "','" + grp + "']")) {
if (s.equals(sep) && check.indexOf(sep) == -1 || !s.equals(sep))
super.insertString(offs, s, a);
} else if (offs == 0 && s.matches("[+,-,0-9]")) {
if ( (s.equals("+") && check.indexOf("+") == -1) ||
(s.equals("-") && check.indexOf("-") == -1) ||
(!s.equals("-") && !s.equals("+")))
super.insertString(offs, s, a);
}
} else {
super.insertString(offs, s, a);
}
}
}
@Override
public JToolTip createToolTip() {
return new DcMultiLineToolTip();
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(DcSwingUtilities.setRenderingHint(g));
}
@Override
public void refresh() {}
}
|
public class CountEachVowel {
public static void main(String[] args) {
String sentence = "How are you today?";
countVowels(sentence);
}
public static void countVowels(String sentence){
int countA=0,countE=0,countI=0,countO=0,countU=0;
for (int i = 0; i < sentence.length(); i++) {
if(sentence.charAt(i)=='a' || sentence.charAt(i)=='A' ){
countA++;
}
else if(sentence.charAt(i)=='e' || sentence.charAt(i)=='E' ){
countE++;
}
else if(sentence.charAt(i)=='i' || sentence.charAt(i)=='I' ){
countI++;
}
else if(sentence.charAt(i)=='o' || sentence.charAt(i)=='O' ){
countO++;
}
else if(sentence.charAt(i)=='u' || sentence.charAt(i)=='U' ){
countU++;
}
}
System.out.println("a:" + countA);
System.out.println("e:" + countE);
System.out.println("i:" + countI);
System.out.println("o:" + countO);
System.out.println("u:" + countU);
}
}
|
package com.cemsserver.entity;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.Id;
import com.cemsserver.model.UserType;
@Entity
public class CurrentSession
{
@Id
String apiKey;
@Enumerated(EnumType.STRING)
private UserType userType;
String userID;
public CurrentSession() { super(); }
public CurrentSession(String apiKey, UserType userType, String userID)
{
this.apiKey = apiKey;
this.userType = userType;
this.userID = userID;
}
public String getApiKey()
{
return apiKey;
}
public void setApiKey(String apiKey)
{
this.apiKey = apiKey;
}
public UserType getUserType()
{
return userType;
}
public void setUserType(UserType userType)
{
this.userType = userType;
}
public String getUserID()
{
return userID;
}
public void setUserID(String userID)
{
this.userID = userID;
}
@Override
public String toString()
{
return "CurrentSession [apiKey=" + apiKey + ", userType=" + userType + ", userID=" + userID + "]";
}
}
|
/**
* Sencha GXT 1.0.0-SNAPSHOT - Sencha for GWT
* Copyright (c) 2006-2018, Sencha Inc.
*
* licensing@sencha.com
* http://www.sencha.com/products/gxt/license/
*
* ================================================================================
* Commercial License
* ================================================================================
* This version of Sencha GXT is licensed commercially and is the appropriate
* option for the vast majority of use cases.
*
* Please see the Sencha GXT Licensing page at:
* http://www.sencha.com/products/gxt/license/
*
* For clarification or additional options, please contact:
* licensing@sencha.com
* ================================================================================
*
*
*
*
*
*
*
*
* ================================================================================
* Disclaimer
* ================================================================================
* THIS SOFTWARE IS DISTRIBUTED "AS-IS" WITHOUT ANY WARRANTIES, CONDITIONS AND
* REPRESENTATIONS WHETHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE
* IMPLIED WARRANTIES AND CONDITIONS OF MERCHANTABILITY, MERCHANTABLE QUALITY,
* FITNESS FOR A PARTICULAR PURPOSE, DURABILITY, NON-INFRINGEMENT, PERFORMANCE AND
* THOSE ARISING BY STATUTE OR FROM CUSTOM OR USAGE OF TRADE OR COURSE OF DEALING.
* ================================================================================
*/
package com.sencha.gxt.explorer.client.toolbar;
import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.KeyUpEvent;
import com.google.gwt.event.dom.client.KeyUpHandler;
import com.google.gwt.regexp.shared.RegExp;
import com.google.gwt.regexp.shared.SplitResult;
import com.google.gwt.user.client.ui.IsWidget;
import com.google.gwt.user.client.ui.Widget;
import com.sencha.gxt.core.client.util.DelayedTask;
import com.sencha.gxt.core.client.util.Margins;
import com.sencha.gxt.core.client.util.Util;
import com.sencha.gxt.explorer.client.app.ui.ExampleContainer;
import com.sencha.gxt.explorer.client.model.Example.Detail;
import com.sencha.gxt.widget.core.client.ContentPanel;
import com.sencha.gxt.widget.core.client.Status;
import com.sencha.gxt.widget.core.client.Status.BoxStatusAppearance;
import com.sencha.gxt.widget.core.client.Status.StatusAppearance;
import com.sencha.gxt.widget.core.client.container.VerticalLayoutContainer;
import com.sencha.gxt.widget.core.client.container.VerticalLayoutContainer.VerticalLayoutData;
import com.sencha.gxt.widget.core.client.form.TextArea;
import com.sencha.gxt.widget.core.client.toolbar.FillToolItem;
import com.sencha.gxt.widget.core.client.toolbar.LabelToolItem;
import com.sencha.gxt.widget.core.client.toolbar.ToolBar;
@Detail(
name = "Status Tool Bar",
category = "Tool Bar & Menu",
icon = "statustoolbar",
minHeight = StatusToolBarExample.MIN_HEIGHT,
minWidth = StatusToolBarExample.MIN_WIDTH
)
public class StatusToolBarExample implements IsWidget, EntryPoint {
protected static final int MIN_HEIGHT = 320;
protected static final int MIN_WIDTH = 480;
private DelayedTask task = new DelayedTask() {
@Override
public void onExecute() {
status.clearStatus("Not writing");
}
};
private Status charCount;
private Status wordCount;
private Status status;
private ContentPanel panel;
@Override
public Widget asWidget() {
if (panel == null) {
status = new Status();
status.setText("Not writing");
status.setWidth(150);
charCount = new Status(GWT.<StatusAppearance> create(BoxStatusAppearance.class));
charCount.setWidth(100);
charCount.setText("0 Chars");
wordCount = new Status(GWT.<StatusAppearance> create(BoxStatusAppearance.class));
wordCount.setWidth(100);
wordCount.setText("0 Words");
VerticalLayoutData data = new VerticalLayoutData(1, 1);
data.setMargins(new Margins(5));
TextArea textArea = new TextArea();
textArea.addKeyUpHandler(new KeyUpHandler() {
@Override
public void onKeyUp(KeyUpEvent event) {
status.setBusy("writing...");
TextArea t = (TextArea) event.getSource();
String value = t.getCurrentValue();
int length = value != null ? value.length() : 0;
charCount.setText(length + (length == 1 ? " Char" : " Chars"));
if (value != null) {
int wc = getWordCount(value);
wordCount.setText(wc + (wc == 1 ? " Word" : " Words"));
}
task.delay(1000);
}
});
ToolBar toolBar = new ToolBar();
toolBar.setBorders(false);
toolBar.add(status);
toolBar.add(new FillToolItem());
toolBar.add(charCount);
toolBar.add(new LabelToolItem(Util.NBSP_SAFE_HTML));
toolBar.add(wordCount);
toolBar.setLayoutData(new VerticalLayoutData(1, -1));
VerticalLayoutContainer form = new VerticalLayoutContainer();
form.add(textArea, new VerticalLayoutData(1, 1, new Margins(5)));
form.add(toolBar);
panel = new ContentPanel();
panel.setHeading("Status Tool Bar");
panel.add(form);
}
return panel;
}
public int getWordCount(String v) {
SplitResult result = RegExp.compile("\\b", "g").split(v);
return result.length() / 2;
}
@Override
public void onModuleLoad() {
new ExampleContainer(this)
.setMinHeight(MIN_HEIGHT)
.setMinWidth(MIN_WIDTH)
.doStandalone();
}
}
|
// **********************************************************
// 1. 제 목: 우편번호 Data
// 2. 프로그램명 : PostSearchData.java
// 3. 개 요: 우편번호 Data
// 4. 환 경: JDK 1.3
// 5. 버 젼: 1.0
// 6. 작 성: 2003. 7. 7
// 7. 수 정:
// **********************************************************
package com.ziaan.common;
public class PostSearchData
{
private String zipcode;
private String sido;
private String gugun;
private String dong;
private String bunji;
public PostSearchData() { }
public void setZipcode(String zipcode) { this.zipcode = zipcode; }
public String getZipcode() { return zipcode; }
public void setSido(String sido) { this.sido = sido; }
public String getSido() { return sido; }
public void setGugun(String gugun) { this.gugun = gugun; }
public String getGugun() { return gugun; }
public void setDong(String dong) { this.dong = dong; }
public String getDong() { return dong; }
public void setBunji(String bunji) { this.bunji = bunji; }
public String getBunji() { return bunji; }
}
|
package ru.mcfr.oxygen.framework.operations.table;
import ro.sync.ecss.extensions.api.ArgumentDescriptor;
import ro.sync.ecss.extensions.api.AuthorOperationException;
import ro.sync.ecss.extensions.api.node.AttrValue;
import ro.sync.ecss.extensions.api.node.AuthorDocumentFragment;
import ro.sync.ecss.extensions.api.node.AuthorElement;
import ro.sync.ecss.extensions.api.node.AuthorNode;
import ru.mcfr.oxygen.framework.operations.McfrBaseAuthorOperation;
import javax.swing.text.BadLocationException;
/**
* Created by IntelliJ IDEA.
* User: wstarcev
* Date: 12.07.11
* Time: 16:45
* To change this template use File | Settings | File Templates.
*/
public class InsertColumnOperation extends McfrBaseAuthorOperation{
{
description = "Вставка|Удаление столбца в таблицу";
argumentsNameArray = new String[]{"направление", "вставить/удалить"};
argumentsTypesArray = new Object[]{ArgumentDescriptor.TYPE_STRING, ArgumentDescriptor.TYPE_STRING};
argumentsDescriptionsArray = new String[]{"Направление вставки от выбранного столбца: справа/слева", ""};
}
@Override
public void doMainOperation() {
AuthorNode selectedCell = selectedElement;
while (!selectedCell.getName().equalsIgnoreCase("ячейка"))
selectedCell = selectedCell.getParent();
AuthorNode table = selectedCell;
while (!table.getName().equalsIgnoreCase("таблица"))
table = table.getParent();
int[] thisCoord = authorAccess.getTableAccess().getTableCellIndex((AuthorElement) selectedCell);
int columnIndex = thisCoord[1];
int rowsCount = authorAccess.getTableAccess().getTableRowCount((AuthorElement) table);
for (int i = 0; i < rowsCount; i++){
AuthorElement thisCell = authorAccess.getTableAccess().getTableCellAt(i, columnIndex, (AuthorElement) table);
if (argumentsValues.get("вставить/удалить").equalsIgnoreCase("удалить")){
try {
int rowspan = Integer.valueOf(thisCell.getAttribute("rowspan").getValue());
i = i + rowspan - 1;
} catch (Exception e) {
}
try {
int colspan = Integer.valueOf(thisCell.getAttribute("colspan").getValue());
controller.setAttribute("colspan", new AttrValue("" + (--colspan)), thisCell);
} catch (Exception e) {
controller.deleteNode(thisCell);
}
} else {
String newCell = "<ячейка";
for (int a = 0; a < thisCell.getAttributesCount(); a++) {
String attrName = thisCell.getAttributeAtIndex(a);
if (attrName.contains("border") | attrName.contains("rowspan")) {
String attrValue = thisCell.getAttribute(attrName).getRawValue();
newCell += " " + attrName + "=\"" + attrValue + "\"";
}
}
newCell += "/>";
int position = thisCell.getEndOffset() + 1;
try {
AuthorDocumentFragment frag = controller.createNewDocumentFragmentInContext(newCell, position);
controller.beginCompoundEdit();
controller.insertFragment(position, frag);
controller.endCompoundEdit();
} catch (AuthorOperationException e) {
e.printStackTrace();
}
try {
int rowspan = Integer.valueOf(thisCell.getAttribute("rowspan").getValue());
i = i + rowspan - 1;
} catch (Exception e) {
}
}
}
}
@Override
public void doOperationWithSelected() throws AuthorOperationException, BadLocationException {
}
@Override
public void doOperationAtCaretPos() throws AuthorOperationException {
}
}
|
package com.alex.pets;
public class Mouse extends Pet implements Alive {
public Mouse() {
super();
}
}
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package jc.fog.data.dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javafx.util.Pair;
/**
*
* @author Claus
*/
public class AbstractDAO
{
protected static Connection connection = null;
public AbstractDAO(Connection connection)
{
this.connection = connection;
}
/**
* Opretter et PreparedStatement med argumenter indsat hvor sql indeholder wildcards ('?').
* @param connection
* @param sql
* @param autoGeneratedKeys Enten Statement.NO_GENERATED_KEYS eller Statement.RETURN_GENERATED_KEYS.
* @param parameters [optional] varargs af Pair objekter af Integer/Object par. Hvert par indikerer index på wildcard hvor Object skal indsættes, f.eks. (1, 250) sætter værdien 250 på første ?-wildcard i sql sætningen. Skal ingen værdier indsættes på wildcards, kan null angives.
* @return PreparedStatement objekt som kan returnere nøgler hvis autoGeneratedKeys er Statement.RETURN_GENERATED_KEYS. Ellers returneres et alm. PreparedStatement.
* @throws SQLException
*/
protected PreparedStatement createPreparedStatement(Connection connection, String sql, int autoGeneratedKeys, Pair<Integer, Object>... parameters) throws SQLException
{
PreparedStatement pstm;
// Hvis autoGeneratedKeys ikke har en gyldig værdi, oprettes 'alm.' PreparedStatement objekt.
if (autoGeneratedKeys != Statement.NO_GENERATED_KEYS && autoGeneratedKeys != Statement.RETURN_GENERATED_KEYS)
pstm = connection.prepareStatement(sql);
else
pstm = connection.prepareStatement(sql, autoGeneratedKeys);
// Sæt de evt. modtagne key-value par ind i sql sætningen.
if (parameters != null)
for (Pair<Integer, Object> pair : parameters)
{
pstm.setObject(pair.getKey(), pair.getValue());
}
return pstm;
}
/**
* Udfører executeUpdate() på et PreparedStatement objekt som returnerer auto-genererede nøgler.
* Efter udførelsen af sql sætningen, returneres det resulterende ResultSet med nøgler.
* PRE: PreparedStatement skal have sin sql sat.
* POST: executeUpdate er kaldt.
* @param preparedStatement PreparedStatement objekt med sql klar til udførelse.
* @return ResultSet Med automatisk oprettede nøgler. ResultSet fås fra preparedStatement.getGeneratedKeys().
* @throws SQLException
*/
protected ResultSet updateAndGetKeys(PreparedStatement preparedStatement) throws SQLException
{
preparedStatement.executeUpdate();
ResultSet rs = preparedStatement.getGeneratedKeys();
return rs;
}
}
|
package com.java8.streams;
import java.util.List;
import java.util.stream.Collectors;
public class StreamsUndetstanding {
public static void main(String[] args) {
// get all dishes whos calories less than 400
List<Dish> dishesLessThan400calories = Dish.menu.stream().filter(dish -> dish.getCalories() < 400 ).collect(Collectors.toList());
System.out.println("Printing dishes whose calories less than 400 ");
printDishes(dishesLessThan400calories);
// print first 2 meat dishes
List<Dish> firstTwoMeatDishes = Dish.menu.stream().filter(dish -> dish.getType().equals(Dish.Type.MEAT)).limit(2).collect(Collectors.toList());
System.out.println("\n \nPrinting first two meat dishes");
printDishes(firstTwoMeatDishes);
}
private static void printDishes(List<Dish> dishesLessThan400calories) {
dishesLessThan400calories.stream().forEach(dish -> System.out.print(dish.getName()+", "));
}
}
|
package com.exam.logic.actions;
import com.exam.logic.Action;
import com.exam.logic.services.UserService;
import com.exam.models.User;
import com.exam.util.Security;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.util.Optional;
import static com.exam.logic.Constants.*;
import static com.exam.servlets.ErrorHandler.ErrorCode.LOGIN_FAIL;
public class LoginAction implements Action {
@Override
public String execute(HttpServletRequest request, HttpServletResponse response) {
UserService userService = (UserService) request.getServletContext().getAttribute(USER_SERVICE);
String view;
String login = request.getParameter("j_username");
String password = Security.md5Hex(request.getParameter("j_password"));
//устанавливаем тайм зону
String offset = request.getParameter("time_zone");
ZoneOffset zoneOffset = ZoneOffset.ofHours(-Integer.parseInt(offset) / 60);
request.getSession().setAttribute(USER_ZONE_ID, ZoneId.ofOffset("UTC", zoneOffset));
Optional<User> userOptional = userService.authorize(login, password);
if (userOptional.isPresent()) {
request.getSession().setAttribute(CURRENT_USER, userOptional.get());
view = "/index.jsp";
} else {
request.setAttribute(ERROR_MSG, LOGIN_FAIL.getPropertyName());
view = "/WEB-INF/jsp/not_auth/login.jsp";
}
return view;
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.