text
stringlengths 10
2.72M
|
|---|
package com.example.demo.model;
import java.io.Serializable;
import org.springframework.data.annotation.Id;
import org.springframework.security.core.GrantedAuthority;
public class Authority implements GrantedAuthority,Serializable {
@Id()
private Integer authorityId;
private String authority;
private static final long serialVersionUID = 1L;
public Integer getAuthorityId() {
return authorityId;
}
public void setAuthorityId(Integer id) {
this.authorityId = id;
}
public String getAuthority() {
return authority;
}
public void setAuthority(String authority) {
this.authority = authority == null ? null : authority.trim();
}
@Override
public boolean equals(Object that) {
if (this == that) {
return true;
}
if (that == null) {
return false;
}
if (getClass() != that.getClass()) {
return false;
}
Authority other = (Authority) that;
return (this.getAuthorityId() == null ? other.getAuthorityId() == null : this.getAuthorityId().equals(other.getAuthorityId()))
&& (this.getAuthority() == null ? other.getAuthority() == null
: this.getAuthority().equals(other.getAuthority()));
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((getAuthorityId() == null) ? 0 : getAuthorityId().hashCode());
result = prime * result + ((getAuthority() == null) ? 0 : getAuthority().hashCode());
return result;
}
}
|
/****************************************************
* $Project: DinoAge
* $Date:: Jun 23, 2009
* $Revision:
* $Author:: khoanguyen
* $Comment::
**************************************************/
package org.ddth.dinoage.core;
/**
* @author khoanguyen
*
*/
public class WorkspaceChangeEvent {
public static final int PROFILE_ADDED_CHANGE = 1;
public static final int PROFILE_REMOVED_CHANGE = 2;
public static final int WORKSPACE_RELOADED_CHANGE = 3;
private Workspace workspace;
private Object data;
private int type;
/**
*
*/
public WorkspaceChangeEvent(Workspace workspace, Object data, int type) {
this.workspace = workspace;
this.data = data;
this.type = type;
}
/**
* @return The workspace
*/
public Workspace getWorkspace() {
return workspace;
}
/**
* @return The object
*/
public Object getData() {
return data;
}
/**
* @return The event type
*/
public int getType() {
return type;
}
}
|
package com.yfancy.app.log;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Main_App_Log {
private final static Logger log = LoggerFactory.getLogger(Main_App_Log.class);
public static void main( String[] args ){
try {
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(new String[] { "spring/spring-context.xml" });
context.start();
log.info("[hy-blog-app-log Service] == context start");
} catch (Exception e) {
log.error("[hy-blog-app-log Service] == application start error:", e);
return;
}
synchronized (Main_App_Log.class) {
while (true) {
try {
Main_App_Log.class.wait();
} catch (InterruptedException e) {
log.error("== synchronized error:", e);
}
}
}
}
}
|
package com.feelyou.service;
public class MusicService {
}
|
/*
LeetCode Problem 102
Binary Tree Level Order Traversal
Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level).
For example:
Given binary tree [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
return its level order traversal as:
[
[3],
[9,20],
[15,7]
]
*/
/*
This is also knows as Breadth-First traversal and is a very popular algorithm and has a number of applications.
We traverse each level and visit it's nodes before moving on to the next level.
A simple trick for Breadth-First and Depth-First traversal is: Use Queue for BFS since Queue can be thought of as
a horizontal data structure and use Stack for DFS since Stack can be thought of a vertical data structure or something
that has depth.
We start from the root and insert both it's left and right children into the queue.
Then we begin constructing our traversal. To ensure for missing children, we calculate the number of nodes at each level
as the size of the queue and to only account for those nodes while building our traversal.
After we have completed a level, pop the nodes, add it to the result and insert it's children into the queue.
Continue this process until the queue is empty.
Time Complexity: O(n) where n is number of nodes in the Tree
Space Complexity: O(n) since each nodes gets stored in the queue exactly once.
*/
public List<List<Integer>> levelOrder(TreeNode root) {
List<List<Integer>> result = new ArrayList();
if(root==null)
return result;
Queue<TreeNode> level = new LinkedList();
TreeNode node = root;
level.add(root);
while(!level.isEmpty())
{
List<Integer> current = new ArrayList();
int levelsize = level.size();
for(int i=0;i<levelsize;i++)
{
TreeNode temp = level.remove();
current.add(temp.val);
if(temp.left!=null)
level.add(temp.left);
if(temp.right!=null)
level.add(temp.right);
}
result.add(current);
}
return result;
}
|
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.raid;
import java.io.OutputStream;
import java.io.InputStream;
import java.io.IOException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.FSDataInputStream;
import org.apache.hadoop.fs.FSDataOutputStream;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.util.Progressable;
public class XOREncoder extends Encoder {
public static final Log LOG = LogFactory.getLog(
"org.apache.hadoop.raid.XOREncoder");
public XOREncoder(
Configuration conf, int stripeSize) {
super(conf, stripeSize, 1);
}
@Override
protected void encodeStripe(
InputStream[] blocks,
long stripeStartOffset,
long blockSize,
OutputStream[] outs,
Progressable reporter) throws IOException {
LOG.info("Peforming XOR ");
ParityInputStream parityIn =
new ParityInputStream(blocks, blockSize, readBufs[0], writeBufs[0]);
try {
parityIn.drain(outs[0], reporter);
} finally {
parityIn.close();
}
}
@Override
public Path getParityTempPath() {
return new Path(RaidNode.unraidTmpDirectory(conf));
}
}
|
package pl.coderslab.services;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import pl.coderslab.dal.repositories.LocationRepo;
import pl.coderslab.domain.location.Location;
import pl.coderslab.web.dtos.LocationFormDTO;
import javax.validation.Valid;
import java.util.List;
@Service
@Transactional
public class LocationService {
@Autowired
LocationRepo locationRepo;
public List<Location> getAllLocations() {
return locationRepo.findAllOrdered();
}
public void saveLocation(@Valid LocationFormDTO form) {
Location location = new Location();
location.setName(form.getName());
location.setType(form.getType());
location.setFloor(form.getFloor());
locationRepo.save(location);
}
public Location getLocationById(Long id) {
return locationRepo.findFirstById(id);
}
// public void editLocation(); //todo editing locations
}
|
package com.quizcore.quizapp.model.network.response.master;
import java.util.UUID;
public class CategoryResponse {
private UUID productkey;
private String categoryname;
private UUID categoryId;
public UUID getProductkey() {
return productkey;
}
public void setProductkey(UUID productkey) {
this.productkey = productkey;
}
public String getCategoryname() {
return categoryname;
}
public void setCategoryname(String categoryname) {
this.categoryname = categoryname;
}
public UUID getCategoryId() {
return categoryId;
}
public void setCategoryId(UUID categoryId) {
this.categoryId = categoryId;
}
}
|
package fr.lteconsulting.exception;
public class DAOException extends Exception
{
public DAOException( String message )
{
this( message, null );
}
public DAOException( String message, Throwable throwable )
{
super( message, throwable );
}
}
|
public enum MyEnumm {
PROTOCOL((String)"http"),
ROOT((String)"sandy.atr.local");
private MyEnumm(String val) {
this.val = val;
}
private String val;
public String getVal() {
return this.val;
}
}
|
package com.box.androidsdk.content.models;
import android.text.TextUtils;
import com.eclipsesource.json.JsonObject;
import java.util.Date;
import java.util.Locale;
/**
* Class that represents a collaboration on Box.
*/
public class BoxCollaboration extends BoxEntity {
private static final long serialVersionUID = 8125965031679671555L;
public static final String TYPE = "collaboration";
public static final String FIELD_CREATED_BY = "created_by";
public static final String FIELD_CREATED_AT = "created_at";
public static final String FIELD_MODIFIED_AT = "modified_at";
public static final String FIELD_EXPIRES_AT = "expires_at";
public static final String FIELD_STATUS = "status";
public static final String FIELD_ACCESSIBLE_BY = "accessible_by";
public static final String FIELD_ROLE = "role";
public static final String FIELD_ACKNOWLEDGED_AT = "acknowledged_at";
public static final String FIELD_ITEM = "item";
public static final String FIELD_INVITE_EMAIL = "invite_email";
public static final String[] ALL_FIELDS = new String[]{
FIELD_TYPE,
FIELD_ID,
FIELD_CREATED_BY,
FIELD_CREATED_AT,
FIELD_MODIFIED_AT,
FIELD_EXPIRES_AT,
FIELD_STATUS,
FIELD_ACCESSIBLE_BY,
FIELD_ROLE,
FIELD_ACKNOWLEDGED_AT,
FIELD_ITEM,
FIELD_INVITE_EMAIL
};
/**
* Constructs an empty BoxCollaboration object.
*/
public BoxCollaboration() {
super();
}
/**
* Constructs a BoxCollaboration with the provided JsonObject
*
* @param jsonObject jsonObject to use to create an instance of this class.
*/
public BoxCollaboration(JsonObject jsonObject) {
super(jsonObject);
}
/**
* Gets the user who created the collaboration.
*
* @return the user who created the collaboration.
*/
public BoxCollaborator getCreatedBy() {
return (BoxCollaborator) getPropertyAsJsonObject(BoxEntity.getBoxJsonObjectCreator(), FIELD_CREATED_BY);
}
/**
* Gets the time the collaboration was created.
*
* @return the time the collaboration was created.
*/
public Date getCreatedAt() {
return getPropertyAsDate(FIELD_CREATED_AT);
}
/**
* Gets the time the collaboration was last modified.
*
* @return the time the collaboration was last modified.
*/
public Date getModifiedAt() {
return getPropertyAsDate(FIELD_MODIFIED_AT);
}
/**
* Gets the time the collaboration will expire.
*
* @return the time the collaboration will expire.
*/
public Date getExpiresAt() {
return getPropertyAsDate(FIELD_EXPIRES_AT);
}
/**
* Gets the status of the collaboration.
*
* @return the status of the collaboration.
*/
public Status getStatus() {
return Status.fromString(getPropertyAsString(FIELD_STATUS));
}
/**
* Gets the collaborator who this collaboration applies to.
*
* @return the collaborator who this collaboration applies to.
*/
public BoxCollaborator getAccessibleBy() {
return (BoxCollaborator) getPropertyAsJsonObject(BoxEntity.getBoxJsonObjectCreator(), FIELD_ACCESSIBLE_BY);
}
/**
* Gets the email that this collaboration applies to.
*
* @return the email that this collaboration applies to.
*/
public String getInviteEmail() {
return getPropertyAsString(FIELD_INVITE_EMAIL);
}
/**
* Gets the level of access the collaborator has.
*
* @return the level of access the collaborator has.
*/
public Role getRole() {
return Role.fromString(getPropertyAsString(FIELD_ROLE));
}
/**
* Gets the time the collaboration's status was changed.
*
* @return the time the collaboration's status was changed.
*/
public Date getAcknowledgedAt() {
return getPropertyAsDate(FIELD_ACKNOWLEDGED_AT);
}
/**
* Gets the collaborative item the collaboration is related to.
*
* @return the item the collaboration is related to.
*/
public BoxCollaborationItem getItem() {
return (BoxCollaborationItem) getPropertyAsJsonObject(BoxEntity.getBoxJsonObjectCreator(), FIELD_ITEM);
}
/**
* Enumerates the possible statuses that a collaboration can have.
*/
public enum Status {
/**
* The collaboration has been accepted.
*/
ACCEPTED("accepted"),
/**
* The collaboration is waiting to be accepted or rejected.
*/
PENDING("pending"),
/**
* The collaboration has been rejected.
*/
REJECTED("rejected");
private final String mValue;
Status(String value) {
this.mValue = value;
}
public static Status fromString(String text) {
if (!TextUtils.isEmpty(text)) {
for (Status e : Status.values()) {
if (text.equalsIgnoreCase(e.toString())) {
return e;
}
}
}
throw new IllegalArgumentException(String.format(Locale.ENGLISH, "No enum with text %s found", text));
}
@Override
public String toString() {
return this.mValue;
}
}
/**
* Enumerates the possible access levels that a collaborator can have.
*/
public enum Role {
/**
* The owner role has all of the functional capabilities of a co-owner. However, they will be able to manipulate the owner of the folder or transfer
* ownership to another user. This role is only available to enterprise accounts.
*/
OWNER("owner"),
/**
* The co-owner role has all of the functional read/write access that an editor does. This permission level has the added ability of being able to
* manage users in the folder. A co-owner can add new collaborators, change access levels of existing collaborators, and remove collaborators. However,
* they will not be able to manipulate the owner of the folder or transfer ownership to another user. This role is only available to enterprise
* accounts.
*/
CO_OWNER("co-owner"),
/**
* An Editor has full read/write access to a folder. Once invited to a folder, they will be able to view, download, upload, edit, delete, copy, move,
* rename, generate shared links, make comments, assign tasks, create tags, and invite/remove collaborators. They will not be able to delete or move
* root level folders.
*/
EDITOR("editor"),
/**
* The viewer-uploader role is a combination of viewer and uploader. A viewer-uploader has full read access to a folder and limited write access. They
* are able to preview, download, add comments, generate shared links, and upload content to the folder. They will not be able to add tags, invite new
* collaborators, edit, or delete items in the folder. This role is only available to enterprise accounts.
*/
VIEWER_UPLOADER("viewer uploader"),
/**
* The previewer-uploader role is a combination of previewer and uploader. A user with this access level will be able to preview files using the
* integrated content viewer as well as upload items into the folder. They will not be able to download, edit, or share, items in the folder. This role
* is only available to enterprise accounts.
*/
PREVIEWER_UPLOADER("previewer uploader"),
/**
* The viewer role has full read access to a folder. Once invited to a folder, they will be able to preview, download, make comments, and generate
* shared links. They will not be able to add tags, invite new collaborators, upload, edit, or delete items in the folder.
*/
VIEWER("viewer"),
/**
* The previewer role has limited read access to a folder. They will only be able to preview the items in the folder using the integrated content
* viewer. They will not be able to share, upload, edit, or delete any content. This role is only available to enterprise accounts.
*/
PREVIEWER("previewer"),
/**
* The uploader has limited write access to a folder. They will only be able to upload and see the names of the items in a folder. They will not able to
* download or view any content. This role is only available to enterprise accounts.
*/
UPLOADER("uploader");
private final String mValue;
Role(String value) {
this.mValue = value;
}
public static Role fromString(String text) {
if (!TextUtils.isEmpty(text)) {
for (Role e : Role.values()) {
if (text.equalsIgnoreCase(e.toString())) {
return e;
}
}
}
throw new IllegalArgumentException(String.format(Locale.ENGLISH, "No enum with text %s found", text));
}
@Override
public String toString() {
return this.mValue;
}
}
}
|
package org.bardibardi.guice;
import com.google.inject.Injector;
/**
* Get a Guice Injector
*
* @author Bardi Einarsson, bardibardi.org
*
*/
public interface IInjectorFactory {
/**
* Get a Guice Injector
*
* @return Injector, a Guice Injector
*/
public Injector getInjector();
}
|
package com.kodilla.good.patterns.challenges;
import java.time.LocalDateTime;
public class OrderDbMySql implements OrderRepository {
public boolean createOrder(User user, LocalDateTime orderDate) {
System.out.println("Order made by " + user + " on " + orderDate + " has been stored.");
return true;
}
}
|
package com.example.zealience.oneiromancy.ui.fragment;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.cooltechworks.views.shimmer.ShimmerRecyclerView;
import com.example.zealience.oneiromancy.R;
import com.example.zealience.oneiromancy.constant.KeyConstant;
import com.example.zealience.oneiromancy.entity.NewsEntity;
import com.example.zealience.oneiromancy.mvp.contract.NewsContract;
import com.example.zealience.oneiromancy.mvp.model.NewsModel;
import com.example.zealience.oneiromancy.mvp.presenter.NewsPresenter;
import com.example.zealience.oneiromancy.ui.NewsListAdapter;
import com.example.zealience.oneiromancy.ui.activity.WebViewActivity;
import com.scwang.smartrefresh.header.MaterialHeader;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import java.util.ArrayList;
import java.util.List;
import me.yokeyword.fragmentation.SupportFragment;
/**
* @user steven
* @createDate 2019/3/7 15:39
* @description 自定义
*/
public class NewsChildFragment extends SupportFragment implements NewsContract.View, OnRefreshListener {
private NewsPresenter mPresenter;
private NewsModel mModel;
private ShimmerRecyclerView recyclerviewNewsList;
private SmartRefreshLayout refreshNews;
private NewsListAdapter newsListAdapter;
private List<NewsEntity> mNewsList = new ArrayList<>();
private String title = "top";
public static NewsChildFragment getInstance(String title) {
NewsChildFragment childFragment = new NewsChildFragment();
Bundle bundle = new Bundle();
bundle.putString("title", title);
childFragment.setArguments(bundle);
return childFragment;
}
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = LayoutInflater.from(getActivity()).inflate(R.layout.fragment_news_child, null);
refreshNews = (SmartRefreshLayout) view.findViewById(R.id.refresh__news);
recyclerviewNewsList = (ShimmerRecyclerView) view.findViewById(R.id.recyclerview_news_list);
mPresenter = new NewsPresenter();
mModel = new NewsModel();
if (mPresenter != null) {
mPresenter.mContext = this.getActivity();
}
return view;
}
@Override
public void onLazyInitView(@Nullable Bundle savedInstanceState) {
initPresenter();
initView(savedInstanceState);
}
private void initPresenter() {
mPresenter.setVM(this, mModel);
}
private void initView(Bundle savedInstanceState) {
DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(_mActivity, DividerItemDecoration.VERTICAL);
dividerItemDecoration.setDrawable(_mActivity.getResources().getDrawable(R.drawable.list_divider_1dp));
recyclerviewNewsList.addItemDecoration(dividerItemDecoration);
recyclerviewNewsList.setLayoutManager(new LinearLayoutManager(_mActivity));
newsListAdapter = new NewsListAdapter(new ArrayList<>());
recyclerviewNewsList.setAdapter(newsListAdapter);
recyclerviewNewsList.showShimmerAdapter();
refreshNews.setOnRefreshListener(this);
refreshNews.setRefreshHeader(new MaterialHeader(_mActivity));
refreshNews.autoRefresh();
title = getArguments().getString("title");
}
@Override
public void setNewsList(List<NewsEntity> newsEntities) {
recyclerviewNewsList.hideShimmerAdapter();
recyclerviewNewsList.addOnItemTouchListener(new OnItemClickListener() {
@Override
public void onSimpleItemClick(BaseQuickAdapter adapter, View view, int position) {
Bundle bundle = new Bundle();
bundle.putString(KeyConstant.URL_KEY, mNewsList.get(position).getUrl());
bundle.putBoolean(KeyConstant.ISSHOW_SHARE_KEY, true);
WebViewActivity.startActivity(_mActivity, bundle);
}
});
refreshNews.finishRefresh();
newsListAdapter.setNewData(newsEntities);
mNewsList.clear();
mNewsList.addAll(newsEntities);
}
@Override
public void onError(String msg) {
refreshNews.finishRefresh();
}
@Override
public void onRefresh(RefreshLayout refreshLayout) {
mPresenter.getNewsList(mPresenter.getNewsTypeByName(title));
}
}
|
package com.wellhope.dubbouserservice;
import com.alibaba.dubbo.config.spring.context.annotation.EnableDubbo;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
@EnableDubbo
@MapperScan("com.wellhope.mapper")
public class DubboUserServiceApplication {
public static void main(String[] args) {
SpringApplication.run(DubboUserServiceApplication.class, args);
}
}
|
package com.zznode.opentnms.isearch.model.bo;
public class ODU0 extends ODU{
private static final long serialVersionUID = 8336332184907258020L;
private DSR dsr ;
public void assignOchSncid(String ochsncobjectid){
this.setOchSncid(ochsncobjectid);
if(dsr!=null){
dsr.assignOchSncid(ochsncobjectid);
}
}
public String getFreeODU(Integer rate_i){
Integer ratelevel = ConstBusiness.rateMap.get(rate_i);
if( ratelevel!=null && ratelevel.intValue() == 0 ){
if( dsr==null ){
return "/odu0=" + index ;
}
}
Integer odulevel = ConstBusiness.odukMap.get(rate_i);
if( odulevel!=null && ratelevel.intValue() == 1 ){
if( dsr==null ){
return "/odu0=" + index ;
}
}
return "";
}
public DSR getDsr() {
return dsr;
}
public void setDsr(DSR dsr) {
this.dsr = dsr;
}
}
|
/*
* 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 Hilo;
import archivos.LeerDistricto;
import controlador.ContraladorH;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author Che
*/
public class hilos {
private final lock Lock;
private final int id;
private LeerDistricto leer;
private File path;
private ContraladorH controlador;
public hilos(lock lock, int id, LeerDistricto leer, File path, ContraladorH controlador,String nombre) {
super(nombre);
this.Lock = lock;
this.id = id;
this.leer = leer;
this.path = path;
this.controlador = controlador;
}
public void run() {
try {
LeerDistricto.open(path);
LeerDistricto.read( Lock);
LeerDistricto.close();
} catch (FileNotFoundException ex) {
Logger.getLogger(hilos.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(hilos.class.getName()).log(Level.SEVERE, null, ex);
} catch (Exception ex) {
Logger.getLogger(hilos.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
|
package com.fro.wifi_rfidcase;
public class Constant {
//IP地址
public static String IP="192.168.0.109";
//端口
public static int port=4001;
public static String CARD_ID="5A EF C6 04";
public static String AREA_DATA="00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00";//17位
//寻卡
public static final String FIND_CARD_CMD="aa bb 06 00 00 00 01 02 52 51";
public static final String FIND_CARD_SUCCESS="aa bb 08 00 00 00 01 02 00 04 00 07";
public static final String FIND_CARD_ERROR="aa bb 06 00 00 00 01 02 14 14";
//读卡
public static final String READ_CARD_CMD="AA BB 06 00 00 00 02 02 04 04";
public static String READ_CARD_SUCCESS="AA BB 0A 00 00 00 02 02 00 5A EF C6 04 77";
public static final String READ_CARD_ERROR="aa bb 06 00 00 00 02 02 0a 0a";
//选卡
public static String CHOOSE_CARD_CMD="AA BB 09 00 00 00 03 02 5A EF C6 04 76";
public static String CHOOSE_CARD_SUCCESS="AA BB 07 00 00 00 03 02 00 08 09";
public static final String CHOOSE_CARD_ERROR="AA BB 06 00 00 00 03 02 0A 0A";
//选块
public static String CHOOSE_AREA_CMD="AA BB 0D 00 00 00 07 02 60 01 FF FF FF FF FF FF 64";
public static String CHOOSE_AREA_SUCCESS="AA BB 06 00 00 00 07 02 00 05";
public static final String CHOOSE_AREA_ERROR="AA BB 06 00 00 00 07 02 16 16";
//读块
public static final String READ_AREA_CMD="AA BB 06 00 00 00 08 02 01 0B";
public static String READ_AREA_SUCCESS="AA BB 16 00 00 00 08 02 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0A";
public static final String READ_AREA_ERROR="AA BB 06 00 00 00 08 02 17 17";
}
|
package com.tencent.mm.view.a;
import android.graphics.Bitmap;
import com.tencent.mm.a.e;
import com.tencent.mm.ak.a.c.l;
import com.tencent.mm.plugin.gif.g;
class c$3 implements l {
final /* synthetic */ c uTM;
c$3(c cVar) {
this.uTM = cVar;
}
public final Bitmap K(byte[] bArr) {
return g.ay(bArr);
}
public final Bitmap mf(String str) {
return g.ay(e.e(str, 0, e.cm(str)));
}
}
|
package com.tiandi.logistics.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tiandi.logistics.entity.front.CompanyFront;
import com.tiandi.logistics.entity.pojo.Company;
/**
* <p>
* 公司管理 Mapper 接口
* </p>
*
* @author TP
* @since 2020-11-25
*/
public interface CompanyMapper extends BaseMapper<Company> {
Page<CompanyFront> getAllCompany(Page<?> page, String idCompany, String nameCompany);
Integer getMaxID();
}
|
package com.yuecheng.yue.widget.picloadlib.view;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.Button;
import com.yuecheng.yue.R;
import com.yuecheng.yue.ui.bean.YUE_SPsave;
import com.yuecheng.yue.util.CommonUtils;
import com.yuecheng.yue.util.YUE_SharedPreferencesUtils;
import com.yuecheng.yue.widget.photoview.PhotoView;
import com.yuecheng.yue.widget.picloadlib.PhotoPickActivity;
import com.yuecheng.yue.widget.picloadlib.util.Bimp;
import com.yuecheng.yue.widget.picloadlib.util.PublicWay;
import com.yuecheng.yue.widget.picloadlib.zoom.ViewPagerFixed;
import com.yuecheng.yue.widget.selector.YUE_BackResUtils;
import java.util.ArrayList;
import java.util.List;
/**
* Created by administraot on 2017/11/26.
*/
public class GalleryActivity extends AppCompatActivity {
private Intent intent;
// 完成按钮
private Button send_bt;
//获取前一个activity传过来的position
private int position;
//当前的位置
private int location = 0;
private ArrayList<View> listViews = null;
private ViewPagerFixed pager;
private MyPageAdapter adapter;
public List<Bitmap> bmp = new ArrayList<Bitmap>();
public List<String> drr = new ArrayList<String>();
public List<String> del = new ArrayList<String>();
private Context mContext;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
PublicWay.activityList.add(this);
// 此部分主要是适配我的主题切换,这个库我没有集成项目的baseactivity,所以此处重复添加此代码了。
String mThem = (String) YUE_SharedPreferencesUtils.getParam(this, YUE_SPsave.YUE_THEM,
"默认主题");
Window window = getWindow();
switch (mThem) {
case "默认主题":
setTheme(R.style.AppThemeDefault);
break;
case "热情似火":
setTheme(R.style.AppThemeRed);
break;
case "梦幻紫":
setTheme(R.style.AppThemePurple);
break;
case "乌金黑":
setTheme(R.style.AppThemeHardwareblack);
break;
default:
if (android.os.Build.VERSION.SDK_INT >= 21)
window.setStatusBarColor(CommonUtils.getColorByAttrId(mContext,R.attr.colorPrimary));
break;
}
// 此部分主要是适配我的主题切换,这个库我没有集成项目的baseactivity,所以此处重复添加此代码了。
setContentView(R.layout.plugin_camera_gallery);
mContext = this;
initToolBar();
initViews();
initDataEvents();
}
private void initToolBar() {
Toolbar mToolBar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(mToolBar);
ActionBar ab = getSupportActionBar();
//使能app bar的导航功能
ab.setDisplayHomeAsUpEnabled(true);
ab.setTitle("相册");
mToolBar.setTitleTextColor(getResources().getColor(R.color.white));
mToolBar.setOnMenuItemClickListener(onMenuItemClick);
// toolbar 返回按钮监听
mToolBar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
intent.setClass(GalleryActivity.this, AlbumActivity.class);
startActivity(intent);
}
});
}
Toolbar.OnMenuItemClickListener onMenuItemClick = new Toolbar.OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem menuItem) {
String msg = "";
switch (menuItem.getItemId()) {
case R.id.action_delete:
//todo 删除按钮事件
if (listViews.size() == 1) {
Bimp.tempSelectBitmap.clear();
Bimp.max = 0;
send_bt.setText("完成"+"(" + Bimp.tempSelectBitmap.size() + "/"+PublicWay.num+")");
Intent intent = new Intent("data.broadcast.action");
sendBroadcast(intent);
finish();
} else {
Bimp.tempSelectBitmap.remove(location);
Bimp.max--;
pager.removeAllViews();
listViews.remove(location);
adapter.setListViews(listViews);
send_bt.setText("完成"+"(" + Bimp.tempSelectBitmap.size() + "/"+PublicWay.num+")");
adapter.notifyDataSetChanged();
}
break;
}
return true;
}
};
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_delete, menu);
return true;
}
private void initDataEvents() {
send_bt.setBackground(YUE_BackResUtils.getInstance(this).getLoginDrawableSelector());
send_bt.setOnClickListener(new GallerySendListener());
intent = getIntent();
position = Integer.parseInt(intent.getStringExtra("position"));
// 为发送按钮设置文字
isShowOkBt();
pager.addOnPageChangeListener(pageChangeListener);
for (int i = 0; i < Bimp.tempSelectBitmap.size(); i++) {
initListViews( Bimp.tempSelectBitmap.get(i).getBitmap() );
}
adapter = new MyPageAdapter(listViews);
pager.setAdapter(adapter);
pager.setPageMargin((int)10);
int id = intent.getIntExtra("ID", 0);
pager.setCurrentItem(id);
}
private void initListViews(Bitmap bm) {
if (listViews == null)
listViews = new ArrayList<View>();
PhotoView img = new PhotoView(this);
img.enable();
img.setBackgroundColor(0xff000000);
img.setImageBitmap(bm);
img.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT));
listViews.add(img);
}
private void initViews() {
send_bt = (Button) findViewById(R.id.send_button);
pager = (ViewPagerFixed) findViewById(R.id.gallery01);
}
public void isShowOkBt() {
if (Bimp.tempSelectBitmap.size() > 0) {
send_bt.setText("完成" + "(" + Bimp.tempSelectBitmap.size() + "/" +
PublicWay.num + ")");
send_bt.setPressed(true);
send_bt.setClickable(true);
send_bt.setTextColor(Color.WHITE);
} else {
send_bt.setPressed(false);
send_bt.setClickable(false);
send_bt.setTextColor(Color.parseColor("#E1E0DE"));
}
}
// 完成按钮的监听
private class GallerySendListener implements View.OnClickListener {
public void onClick(View v) {
finish();
intent.setClass(mContext, PhotoPickActivity.class);
startActivity(intent);
}
}
/**
* 监听返回按钮
*/
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
if(position==1){
this.finish();
intent.setClass(GalleryActivity.this, AlbumActivity.class);
startActivity(intent);
}else if(position==2){
this.finish();
intent.setClass(GalleryActivity.this, ShowAllPhoto.class);
startActivity(intent);
}
}
return true;
}
private ViewPager.OnPageChangeListener pageChangeListener = new ViewPager.OnPageChangeListener() {
public void onPageSelected(int arg0) {
location = arg0;
}
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
public void onPageScrollStateChanged(int arg0) {
}
};
private class MyPageAdapter extends PagerAdapter {
private ArrayList<View> listViews;// content
private int size;// 页数
public MyPageAdapter(ArrayList<View> listViews) {// 构造函数
// 初始化viewpager的时候给的一个页面
this.listViews = listViews;
size = listViews == null ? 0 : listViews.size();
}
public void setListViews(ArrayList<View> listViews) {// 自己写的一个方法用来添加数据
this.listViews = listViews;
size = listViews == null ? 0 : listViews.size();
}
public int getCount() {// 返回数量
return size;
}
public int getItemPosition(Object object) {
return POSITION_NONE;
}
public void destroyItem(View arg0, int arg1, Object arg2) {// 销毁view对象
((ViewPager) arg0).removeView(listViews.get(arg1 % size));
}
public void finishUpdate(View arg0) {
}
public Object instantiateItem(View arg0, int arg1) {// 返回view对象
try {
((ViewPager) arg0).addView(listViews.get(arg1 % size), 0);
} catch (Exception e) {
}
return listViews.get(arg1 % size);
}
public boolean isViewFromObject(View arg0, Object arg1) {
return arg0 == arg1;
}
}
@Override
protected void onDestroy() {
super.onDestroy();
synchronized (PublicWay.activityList){
if (PublicWay.activityList.contains(this))
PublicWay.activityList.remove(this);
}
}
}
|
/*
* (C) Copyright 2014-2016 Hewlett Packard Enterprise Development LP
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package monasca.api.app.command;
import static monasca.common.dropwizard.JsonHelpers.jsonFixture;
import static org.testng.Assert.assertEquals;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
import javax.ws.rs.WebApplicationException;
import org.apache.commons.lang3.StringUtils;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import com.fasterxml.jackson.databind.JsonMappingException;
import monasca.api.app.command.CreateNotificationMethodCommand;
import monasca.api.domain.model.AbstractModelTest;
@Test
public class CreateNotificationMethodTest extends AbstractModelTest {
private static final String NOTIFICATION_METHOD_WEBHOOK = "WEBHOOK";
private static final String NOTIFICATION_METHOD_EMAIL = "EMAIL";
private static final String NOTIFICATION_METHOD_PAGERDUTY = "PAGERDUTY";
private static Validator validator;
private List<Integer> validPeriods = Arrays.asList(0, 60);
@BeforeClass
public static void setUp() {
ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
validator = factory.getValidator();
}
public void shouldDeserializeFromJson() throws Exception {
CreateNotificationMethodCommand newNotificationMethod =
new CreateNotificationMethodCommand("MyEmail", NOTIFICATION_METHOD_EMAIL, "a@b", "0");
String json = jsonFixture("fixtures/newNotificationMethod.json");
CreateNotificationMethodCommand other = fromJson(json, CreateNotificationMethodCommand.class);
assertEquals(other, newNotificationMethod);
}
public void shouldDeserializeFromJsonLowerCaseEnum() throws Exception {
CreateNotificationMethodCommand newNotificationMethod =
new CreateNotificationMethodCommand("MyEmail", NOTIFICATION_METHOD_EMAIL, "a@b", "0");
String json = jsonFixture("fixtures/newNotificationMethodWithLowercaseEnum.json");
CreateNotificationMethodCommand other = fromJson(json, CreateNotificationMethodCommand.class);
assertEquals(other, newNotificationMethod);
}
public void shouldDeserializeFromJsonDefinedPeriod() throws Exception {
CreateNotificationMethodCommand newNotificationMethod =
new CreateNotificationMethodCommand("MyWebhook", NOTIFICATION_METHOD_WEBHOOK, "http://somedomain.com", "60");
String json = jsonFixture("fixtures/newNotificationMethodWithPeriod.json");
CreateNotificationMethodCommand other = fromJson(json, CreateNotificationMethodCommand.class);
assertEquals(other, newNotificationMethod);
}
@Test(expectedExceptions = java.lang.AssertionError.class)
public void shouldDeserializeFromJsonEnumError() throws Exception {
CreateNotificationMethodCommand newNotificationMethod =
new CreateNotificationMethodCommand("MyEmail", NOTIFICATION_METHOD_EMAIL, "a@b", "0");
String json = jsonFixture("fixtures/newNotificationMethodWithInvalidEnum.json");
CreateNotificationMethodCommand other = fromJson(json, CreateNotificationMethodCommand.class);
assertEquals(other, newNotificationMethod);
}
public void testValidationForEmail() {
CreateNotificationMethodCommand newNotificationMethod =
new CreateNotificationMethodCommand("MyEmail", NOTIFICATION_METHOD_EMAIL, "name@domain.com", "0");
newNotificationMethod.validate(validPeriods );
}
@Test(expectedExceptions = WebApplicationException.class)
public void testValidationExceptionForEmail() throws Exception {
CreateNotificationMethodCommand newNotificationMethod =
new CreateNotificationMethodCommand("MyEmail", NOTIFICATION_METHOD_EMAIL, "name@domain.", "0");
newNotificationMethod.validate(validPeriods );
}
@Test(expectedExceptions = WebApplicationException.class)
public void testValidationExceptionForNonZeroPeriodForEmail() {
CreateNotificationMethodCommand newNotificationMethod =
new CreateNotificationMethodCommand("MyEmail", NOTIFICATION_METHOD_EMAIL, "name@domain.", "60");
newNotificationMethod.validate(validPeriods);
}
public void testValidationForWebhook() {
CreateNotificationMethodCommand newNotificationMethod =
new CreateNotificationMethodCommand("MyWebhook", NOTIFICATION_METHOD_WEBHOOK, "http://somedomain.com", "0");
newNotificationMethod.validate(validPeriods);
}
public void testValidationNonZeroPeriodForWebhook() {
CreateNotificationMethodCommand newNotificationMethod =
new CreateNotificationMethodCommand("MyWebhook", NOTIFICATION_METHOD_WEBHOOK, "http://somedomain.com", "60");
newNotificationMethod.validate(validPeriods);
}
public void testValidationTestDomainForWebhook() {
CreateNotificationMethodCommand newNotificationMethod =
new CreateNotificationMethodCommand("MyWebhook", NOTIFICATION_METHOD_WEBHOOK, "http://test.test", "60");
newNotificationMethod.validate(validPeriods);
}
public void testValidationTestDomainWithPortForWebhook() {
CreateNotificationMethodCommand newNotificationMethod =
new CreateNotificationMethodCommand("MyWebhook", NOTIFICATION_METHOD_WEBHOOK, "http://test.test:4522", "60");
newNotificationMethod.validate(validPeriods);
}
@Test(expectedExceptions = WebApplicationException.class)
public void testValidationInvalidTestDomainForWebhook() {
CreateNotificationMethodCommand newNotificationMethod =
new CreateNotificationMethodCommand("MyWebhook", NOTIFICATION_METHOD_WEBHOOK, "http://test.invalid:4522", "60");
newNotificationMethod.validate(validPeriods );
}
@Test(expectedExceptions = WebApplicationException.class)
public void testValidationTestDomainWithInvalidPortForWebhook() {
CreateNotificationMethodCommand newNotificationMethod =
new CreateNotificationMethodCommand("MyWebhook", NOTIFICATION_METHOD_WEBHOOK, "http://test.test:4522AA/mywebhook", "60");
newNotificationMethod.validate(validPeriods);
}
@Test(expectedExceptions = WebApplicationException.class)
public void testValidationTestDomainWithInvalidMultiplePortsForWebhook() {
CreateNotificationMethodCommand newNotificationMethod =
new CreateNotificationMethodCommand("MyWebhook", NOTIFICATION_METHOD_WEBHOOK, "http://test.test:4522:33/mywebhook", "60");
newNotificationMethod.validate(validPeriods);
}
@Test(expectedExceptions = WebApplicationException.class)
public void testValidationInvalidDomainForWebhook() {
CreateNotificationMethodCommand newNotificationMethod =
new CreateNotificationMethodCommand("MyWebhook", NOTIFICATION_METHOD_WEBHOOK, "http://test.fred", "60");
newNotificationMethod.validate(validPeriods);
}
@Test(expectedExceptions = WebApplicationException.class)
public void testValidationExceptionForWebhook() throws Exception {
CreateNotificationMethodCommand newNotificationMethod =
new CreateNotificationMethodCommand("MyWebhook", NOTIFICATION_METHOD_WEBHOOK, "ftp://localhost", "0");
newNotificationMethod.validate(validPeriods);
}
public void testValidationForPagerduty() {
CreateNotificationMethodCommand newNotificationMethod =
new CreateNotificationMethodCommand("MyPagerduty", NOTIFICATION_METHOD_PAGERDUTY, "nzH2LVRdMzun11HNC2oD", "0");
newNotificationMethod.validate(validPeriods);
}
@Test(expectedExceptions = WebApplicationException.class)
public void testValidationExceptionForNonZeroPeriodForPagerDuty() {
CreateNotificationMethodCommand newNotificationMethod =
new CreateNotificationMethodCommand("MyPagerduty", NOTIFICATION_METHOD_PAGERDUTY, "nzH2LVRdMzun11HNC2oD", "60");
newNotificationMethod.validate(validPeriods );
}
public void testValidationForMaxNameAddress() {
String name = StringUtils.repeat("A", 250);
assertEquals(name.length(), 250);
String address = "http://" + StringUtils.repeat("A", 502) + ".io";
assertEquals(address.length(), 512);
CreateNotificationMethodCommand newNotificationMethod =
new CreateNotificationMethodCommand(name, NOTIFICATION_METHOD_WEBHOOK, address, "0");
Set<ConstraintViolation<CreateNotificationMethodCommand>> constraintViolations =
validator.validate(newNotificationMethod);
assertEquals(constraintViolations.size(), 0);
}
public void testValidationExceptionForExceededNameLength() {
String name = StringUtils.repeat("A", 251);
assertEquals(name.length(), 251);
CreateNotificationMethodCommand newNotificationMethod =
new CreateNotificationMethodCommand(name, NOTIFICATION_METHOD_WEBHOOK, "http://somedomain.com", "0");
Set<ConstraintViolation<CreateNotificationMethodCommand>> constraintViolations =
validator.validate(newNotificationMethod);
assertEquals(constraintViolations.size(), 1);
assertEquals(constraintViolations.iterator().next().getMessage(),
"size must be between 1 and 250");
}
public void testValidationExceptionForExceededAddressLength() {
String address = "http://" + StringUtils.repeat("A", 503) + ".io";
assertEquals(address.length(), 513);
CreateNotificationMethodCommand newNotificationMethod =
new CreateNotificationMethodCommand("MyWebhook", NOTIFICATION_METHOD_WEBHOOK, address, "0");
Set<ConstraintViolation<CreateNotificationMethodCommand>> constraintViolations =
validator.validate(newNotificationMethod);
assertEquals(constraintViolations.size(), 1);
assertEquals(constraintViolations.iterator().next().getMessage(),
"size must be between 1 and 512");
}
@Test(expectedExceptions = WebApplicationException.class)
public void testValidationExceptionForNonIntPeriod() {
CreateNotificationMethodCommand newNotificationMethod =
new CreateNotificationMethodCommand("MyEmail", NOTIFICATION_METHOD_EMAIL, "name@domain.com", "interval");
newNotificationMethod.validate(validPeriods);
}
@Test(expectedExceptions = WebApplicationException.class)
public void testValidationExceptionForInvalidPeriod() {
CreateNotificationMethodCommand newNotificationMethod =
new CreateNotificationMethodCommand("MyWebhook", NOTIFICATION_METHOD_WEBHOOK, "http://somedomain.com", "10");
newNotificationMethod.validate(validPeriods);
}
}
|
package sevenkyu.oddoreven;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.AssertionsForClassTypes.assertThat;
class OddOrEvenTest {
OddOrEven oddOrEven;
@BeforeEach
public void init() {
oddOrEven = new OddOrEven();
}
@Test
public void givenSumIsOdd_oddOrEven_shouldReturnWithOdd() {
// Given
// When
String oddity = oddOrEven.oddOrEven(new int[]{2, 5, 34, 6});
// Then
assertThat(oddity).isEqualTo(OddOrEven.ODD);
}
@Test
public void givenSumIsEven_oddOrEven_shouldReturnWithEven() {
// Given
// When
String oddity = oddOrEven.oddOrEven(new int[]{2, 8, 34, 6});
// Then
assertThat(oddity).isEqualTo(OddOrEven.EVEN);
}
@Test
public void givenSumIsZero_oddOrEven_shouldReturnWithEven() {
// Given
// When
String oddity = oddOrEven.oddOrEven(new int[]{});
// Then
assertThat(oddity).isEqualTo(OddOrEven.EVEN);
}
}
|
package com.gikk.util;
/**
*
* @author Gikkman
*/
public class StackTrace {
/**
* Prints a message, and appends a stack trace link.
* <p>
* This will allow the user to click a link in the IDE to go directly to the
* stack trace position.
*
* @param message The message to print
*/
public static void error(String message) {
System.err.println(message + " - " + getStackPos());
}
/**
* Returns a link to a code position. Intended to be inserted in an error
* message.
* <br>This will produce an error message in the output console with a
* clickable link that opens the file that caused the error.
* <p>
* <br><br><b>Example</b>
* <br><code>System.err.println("Error. Unknown args. " + StackTrace.getStackPos() );</code>
*
* @return A stack trace position link
*/
public static String getStackPos() {
String out = " ";
StackTraceElement[] e = new Exception().getStackTrace();
for (int i = 3; i < e.length && i < 6; i++) {
String s = e[i].toString();
int f = s.indexOf("(");
int l = s.lastIndexOf(")") + 1;
out += s.substring(f, l) + " ";
}
return out;
}
}
|
package com.tencent.mm.modelvoiceaddr;
import android.os.Message;
import com.tencent.mm.kernel.g;
import com.tencent.mm.plugin.appbrand.jsapi.a.b;
import com.tencent.mm.sdk.platformtools.ag;
import com.tencent.mm.sdk.platformtools.x;
class e$2 extends ag {
final /* synthetic */ e eqC;
e$2(e eVar) {
this.eqC = eVar;
}
public final void handleMessage(Message message) {
if (message.what == 2) {
if (this.eqC.eqy != null) {
this.eqC.eqy.TZ();
}
} else if (message.what == 0) {
if (e.b(this.eqC) == 0) {
x.d("MicroMsg.SceneVoiceAddr", "addSceneEndListener MMFunc_UploadInputVoice");
g.DF().a(349, this.eqC);
} else {
g.DF().a(b.CTRL_INDEX, this.eqC);
}
if (e.b(this.eqC) != 0) {
e.a(this.eqC, new c(e.d(this.eqC), e.b(this.eqC)));
} else if (e.c(this.eqC)) {
e.a(this.eqC, new d(e.d(this.eqC), 1));
} else {
e.a(this.eqC, new d(e.d(this.eqC), 0));
}
g.DF().a(e.e(this.eqC), 0);
} else if (message.what == 3 && this.eqC.eqy != null) {
this.eqC.eqy.a(new String[0], -1);
}
}
}
|
public class testGit_1 {
public static void main(String[] args) {
System.out.println("test git 1");
System.out.println("test git commit - 2");
System.out.println("test git commit - 3");
System.out.println("test git commit - 4");
}
}
|
package com.basic.dao.impl;
import com.basic.db.FBos;
import com.basic.entity.Bos;
import com.global.util.Err;
import com.orientechnologies.orient.core.db.document.ODatabaseDocumentTx;
import com.orientechnologies.orient.core.record.impl.ODocument;
import org.basic.dao.abst.DaoAbstract;
import java.util.Random;
import java.util.prefs.Preferences;
public class BosDao extends DaoAbstract {
public BosDao() {
super(FBos.TABLE);
}
// public ODocument factoryModel(int id, String name, int jml) {
// ODocument o = new ODocument(getClassName());
// setId(o, id);
// setName(o, name);
// setJml(o, jml);
// return o;
// }
//
// public ODocument factoryModelUpdate(ODocument o,int id, String name, int jml) {
// setId(o, id);
// setName(o, name);
// setJml(o, jml);
// return o;
// }
//
public void factoryFirst(ODatabaseDocumentTx db){
Bos bos=new Bos();
bos.setId("1");
bos.setName("jmllog");
bos.setJml(2000);
save(db, bos.getDoc());
bos=new Bos();
bos.setId("2");
bos.setName(creatRendom());
bos.setJml(0);
save(db, bos.getDoc());
}
//
// public String getName(ODocument o) {
// return o.field(FBos.NAME);
// }
//
// public ODocument setName(ODocument o,String name) {
// o.field(FBos.NAME, name);
// return o;
// }
//
// public int getJml(ODocument o) {
// return o.field(FBos.JML);
// }
//
// public ODocument setJml(ODocument o, int jml) {
// o.field(FBos.JML, jml, OType.INTEGER);
// return o;
// }
//
// public int getId(ODocument o) {
// return o.field(FBos.ID);
// }
//
// public ODocument setId(ODocument o, int id) {
// o.field(FBos.ID, id, OType.INTEGER);
// return o;
// }
public boolean check(ODatabaseDocumentTx db){
ODocument o=getOne(db, FBos.ID, 2);
if (o==null) {
factoryFirst(db);
//baru pertama jadi belum reg
return false;
}
Bos bos=new Bos(o);
if (bos.getJml()==1) {
//sudah registrasi
Preferences userPref = Preferences.userRoot();
String x=userPref.get("ortptnk", "x");
if (!x.equalsIgnoreCase(bos.getName())) {
if (bos.getJml()==1) {
bos.setName(creatRendom());
bos.setJml(0);
save(db, bos.getDoc());
}
//di hack
return false;
}
return true;
}
return false;
}
public String creatRendom(){
Random r = new Random();
String alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZOIUYTR";
StringBuilder tmp = new StringBuilder();
for (int i = 0; i < 5; i++) {
tmp.append(alphabet.charAt(r.nextInt(alphabet.length())));
}
return tmp.toString();
}
/**
* Ini di gunkan untuk mengurangi jumlah login
* @param db
*/
public void minus(ODatabaseDocumentTx db){
ODocument o=getOne(db, FBos.ID, 2);
if (o!=null) {
Bos bos=new Bos(o);
if (bos.getJml()==0) {
//belum reg
ODocument o1=getOne(db, FBos.ID, 1);
if (o1!=null) {
Bos bos1=new Bos(o1);
if (bos1.getJml()<0) {
Err.showErrMasaTrialSudahHabis();
System.exit(0);
}
int jml=bos1.getJml();
jml=jml-1;
bos1.setJml(jml);
save(db, bos1.getDoc());
}else{
factoryFirst(db);
db.close();
System.exit(0);
}
}else{
//System.exit(1);
}
}else{
factoryFirst(db);
db.close();
System.exit(0);
}
}
}
|
public class Coins {
private static int[] COINS_NOM = {1, 5, 10, 25, 50};
public static int getCountOfWays(int money) {
return getCountOfWays(money, 4);
}
/**
* КАК ДО ТАКОГО ДОДУМАТЬСЯ???
*/
private static int getCountOfWays(int money, int indexOfCoin) {
if (money < 0 || indexOfCoin < 0) return 0;
if (money == 0 || indexOfCoin == 0) return 1;
return getCountOfWays(money, indexOfCoin - 1) + getCountOfWays(money - COINS_NOM[indexOfCoin], indexOfCoin);
}
public static void main(String[] args) {
System.out.println(Coins.getCountOfWays(78));
}
}
|
package hyghlander.mods.ports.DragonScales.common.items;
import net.minecraft.client.model.ModelBiped;
import net.minecraft.client.renderer.texture.IIconRegister;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityLiving;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemArmor;
import net.minecraft.item.ItemStack;
import net.minecraft.potion.Potion;
import net.minecraft.potion.PotionEffect;
import net.minecraft.world.World;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import hyghlander.mods.ports.DragonScales.DragonScales;
import hyghlander.mods.ports.DragonScales.Lib;
import hyghlander.mods.ports.DragonScales.client.models.ModelDragonChestplate;
import hyghlander.mods.ports.DragonScales.common.DragonScalesHandler;
public class ItemDragonArmor extends ItemArmor
{
public ItemDragonArmor(ArmorMaterial armorMaterial, int armorType, String name)
{
super(armorMaterial, 0, armorType);
//setUnlocalizedName(name);
}
@Override
public String getArmorTexture(ItemStack stack, Entity entity, int slot, String type) {
if (stack.getItem().equals(DragonScalesHandler.dragonLeggings)) {
return Lib.TEXTURE_PATH + "textures/models/armor/dragon_layer_2.png";
}
if (stack.getItem().equals(DragonScalesHandler.dragonChestplate)) {
return Lib.TEXTURE_PATH + "textures/models/armor/dragonchest3d.png";
}
return Lib.TEXTURE_PATH + "textures/models/armor/dragon_layer_1.png";
}
@Override
@SideOnly(Side.CLIENT)
public ModelBiped getArmorModel(EntityLivingBase entityLiving, ItemStack itemStack, int armorSlot) {
if (itemStack != null && itemStack.getItem() instanceof ItemDragonArmor)
{
ModelBiped armorModel = DragonScales.proxy.getArmorModel(armorSlot);
armorModel.bipedHead.showModel = armorSlot == 0;
armorModel.bipedHeadwear.showModel = armorSlot == 0;
armorModel.bipedBody.showModel = armorSlot == 1 || armorSlot == 2;
armorModel.bipedRightArm.showModel = armorSlot == 1;
armorModel.bipedLeftArm.showModel = armorSlot == 1;
armorModel.bipedRightLeg.showModel = armorSlot == 2 || armorSlot == 3;
armorModel.bipedLeftLeg.showModel = armorSlot == 2 || armorSlot == 3;
armorModel.isSneak = entityLiving.isSneaking();
armorModel.isRiding = entityLiving.isRiding();
armorModel.isChild = entityLiving.isChild();
if(entityLiving instanceof EntityLiving)
{
armorModel.heldItemRight = ((EntityPlayer) entityLiving).getCurrentArmor(0) != null ? 1 :0;
}
if(entityLiving instanceof EntityPlayer){
armorModel.aimedBow = ((EntityPlayer)entityLiving).getItemInUseDuration() > 2;
}
return armorModel;
}
return null; //Default Rendering
/*
ModelBiped armorModel = new ModelBiped();
if(itemStack != null){
if(itemStack.getItem() instanceof ItemDragonArmor){
int type = ((ItemArmor)itemStack.getItem()).armorType;
if(type == 1){
armorModel = MainClass.proxy.getArmorModel(0);
}else if(type == 3){
armorModel = MainClass.proxy.getArmorModel(1);
}else if(type == 2/4){
armorModel = MainClass.proxy.getArmorModel(2);
}
}
if(armorModel != null){
armorModel.bipedHead.showModel = armorSlot == 0;
armorModel.bipedHeadwear.showModel = armorSlot == 0;
armorModel.bipedBody.showModel = armorSlot == 1 || armorSlot == 2;
armorModel.bipedRightArm.showModel = armorSlot == 1;
armorModel.bipedLeftArm.showModel = armorSlot == 1;
armorModel.bipedRightLeg.showModel = armorSlot == 2 || armorSlot == 3;
armorModel.bipedLeftLeg.showModel = armorSlot == 2 || armorSlot == 3;
armorModel.isSneak = entityLiving.isSneaking();
armorModel.isRiding = entityLiving.isRiding();
armorModel.isChild = entityLiving.isChild();
armorModel.heldItemRight = entityLiving.getCurrentArmor(0) != null ? 1 :0;
if(entityLiving instanceof EntityPlayer){
armorModel.aimedBow =((EntityPlayer)entityLiving).getItemInUseDuration() > 2;
}
return armorModel;
}
}
return null;*/
}
public void onArmorTick(World world, EntityPlayer player, ItemStack itemStack){
if(player.getCurrentArmor(3) != null && player.getCurrentArmor(3).getItem() == DragonScalesHandler.dragonHelmet)
{
player.addPotionEffect(new PotionEffect(Potion.nightVision.getId(), 260, 0));
}
if(player.getCurrentArmor(2) != null && player.getCurrentArmor(2).getItem() == DragonScalesHandler.dragonChestplate)
{
player.addPotionEffect(new PotionEffect(Potion.resistance.getId(), 40, 1));
player.addPotionEffect(new PotionEffect(Potion.fireResistance.getId(), 40, 1));
player.fallDistance = 0.0F;
player.capabilities.allowFlying = true;
}
if(player.getCurrentArmor(1) != null && player.getCurrentArmor(1).getItem() == DragonScalesHandler.dragonLeggings)
{
player.addPotionEffect(new PotionEffect(Potion.moveSpeed.getId(), 40, 3));
}
if(player.getCurrentArmor(0) != null && player.getCurrentArmor(0).getItem() == DragonScalesHandler.dragonBoots)
{
player.addPotionEffect(new PotionEffect(Potion.jump.getId(), 40, 3));
player.fallDistance = 0.0F;
}
if((player.getCurrentArmor(2) == null || player.getCurrentArmor(2).getItem() != DragonScalesHandler.dragonChestplate) && player.capabilities.isCreativeMode == false && player.capabilities.allowFlying == true)
{
player.capabilities.allowFlying = false;
player.capabilities.isFlying = false;
}
}
}
|
package company;
import Parts.OS;
import Parts.PartStruct;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;
public class Lenovo {
private static DecimalFormat df2 = new DecimalFormat("#.##");
public Lenovo() {
}
public static void Find_Laptops(List<Laptop> LaptopArray) {
Boolean is_exist = false;
List<String> links = new ArrayList<String>();
String SeriesList[] = {"https://www.lenovo.com/us/en/laptops/thinkpad/thinkpad-x/c/thinkpadx",
"https://www.lenovo.com/us/en/laptops/thinkpad/thinkpad-t-series/c/thinkpadt",
"https://www.lenovo.com/us/en/laptops/thinkpad/thinkpad-p/c/thinkpadp",
"https://www.lenovo.com/us/en/laptops/thinkpad/thinkpad-e-series/c/thinkpade",
"https://www.lenovo.com/us/en/laptops/thinkpad/thinkpad-a-series/c/thinkpada",
"https://www.lenovo.com/us/en/laptops/thinkpad/11e-and-chromebooks/c/thinkpad11e"};
try {
for (String url : SeriesList) {
final Document document3 = Jsoup.connect(url).get();
Element comp_urls = document3.select(".cd-products-comparison-table").first();
if (comp_urls != null) {
Elements com = comp_urls.select("a");
for (Element comp : com) {
String atar = comp.attr("href");
if (!links.contains("https://www.lenovo.com" + atar)) {
newParseLaptop("https://www.lenovo.com" + atar, LaptopArray);
links.add("https://www.lenovo.com" + atar);
}
}
}
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
public static void newParseLaptop(String url, List<Laptop> LaptopArray) {
String LaptopSummeryHeader;
String LaptopSummeryBody;
String[] attributes_lables;
String[] attributes_values;
String[] StringFormatLaptop;
try {
final Document LenovoLeptopUrlDocument = Jsoup.connect(url).get();
String imgUrl = "https://www.lenovo.com" + LenovoLeptopUrlDocument.select(".noeSpot.subseriesHeader > .single_img.hero-column-two.hero-column > .no-margin.rollovercartItemImg.subSeries-Hero").attr("src");
LaptopSummeryBody = LenovoLeptopUrlDocument.select(".noeSpot.subseriesHeader > .hero-column-one.hero-column > .mediaGallery-productDescription.hero-productDescription > .mediaGallery-productDescription-body.hero-productDescription-body").text();
final Element table = LenovoLeptopUrlDocument.select("ol").first();
if (table != null) {
final Elements versionModel = table.select("div.tabbedBrowse-productListing");
for (Element version : versionModel) {
Laptop laptop = new Laptop();
laptop.setDescription(LaptopSummeryBody);
laptop.setImg_url(imgUrl);
String FinalModelName = version.select(".tabbedBrowse-productListing-header > .tabbedBrowse-productListing-title").text();
String FinalPrice = version.select(".tabbedBrowse-productListing-body > .pricingSummary > .pricingSummary-details > .pricingSummary-details-final-price.saleprice").text();
final Elements details = version.select("dl");
int i = 0;
Element values = null;
for (Element det : details) {
if (i == 1)
values = det;
i++;
}
Elements a = values.select("dt");
Elements b = values.select("dd");
attributes_lables = new String[a.size()];
attributes_values = new String[b.size()];
i = 0;
for (Element c : a) {
attributes_lables[i] = c.text();
i++;
}
i = 0;
for (Element d : b) {
attributes_values[i] = d.text();
i++;
}
for (i = 0; i < attributes_lables.length; i++) {
if (attributes_lables[i].equals("Operating System"))
laptop.setOperation_system(getFormat_OS(attributes_values[i]));
else if (attributes_lables[i].equals("Processor")) {
laptop.setProcessor(getFormat_CPU(attributes_values[i]));
} else if (attributes_lables[i].equals("Memory"))
laptop.setMemory(getFormat_Memory(attributes_values[i]));
else if (attributes_lables[i].equals("Graphics"))
laptop.setGpu(getFormat_GPU(attributes_values[i]));
else if (attributes_lables[i].equals("Hard Drive"))
laptop.setStorage(getFormat_Storage(attributes_values[i]));
else if (attributes_lables[i].equals("Display Type")) {
laptop.setScreen_size(getFormat_ScreenSize(attributes_values[i]));
if (attributes_values[i].toLowerCase().contains("multi-touch"))
laptop.setTouch_screen(true);
else
laptop.setTouch_screen(false);
} else if (attributes_lables[i].equals("Battery"))
laptop.setBattery(getFormat_Battery(attributes_values[i]));
}
if (laptop.NotAllAttributeisFilled()) {
ParseLaptop(url, laptop);
}
laptop.setId_prod(LaptopArray.size());
laptop.setCompany_name("Lenovo");
laptop.setUrl_model(url);
laptop.setModel_name(FinalModelName);
laptop.setPrice(getFormat_Price(FinalPrice));
// if (laptop.NotAllAttributeisFilled())
// System.out.println("FOUND NULL. "+url);
LaptopArray.add(laptop);
}
}
} catch (Exception ex) {
System.out.println(url);
ex.printStackTrace();
}
}
public static void ParseLaptop(String url, Laptop laptop) {
try {
final Document LenovoLeptopUrlDocument = Jsoup.connect(url).get();
final Elements table = LenovoLeptopUrlDocument.select(".techSpecs-table");
for (Element line : table.select("tr")) {
String attribute_lable = (line.select("td:nth-child(1)").text());
attribute_lable = attribute_lable.split("\\?")[0].trim();
Elements attribute_value = line.select("td:nth-child(2)");
if (line.select("td:nth-child(2)").select("li").size() != 0) {
for (Element li : line.select("td:nth-child(2)").select("li")) {
parseLenovoElement(laptop, attribute_value, attribute_lable);
}
} else {
parseLenovoElements(laptop, attribute_value, attribute_lable);
}
}
} catch (Exception ex) {
System.out.println(url);
ex.printStackTrace();
}
}
public static void parseLenovoElements(Laptop laptop, Elements elememt, String attribute_lable) {
if (attribute_lable.equals("Processor") && laptop.getProcessor() == null)
laptop.setProcessor(getFormat_CPU(elememt.text()));
if (attribute_lable.equals("Memory") && laptop.getMemory() == 0)
laptop.setMemory(getFormat_Memory(elememt.text()));
if (attribute_lable.equals("Operating System") && laptop.getOperation_system() == null)
laptop.setOperation_system(getFormat_OS(elememt.text()));
if (attribute_lable.equals("Graphics") && laptop.getGpu() == null)
laptop.setGpu(getFormat_GPU(elememt.text()));
if (attribute_lable.equals("Storage") && laptop.getStorage() == 0)
laptop.setStorage(getFormat_Storage(elememt.text()));
if (attribute_lable.equals("Display") && laptop.getScreen_size() == 0)
laptop.setScreen_size(getFormat_ScreenSize(elememt.text()));
if (attribute_lable.equals("Weight") && laptop.getWeight() == 0)
laptop.setWeight(getFormat_Weight(elememt.text()));
if (attribute_lable.equals("Battery") && laptop.getBattery() == 0)
laptop.setBattery(getFormat_Battery(elememt.text()));
if (attribute_lable.equals("Touch Screen") && laptop.getTouch_screen() == null) {
if (elememt.text().contains("multi-touch"))
laptop.setTouch_screen(true);
else
laptop.setTouch_screen(false);
}
}
public static void parseLenovoElement(Laptop laptop, Elements elememt, String attribute_lable) {
if (attribute_lable.equals("Processor") && laptop.getProcessor() == null)
laptop.setProcessor(getFormat_CPU(elememt.text()));
if (attribute_lable.equals("Memory") && laptop.getMemory() == 0)
laptop.setMemory(getFormat_Memory(elememt.text()));
if (attribute_lable.equals("Operating System") && laptop.getOperation_system() == null)
laptop.setOperation_system(getFormat_OS(elememt.text()));
if (attribute_lable.equals("Graphics") && laptop.getGpu() == null)
laptop.setGpu(getFormat_GPU(elememt.text()));
if (attribute_lable.equals("Storage") && laptop.getStorage() == 0)
laptop.setStorage(getFormat_Storage(elememt.text()));
if (attribute_lable.equals("Display") && laptop.getScreen_size() == 0)
laptop.setScreen_size(getFormat_ScreenSize(elememt.text()));
if (attribute_lable.equals("Weight") && laptop.getWeight() == 0)
laptop.setWeight(getFormat_Weight(elememt.text()));
if (attribute_lable.equals("Battery") && laptop.getBattery() == 0)
laptop.setBattery(getFormat_Battery(elememt.text()));
if (attribute_lable.equals("Touch Screen") && laptop.getTouch_screen() == null) {
if (elememt.text().contains("multi-touch"))
laptop.setTouch_screen(true);
else
laptop.setTouch_screen(false);
}
}
public static OS getFormat_OS(String OS_String_format)
{
String[] OS_String;
String Manufacture="";
String Version="";
int Serios = 0;
int Bit_Siz = 0;
if(OS_String_format.toLowerCase().contains("windows"))
{
OS_String = OS_String_format.split(" ");
//System.out.println(OS_String[0]+"\n"+OS_String[1]+"\n"+OS_String[2]+"\n"+OS_String[3]+"\n");
Manufacture = OS_String[0];
Serios = Integer.parseInt(OS_String[1]);
Version = OS_String[2];
Bit_Siz = 64;
}
OS OS_Struct = new OS(Manufacture,Version,Serios,Bit_Siz);
return OS_Struct;
}
public static PartStruct getFormat_CPU(String CPU_String_format) {
String CPU_Split[];
String CPU_Split1[];
String CPU_Split2[];
String Manufacture = "";
String Model = "";
if (CPU_String_format.contains("Intel")) {
Manufacture = "Intel";
CPU_Split = CPU_String_format.split("-");
CPU_Split1 = CPU_Split[0].split(" ");
CPU_Split2 = CPU_Split[1].split(" ");
Model = CPU_Split1[CPU_Split1.length - 1] + "-" + CPU_Split2[0];
} else if (CPU_String_format.contains("AMD")) {
Manufacture = "AMD";
CPU_Split = CPU_String_format.split("U");
CPU_Split1 = CPU_Split[0].split(" ");
Model = CPU_Split1[CPU_Split1.length - 1];
}
PartStruct CPUStruct = new PartStruct(Manufacture, Model);
return CPUStruct;
}
public static int getFormat_Memory(String Memory_String_format) {
int Memory = 0;
if (Memory_String_format.toLowerCase().contains("gb"))
Memory = Integer.parseInt(Memory_String_format.split("GB")[0].trim());
else
Memory = Integer.parseInt(Memory_String_format.trim());
return (Memory);
}
public static int getFormat_Storage(String Storage_String_format) {
int Storage = 0;
if (Storage_String_format.contains("GB"))
Storage = Integer.parseInt(Storage_String_format.split("GB")[0].trim());
else if (Storage_String_format.contains("TB"))
Storage = 1024 * Integer.parseInt(Storage_String_format.split("TB")[0].trim());
return Storage;
}
public static double getFormat_ScreenSize(String ScreenSize_String_format) {
String ScreenSizeString = "";
double ScreenSize = 0;
if (ScreenSize_String_format.contains(" FHD "))
ScreenSizeString = ScreenSize_String_format.split("FHD")[0];
if (ScreenSize_String_format.contains(" UHD "))
ScreenSizeString = ScreenSize_String_format.split("UHD")[0];
if (ScreenSize_String_format.contains(" WQHD "))
ScreenSizeString = ScreenSize_String_format.split("WQHD")[0];
if (ScreenSize_String_format.contains(" HDR "))
ScreenSizeString = ScreenSize_String_format.split("HDR")[0];
if (ScreenSize_String_format.contains(" HD "))
ScreenSizeString = ScreenSize_String_format.split("HD")[0];
ScreenSizeString = ScreenSizeString.replaceAll("[^\\d.]", "");
ScreenSize = Double.parseDouble(ScreenSizeString.trim());
return (ScreenSize);
}
public static double getFormat_Weight(String Weight_String_format) {
double Weight = 0;
df2.setRoundingMode(RoundingMode.UP);
String[] WeightSplit;
String WeightString;
WeightSplit = Weight_String_format.split("lbs");
WeightString = WeightSplit[0].trim();
if (WeightString.contains("kg"))
WeightString = WeightString.split("kg")[1].replaceAll("[^.?0-9]+", "");
else
WeightString = WeightString.replaceAll("[^.?0-9]+", "");
Weight = 0.45 * Double.parseDouble(WeightString.trim());
return Double.parseDouble(df2.format(Weight));
}
public static int getFormat_Battery(String Battery_String_format) {
int Battery = 0;
String[] BatterySplit;
//System.out.println(Battery_String_format);
if (Battery_String_format.toLowerCase().contains("whr")) {
BatterySplit = Battery_String_format.split("Whr")[0].split(" ");
//System.out.println(BatterySplit[BatterySplit.length - 1]);
Battery = Integer.parseInt(BatterySplit[BatterySplit.length - 1].trim());
} else if (Battery_String_format.toLowerCase().contains("wh")) {
BatterySplit = Battery_String_format.split("Wh")[0].split(" ");
//System.out.println(BatterySplit[BatterySplit.length - 1]);
Battery = Integer.parseInt(BatterySplit[BatterySplit.length - 1].trim());
} else
Battery = Integer.parseInt(Battery_String_format.trim());
//System.out.println(Battery);
return Battery;
}
public static double getFormat_Price(String Price_String_format) {
double Price = 0;
String PriceString;
PriceString = Price_String_format.replaceAll(",", "");
PriceString = PriceString.replaceAll("\\$", "");
PriceString = PriceString.split("\\.")[0];
Price = Double.parseDouble(PriceString.trim());
return Price;
}
public static PartStruct getFormat_GPU(String GPU_String_format) {
String GPU_Split[];
String Manufacture = "";
String Model = "";
if (GPU_String_format.contains("Intel")) {
Manufacture = "Intel";
Model = GPU_String_format.replaceAll("[^0-9]+", " ").trim();
} else if (GPU_String_format.toLowerCase().contains("nvidia")) {
Manufacture = "Nvidia";
if (GPU_String_format.contains(" GTX ")) {
GPU_Split = GPU_String_format.split(" GTX ");
Model = ("P" + GPU_Split[1].split(" ")[0]).trim();
} else if (GPU_String_format.contains(" P")) {
GPU_Split = GPU_String_format.split(" P");
Model = ("P" + GPU_Split[1].split(" ")[0]).trim();
} else if (GPU_String_format.contains(" M")) {
GPU_Split = GPU_String_format.split(" M");
Model = ("M" + GPU_Split[1].split(" ")[0]).trim();
}
}
PartStruct GPUStruct = new PartStruct(Manufacture, Model);
return GPUStruct;
}
}
|
package com.daw.club.services;
import java.util.Set;
/** Service interface for managing user credentials and authentication
*
* @author jrbalsas
*/
public interface ClubAuthService {
boolean authUser(String username, String password);
Set<String> getRoles(String username);
String encryptPassword(String password);
boolean verifyPassword(String password, String hashedPassword);
}
|
package Exercises527;
import java.util.Scanner;
public class FindZero {
public static void main(String[] args) {
//输入数字n
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
if (n >= 1 && n <= 1000) {
//求n!
double num = fac(n);
//判断阶乘中末尾0的个数
int result = hasZero(num);
System.out.println(result);
} else {
return;
}
}
private static double fac(double num) {
if (num == 1) {
return 1;
}
return num * fac(num - 1);
}
private static int hasZero(double num) {
int count = 0;
double tmp = num;
while (tmp % 10 == 0) {
tmp /= 10;
count++;
}
return count;
}
}
|
package de.jmda.gen;
import de.jmda.core.util.StringUtil;
public class LineIndenter
{
public final static LineIndenter TAB_SINGLE = new LineIndenter("\t", 1);
public final static LineIndenter TAB_DOUBLE = new LineIndenter("\t", 2);
public final static LineIndenter TAB_TRIPLE = new LineIndenter("\t", 3);
/**
* String used for indentation of lines in {@link #indent(String)} and {@link
* #indent(StringBuffer)}.
*/
private String indentation;
/**
* Number of times {@link #indentation} is used for indenting.
*/
private int indentationLevel;
/**
* Switch that turns indentation on (<code>true</code>) and off (<code>false
* </code>)
*/
private boolean indenting;
/**
* @param indentation
* @param indentationLevel values < 0 will be handled as 0
* @param indenting
*
* @see #indentation
* @see #indentationLevel
* @see #indenting
*/
public LineIndenter(
String indentation, int indentationLevel, boolean indenting)
{
super();
setIndentation(indentation);
setIndentationLevel(indentationLevel);
setIndenting(indenting);
}
/**
* Shortcut to {@link LineIndenter#LineIndenter(String, int, boolean)} with
* the parameter values <code>indentation</code>, <code>indentationLevel
* </code> and <code>true</code>. The line indenter will indent lines.
*
* @param indentation
* @param indentationLevel
*/
public LineIndenter(String indentation, int indentationLevel)
{
this(indentation, indentationLevel, true);
}
/**
* Shortcut to {@link LineIndenter#LineIndenter(String, int, boolean)} with
* the parameter values <code>""</code>, <code>0</code> and <code>false
* </code>. The line indenter will not indent lines.
*/
public LineIndenter()
{
this("", 0, false);
}
public String getIndentation()
{
return indentation;
}
/**
* @param indentation <code>null</code> values are handled as <code>""</code>
*/
public void setIndentation(String indentation)
{
if (indentation == null)
{
this.indentation = "";
}
else
{
this.indentation = indentation;
}
}
public int getIndentationLevel()
{
return indentationLevel;
}
/**
* @param indentationLevel values < 0 are handled as 0
*/
public void setIndentationLevel(int indentationLevel)
{
if (indentationLevel < 0)
{
this.indentationLevel = 0;
}
else
{
this.indentationLevel = indentationLevel;
}
}
public void setIndenting(boolean indenting)
{
this.indenting = indenting;
}
public boolean getIndenting()
{
return indenting;
}
public String indent(String string)
{
if (indenting)
{
return StringUtil.indent(string, indentation, indentationLevel);
}
return string;
}
public StringBuffer indent(StringBuffer stringbuffer)
{
if (indenting)
{
return StringUtil.indent(stringbuffer, indentation, indentationLevel);
}
return stringbuffer;
}
/**
* @param lineIndenter
* @param by
* @return new line indenter based on <code>lineIndenter</code> with
* indentation increased by <code>by</code>
*/
public static LineIndenter newIncreasedBy(LineIndenter lineIndenter, int by)
{
return new LineIndenter(lineIndenter.indentation, lineIndenter.indentationLevel + by);
}
}
|
/**
* Solutii Ecommerce, Automatizare, Validare si Analiza | Seava.ro
* Copyright: 2013 Nan21 Electronics SRL. All rights reserved.
* Use is subject to license terms.
*/
package seava.ad.presenter.impl.system.model;
import seava.ad.domain.impl.system.TargetRule;
import seava.j4e.api.annotation.Ds;
import seava.j4e.api.annotation.DsField;
import seava.j4e.presenter.impl.model.AbstractAuditable_Ds;
@Ds(entity = TargetRule.class)
public class TargetRule_Ds extends AbstractAuditable_Ds<TargetRule> {
public static final String ALIAS = "ad_TargetRule_Ds";
public static final String f_sourceRefId = "sourceRefId";
public static final String f_targetAlias = "targetAlias";
public static final String f_targetType = "targetType";
@DsField
private String sourceRefId;
@DsField
private String targetAlias;
@DsField
private String targetType;
public TargetRule_Ds() {
super();
}
public TargetRule_Ds(TargetRule e) {
super(e);
}
public String getSourceRefId() {
return this.sourceRefId;
}
public void setSourceRefId(String sourceRefId) {
this.sourceRefId = sourceRefId;
}
public String getTargetAlias() {
return this.targetAlias;
}
public void setTargetAlias(String targetAlias) {
this.targetAlias = targetAlias;
}
public String getTargetType() {
return this.targetType;
}
public void setTargetType(String targetType) {
this.targetType = targetType;
}
}
|
package org.rebioma.client.gxt3.treegrid;
import com.google.gwt.user.client.Event;
import com.sencha.gxt.widget.core.client.tree.Tree.TreeNode;
public interface CheckBoxTreeGridListener<M> {
/**
*
* @param event
*/
void onTreeNodeStatisticIconClick(Event event, TreeNode<M> node);
/**
*
* @param event
*/
void onTreeNodeMoreInformationIconClick(Event event, TreeNode<M> node);
}
|
/**
*
*/
package com.cnk.travelogix.communication.strategies;
import com.cnk.travelogix.communication.model.cms2.pages.CommunicationTemplateModel;
/**
* @author I319924
*
*/
public interface CloneCommunicationTemplateStrategy
{
CommunicationTemplateModel clone(final CommunicationTemplateModel original);
}
|
/*
* #%L
* Organisation: diozero
* Project: diozero - IMU device classes
* Filename: MPU6050.java
*
* This file is part of the diozero project. More information about this project
* can be found at https://www.diozero.com/.
* %%
* Copyright (C) 2016 - 2023 diozero
* %%
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
* #L%
*/
package com.diozero.devices.imu.invensense;
import java.util.HashMap;
import java.util.Map;
import org.hipparchus.geometry.Vector;
import org.hipparchus.geometry.euclidean.threed.Vector3D;
import com.diozero.api.I2CDevice;
import com.diozero.api.RuntimeIOException;
import com.diozero.devices.imu.ImuData;
import com.diozero.devices.imu.ImuInterface;
import com.diozero.devices.imu.OrientationListener;
import com.diozero.devices.imu.TapListener;
import com.diozero.util.SleepUtil;
/**
* The TDK InvenSense MPU6050 is an I2c 6-axis (3 for accelerometer, 3 for gyroscope) processor, with a high-precision
* temperature sensor.
* <ul>
* <li><a href="https://invensense.tdk.com/wp-content/uploads/2015/02/MPU-6000-Datasheet1.pdf">Spec sheet</a></li>
* <li><a href="https://invensense.tdk.com/wp-content/uploads/2015/02/MPU-6000-Register-Map1.pdf">Register map</a></li>
* </ul>
*/
public class MPU6050 implements ImuInterface {
public static final int DEFAULT_ADDRESS = 0x68;
public static final int OTHER_ADDRESS = 0x69;
// default sensitivities
private static final float GYRO_SENSITIVITY = 131f;
private static final float ACCELERATOR_SENSITIVITY = 16384f;
// temperature values
private static final float TEMPERATURE_DIVISOR = 340f;
private static final float TEMPERATURE_OFFSET = 36.53f;
private final I2CDevice delegate;
/**
* Creates the device on the given controller using the default address.
*
* @param controller the I2C controller bus
*/
public MPU6050(int controller) {
this(controller, DEFAULT_ADDRESS);
}
/**
* Creates the device on the given controller and address. (Note that if pin `AD0` is <b>high</b>, the alternate
* address is used.)
*
* @param controller the I2C controller bus
* @param address the I2C address of the sensor
*/
public MPU6050(int controller, int address) {
delegate = new I2CDevice(controller, address);
writeConfiguration("Waking up device",
Registers.POWER_MANAGEMENT_CONFIG,
RegisterValues.WAKEUP);
writeConfiguration("Configuring sample rate",
Registers.SAMPLE_RATE_DIVISOR,
RegisterValues.DEFAULT_SAMPLE_DIVISOR);
writeConfiguration("Setting global config (digital low pass filter)",
Registers.LOW_PASS_FILTER,
RegisterValues.LOW_PASS_CONFIG);
writeConfiguration("Configuring gyroscope",
Registers.GYRO_CONFIGURATION,
RegisterValues.DEFAULT_GYRO_CONFIGURATION);
writeConfiguration("Configuring accelerometer",
Registers.ACCELEROMETER_CONFIGURATION,
RegisterValues.DEFAULT_ACCELERATOR_CONFIGURATION);
writeConfiguration("Configuring interrupts",
Registers.ENABLE_INTERRUPTS,
RegisterValues.INTERRUPT_DISABLED);
writeConfiguration("Configuring low power operations",
Registers.STANDBY_MANAGEMENT_CONFIG,
RegisterValues.STANDBY_DISABLED);
}
@Override
public void close() throws RuntimeIOException {
delegate.close();
}
/**
* Read all registers - this is the _raw_ value.
*
* @return the bytes for each register
*/
public Map<Integer, Byte> dumpRegisters() {
Map<Integer, Byte> values = new HashMap<>();
for (int i = 1; i <= 120; i++) {
byte registerData = delegate.readByteData(i);
values.put(i, registerData);
}
return values;
}
@Override
public String getImuName() {
return "MPU-6050";
}
@Override
public int getPollInterval() {
// TODO this is a wild guess
return 10;
}
@Override
public boolean hasGyro() {
return true;
}
@Override
public boolean hasAccelerometer() {
return true;
}
@Override
public boolean hasCompass() {
return false;
}
@Override
public void startRead() {
throw new UnsupportedOperationException("Background reads are not supported.");
}
@Override
public void stopRead() {
throw new UnsupportedOperationException("Background reads are not supported.");
}
@Override
public ImuData getImuData() throws RuntimeIOException {
return new ImuData(getGyroData(), getAccelerometerData(), null, null, getTemperature(), System.currentTimeMillis());
}
@Override
public Vector3D getGyroData() throws RuntimeIOException {
return new Vector3D(readRegister(Registers.GYRO_X_REGISTER) / GYRO_SENSITIVITY,
readRegister(Registers.GYRO_Y_REGISTER) / GYRO_SENSITIVITY,
readRegister(Registers.GYRO_Z_REGISTER) / GYRO_SENSITIVITY);
}
@Override
public Vector3D getAccelerometerData() throws RuntimeIOException {
return new Vector3D(readRegister(Registers.ACCELERATOR_X_REGISTER) / ACCELERATOR_SENSITIVITY,
readRegister(Registers.ACCELERATOR_Y_REGISTER) / ACCELERATOR_SENSITIVITY,
readRegister(Registers.ACCELERATOR_Z_REGISTER) / ACCELERATOR_SENSITIVITY);
}
@Override
public Vector3D getCompassData() throws RuntimeIOException {
return null;
}
@Override
public void addTapListener(TapListener listener) {
throw new UnsupportedOperationException("Taps are not supported.");
}
@Override
public void addOrientationListener(OrientationListener listener) {
throw new UnsupportedOperationException("Background reads are not supported.");
}
/**
* Get the temperature reading.
*
* @return the temperature in degrees C
*/
public float getTemperature() {
return (readRegister(Registers.TEMPERATURE_REGISTER) / TEMPERATURE_DIVISOR) + TEMPERATURE_OFFSET;
}
/**
* Get the device's hardware I2C address.
*
* @return the I2C address
*/
public byte getI2CAddress() {
return delegate.readByteData(Registers.WHO_AM_I);
}
/**
* Calibration data for the gyroscope: basically computes the average values.
* <p>
* <B>THE DEVICE MUST BE STILL UNTIL THIS COMPLETES!!!!</B>
* <pre>
* Example:
* Vector3D adjusted = sensor.getGyroData().subtract(calibrationData);
* </pre>
* @param numberOfReadings how many readings to take
* @return the averaged readings for the gyroscope
* @see Vector3D#subtract(Vector)
*/
public Vector3D calibrateGyro(int numberOfReadings) {
float x = 0f;
float y = 0f;
float z = 0f;
for (int i = 0; i < numberOfReadings; i++) {
Vector3D initialSpeeds = getGyroData();
x += initialSpeeds.getX();
y += initialSpeeds.getY();
z += initialSpeeds.getZ();
SleepUtil.sleepMillis(100);
}
return new Vector3D(x / numberOfReadings, y / numberOfReadings, z / numberOfReadings);
}
/**
* Write and verify a device configuration value.
*
* @param configurationName name of the config for error messages
* @param register the register to write to
* @param data the configuration data
*/
private void writeConfiguration(String configurationName, byte register, byte data) {
delegate.writeByteData(register, data);
byte actual = delegate.readByteData(register);
if (actual != data) {
throw new RuntimeIOException(
String.format("%s: Tried to write '%02x' to register %02x, but value is '%02x'",
configurationName, data, register, actual));
}
}
/**
* Read a "double byte" from this register and the next one.
*
* @param register the register to read from
* @return the 2-byte integer value
*/
private int readRegister(int register) {
byte high = delegate.readByteData(register);
byte low = delegate.readByteData(register + 1);
int value = (high << 8) + low;
if (value >= 0x8000) return -(65536 - value);
return value;
}
private interface Registers {
/**
* Set the sample rate (the values are divided by this).
*/
byte SAMPLE_RATE_DIVISOR = 0x19;
/**
* Set up the low-pass filter
*/
byte LOW_PASS_FILTER = 0x1a;
/**
* Set up the gyroscope
*/
byte GYRO_CONFIGURATION = 0x1b;
/**
* Accelerometer configuration
*/
byte ACCELEROMETER_CONFIGURATION = 0x1c;
/**
* FIFO (not used)
*/
byte FIFO_CONFIGURATION = 0x23;
/**
* Enable interrupts (disabling)
*/
byte ENABLE_INTERRUPTS = 0x38;
/**
* Register for high bits of a 2's complement 16-bit value. The low bits
* are assumed to be in the next register (this + 1).
* <p>
* This is the most recent reading from the accelerometer's X axis.
*/
byte ACCELERATOR_X_REGISTER = 0x3b;
/**
* Register for high bits of a 2's complement 16-bit value. The low bits
* are assumed to be in the next register (this + 1).
* <p>
* This is the most recent reading from the accelerometer's Y axis.
*/
byte ACCELERATOR_Y_REGISTER = 0x3d;
/**
* Register for high bits of a 2's complement 16-bit value. The low bits
* are assumed to be in the next register (this + 1).
* <p>
* This is the most recent reading from the accelerometer's Z axis.
*/
byte ACCELERATOR_Z_REGISTER = 0x3f;
/**
* Register for high bits of a 2's complement 16-bit value. The low bits
* are assumed to be in the next register (this + 1).
* <p>
* This is the most recent reading from the temperature sensor.
*/
byte TEMPERATURE_REGISTER = 0x41;
/**
* Register for high bits of a 2's complement 16-bit value. The low bits
* are assumed to be in the next register (this + 1).
* <p>
* This is the most recent reading from the gyro's X axis.
*/
byte GYRO_X_REGISTER = 0x43;
/**
* Register for high bits of a 2's complement 16-bit value. The low bits
* are assumed to be in the next register (this + 1).
* <p>
* This is the most recent reading from the gyro's Y axis.
*/
byte GYRO_Y_REGISTER = 0x45;
/**
* Register for high bits of a 2's complement 16-bit value. The low bits
* are assumed to be in the next register (this + 1).
* <p>
* This is the most recent reading from the gyro's Z axis.
*/
byte GYRO_Z_REGISTER = 0x47;
/**
* Resets the various signals.
*/
byte SIGNAL_PATH_RESET = 0x68;
/**
* I2C management
*/
byte I2C_CONFIG = 0x6a;
/**
* Basic power management
*/
byte POWER_MANAGEMENT_CONFIG = 0x6b;
/**
* The I2C address (6-bits)
*/
byte WHO_AM_I = 0x75;
/**
* Standby mode management.
*/
byte STANDBY_MANAGEMENT_CONFIG = 0x6c;
}
private interface RegisterValues {
/**
* Just wakes the device up, because it sets the sleep bit to 0. Also sets
* the clock source to internal.
*/
byte WAKEUP = 0x0;
/**
* Sets the full scale range of the gyroscopes to ± 2000 °/s
*/
byte DEFAULT_GYRO_CONFIGURATION = 0x18;
/**
* Sets the sample rate divider for the gyroscopes and accelerometers. This
* means<br> acc-rate = 1kHz / 1+ sample-rate<br> and <br>gyro-rate = 8kHz /
* 1+ sample-rate. <br> <br> The concrete value 0 leaves the sample rate on
* default, which means 1kHz for acc-rate and 8kHz for gyr-rate.
*/
byte DEFAULT_SAMPLE_DIVISOR = 0x0;
/**
* Setting the digital low pass filter to <br>
* Acc Bandwidth (Hz) = 184 <br>
* Acc Delay (ms) = 2.0 <br>
* Gyro Bandwidth (Hz) = 188 <br>
* Gyro Delay (ms) = 1.9 <br>
* Fs (kHz) = 1
*/
byte LOW_PASS_CONFIG = 0x1;
/**
* Setting accelerometer sensitivity to ± 2g
*/
byte DEFAULT_ACCELERATOR_CONFIGURATION = 0x0;
/**
* Disabling FIFO buffer
*/
byte FIFO_DISABLED = 0x0;
/**
* Disabling interrupts
*/
byte INTERRUPT_DISABLED = 0x0;
/**
* Disabling standby modes
*/
byte STANDBY_DISABLED = 0x0;
}
}
|
package com.rc.portal.service.impl;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.rc.portal.dao.OpenSqlDAO;
import com.rc.portal.dao.TGoodsDAO;
import com.rc.portal.dao.TGoodsExtendDAO;
import com.rc.portal.dao.TGoodsImagesDAO;
import com.rc.portal.service.TGoodsManager;
import com.rc.portal.vo.TGoods;
import com.rc.portal.vo.TGoodsExample;
import com.rc.portal.vo.TGoodsImages;
import com.rc.portal.vo.TGoodsImagesExample;
import com.rc.portal.vo.TGoodsPremiumsExample;
import com.rc.portal.webapp.model.GoodsGroupModel;
import com.rc.portal.webapp.model.GroupModel;
@SuppressWarnings({"rawtypes","unchecked"})
public class TGoodsManagerImpl implements TGoodsManager
{
private TGoodsDAO tgoodsdao;
private TGoodsExtendDAO tgoodsextenddao;
private TGoodsImagesDAO tgoodsimagesdao;
private OpenSqlDAO opensqldao;
public TGoodsExtendDAO getTgoodsextenddao()
{
return tgoodsextenddao;
}
public void setTgoodsextenddao(TGoodsExtendDAO tgoodsextenddao)
{
this.tgoodsextenddao = tgoodsextenddao;
}
public TGoodsImagesDAO getTgoodsimagesdao()
{
return tgoodsimagesdao;
}
public void setTgoodsimagesdao(TGoodsImagesDAO tgoodsimagesdao)
{
this.tgoodsimagesdao = tgoodsimagesdao;
}
public OpenSqlDAO getOpensqldao()
{
return opensqldao;
}
public void setOpensqldao(OpenSqlDAO opensqldao)
{
this.opensqldao = opensqldao;
}
public TGoodsManagerImpl()
{
super();
}
public void setTgoodsdao(TGoodsDAO tgoodsdao)
{
this.tgoodsdao=tgoodsdao;
}
public TGoodsDAO getTgoodsdao()
{
return this.tgoodsdao;
}
public int countByExample(TGoodsExample example) throws SQLException
{
return tgoodsdao. countByExample( example);
}
public int deleteByExample(TGoodsExample example) throws SQLException
{
return tgoodsdao. deleteByExample( example);
}
public int deleteByPrimaryKey(Long id) throws SQLException
{
return tgoodsdao. deleteByPrimaryKey( id);
}
public Long insert(TGoods record) throws SQLException
{
return tgoodsdao. insert( record);
}
public Long insertSelective(TGoods record) throws SQLException
{
return tgoodsdao. insertSelective( record);
}
public List selectByExample(TGoodsExample example) throws SQLException
{
return tgoodsdao. selectByExample( example);
}
public TGoods selectByPrimaryKey(Long id) throws SQLException
{
return tgoodsdao. selectByPrimaryKey( id);
}
public int updateByExampleSelective(TGoods record, TGoodsExample example) throws SQLException
{
return tgoodsdao. updateByExampleSelective( record, example);
}
public int updateByExample(TGoods record, TGoodsExample example) throws SQLException
{
return tgoodsdao. updateByExample( record, example);
}
public int updateByPrimaryKeySelective(TGoods record) throws SQLException
{
return tgoodsdao. updateByPrimaryKeySelective( record);
}
public int updateByPrimaryKey(TGoods record) throws SQLException
{
return tgoodsdao. updateByPrimaryKey( record);
}
//查看商品详情
public Map<String, Object> selectByPrimaryKey1(Long id,String type) throws SQLException
{
Map<String, Object> map = new HashMap<String, Object>();
map.put("id", id);
map = (Map<String, Object>) opensqldao.selectForObjectByMap(map, "t_goods.selectGoodsById");
byte[] instructions = (byte[]) map.get("instruction");
if(null != instructions)
{
map.put("instructions", new String(instructions));
}
byte[] goodsDescribes = (byte[]) map.get("goodsDescribe");
if(null != goodsDescribes)
{
map.put("goodsDescribes", new String(goodsDescribes));
}
TGoodsImagesExample examplei = new TGoodsImagesExample();
examplei.createCriteria().andGoodsidEqualTo(id).andUserTypeEqualTo(Integer.parseInt(type));
examplei.setOrderByClause("sort desc");
List<TGoodsImages> listi = tgoodsimagesdao.selectByExample(examplei);
if(null != listi && 0<listi.size())
{
map.put("defaultimg", listi.get(0).getArtworkUrl());
if(type == "1" || "1".equals(type))
{
map.put("defaultimgs", listi.get(0).getImageUrl());
}
}
TGoodsPremiumsExample examplep = new TGoodsPremiumsExample();
examplep.createCriteria().andGoodsIdEqualTo(id);
Map<String, Object> valmap = new HashMap<String, Object>();
valmap.put("id", id);
List<GoodsGroupModel> listg = opensqldao.selectForListByMap(valmap, "t_goods.selectGroupByGoodsId");
List<Map<String, String>> listpc = getCategory(id);
valmap.clear();
for(GoodsGroupModel obj : listg)
{
valmap.put("id", obj.getId());
List<GroupModel> listgg = opensqldao.selectForListByMap(valmap, "t_goods.selectGoodsGroupByGoodsId");
obj.setList(listgg);
}
valmap.clear();
valmap.put("skuid", map.get("skuid"));
List<Map<Long,String>> lists = opensqldao.selectForListByMap(valmap, "t_goods.selectSpecByMap");
//获取商品扩展信息
map.put("lists", lists);
map.put("listi", listi);
map.put("listg", listg);
map.put("listpc", listpc);
return map;
}
//获取分类
private List<Map<String, String>> getCategory(long id)
{
Map<String, Object> valmap = new HashMap<String, Object>();
valmap.put("id", id);
valmap.put("type", 2);
Map<String,String> mappc =(Map<String, String>) opensqldao.selectForObjectByMap(valmap, "t_goods.selectCategoryByCId");
List<Map<String, String>> listpc = new ArrayList<Map<String,String>>();
if(null != mappc)
{
String[] ids = null;
if(null!=mappc.get("idall")&&!"".equals(mappc.get("idall")))
{
ids = mappc.get("idall").split(",");
}
String level = mappc.get("clevel");
if("4"==level||"4".equals(level))
{
Map<String, String> map1 = new HashMap<String, String>();
map1.put("name", mappc.get("name3"));
map1.put("id", ids[2]);
listpc.add(map1);
Map<String, String> map2 = new HashMap<String, String>();
map2.put("name", mappc.get("name2"));
map2.put("id", ids[3]);
listpc.add(map2);
Map<String, String> map3 = new HashMap<String, String>();
map3.put("name", mappc.get("name1"));
map3.put("id", mappc.get("id"));
listpc.add(map3);
}
else if("3"==level||"3".equals(level))
{
Map<String, String> map1 = new HashMap<String, String>();
map1.put("name", mappc.get("name2"));
map1.put("id", ids[2]);
listpc.add(map1);
Map<String, String> map3 = new HashMap<String, String>();
map3.put("name", mappc.get("name1"));
map3.put("id", mappc.get("id"));
listpc.add(map3);
}
else if("2"==level||"2".equals(level))
{
Map<String, String> map3 = new HashMap<String, String>();
map3.put("name", mappc.get("name1"));
map3.put("id", mappc.get("id"));
listpc.add(map3);
}
}
return listpc;
}
}
|
package com.dais.mapper;
import com.dais.model.CoinTradeRankHour;
import com.dais.model.CoinTradeRankHourExample;
import org.apache.ibatis.annotations.Param;
import java.util.List;
public interface CoinTradeRankHourMapper {
int countByExample(CoinTradeRankHourExample example);
int deleteByExample(CoinTradeRankHourExample example);
int deleteByPrimaryKey(Integer id);
int insert(CoinTradeRankHour record);
int insertSelective(CoinTradeRankHour record);
List<CoinTradeRankHour> selectByExample(CoinTradeRankHourExample example);
CoinTradeRankHour selectByPrimaryKey(Integer id);
int updateByExampleSelective(@Param("record") CoinTradeRankHour record, @Param("example") CoinTradeRankHourExample example);
int updateByExample(@Param("record") CoinTradeRankHour record, @Param("example") CoinTradeRankHourExample example);
int updateByPrimaryKeySelective(CoinTradeRankHour record);
int updateByPrimaryKey(CoinTradeRankHour record);
}
|
package Bars;
import java.awt.Color;
import GameObjects.GameObject;
public class CollectingBar extends Bar {
public CollectingBar(long maxValue) {
super(maxValue, 0);
}
@Override
public void performEmptyAction(GameObject gameObj) {
// TODO Auto-generated method stub
}
@Override
public Color getColor() {
return Color.pink;
}
public String getName() {
return "MN";
}
}
|
package com.example;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
/**
* Created by trainer8 on 4/26/17.
*/
@Service
public class UsersService {
private final UsersServiceConfig config;
private final RestTemplate restTemplate = new RestTemplate();
public UsersService(UsersServiceConfig config) {
this.config = config;
}
public RestTemplate getRestTemplate() {
return this.restTemplate;
}
// public User createUser(User inputUser) {
// HttpHeader headers = new HttpHeaders();
//
//
// }
public String getCount(){
String response = this.restTemplate.getForObject(String.format("%s/users/count",
this.config.getUrl()), String.class);
// String res = "{\""
return String.format("There are %s users", response);
// return res;
}
}
|
package com.maianfcnative;
import android.os.Bundle;
import android.content.Intent;
import android.app.Activity;
import android.nfc.NdefMessage;
import android.nfc.NdefRecord;
import android.nfc.NfcAdapter;
import android.os.Parcelable;
import android.util.Log;
import javax.annotation.Nullable;
import com.facebook.react.ReactActivityDelegate;
import com.facebook.react.modules.core.DeviceEventManagerModule;
import com.facebook.react.bridge.Arguments;
import com.facebook.react.bridge.WritableMap;
public class MaiaNFCActivityDelegate extends ReactActivityDelegate {
private Bundle initialProps = null;
private final @Nullable Activity activity;
public MaiaNFCActivityDelegate(Activity activity, String mainComponentName) {
super(activity, mainComponentName);
Log.i("ACTIVITY DELEGATE", "TESTING");
this.activity = activity;
}
@Override
protected Bundle getLaunchOptions() {
return initialProps;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
initialProps = new Bundle();
Intent intent = activity.getIntent();
String action = intent.getAction();
if (action != null && action.equals(NfcAdapter.ACTION_NDEF_DISCOVERED)) {
WritableMap map = parseNFCIntent(intent);
initialProps.putString("mime_type", map.getString("payload"));
initialProps.putString("mime_type", map.getString("mime_type"));
}
super.onCreate(savedInstanceState);
}
@Override
public boolean onNewIntent(Intent intent) {
String action = intent.getAction();
if (action != null && action.equals(NfcAdapter.ACTION_NDEF_DISCOVERED)) {
Log.i("NEW INTENT", action);
WritableMap map = parseNFCIntent(intent);
getReactInstanceManager().getCurrentReactContext()
.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)
.emit("new_tag", map);
}
return super.onNewIntent(intent);
}
private WritableMap parseNFCIntent(Intent intent) {
Parcelable[] rawMsgs = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
WritableMap map = Arguments.createMap();
for (int i = 0; i < rawMsgs.length; i++) {
NdefMessage msg = (NdefMessage) rawMsgs[i];
NdefRecord record = msg.getRecords()[0];
byte[] payload = record.getPayload();
String payload_string = new String(payload);
map.putString("payload", payload_string);
map.putString("mime_type", record.toMimeType());
}
return map;
}
};
|
package nl.pvanassen.highchart.api;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlTransient;
import javax.xml.bind.annotation.XmlType;
import nl.pvanassen.highchart.api.base.BaseObject;
import nl.pvanassen.highchart.api.label.LabelsItems;
import nl.pvanassen.highchart.api.utils.JsonArray;
@XmlAccessorType( XmlAccessType.NONE )
@XmlType( namespace = "chart-options" )
public class Labels extends BaseObject {
@XmlTransient
private JsonArray<LabelsItems> items;
public Labels() {
}
@XmlTransient
public JsonArray<LabelsItems> getItems() {
if ( items == null ) {
items = new JsonArray<LabelsItems>();
}
return items;
}
}
|
package com.Oovever.esayTool.io;
import com.Oovever.esayTool.util.StringUtil;
import org.junit.Test;
import java.io.File;
import static org.junit.Assert.*;
/**
* @author OovEver
* 2018/6/8 17:01
*/
public class FileUtilTest {
@Test
public void touch() {
String path = "D:\\tmp\\generator-result\\src\\main\\resources";
File file = new File(path);
FileUtil.del(file);
}
}
|
import java.util.*;
public class MinConflicts {
private static int no_of_states = 0;
private static int no_of_restarts = 0;
private static int size = 0;
private static int[] conflicts;
//no of conflicts
private static int heuristics(int col, int row, int[] arr){
return noOfDiaCollisions(col,row,arr) + noOfRowCollisions(col,row,arr);
}
static int getRand(int mod){
return (int) ((Math.random()*10) % mod);
}
private static void calculateConf(int[] arr){
for(int i=0;i<size;i++){
conflicts[i] = heuristics(i, arr[i], arr);
}
}
private static boolean isHeuZero(int[] arr){
for(int i=0;i<size;i++){
if(conflicts[i]!=0)
return false;
}
return true;
}
//row wise conflicts
static int noOfRowCollisions(int col, int row, int arr[]){
int count = 0;
for(int j=0;j<size;j++){
if(arr[col]==arr[j] && j!=col)
count++;
}
return count;
}
//diagonal conflicts
private static int noOfDiaCollisions(int col, int row, int[] arr){
int count = 0;
int leftAdd[] = new int[size];
int rightSub[] = new int[size];
for(int i=0;i<size;i++){
leftAdd[i] = arr[i]+i;
}
for(int i=0;i<size;i++){
rightSub[i] = arr[i]-i;
}
for(int i=0;i<size;i++){
if(leftAdd[col] == leftAdd[i] && i!= col)
count++;
}
for(int i=0;i<size;i++){
if(rightSub[col] == rightSub[i] && i!=col)
count++;
}
return count;
}
//min conflicts
private static void minConflicts(int[] arr){
boolean flag = false;
if(isHeuZero(arr)){
System.out.println("SOLUTION FOUND!!!");
printBoard(arr);
return;
}
if(no_of_states<50){
for(int i=0;i<size;i++){
int pos = getRand(size);//select a random queen
if(conflicts[pos]!=0){
for(int j=0;j<size;j++){
int oldval = arr[pos];//preserve the old position of the queen
if(oldval!=j){
arr[pos] = j;
no_of_states++;
if(heuristics(pos, j, arr)<conflicts[pos]){
calculateConf(arr);//calculate the heuristics for each queen again after modification
if(isHeuZero(arr)){
System.out.println("SOLUTION FOUND!!!");
printBoard(arr);
flag = true;
return;
}
else{
minConflicts(arr);
return;
}
}
arr[pos] = oldval;
}
}
}
}
}
//if no solution is found restart
if(!flag){
System.out.println("\nRESTART");
no_of_restarts++;
no_of_states = 0;
NQueens current = new NQueens(size);
current = current.createBoard();
int currArr[] = current.getArray();
calculateConf(currArr);
System.out.println("Current state " );
printBoard(currArr);
minConflicts(currArr);
return;
}
return;
}
// to print the chessBoard
public static void printBoard(int[] arr){
int chessboard[][] = new int[size][size];
for(int i=0;i<size;i++){
chessboard[arr[i]][i] = 1;
}
for(int i=0;i<size;i++){
for(int j=0;j<size;j++){
System.out.print(chessboard[i][j] + " ");
}
System.out.println();
}
}
//driver
public static void main(String[] args){
Scanner s = new Scanner(System.in);
System.out.println("Enter no of queens greater than 3 ");
int n = s.nextInt();
size = n;
NQueens current = new NQueens(n);
conflicts = new int[size];
current = current.createBoard();
int currArr[] = current.getArray();
calculateConf(currArr);
System.out.println("Current state");
printBoard(currArr);
minConflicts(currArr);
System.out.println("No of state changes " + no_of_states);
System.out.println("No of restarts " + no_of_restarts);
}
}
|
package com.peng.pp_app_sdk.utils;
import android.content.Context;
import android.content.SharedPreferences;
import java.io.File;
/**
* Created on 2015/12/7 0007.
* Author wangpengpeng
* Email 1678173987@qq.com
* Description
*/
public class GuidePageUtils {
/**
* 判断用户是否是第一次进入
*/
public static boolean isFirst(Context context) {
SharedPreferences sharedPreferences = context.getSharedPreferences("isfirst",
context.MODE_PRIVATE);
boolean isFirstin = sharedPreferences.getBoolean("isFirst", true);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean("isFirst", false);
editor.commit();
return isFirstin;
}
/**
* 判断用户是否是第一次进入则
* 或者是检测文件是否存在
*/
public static boolean isExists(Context context) {
boolean isexists = false;
File f = new File("/data/data/com.peng.pp_app_sdk/shared_prefs/isfirst.xml");
if (f.exists()) {
isexists = true;
} else {
isexists = false;
}
return isexists;
}
}
|
package org.openhab.support.knx2openhab;
public class ThingExtractorException extends RuntimeException
{
/**
*
*/
private static final long serialVersionUID = -3677469994400752075L;
public ThingExtractorException(final String message, final Throwable cause)
{
super(message, cause);
}
public ThingExtractorException(final String message)
{
super(message);
}
public ThingExtractorException(final Throwable cause)
{
super(cause);
}
}
|
package com.fixit.general;
import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import com.fixit.config.AppConfig;
import com.fixit.data.JobLocation;
import com.fixit.data.MutableLatLng;
import com.fixit.data.Profession;
import com.fixit.data.Tradesman;
import com.fixit.rest.APIError;
import com.fixit.rest.apis.SearchServiceAPI;
import com.fixit.rest.callbacks.GeneralServiceErrorCallback;
import com.fixit.rest.callbacks.ManagedServiceCallback;
import com.fixit.rest.requests.data.SearchRequestData;
import com.fixit.rest.requests.data.SearchResultRequestData;
import com.fixit.rest.responses.APIResponse;
import com.fixit.rest.responses.APIResponseHeader;
import com.fixit.rest.responses.data.SearchResponseData;
import com.fixit.rest.responses.data.SearchResultResponseData;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import retrofit2.Call;
/**
* Created by konstantin on 3/30/2017.
*/
public class SearchManager {
private final SearchServiceAPI mApi;
public SearchManager(SearchServiceAPI api) {
this.mApi = api;
}
public void sendSearch(Context context, final Profession profession, JobLocation location, final SearchCallback searchCallback) {
double lat = location.getLat();
double lng = location.getLng();
SearchRequestData requestData = new SearchRequestData(profession.getId(), new MutableLatLng(lat, lng));
mApi.beginSearch(requestData, new ManagedServiceCallback<SearchResponseData>(context, searchCallback) {
@Override
public void onResponse(SearchResponseData responseData) {
searchCallback.onSearchStarted(profession, location, responseData.getSearchKey());
}
@Override
public void onAppServiceError(List<APIError> errors) {
if (APIError.contains(APIError.Error.UNSUPPORTED, errors)){
searchCallback.unsupportedAddress();
} else {
super.onAppServiceError(errors);
}
}
});
}
public ResultsFetcher fetchResults(Context context, String searchId, ResultCallback resultCallback) {
ResultsFetcher resultsFetcher = new ResultsFetcher(context, searchId, resultCallback, mApi);
resultsFetcher.start();
return resultsFetcher;
}
public interface SearchCallback extends GeneralServiceErrorCallback {
void invalidAddress();
void unsupportedAddress();
void onSearchStarted(Profession profession, JobLocation location, String searchId);
}
public interface ResultCallback extends GeneralServiceErrorCallback {
void onResultsReceived(List<Tradesman> tradesmen, Map<String, Integer> reviewCountForTradesmen);
void onResultsFetchTimeout();
}
public static class ResultsFetcher extends Thread {
private final String searchId;
private final ResultCallback resultCallback;
private final SearchServiceAPI searchApi;
private final Handler handler;
private final int pollingRetryLimit;
private final int pollingRetryIntervalMs;
private final int errorRetryLimit;
private final int errorRetryIntervalMs;
private int pollingRetries = 0;
private int errorRetries = 0;
private volatile boolean isCancelled = false;
private boolean isFinished = false;
private ResultsFetcher(Context context, String searchId, ResultCallback resultCallback, SearchServiceAPI searchApi) {
this.searchId = searchId;
this.searchApi = searchApi;
this.resultCallback = resultCallback;
this.handler = new Handler(Looper.getMainLooper());
this.pollingRetryLimit = AppConfig.getInteger(context, AppConfig.KEY_SEARCH_RESULT_POLLING_RETRY_LIMIT, 5);
this.pollingRetryIntervalMs = AppConfig.getInteger(context, AppConfig.KEY_SEARCH_RESULT_POLLING_RETRY_INTERVAL_MS, 800);
this.errorRetryLimit = AppConfig.getInteger(context, AppConfig.KEY_SERVER_CONNECTION_RETRY_LIMIT, 5);
this.errorRetryIntervalMs = AppConfig.getInteger(context, AppConfig.KEY_SERVER_CONNECTION_RETRY_INTERVAL_MS, 800);
}
@Override
public void run() {
SearchResultRequestData requestData = new SearchResultRequestData(searchId);
execute(searchApi.fetchResults(requestData));
isFinished = true;
}
private SearchResultResponseData execute(Call<APIResponse<SearchResultResponseData>> call) {
if(call != null && !isCancelled) {
try {
APIResponse<SearchResultResponseData> response = call.execute().body();
if(response != null) {
final APIResponseHeader header = response.getHeader();
final SearchResultResponseData data = response.getData();
if(header.hasErrors()) {
handler.post(new Runnable() {
@Override
public void run() {
resultCallback.onAppServiceError(header.getErrors());
}
});
} else if(data.isComplete()) {
handler.post(new Runnable() {
@Override
public void run() {
resultCallback.onResultsReceived(data.getTradesmen(), data.getReviewCountForTradesmen());
}
});
} else {
poll(call);
}
} else {
poll(call);
}
} catch (IOException e) {
handleError(call, e);
}
}
return null;
}
private SearchResultResponseData poll(Call<APIResponse<SearchResultResponseData>> call) {
if(pollingRetries < pollingRetryLimit) {
pollingRetries++;
if(!isCancelled) {
try {
synchronized (this) {
wait(pollingRetryIntervalMs);
}
} catch (InterruptedException e1) {
// do nothing, continue with the flow.
}
}
return execute(call.clone());
} else {
handler.post(new Runnable() {
@Override
public void run() {
resultCallback.onResultsFetchTimeout();
}
});
}
return null;
}
private SearchResultResponseData handleError(Call<APIResponse<SearchResultResponseData>> call, final Throwable t) {
if(errorRetries < errorRetryLimit) {
errorRetries++;
if(!isCancelled) {
try {
synchronized (this) {
wait(errorRetryIntervalMs);
}
} catch (InterruptedException e1) {
// do nothing, continue with the flow.
}
}
return execute(call.clone());
} else {
handler.post(new Runnable() {
@Override
public void run() {
resultCallback.onUnexpectedErrorOccurred(t.getMessage(), t);
}
});
}
return null;
}
public void cancel() {
isCancelled = true;
}
public boolean isCancelled() {
return isCancelled;
}
public boolean isFinished() {
return isFinished;
}
}
}
|
package oop.ex6.component.variable;
import oop.ex6.fileanalyzer.BadLineFormatException;
/**
* Exception of a bad variable declaration.
*/
public class VariableDeclarationException extends BadLineFormatException {
/** prevents annoying warning */
private static final long serialVersionUID = 1L;
}
|
/*
* 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 hojadetrabajo8;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.*;
/**
*
* @author Manolo
*/
public class PacienteTest {
public PacienteTest() {
}
@BeforeClass
public static void setUpClass() {
}
@AfterClass
public static void tearDownClass() {
}
@Before
public void setUp() {
}
@After
public void tearDown() {
}
/**
* Test of getNombre method, of class Paciente.
*/
@Test
public void testGetNombre() {
System.out.println("getNombre");
Paciente instance = new Paciente();
String expResult = "";
String result = instance.getNombre();
assertEquals(expResult, result);
// TODO review the generated test code and remove the default call to fail.
fail("The test case is a prototype.");
}
/**
* Test of setNombre method, of class Paciente.
*/
@Test
public void testSetNombre() {
System.out.println("setNombre");
String nombre = "";
Paciente instance = new Paciente();
instance.setNombre(nombre);
// TODO review the generated test code and remove the default call to fail.
fail("The test case is a prototype.");
}
/**
* Test of getEnfermedad method, of class Paciente.
*/
@Test
public void testGetEnfermedad() {
System.out.println("getEnfermedad");
Paciente instance = new Paciente();
String expResult = "";
String result = instance.getEnfermedad();
assertEquals(expResult, result);
// TODO review the generated test code and remove the default call to fail.
fail("The test case is a prototype.");
}
/**
* Test of setEnfermedad method, of class Paciente.
*/
@Test
public void testSetEnfermedad() {
System.out.println("setEnfermedad");
String enfermedad = "";
Paciente instance = new Paciente();
instance.setEnfermedad(enfermedad);
// TODO review the generated test code and remove the default call to fail.
fail("The test case is a prototype.");
}
/**
* Test of getPrioridad method, of class Paciente.
*/
@Test
public void testGetPrioridad() {
System.out.println("getPrioridad");
Paciente instance = new Paciente();
String expResult = "";
String result = instance.getPrioridad();
assertEquals(expResult, result);
// TODO review the generated test code and remove the default call to fail.
fail("The test case is a prototype.");
}
/**
* Test of setPrioridad method, of class Paciente.
*/
@Test
public void testSetPrioridad() {
System.out.println("setPrioridad");
String prioridad = "";
Paciente instance = new Paciente();
instance.setPrioridad(prioridad);
// TODO review the generated test code and remove the default call to fail.
fail("The test case is a prototype.");
}
/**
* Test of compareTo method, of class Paciente.
*/
@Test
public void testCompareTo() {
System.out.println("compareTo");
Paciente paciente = null;
Paciente instance = new Paciente();
int expResult = 0;
int result = instance.compareTo(paciente);
assertEquals(expResult, result);
// TODO review the generated test code and remove the default call to fail.
fail("The test case is a prototype.");
}
}
|
package com.blood.view;
import com.blood.view.blood.*;
import com.blood.view.Buyer.*;
import com.blood.view.Seller.*;
import com.blood.view.sell.*;
import com.blood.view.buy.*;
import javax.swing.JInternalFrame;
import com.blood.view.help.About;
import java.awt.Toolkit;
/**
*
* @author Shishir
*/
public class Home extends javax.swing.JFrame {
public Home() {
super("Blood Bank Management Software");
initComponents();
setIconImage(Toolkit.getDefaultToolkit().getImage(getClass().getResource("blood.png")));
}
private void allclose() {
for (JInternalFrame jfin : desktopPane.getAllFrames()) {
jfin.dispose();
}
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jPanel1 = new javax.swing.JPanel();
btn_donor = new javax.swing.JButton();
btn_customer = new javax.swing.JButton();
btn_sell = new javax.swing.JButton();
btn_blood_list = new javax.swing.JButton();
btn_logout = new javax.swing.JButton();
btn_buy = new javax.swing.JButton();
btn_reserve = new javax.swing.JButton();
desktopPane = new javax.swing.JDesktopPane();
jLabel1 = new javax.swing.JLabel();
menuBar = new javax.swing.JMenuBar();
menu_user = new javax.swing.JMenu();
menuItem_log_out = new javax.swing.JMenuItem();
exitMenuItem = new javax.swing.JMenuItem();
menu_donor = new javax.swing.JMenu();
menuItem_donor_new = new javax.swing.JMenuItem();
menuItem_donor_edit = new javax.swing.JMenuItem();
menuItem_donor_list = new javax.swing.JMenuItem();
menu_customer = new javax.swing.JMenu();
menuItem_new_customer = new javax.swing.JMenuItem();
menuItem_edit_customer = new javax.swing.JMenuItem();
menuItem_customer_list = new javax.swing.JMenuItem();
menu_blood = new javax.swing.JMenu();
menuItem_blood_setting = new javax.swing.JMenuItem();
menuItem_blood_list = new javax.swing.JMenuItem();
menu_Buy = new javax.swing.JMenu();
menuItem_bbuy = new javax.swing.JMenuItem();
menuItem_bbuy_list = new javax.swing.JMenuItem();
menu_donate = new javax.swing.JMenu();
menuItem_bsell = new javax.swing.JMenuItem();
menuItem_bsell_list = new javax.swing.JMenuItem();
menu_help = new javax.swing.JMenu();
menuItem_about = new javax.swing.JMenuItem();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setResizable(false);
btn_donor.setFont(new java.awt.Font("Times New Roman", 1, 18)); // NOI18N
btn_donor.setText("New Seller");
btn_donor.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btn_donorActionPerformed(evt);
}
});
btn_customer.setFont(new java.awt.Font("Times New Roman", 1, 18)); // NOI18N
btn_customer.setText("New Buyer");
btn_customer.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btn_customerActionPerformed(evt);
}
});
btn_sell.setFont(new java.awt.Font("Times New Roman", 1, 18)); // NOI18N
btn_sell.setText("Blood Sell");
btn_sell.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btn_sellActionPerformed(evt);
}
});
btn_blood_list.setFont(new java.awt.Font("Times New Roman", 1, 18)); // NOI18N
btn_blood_list.setText("Blood List");
btn_blood_list.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btn_blood_listActionPerformed(evt);
}
});
btn_logout.setFont(new java.awt.Font("Times New Roman", 1, 18)); // NOI18N
btn_logout.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/blood/photos/logoutBig.png"))); // NOI18N
btn_logout.setToolTipText("Logout");
btn_logout.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btn_logoutActionPerformed(evt);
}
});
btn_buy.setFont(new java.awt.Font("Times New Roman", 1, 18)); // NOI18N
btn_buy.setText("Blood Buy");
btn_buy.setToolTipText("");
btn_buy.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btn_buyActionPerformed(evt);
}
});
btn_reserve.setFont(new java.awt.Font("Times New Roman", 1, 18)); // NOI18N
btn_reserve.setText("Blood Reserve");
btn_reserve.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btn_reserveActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addComponent(btn_donor, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(btn_customer, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(btn_sell, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(btn_buy, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(btn_blood_list, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGap(6, 6, 6)
.addComponent(btn_reserve, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(btn_logout, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGap(146, 146, 146))
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(btn_blood_list, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(btn_donor, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(btn_customer, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(btn_sell, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(btn_logout, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(btn_buy, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(btn_reserve, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addContainerGap())
);
desktopPane.setFont(new java.awt.Font("Times New Roman", 0, 14)); // NOI18N
jLabel1.setBackground(new java.awt.Color(255, 51, 153));
jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/blood/photos/blood_bd.jpg"))); // NOI18N
jLabel1.setIconTextGap(0);
javax.swing.GroupLayout desktopPaneLayout = new javax.swing.GroupLayout(desktopPane);
desktopPane.setLayout(desktopPaneLayout);
desktopPaneLayout.setHorizontalGroup(
desktopPaneLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
desktopPaneLayout.setVerticalGroup(
desktopPaneLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
desktopPane.setLayer(jLabel1, javax.swing.JLayeredPane.DEFAULT_LAYER);
menuBar.setFont(new java.awt.Font("Times New Roman", 1, 18)); // NOI18N
menu_user.setMnemonic('f');
menu_user.setText("User");
menu_user.setFont(new java.awt.Font("Times New Roman", 1, 18)); // NOI18N
menuItem_log_out.setFont(new java.awt.Font("Times New Roman", 1, 14)); // NOI18N
menuItem_log_out.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/blood/photos/logout.png"))); // NOI18N
menuItem_log_out.setMnemonic('o');
menuItem_log_out.setText("Log Out");
menuItem_log_out.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
menuItem_log_outActionPerformed(evt);
}
});
menu_user.add(menuItem_log_out);
exitMenuItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_F4, java.awt.event.InputEvent.ALT_MASK | java.awt.event.InputEvent.CTRL_MASK));
exitMenuItem.setFont(new java.awt.Font("Times New Roman", 1, 14)); // NOI18N
exitMenuItem.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/blood/photos/exit.png"))); // NOI18N
exitMenuItem.setMnemonic('x');
exitMenuItem.setText("Exit");
exitMenuItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
exitMenuItemActionPerformed(evt);
}
});
menu_user.add(exitMenuItem);
menuBar.add(menu_user);
menu_donor.setMnemonic('e');
menu_donor.setText("Seller");
menu_donor.setFont(new java.awt.Font("Times New Roman", 1, 18)); // NOI18N
menuItem_donor_new.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_N, java.awt.event.InputEvent.SHIFT_MASK | java.awt.event.InputEvent.CTRL_MASK));
menuItem_donor_new.setFont(new java.awt.Font("Times New Roman", 1, 14)); // NOI18N
menuItem_donor_new.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/blood/photos/add_students.png"))); // NOI18N
menuItem_donor_new.setText("New Seller");
menuItem_donor_new.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
menuItem_donor_newActionPerformed(evt);
}
});
menu_donor.add(menuItem_donor_new);
menuItem_donor_edit.setFont(new java.awt.Font("Times New Roman", 1, 14)); // NOI18N
menuItem_donor_edit.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/blood/photos/edit.png"))); // NOI18N
menuItem_donor_edit.setMnemonic('y');
menuItem_donor_edit.setText("Edit Seller");
menuItem_donor_edit.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
menuItem_donor_editActionPerformed(evt);
}
});
menu_donor.add(menuItem_donor_edit);
menuItem_donor_list.setFont(new java.awt.Font("Times New Roman", 1, 14)); // NOI18N
menuItem_donor_list.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/blood/photos/list.png"))); // NOI18N
menuItem_donor_list.setMnemonic('y');
menuItem_donor_list.setText("Seller List");
menuItem_donor_list.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
menuItem_donor_listActionPerformed(evt);
}
});
menu_donor.add(menuItem_donor_list);
menuBar.add(menu_donor);
menu_customer.setText("Buyer");
menu_customer.setFont(new java.awt.Font("Times New Roman", 1, 18)); // NOI18N
menuItem_new_customer.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_C, java.awt.event.InputEvent.SHIFT_MASK | java.awt.event.InputEvent.CTRL_MASK));
menuItem_new_customer.setFont(new java.awt.Font("Times New Roman", 1, 14)); // NOI18N
menuItem_new_customer.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/blood/photos/add_students.png"))); // NOI18N
menuItem_new_customer.setText("New Buyer");
menuItem_new_customer.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
menuItem_new_customerActionPerformed(evt);
}
});
menu_customer.add(menuItem_new_customer);
menuItem_edit_customer.setFont(new java.awt.Font("Times New Roman", 1, 14)); // NOI18N
menuItem_edit_customer.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/blood/photos/edit.png"))); // NOI18N
menuItem_edit_customer.setText("Edit Buyer");
menuItem_edit_customer.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
menuItem_edit_customerActionPerformed(evt);
}
});
menu_customer.add(menuItem_edit_customer);
menuItem_customer_list.setFont(new java.awt.Font("Times New Roman", 1, 14)); // NOI18N
menuItem_customer_list.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/blood/photos/list.png"))); // NOI18N
menuItem_customer_list.setText("Buyer List");
menuItem_customer_list.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
menuItem_customer_listActionPerformed(evt);
}
});
menu_customer.add(menuItem_customer_list);
menuBar.add(menu_customer);
menu_blood.setMnemonic('h');
menu_blood.setText("Blood");
menu_blood.setFont(new java.awt.Font("Times New Roman", 1, 18)); // NOI18N
menuItem_blood_setting.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_B, java.awt.event.InputEvent.ALT_MASK | java.awt.event.InputEvent.CTRL_MASK));
menuItem_blood_setting.setFont(new java.awt.Font("Times New Roman", 1, 14)); // NOI18N
menuItem_blood_setting.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/blood/photos/setting.png"))); // NOI18N
menuItem_blood_setting.setMnemonic('c');
menuItem_blood_setting.setText("Blood Setting");
menuItem_blood_setting.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
menuItem_blood_settingActionPerformed(evt);
}
});
menu_blood.add(menuItem_blood_setting);
menuItem_blood_list.setFont(new java.awt.Font("Times New Roman", 1, 14)); // NOI18N
menuItem_blood_list.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/blood/photos/list.png"))); // NOI18N
menuItem_blood_list.setMnemonic('c');
menuItem_blood_list.setText("Blood List");
menuItem_blood_list.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
menuItem_blood_listActionPerformed(evt);
}
});
menu_blood.add(menuItem_blood_list);
menuBar.add(menu_blood);
menu_Buy.setText("Blood Buy");
menu_Buy.setFont(new java.awt.Font("Times New Roman", 1, 18)); // NOI18N
menuItem_bbuy.setFont(new java.awt.Font("Times New Roman", 1, 14)); // NOI18N
menuItem_bbuy.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/blood/photos/Buy.png"))); // NOI18N
menuItem_bbuy.setText("Blood Buy");
menuItem_bbuy.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
menuItem_bbuyActionPerformed(evt);
}
});
menu_Buy.add(menuItem_bbuy);
menuItem_bbuy_list.setFont(new java.awt.Font("Times New Roman", 1, 14)); // NOI18N
menuItem_bbuy_list.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/blood/photos/list.png"))); // NOI18N
menuItem_bbuy_list.setText("Blood Buy List");
menuItem_bbuy_list.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
menuItem_bbuy_listActionPerformed(evt);
}
});
menu_Buy.add(menuItem_bbuy_list);
menuBar.add(menu_Buy);
menu_donate.setText("Blood Sell");
menu_donate.setFont(new java.awt.Font("Times New Roman", 1, 18)); // NOI18N
menuItem_bsell.setFont(new java.awt.Font("Times New Roman", 1, 14)); // NOI18N
menuItem_bsell.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/blood/photos/Buy.png"))); // NOI18N
menuItem_bsell.setText("Blood Sell");
menuItem_bsell.setToolTipText("");
menuItem_bsell.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
menuItem_bsellActionPerformed(evt);
}
});
menu_donate.add(menuItem_bsell);
menuItem_bsell_list.setFont(new java.awt.Font("Times New Roman", 1, 14)); // NOI18N
menuItem_bsell_list.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/blood/photos/list.png"))); // NOI18N
menuItem_bsell_list.setText("Blood Sell List");
menuItem_bsell_list.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
menuItem_bsell_listActionPerformed(evt);
}
});
menu_donate.add(menuItem_bsell_list);
menuBar.add(menu_donate);
menu_help.setText("Help");
menu_help.setFont(new java.awt.Font("Times New Roman", 1, 18)); // NOI18N
menuItem_about.setFont(new java.awt.Font("Times New Roman", 1, 14)); // NOI18N
menuItem_about.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/blood/photos/support.png"))); // NOI18N
menuItem_about.setText("About");
menuItem_about.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
menuItem_aboutActionPerformed(evt);
}
});
menu_help.add(menuItem_about);
menuBar.add(menu_help);
setJMenuBar(menuBar);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(desktopPane)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(desktopPane))
);
setSize(new java.awt.Dimension(1018, 820));
setLocationRelativeTo(null);
}// </editor-fold>//GEN-END:initComponents
private void exitMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_exitMenuItemActionPerformed
System.exit(0);
}//GEN-LAST:event_exitMenuItemActionPerformed
private void menuItem_bsell_listActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_menuItem_bsell_listActionPerformed
// TODO add your handling code here:
allclose();
Blood_sell_list do1 = new Blood_sell_list();
this.desktopPane.add(do1);
do1.setVisible(true);
}//GEN-LAST:event_menuItem_bsell_listActionPerformed
private void menuItem_log_outActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_menuItem_log_outActionPerformed
// TODO add your handling code here:
setVisible(false);
Login sl = new Login();
sl.setVisible(true);
}//GEN-LAST:event_menuItem_log_outActionPerformed
private void menuItem_donor_newActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_menuItem_donor_newActionPerformed
// TODO add your handling code here
allclose();
New_seller dl = new New_seller();
this.desktopPane.add(dl);
dl.setVisible(true);
}//GEN-LAST:event_menuItem_donor_newActionPerformed
private void btn_logoutActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_logoutActionPerformed
// TODO add your handling code here:
setVisible(false);
Login sl = new Login();
sl.setVisible(true);
}//GEN-LAST:event_btn_logoutActionPerformed
private void btn_donorActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_donorActionPerformed
// TODO add your handling code here:
allclose();
New_seller dl = new New_seller();
this.desktopPane.add(dl);
dl.setVisible(true);
}//GEN-LAST:event_btn_donorActionPerformed
private void menuItem_donor_editActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_menuItem_donor_editActionPerformed
// TODO add your handling code here:
allclose();
Edit_seller d2 = new Edit_seller();
this.desktopPane.add(d2);
d2.setVisible(true);
}//GEN-LAST:event_menuItem_donor_editActionPerformed
private void menuItem_donor_listActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_menuItem_donor_listActionPerformed
// TODO add your handling code here:
allclose();
Seller_list d3 = new Seller_list();
this.desktopPane.add(d3);
d3.setVisible(true);
}//GEN-LAST:event_menuItem_donor_listActionPerformed
private void btn_customerActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_customerActionPerformed
// TODO add your handling code here:
allclose();
New_Buyer c1 = new New_Buyer();
this.desktopPane.add(c1);
c1.setVisible(true);
}//GEN-LAST:event_btn_customerActionPerformed
private void menuItem_new_customerActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_menuItem_new_customerActionPerformed
// TODO add your handling code here:
allclose();
New_Buyer c2 = new New_Buyer();
this.desktopPane.add(c2);
c2.setVisible(true);
}//GEN-LAST:event_menuItem_new_customerActionPerformed
private void menuItem_customer_listActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_menuItem_customer_listActionPerformed
// TODO add your handling code here:
allclose();
Buyer_list c3 = new Buyer_list();
this.desktopPane.add(c3);
c3.setVisible(true);
}//GEN-LAST:event_menuItem_customer_listActionPerformed
private void menuItem_blood_settingActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_menuItem_blood_settingActionPerformed
// TODO add your handling code here:
allclose();
Blood_setting b1 = new Blood_setting();
this.desktopPane.add(b1);
b1.setVisible(true);
}//GEN-LAST:event_menuItem_blood_settingActionPerformed
private void menuItem_blood_listActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_menuItem_blood_listActionPerformed
// TODO add your handling code here:
allclose();
Blood_list b2 = new Blood_list();
this.desktopPane.add(b2);
b2.setVisible(true);
}//GEN-LAST:event_menuItem_blood_listActionPerformed
private void menuItem_edit_customerActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_menuItem_edit_customerActionPerformed
// TODO add your handling code here:
allclose();
Edit_Buyer c2 = new Edit_Buyer();
this.desktopPane.add(c2);
c2.setVisible(true);
}//GEN-LAST:event_menuItem_edit_customerActionPerformed
private void btn_blood_listActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_blood_listActionPerformed
// TODO add your handling code here:
allclose();
Blood_list bl = new Blood_list();
this.desktopPane.add(bl);
bl.setVisible(true);
}//GEN-LAST:event_btn_blood_listActionPerformed
private void menuItem_aboutActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_menuItem_aboutActionPerformed
// TODO add your handling code here:
allclose();
About ab = new About();
this.desktopPane.add(ab);
ab.setVisible(true);
}//GEN-LAST:event_menuItem_aboutActionPerformed
private void btn_buyActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_buyActionPerformed
// TODO add your handling code here:
allclose();
Blood_Buy bs = new Blood_Buy();
this.desktopPane.add(bs);
bs.setVisible(true);
}//GEN-LAST:event_btn_buyActionPerformed
private void btn_sellActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_sellActionPerformed
// TODO add your handling code here:
allclose();
Blood_Sell bb = new Blood_Sell();
this.desktopPane.add(bb);
bb.setVisible(true);
}//GEN-LAST:event_btn_sellActionPerformed
private void menuItem_bbuy_listActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_menuItem_bbuy_listActionPerformed
// TODO add your handling code here:
allclose();
Blood_buy_list do1 = new Blood_buy_list();
this.desktopPane.add(do1);
do1.setVisible(true);
}//GEN-LAST:event_menuItem_bbuy_listActionPerformed
private void menuItem_bsellActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_menuItem_bsellActionPerformed
// TODO add your handling code here:
allclose();
Blood_Sell bb = new Blood_Sell();
this.desktopPane.add(bb);
bb.setVisible(true);
}//GEN-LAST:event_menuItem_bsellActionPerformed
private void menuItem_bbuyActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_menuItem_bbuyActionPerformed
// TODO add your handling code here:
allclose();
Blood_Buy bsn = new Blood_Buy();
this.desktopPane.add(bsn);
bsn.setVisible(true);
}//GEN-LAST:event_menuItem_bbuyActionPerformed
private void btn_reserveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_reserveActionPerformed
// TODO add your handling code here:
allclose();
Reserve_frame rf = new Reserve_frame();
this.desktopPane.add(rf);
rf.setVisible(true);
}//GEN-LAST:event_btn_reserveActionPerformed
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Home.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new Home().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton btn_blood_list;
private javax.swing.JButton btn_buy;
private javax.swing.JButton btn_customer;
private javax.swing.JButton btn_donor;
private javax.swing.JButton btn_logout;
private javax.swing.JButton btn_reserve;
private javax.swing.JButton btn_sell;
private javax.swing.JDesktopPane desktopPane;
private javax.swing.JMenuItem exitMenuItem;
private javax.swing.JLabel jLabel1;
private javax.swing.JPanel jPanel1;
private javax.swing.JMenuBar menuBar;
private javax.swing.JMenuItem menuItem_about;
private javax.swing.JMenuItem menuItem_bbuy;
private javax.swing.JMenuItem menuItem_bbuy_list;
private javax.swing.JMenuItem menuItem_blood_list;
private javax.swing.JMenuItem menuItem_blood_setting;
private javax.swing.JMenuItem menuItem_bsell;
private javax.swing.JMenuItem menuItem_bsell_list;
private javax.swing.JMenuItem menuItem_customer_list;
private javax.swing.JMenuItem menuItem_donor_edit;
private javax.swing.JMenuItem menuItem_donor_list;
private javax.swing.JMenuItem menuItem_donor_new;
private javax.swing.JMenuItem menuItem_edit_customer;
private javax.swing.JMenuItem menuItem_log_out;
private javax.swing.JMenuItem menuItem_new_customer;
private javax.swing.JMenu menu_Buy;
private javax.swing.JMenu menu_blood;
private javax.swing.JMenu menu_customer;
private javax.swing.JMenu menu_donate;
private javax.swing.JMenu menu_donor;
private javax.swing.JMenu menu_help;
private javax.swing.JMenu menu_user;
// End of variables declaration//GEN-END:variables
}
|
package com.tencent.mm.plugin.fav.a;
public interface o {
void Bp(String str);
void Bq(String str);
void c(c cVar);
void eN(boolean z);
void pauseDownload(String str);
void run();
}
|
package edu.neumont.learnignChess.model;
import java.util.Enumeration;
import edu.neumont.learningChess.api.Location;
public class Rook extends ChessPiece {
public static final String NAME = "Rook";
private static final int WORTH = 5;
public Rook() {
super(WORTH);
}
public String getName() {
return NAME;
}
public Enumeration<Location> getLegalMoves(ChessBoard board) {
MoveEnumeration moves = new MoveEnumeration(board, location);
moves.addPerps();
return moves;
}
}
|
package bobing.backend.model;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;
import javax.persistence.Entity;
import javax.persistence.EntityListeners;
import javax.persistence.Table;
/**
* 博饼结果的点数集合
*/
@Entity
@Table
@EntityListeners(AuditingEntityListener.class)
public class DianShu extends IdEntity implements Comparable<DianShu>{
private String result;
public String getResult() {
return result;
}
public void setResult(String result) {
this.result = result;
}
@Override
public int compareTo(DianShu anotherDianShu) {
long id = this.getId();
long anotherId = anotherDianShu.getId();
return (id < anotherId ? -1 : (id == anotherId ? 0 : 1));
}
}
|
package Bomberman;
import javax.swing.*;
import java.awt.*;
public class Scene extends JPanel {
@Override
protected void paintComponent(Graphics g) {
//we check if we have the data to print the map
if(Main.game!=null && Main.game.getMap()!=null && Main.game.getMap().isMapGenerated())
{
//if we are on the first print, we have to print all the map first
printAllMap(g);
Main.game.getMap().getEntitiesList().forEach(entity-> {
//we paint the entity itself
g.drawImage(entity.getContainer().getCurrentImage(), entity.getPosInPixelMap().x, entity.getPosInPixelMap().y, Map.WIDTH_TILE, Map.HEIGHT_TILE, null);
//}
});
}
}
private void printAllMap(Graphics g)
{
//we watch each tile and print them
Map map=Main.game.getMap();
for(int i=0;i<Map.MAP_SIZE_X;i++)
{
for (int j=0;j<Map.MAP_SIZE_Y;j++)
{
g.drawImage(map.getTile(i,j).getTileType().getImage(),i*Map.WIDTH_TILE, j*Map.HEIGHT_TILE, Map.WIDTH_TILE, Map.HEIGHT_TILE, null);
}
}
}
}
|
package importDataInfo;
/**
* Created by csw on 2016/10/20 9:21.
* Explain:
*/
public class AreaRestTaskInfo {
private String areaNo; //箱区号
private Integer restTaskNumber; //箱区还能作业多少任务数
public String getAreaNo() {
return areaNo;
}
public void setAreaNo(String areaNo) {
this.areaNo = areaNo;
}
public Integer getRestTaskNumber() {
return restTaskNumber;
}
public void setRestTaskNumber(Integer restTaskNumber) {
this.restTaskNumber = restTaskNumber;
}
}
|
package net.razorvine.pyro.test;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import net.razorvine.pyro.Message;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* Unit tests for the Pyro message. Doesn't set HMAC.
*
* @author Irmen de Jong (irmen@razorvine.net)
*/
public class MessageNoHmacTest {
@Test
public void testRecvNoAnnotations() throws IOException
{
Message msg = new Message(Message.MSG_CONNECT, new byte[]{1,2,3,4,5}, 42, 0, 0, null, null);
byte[] data = msg.to_bytes();
InputStream is = new ByteArrayInputStream(data);
msg = Message.recv(is, null, null);
assertEquals(0, is.available());
assertEquals(5, msg.data_size);
assertArrayEquals(new byte[]{1,2,3,4,5}, msg.data);
assertEquals(0, msg.annotations_size);
assertEquals(0, msg.annotations.size());
}
}
|
/**
*
*/
package com.s2rltx.jeudepoker.model;
/**
* @author Stéphanie
*
*/
public class Carreau implements Family{
// pour representer les cartes de la famille Carreau
@Override
public String getRepresentation() {
StringBuilder card = new StringBuilder();
card.append(" _____ ");
card.append("\n");
card.append("|%s^ |");
card.append("\n");
card.append("| / \\ |");
card.append("\n");
card.append("| \\ / |");
card.append("\n");
card.append("| . |");
card.append("\n");
card.append("|___%s|");
card.append("\n");
return card.toString();
}
}
|
/*
* 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 lab4_2;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
*
* @author Admin
*/
public class Xdate {
private static SimpleDateFormat formater= new SimpleDateFormat();
public static Date parse(String text, String pattern) throws RuntimeException{
try {
formater.applyPattern(pattern);
return formater.parse(text);
} catch (Exception e) {
throw new RuntimeException();
}
}
public static Date parse(String text) throws RuntimeException{
return Xdate.parse(text,"dd-MM-yyyy");
}
}
|
package syncAlgorithm;
/* Operation have types:
* Type 1: Download from source remote
* Type 2: Upload The file under certain folder
* Type 3: Delete temporary file on local
* Type 4: Delete Target file on remote
* Type 5: Create a folder
*/
public class Operation {
private int type;
private FileEntry targetEntry;
public Operation(int type, FileEntry targetEntry) {
this.type = type;
this.targetEntry = targetEntry;
}
public int getType() {
return type;
}
public FileEntry getTargetEntry() {
return targetEntry;
}
}
|
package com.zhang.order.client;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import vo.ResponseVO;
@FeignClient("productapi")
public interface ProductApiFeign {
@GetMapping("/product/list")
public ResponseVO queryProductList();
}
|
package tec.mf.handler;
import com.amazonaws.services.lambda.runtime.Context;
import com.amazonaws.services.lambda.runtime.LambdaLogger;
import org.junit.Test;
import tec.mf.handler.io.ImageHandlerResponseWriter;
import tec.mf.handler.io.ImageRequest;
import tec.mf.handler.io.ImageRequestParser;
import tec.mf.handler.service.ImageService;
import java.io.*;
import static org.mockito.BDDMockito.*;
public class ImageHandlerTest {
@Test
public void resizeImage() throws Exception {
InputStream inputStream = new FileInputStream(new File("src/test/resources/image-request-event.json"));
FileOutputStream fileOutputStream = new FileOutputStream("src/test/resources/image-handler-response.json");
FileInputStream resizedStream = new FileInputStream(new File("src/test/resources/51ca22dd0cf293ac67bb394a-100xh.jpg"));
OutputStream outputStream = new ObjectOutputStream(fileOutputStream);
LambdaLogger lambdaLogger = mock(LambdaLogger.class);
Context context = mock(Context.class);
AppConfig appConfig = mock(AppConfig.class);
ImageRequestParser imageRequestParser = mock(ImageRequestParser.class);
ImageHandlerResponseWriter imageHandlerResponseWriter = mock(ImageHandlerResponseWriter.class);
ImageService imageService = mock(ImageService.class);
ImageRequest imageRequest = mock(ImageRequest.class);
given(context.getLogger()).willReturn(lambdaLogger);
given(imageRequest.getFilename()).willReturn("51ca22dd0cf293ac67bb394a-295xh.jpg");
given(imageRequestParser.processInputEvent(any(InputStream.class))).willReturn(imageRequest);
given(imageService.getImageFrom(imageRequest)).willReturn(resizedStream);
given(appConfig.getInputEventParser()).willReturn(imageRequestParser);
given(appConfig.getImageHandlerResponseWriter()).willReturn(imageHandlerResponseWriter);
given(appConfig.getImageService()).willReturn(imageService);
ImageHandler imageHandler = new ImageHandler(appConfig);
imageHandler.handleRequest(inputStream, outputStream, context);
verify(appConfig, times(1)).getInputEventParser();
verify(appConfig, times(1)).getImageService();
verify(appConfig, times(1)).getImageHandlerResponseWriter();
verify(imageRequestParser, times(1)).processInputEvent(any());
verify(imageHandlerResponseWriter, times(1)).writeResponse(any(), any(), any(ImageRequest.class));
}
}
|
package com.octo.repository;
import com.octo.domain.video.Video;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
public interface VideoRepository extends JpaRepository<Video, String>, JpaSpecificationExecutor<Video> {
}
|
import java.util.*;
class EditDistance {
// public static void OutputAlignment(int i, int j, int[][] d,String s, String t) {
// if (i == 0 && j == 0) return;
// int diff;
// if(s.charAt(i-1) == t.charAt(j-1)){
// diff = 0;
// } else {
// diff = 1;
// }
// if(i > 0 && d[i][j] == d[i-1][j]+1) {
// OutputAlignment(i-1,j,d,s,t);
// System.out.println(s.charAt(i-1));
// System.out.println("-");
// } else if (j > 0 && d[i][j] == d[i][j-1]+1) {
// OutputAlignment(i,j-1,d,s,t);
// System.out.println("-");
// System.out.println(t.charAt(j-1));
// } else if (j > 0 && i > 0 && d[i][j] == d[i-1][j-1] + diff){
// OutputAlignment(i-1,j-1,d,s,t);
// System.out.println(s.charAt(i-1));
// System.out.println(t.charAt(j-1));
// }
// }
public static int EditDistance(String s, String t) {
//write your code here
int n = s.length();
int m = t.length();
int[][] d = new int [n+1][m+1];
for(int i = 0; i <= n; i++)
{
d[i][0] = i;
}
for(int j = 0; j <= m; j++)
{
d[0][j] = j;
}
for(int j = 1; j <=m; j++) {
for(int i = 1; i <=n; i++) {
int insertion = d[i][j-1] + 1;
int deletion = d[i-1][j] + 1;
int match = d[i-1][j-1];
int mismatch = d[i-1][j-1]+1;
if (s.charAt(i-1)==t.charAt(j-1)) {
int result = Math.min(insertion, deletion);
result = Math.min(result,match);
d[i][j] = result;
} else {
int result = Math.min(insertion,deletion);
result = Math.min(result,mismatch);
d[i][j] = result;
}
}
}
// for(int i = 0; i <=n; i++) {
// for(int j = 0; j <=m; j++) {
// System.out.print(d[i][j]+ " ");
// }
// System.out.println();
// }
//OutputAlignment(n,m,d,s,t);
return d[n][m];
}
public static void main(String args[]) {
Scanner scan = new Scanner(System.in);
String s = scan.next();
String t = scan.next();
System.out.println(EditDistance(s, t));
}
}
|
package OrientacaoObjetos.Metodos;
public class ConstructorAtributos {
//esses são atributos, assim como mótodos, as variáveis também podem ser definidas com public, private,
//default e protected, funcionando da mesma forma que nos métodos
private String textoSemStatic = "Testando";
private static String textoComStatic = "Testando";
protected int[] array; //não possui static, logo, precisa fazer um objeto da propria classe para usa-la
public static final int INTEIRO = 5; //aqui estamos trabalhando com uma variável constante!
//para definir uma constante, coloca-se o termo 'final' na hora de criá-la!
//variáveis contantes vão ter valores fixos e não alteráveis (modelo recomendado para links ou coisas que
// o objetivo é nunca alterar)
//em variáveis constantes, é obrigatório determinar seu valor na hora da declaração e uma boa prática é
//nomear a variável em <!> UPPERCASE!
public ConstructorAtributos() {
// Esse é um método construtor, toda classe possui um método construtor,
// que vai ser executado toda vez que criar um objeto ou invocar a classe em questão
//em suma, você pode atribuir comandos para toda vez que criar o objeto ou invocar a classe
System.out.println("Classe invocada [<!> Constructor Alert]");
}
public static void main(String[] args) {
new ConstructorAtributos();
//invocando classe
ConstructorAtributos connect = new ConstructorAtributos();
//criando objeto
connect.textoSemStatic = "TESTA ISSO ENTAO";
textoComStatic = "VOU MESMO, ALGUM PROBLEMA?";
System.out.println(connect.textoSemStatic);
System.out.println(textoComStatic);
connect.array = new int[textoComStatic.length()];
System.out.println(connect.array.length);
// length() <- para retornar o tamanho da string
// length <- para descobrir o número de casas de um vetor
System.out.println(INTEIRO);
System.out.println(ConstructorAtributos.INTEIRO);
}
}
|
package com.cg.hcs.dao;
import com.cg.hcs.entity.Users;
import java.time.LocalDateTime;
import com.cg.hcs.entity.DiagnosticCenter;
import com.cg.hcs.entity.Test;
import com.cg.hcs.entity.Users;
public interface IUserDAO {
public String register(Users user);
public boolean validateUser(String userId, String password);
public String makeAppointment(Users user, DiagnosticCenter test, String datetime);
public String getRoleCode(String userId);
}
|
package hu.thom.letsencrypt;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class Validator
*/
@WebServlet(name = "Validator", urlPatterns = { "/.well-known/acme-challenge/<lets encrypt validation string>" })
public class Validator extends HttpServlet {
private static final long serialVersionUID = 1L;
public Validator() {
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/plain");
PrintWriter pw = response.getWriter();
pw.write("<lets encrypt validation string>");
pw.flush();
pw.close();
}
}
|
/*
* FileName: AbstractCommandNode.java
* Description:
* Company: 南宁超创信息工程有限公司
* Copyright: ChaoChuang (c) 2006
* History: 2006-1-8 (guig) 1.0 Create
*/
package com.spower.excel.engine.parse;
/**
* @author guig
* @version 1.0 2006-1-8
*/
public abstract class AbstractCommandNode implements ICommandNode {
protected int col;
protected int row;
protected String command;
public AbstractCommandNode(int col, int row, final String command) {
this.col = col;
this.row = row;
this.command = command;
}
/** (non Javadoc)
* @see com.spower.excel.engine.parse.ICommandNode#getColumn()
*/
public int getColumn() {
return this.col;
}
/** (non Javadoc)
* @see com.spower.excel.engine.parse.ICommandNode#getRow()
*/
public int getRow() {
return this.row;
}
}
|
/**
* ************************************************************************
* Copyright (C) 2010 Atlas of Living Australia All Rights Reserved.
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for
* the specific language governing rights and limitations under the License.
* *************************************************************************
*/
package au.org.ala.spatial.web.zk;
import au.org.ala.spatial.util.AlaspatialProperties;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.io.FileUtils;
import org.zkoss.zk.ui.Component;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.util.GenericForwardComposer;
import org.zkoss.zul.*;
import java.io.File;
import java.io.FilenameFilter;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
public class JobsZK extends GenericForwardComposer {
//Memory tab
Label lMemUsage;
//Analysis tab
Listbox lbwaiting;
Listbox lbrunning;
Listbox lbfinished;
Textbox selectedJob;
Textbox joblog;
Textbox jobparameters;
Iframe jobimage;
Textbox imgpth;
String pid;
Textbox newjob;
Textbox cmdtext;
Textbox txtloggingurl;
//Other tab
Label lCachedImageCount;
@Override
public void doAfterCompose(Component comp) throws Exception {
super.doAfterCompose(comp);
System.out.println("***************** ***********");
setMemoryLabel();
onClick$refreshButton(null);
updateCachedImageCount();
}
public void onClick$btnProcessCommand(Event e) {
if (!cmdtext.getValue().trim().equals("")) {
String[] cmds = cmdtext.getValue().split("\n");
Map<String, String> cmd = new HashMap<String, String>();
for (String c : cmds) {
String key = c.substring(0, c.indexOf("="));
String value = c.substring(c.indexOf("=") + 1);
System.out.println("Adding " + key + " => " + value);
cmd.put(key, value);
}
}
}
public void onClick$refreshButton(Event e) {
String[] s = get("listwaiting").split("\n");
java.util.Arrays.sort(s);
lbwaiting.setModel(new SimpleListModel(s));
s = get("listrunning").split("\n");
java.util.Arrays.sort(s);
lbrunning.setModel(new SimpleListModel(s));
s = get("listfinished").split("\n");
java.util.Arrays.sort(s);
lbfinished.setModel(new SimpleListModel(s));
}
public void onSelect$lbwaiting(Event e) {
String s = lbwaiting.getSelectedItem().getLabel();
pid = s.substring(0, s.indexOf(";"));
selectedJob.setValue(pid);
refreshInfo();
}
public void onSelect$lbrunning(Event e) {
String s = lbrunning.getSelectedItem().getLabel();
pid = s.substring(0, s.indexOf(";"));
selectedJob.setValue(pid);
refreshInfo();
}
public void onSelect$lbfinished(Event e) {
String s = lbfinished.getSelectedItem().getLabel();
pid = s.substring(0, s.indexOf(";"));
selectedJob.setValue(pid);
refreshInfo();
}
public void onClick$lbwaiting(Event e) {
String s = lbwaiting.getSelectedItem().getLabel();
pid = s.substring(0, s.indexOf(";"));
selectedJob.setValue(pid);
refreshInfo();
}
public void onClick$lbrunning(Event e) {
String s = lbrunning.getSelectedItem().getLabel();
pid = s.substring(0, s.indexOf(";"));
selectedJob.setValue(pid);
refreshInfo();
}
public void onClick$lbfinished(Event e) {
String s = lbfinished.getSelectedItem().getLabel();
pid = s.substring(0, s.indexOf(";"));
selectedJob.setValue(pid);
refreshInfo();
}
public void onClick$btnCancel(Event e) {
get("cancel");
}
void refreshInfo() {
pid = selectedJob.getValue();
joblog.setValue(get("log"));
jobparameters.setValue(get("inputs").replace(";", "\r\n"));
String imgsrc = get("image");
if (imgsrc == null) {
imgsrc = "";
}
//jobimage.setSrc(TabulationSettings.alaspatial_path + imgsrc);
imgpth.setText(imgsrc);
jobimage.setSrc(AlaspatialProperties.getBaseOutputURL() + "/" + imgsrc);
}
String get(String type) {
try {
StringBuffer sbProcessUrl = new StringBuffer();
sbProcessUrl.append(AlaspatialProperties.getAlaspatialUrl() + "ws/jobs/").append(type).append("?pid=").append(pid);
System.out.println(sbProcessUrl.toString());
HttpClient client = new HttpClient();
GetMethod get = new GetMethod(sbProcessUrl.toString());
get.addRequestHeader("Accept", "text/plain");
int result = client.executeMethod(get);
String slist = get.getResponseBodyAsString();
System.out.println(slist);
return slist;
} catch (Exception e) {
e.printStackTrace();
}
return "";
}
public void onClick$btnRefreshInfo(Event event) {
refreshInfo();
}
public void onClick$btnCopyJob(Event event) {
pid = get("copy");
refreshInfo();
}
public void onClick$btnMemoryClean(Event event) {
System.gc();
setMemoryLabel();
}
void setMemoryLabel() {
lMemUsage.setValue("Memory usage (total/used/free):" + (Runtime.getRuntime().totalMemory() / 1024 / 1024) + "MB / " + (Runtime.getRuntime().totalMemory() / 1024 / 1024 - Runtime.getRuntime().freeMemory() / 1024 / 1024) + "MB / " + (Runtime.getRuntime().freeMemory() / 1024 / 1024) + "MB");
}
public void onClick$btnNewClassification(Event event) {
String txt = newjob.getText();
try {
int pos = 0;
while (true) {
int p1 = txt.indexOf("pid:", pos);
if (p1 < 0) {
break;
}
int p2 = txt.indexOf("gc:", pos);
int p3 = txt.indexOf("area:", pos);
int p4 = txt.indexOf("envlist:", pos);
int p5 = txt.indexOf("pid:", p1 + 4);
if (p5 < 0) {
p5 = txt.length();
}
pos = p5 - 5;
String pid = txt.substring(p1 + 4, p2).trim();
String gc = txt.substring(p2 + 3, p3).trim();
String area = txt.substring(p3 + 5, p4).trim();
String envlist = txt.substring(p4 + 8, p5).trim();
System.out.println("got [" + pid + "][" + gc + "][" + area + "][" + envlist + "]");
StringBuffer sbProcessUrl = new StringBuffer();
sbProcessUrl.append(AlaspatialProperties.getAlaspatialUrl() + "ws/aloc/processgeoq?");
sbProcessUrl.append("gc="
+ URLEncoder.encode(gc, "UTF-8"));
sbProcessUrl.append("&envlist="
+ URLEncoder.encode(envlist, "UTF-8"));
HttpClient client = new HttpClient();
PostMethod get = new PostMethod(sbProcessUrl.toString());
get.addParameter("area", URLEncoder.encode(area, "UTF-8"));
get.addRequestHeader("Accept", "text/plain");
int result = client.executeMethod(get);
String slist = get.getResponseBodyAsString();
System.out.println("Got response from ALOCWSController: \n" + slist);
}
} catch (Exception e) {
e.printStackTrace();
}
}
public void onClick$btnClearCache(Event event) {
String pth = AlaspatialProperties.getBaseOutputDir() + "output" + File.separator + "sampling" + File.separator;
File dir = new File(pth);
String[] f = dir.list(new FilenameFilter() {
public boolean accept(File dir, String name) {
return name.endsWith("png");
}
});
for (int i = 0; i < f.length; i++) {
FileUtils.deleteQuietly(new File(pth + f[i]));
}
updateCachedImageCount();
}
void updateCachedImageCount() {
File dir = new File(AlaspatialProperties.getBaseOutputDir() + "output" + File.separator + "sampling" + File.separator);
String[] f = dir.list(new FilenameFilter() {
public boolean accept(File dir, String name) {
return name.endsWith("png");
}
});
if (f == null) {
lCachedImageCount.setValue("0");
} else {
lCachedImageCount.setValue(String.valueOf(f.length));
}
}
}
|
package checkers;
public class BoardNotifyTimeLimiter extends Thread{
CheckersClient player;
Move newMove = null;
int isFinished = 0;
int hasException = 0;
Thread waiter;
public BoardNotifyTimeLimiter(CheckersClient client, Move newMove, Thread waiter){
this.newMove = newMove;
player = client;
this.waiter = waiter;
}
public void run() {
try{
player.boardNotify(newMove);
}catch (Exception e){hasException = 1;}
isFinished = 1;
waiter.interrupt();
};
}
|
/*
* Copyright (C) 2022-2023 Hedera Hashgraph, LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hedera.mirror.importer.parser.record.ethereum;
import com.esaulpaugh.headlong.rlp.RLPDecoder;
import com.hedera.mirror.common.domain.transaction.EthereumTransaction;
import com.hedera.mirror.importer.exception.InvalidDatasetException;
import jakarta.inject.Named;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.context.annotation.Primary;
@Named
@Primary
@RequiredArgsConstructor
public class CompositeEthereumTransactionParser implements EthereumTransactionParser {
private final LegacyEthereumTransactionParser legacyEthereumTransactionParser;
private final Eip2930EthereumTransactionParser eip2930EthereumTransactionParser;
private final Eip1559EthereumTransactionParser eip1559EthereumTransactionParser;
@Override
public EthereumTransaction decode(byte[] transactionBytes) {
var ethereumTransactionParser = getEthereumTransactionParser(transactionBytes);
return ethereumTransactionParser.decode(transactionBytes);
}
private EthereumTransactionParser getEthereumTransactionParser(byte[] transactionBytes) {
if (ArrayUtils.isEmpty(transactionBytes) || transactionBytes.length < 2) {
throw new InvalidDatasetException("Ethereum transaction bytes length is less than 2 bytes in length");
}
var decoder = RLPDecoder.RLP_STRICT.sequenceIterator(transactionBytes);
var firstRlpItem = decoder.next();
// legacy transactions are encoded as a list
if (firstRlpItem.isList()) {
return legacyEthereumTransactionParser;
}
// typed transactions encode the type in the first byte
var legacyRlpItemByte = firstRlpItem.asByte();
if (legacyRlpItemByte == Eip2930EthereumTransactionParser.EIP2930_TYPE_BYTE) {
return eip2930EthereumTransactionParser;
} else if (legacyRlpItemByte == Eip1559EthereumTransactionParser.EIP1559_TYPE_BYTE) {
return eip1559EthereumTransactionParser;
}
throw new InvalidDatasetException("Unsupported Ethereum transaction data type");
}
}
|
package org.inftel.socialwind.shared.domain;
import com.google.web.bindery.requestfactory.shared.EntityProxy;
import com.google.web.bindery.requestfactory.shared.EntityProxyId;
import com.google.web.bindery.requestfactory.shared.ProxyForName;
/**
*
* @author ibaca
*
*/
@ProxyForName(value = "org.inftel.socialwind.server.domain.Spot", locator = "org.inftel.socialwind.server.locators.EntityLocator")
public interface SpotProxy extends EntityProxy {
EntityProxyId<SpotProxy> stableId();
String getName();
void setName(String name);
String getDescription();
void setDescription(String description);
String getImgUrl();
void setImgUrl(String imgUrl);
void setLocation(LocationProxy location);
Boolean getHot();
public Integer getSurferCount();
public Integer getSurferCurrentCount();
LocationProxy getLocation();
}
|
package LeetCode.Trees;
public class FlipEquivalentBinaryTrees {
public boolean flipEqiv(TreeNode root1, TreeNode root2 ){
if(root1 == null && root2 == null)
return true;
if(root1 == null || root2 == null || root1.val != root2.val)
return false;
return ((flipEqiv(root1.right, root2.right) && flipEqiv(root1.left, root2.left))
|| (flipEqiv(root1.left, root2.right) && flipEqiv(root1.right, root2.left)));
}
public static void main(String[] args){
TreeNode root1 = new TreeNode(1, new TreeNode(2, new TreeNode(4), new TreeNode(5, new TreeNode(7), new TreeNode(8))), new TreeNode(3, new TreeNode(6), null));
TreeNode root2 = new TreeNode(1, new TreeNode(3, null, new TreeNode(6)), new TreeNode(2, new TreeNode(4), new TreeNode(5, new TreeNode(8), new TreeNode(7))));
FlipEquivalentBinaryTrees b = new FlipEquivalentBinaryTrees();
System.out.print(b.flipEqiv(root1, root2));
}
}
|
package com.tencent.mm.plugin.appbrand.jsapi;
import android.animation.ObjectAnimator;
import com.tencent.mm.plugin.appbrand.l;
import com.tencent.mm.plugin.appbrand.page.e;
import com.tencent.mm.plugin.appbrand.widget.c;
import com.tencent.mm.plugin.appbrand.widget.c.5;
import org.json.JSONObject;
public final class bo extends a {
public static final int CTRL_INDEX = -2;
public static final String NAME = "showTabBar";
public final void a(l lVar, JSONObject jSONObject, int i) {
com.tencent.mm.plugin.appbrand.page.l currentPage = lVar.fdO.fcz.getCurrentPage();
if (currentPage instanceof e) {
int i2;
c tabBar = ((e) currentPage).getTabBar();
boolean optBoolean = jSONObject.optBoolean("animation", true);
String str = "translationY";
float[] fArr = new float[2];
int height = tabBar.getHeight();
if ("top".equals(tabBar.gEi)) {
i2 = -1;
} else {
i2 = 1;
}
fArr[0] = (float) (i2 * height);
fArr[1] = 0.0f;
ObjectAnimator ofFloat = ObjectAnimator.ofFloat(tabBar, str, fArr);
ofFloat.setDuration(optBoolean ? 250 : 0);
tabBar.post(new 5(tabBar, ofFloat));
lVar.E(i, f("ok", null));
return;
}
lVar.E(i, f("fail:not TabBar page", null));
}
}
|
package com.sunteam.library.parse;
import org.json.JSONObject;
import com.sunteam.library.entity.CollectResourceEntity;
import com.sunteam.library.utils.LogUtils;
//添加收藏资源
public class AddCollectResourceParseResponse extends AbsParseResponse
{
public static final String TAG = "AddCollectResourceParseResponse";
@Override
public Object parseResponse(String responseStr) throws Exception
{
// TODO Auto-generated method stub
LogUtils.e(TAG,"responseStr---" + responseStr);
try
{
JSONObject jsonObject = new JSONObject(responseStr);
boolean result = jsonObject.optBoolean("IsSuccess");
if( !result )
{
return null;
}
JSONObject json = jsonObject.optJSONObject("ResultObject");
if( null == json )
{
return null;
}
CollectResourceEntity entity = new CollectResourceEntity();
entity.id = json.optInt("Id");
entity.userName = json.optString("UserName");
entity.title = json.optString("Title");
entity.dbCode = json.optString("DbCode");
entity.sysId = json.optString("SysId");
entity.resType = json.optInt("ResType");
entity.categoryFullName = json.optString("CategoryFullName");
entity.coverUrl = json.optString("CoverUrl");
entity.createTime = json.optString("CreateTime");
return entity;
}
catch( Exception e )
{
e.printStackTrace();
}
return null;
}
}
|
package edu.floridapoly.polycamsportal.schedule;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import edu.floridapoly.polycamsportal.util.TimeUtils;
import org.joda.time.LocalDate;
import java.util.List;
import java.util.Objects;
public class CourseSection {
private int sectionNumber;
private LocalDate startDate;
private LocalDate endDate;
private List<CourseSession> sessions;
/**
* Reference to the course this section belongs to.
*/
private Course course;
/**
* Initializes all values to default values.
* <p>
* This only exists so that JSON deserialization will work. It should not
* be used in actual code.
*/
@SuppressWarnings("unused")
public CourseSection() {
this(0, null, null, null);
}
/**
* Constructs a CourseSection object.
*
* @param sectionNumber Number of this section.
* @param startDate LocalDate describing the starting date.
* @param endDate LocalDate describing the ending date.
* @param sessions Array of CourseSessions in this section.
*/
public CourseSection(int sectionNumber,
LocalDate startDate, LocalDate endDate,
List<CourseSession> sessions) {
this.sectionNumber = sectionNumber;
this.startDate = startDate;
this.endDate = endDate;
this.sessions = sessions;
}
@JsonProperty("section")
public int getSectionNumber() {
return sectionNumber;
}
public LocalDate getStartDate() {
return startDate;
}
@JsonProperty
@SuppressWarnings("unused")
private void setStartDate(int startDate) {
this.startDate = TimeUtils.dateFromTimestamp(startDate);
}
public LocalDate getEndDate() {
return endDate;
}
@JsonProperty
@SuppressWarnings("unused")
private void setEndDate(int endDate) {
this.endDate = TimeUtils.dateFromTimestamp(endDate);
}
public List<CourseSession> getSessions() {
return sessions;
}
// This has to be ignored during (de)serialization since JSON can't
// handle circular references
@JsonIgnore
public Course getCourse() {
return course;
}
/**
* Sets the course for this section.
* <p>
* This can only be called once and should only be called when set as a
* section of a Course object.
*
* @param course The course to set.
*/
void setCourse(Course course) {
if (this.course != null) {
throw new IllegalStateException(
"A sections's course can only be set once");
}
this.course = course;
}
/**
* Determines whether any sessions of this section overlap with the sessions
* of another section.
*
* @param other Other course section.
* @return true if the times of this and other overlap; false otherwise.
*/
public boolean overlaps(CourseSection other) {
for (CourseSession session : sessions) {
for (CourseSession otherSession : other.getSessions()) {
if (session.overlaps(otherSession)) {
return true;
}
}
}
return false;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
CourseSection that = (CourseSection) o;
return sectionNumber == that.sectionNumber &&
Objects.equals(startDate, that.startDate) &&
Objects.equals(endDate, that.endDate) &&
Objects.equals(sessions, that.sessions);
// course is not compared since it is a circular reference
}
@Override
public int hashCode() {
return Objects.hash(sectionNumber, startDate, endDate, sessions);
}
@Override
public String toString() {
return "CourseSection{" +
"sectionNumber=" + sectionNumber +
", startDate=" + startDate +
", endDate=" + endDate +
", sessions=" + sessions +
'}';
}
}
|
package cc.before30.fpij.types;
import java.util.Objects;
import java.util.function.Function;
/**
* User: before30
* Date: 2017. 9. 8.
* Time: PM 3:26
*/
@FunctionalInterface
public interface Function5<T1, T2, T3, T4, T5, R> {
R apply(T1 t1, T2 t2, T3 t3, T4 t4, T5 t5);
default Function4<T2, T3, T4, T5, R> curried(final T1 t1) {
return (t2, t3, t4, t5) -> apply(t1, t2, t3, t4, t5);
}
default<V> Function5<T1, T2, T3, T4, T5, V> andThen(final Function<? super R, ? extends V> after) {
Objects.requireNonNull(after);
return (t1, t2, t3, t4, t5) -> after.apply(apply(t1, t2, t3, t4, t5));
}
}
|
package ctci.ArraysAndStrings;
/**
* Created by joetomjob on 7/27/19.
*/
public class URLify {
public static void main(String[] args) {
String ss = "asdasd asdsad as ";
String s = urlify(ss, 16);
System.out.println(s);
}
public static String urlify(String s, int n){
StringBuilder s1 = new StringBuilder();
int counter = 0;
for (int i = 0; i < n; i++) {
if(s.charAt(i) == ' ') {
s1.append("&%20");
} else {
s1.append(s.charAt(i));
}
counter++;
if(counter >= n)
return s1.toString();
}
return s1.toString();
}
}
|
package web;
import java.io.IOException;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class LoginServlet extends HttpServlet{
//tomact创建Servlet的逻辑:
//LoginServlet s = new LoginServlet();
//ServletConfig c = new ServletConfig();
//c.加载数据();//从web.xml加载数据
//s.init(c);
@Override
public void init(ServletConfig config) throws ServletException {
super.init(config);
String maxOnline = config.getInitParameter("maxOnline");
System.out.println(maxOnline);
}
@Override
protected void service(HttpServletRequest req,
HttpServletResponse resp)
throws ServletException, IOException {
//此config就是init()传入的那个
ServletConfig config = getServletConfig();
String maxOnline = config.getInitParameter("maxOnline");
System.out.println(maxOnline);
System.out.println("正在登录...");
}
}
|
package com.cg.project.castleglobalproject.base.network.base.impl;
import com.cg.project.castleglobalproject.base.network.base.IPostClient;
import com.cg.project.castleglobalproject.base.network.base.Method;
import com.cg.project.castleglobalproject.base.network.base.NetworkClient;
import com.cg.project.castleglobalproject.base.network.base.body.BaseRequestBody;
import com.cg.project.castleglobalproject.base.network.base.response.BaseResponse;
public abstract class BasePostClient<DATA_OUT extends BaseResponse,
DATA_IN extends BaseRequestBody> extends BaseClient<DATA_OUT> implements IPostClient<DATA_OUT, DATA_IN> {
DATA_IN data;
public BasePostClient(NetworkClient client) {
super(client);
}
@Override
public void send(DATA_IN data) {
this.data = data;
client.call(this);
}
public void setData(DATA_IN data) {
this.data = data;
}
@Override
public byte[] getData() {
return data.getBody();
}
public int getMethod() {
return Method.POST;
}
}
|
/* 1: */ package com.kaldin.test.executetest.action;
/* 2: */
/* 3: */ import com.kaldin.test.executetest.common.UtilTest;
/* 4: */ import java.util.ArrayList;
/* 5: */ import javax.servlet.http.HttpServletRequest;
/* 6: */ import javax.servlet.http.HttpServletResponse;
/* 7: */ import javax.servlet.http.HttpSession;
/* 8: */ import org.apache.struts.action.Action;
/* 9: */ import org.apache.struts.action.ActionForm;
/* 10: */ import org.apache.struts.action.ActionForward;
/* 11: */ import org.apache.struts.action.ActionMapping;
/* 12: */
/* 13: */ public class QuestionAction
/* 14: */ extends Action
/* 15: */ {
/* 16: */ public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response)
/* 17: */ throws Exception
/* 18: */ {
/* 19:26 */ String message = "error";
/* 20:27 */ UtilTest utilTest = (UtilTest)request.getSession(false).getAttribute("utilTestObj");
/* 21:28 */ if (utilTest.questionIndexCount < utilTest.listQuestions.size() - 1)
/* 22: */ {
/* 23:29 */ request.setAttribute("status", "next");
/* 24:30 */ utilTest.questionIndexCount += 1;
/* 25:31 */ request.setAttribute("Question", utilTest.listQuestions.get(utilTest.questionIndexCount));
/* 26:34 */ if (utilTest.questionIndexCount + 1 == utilTest.listQuestions.size()) {
/* 27:36 */ request.setAttribute("status", "finish");
/* 28: */ }
/* 29:38 */ message = "success";
/* 30: */ }
/* 31:42 */ return mapping.findForward(message);
/* 32: */ }
/* 33: */ }
/* Location: C:\Java Work\Workspace\Kaldin\WebContent\WEB-INF\classes\com\kaldin\kaldin_java.zip
* Qualified Name: kaldin.test.executetest.action.QuestionAction
* JD-Core Version: 0.7.0.1
*/
|
package dao;
import model.User;
import util.Db_util;
import java.sql.Connection;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.SQLException;
/**
* Created by Pc on 02.07.2017.
*/
public class UserDao {
private static Connection connection;
public UserDao() {
connection = Db_util.getConnection();
}
public void addUsers(User user) {
try {
PreparedStatement preparedStatement = connection
.prepareStatement("INSERT into users1 (firsname, lastname, dob, email) VALUES (?,?,?,?)");
preparedStatement.setString(1, user.getFirstName());
preparedStatement.setString(2, user.getLastName());
preparedStatement.setDate(3, new Date(user.getDob().getTime()));
preparedStatement.setString(4, user.getEmail());
preparedStatement.execute();
} catch (SQLException e) {
e.printStackTrace();
}
}
public void deleteUser(int userID){
try {
PreparedStatement preparedStatement = connection.prepareStatement("DELETE FROM users1 WHERE userId = ?");
preparedStatement.setInt(1,userID);
preparedStatement.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
|
package com.lxy.staticimport;
import static java.lang.System.out;
import org.junit.Test;
/**
* 静态导入
* @author 15072
*
*/
public class StaticTest {
@Test
public void run() {
out.print("haha");
}
}
|
package com.ranz.config;
import com.baomidou.mybatisplus.extension.plugins.OptimisticLockerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import com.baomidou.mybatisplus.extension.plugins.pagination.optimize.JsqlParserCountOptimize;
import org.apache.ibatis.annotations.Mapper;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.transaction.annotation.EnableTransactionManagement;
/**
* @program: mybatis-plus
* @description:
* @author: J.Flying
* @create: 2020-10-10 16:08
*/
@MapperScan("com.ranz.mapper")
@EnableTransactionManagement
@Configuration
public class MyBatisPlusConfig {
/**
* @Description: 乐观锁配置
* @Author: J.Flying
* @Date: 2020/10/10
*/
@Bean
public OptimisticLockerInterceptor optimisticLockerInterceptor() {
return new OptimisticLockerInterceptor();
}
/**
* @Description: 配置分页
* @Author: J.Flying
* @Date: 2020/10/10
*/
@Bean
public PaginationInterceptor paginationInterceptor() {
PaginationInterceptor paginationInterceptor = new PaginationInterceptor();
return paginationInterceptor;
}
}
|
package com.adastrafork.numbersandletters.converters.en;
import com.adastrafork.numbersandletters.generated.antlr4.EnglishNumeralsBaseVisitor;
import com.adastrafork.numbersandletters.generated.antlr4.EnglishNumeralsParser;
import org.antlr.v4.runtime.ParserRuleContext;
/**
* Class to visit the nodes of the tree wich add value to the result of the evaluation of a English numeral.
*/
final class EnglishNumeralRecognitionEngine extends EnglishNumeralsBaseVisitor<Integer> {
@Override
public Integer visitNumeralExpression (EnglishNumeralsParser.NumeralExpressionContext ctx) {
return super.visit (ctx.children.get (0));
}
private ParserRuleContext ruleToVisit (EnglishNumeralsParser.NumeralExpressionContext ctx) {
if (ctx.r0 ( ) != null) {
return ctx.r0 ( );
} else if (ctx.r1 ( ) != null) {
return ctx.r1 ( );
} else if (ctx.r2 ( ) != null) {
return ctx.r2 ( );
} else if (ctx.r3 ( ) != null) {
return ctx.r3 ( );
} else if (ctx.r4 ( ) != null) {
return ctx.r4 ( );
} else {
return null;
}
}
@Override
public Integer visitR0 (EnglishNumeralsParser.R0Context ctx) {
return 0;
}
@Override
public Integer visitR1 (EnglishNumeralsParser.R1Context ctx) {
String oneWordNumeral = ctx.getText ( );
return EnglishNumeralValues.fromNumeral (oneWordNumeral);
}
@Override
public Integer visitR2 (EnglishNumeralsParser.R2Context ctx) {
String oneWordNumeral = ctx.getText ( );
return EnglishNumeralValues.fromNumeral (oneWordNumeral);
}
@Override
public Integer visitR3 (EnglishNumeralsParser.R3Context ctx) {
Integer tens = visitTens (ctx.tens ( ));
if (ctx.r1 ( ) != null) {
Integer units = visitR1 (ctx.r1 ( ));
return tens + units;
} else {
return tens;
}
}
@Override
public Integer visitR4 (EnglishNumeralsParser.R4Context ctx) {
Integer hundreds = 100 * visitR1 (ctx.r1 (0));
if (ctx.r1 (1) != null) {
return hundreds + visitR1 (ctx.r1 (1));
} else if (ctx.r2 ( ) != null) {
return hundreds + visitR2 (ctx.r2 ( ));
} else if (ctx.r3 ( ) != null) {
return hundreds + visitR3 (ctx.r3 ( ));
} else {
return hundreds;
}
}
@Override
public Integer visitTens (EnglishNumeralsParser.TensContext ctx) {
String tensNumeral = ctx.getText ( );
return EnglishNumeralValues.fromNumeral (tensNumeral);
}
}
|
package com.mes.old.meta;
// Generated 2017-5-22 1:25:24 by Hibernate Tools 5.2.1.Final
/**
* BPartWarehouseId generated by hbm2java
*/
public class BPartWarehouseId implements java.io.Serializable {
private String warehouseid;
private String partNumber;
public BPartWarehouseId() {
}
public BPartWarehouseId(String warehouseid, String partNumber) {
this.warehouseid = warehouseid;
this.partNumber = partNumber;
}
public String getWarehouseid() {
return this.warehouseid;
}
public void setWarehouseid(String warehouseid) {
this.warehouseid = warehouseid;
}
public String getPartNumber() {
return this.partNumber;
}
public void setPartNumber(String partNumber) {
this.partNumber = partNumber;
}
public boolean equals(Object other) {
if ((this == other))
return true;
if ((other == null))
return false;
if (!(other instanceof BPartWarehouseId))
return false;
BPartWarehouseId castOther = (BPartWarehouseId) other;
return ((this.getWarehouseid() == castOther.getWarehouseid()) || (this.getWarehouseid() != null
&& castOther.getWarehouseid() != null && this.getWarehouseid().equals(castOther.getWarehouseid())))
&& ((this.getPartNumber() == castOther.getPartNumber())
|| (this.getPartNumber() != null && castOther.getPartNumber() != null
&& this.getPartNumber().equals(castOther.getPartNumber())));
}
public int hashCode() {
int result = 17;
result = 37 * result + (getWarehouseid() == null ? 0 : this.getWarehouseid().hashCode());
result = 37 * result + (getPartNumber() == null ? 0 : this.getPartNumber().hashCode());
return result;
}
}
|
package com.avalara.avatax.services.base;
import com.avalara.avatax.services.base.wss.Password;
import com.avalara.avatax.services.base.wss.SecurityHeader;
import com.avalara.avatax.services.base.wss.UsernameToken;
import org.apache.axis.message.SOAPHeaderElement;
import javax.xml.soap.SOAPException;
/**
*
* Base class for web service interface classes -- Not creatable;
* Create instead {@link com.avalara.avatax.services.address.AddressSvcSoapStub} or
* {@link com.avalara.avatax.services.tax.TaxSvcSoapStub} objects via an Axis Service proxy
* factory class: (@link com.avalara.avatax.services.address.AddressSvc} or
* {@link com.avalara.avatax.services.tax.TaxSvc}.
*
* <pre>
* <b>Example:</b>
* [Java]
* EngineConfiguration config = new FileProvider("avatax4j.wsdd");
*
* AddressSvcLocator svcLoc = new AddressSvcLocator(config);
* AddressSvcSoap svc = svcLoc.getAddressSvcSoap(new URL("http://www.avalara.com/services/"));
*
* // Set the profile
* Profile profile = new Profile();
* profile.setClient("AddressSvcTest,4.0.0.0");
* svc.setProfile(profile);
*
* // Set security
* Security security = new Security();
* security.setAccount("account");
* security.setLicense("license number");
* svc.setSecurity(security);
*
* PingResult result = svc.ping("");
* </pre>
*
* @author brianh
* Copyright (c) 2005, Avalara. All rights reserved.
*/
public class BaseSvcSoapStub extends org.apache.axis.client.Stub
implements com.avalara.avatax.services.base.BaseSvcSoap
{
public static final String WSSE_NAMESPACE = "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd";
public static final String PASSWORD_TEXT_TYPE = "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText";
protected BaseSvcSoapStub()
{
profile = new Profile();
security = new Security();
}
/**
* Provides access to the request profile data; Should be set prior to making a request.
* <pre>
* <b>Example:</b>
* [Java]
* // Set the profile
* Profile profile = new Profile();
* profile.setClient("AddressSvcTest,4.0.0.0");
* svc.setProfile(profile);
* <pre>
*
* @param profile
* @throws javax.xml.soap.SOAPException
*/
public void setProfile(Profile profile) throws SOAPException
{
this.profile = profile;
SOAPHeaderElement profileHeader = profile.getSOAPHeaderElement();
this.setHeader(profileHeader);
}
/**
* Provides access to the request profile data; Should be set prior to making a request.
* <pre>
* <b>Example:</b>
* [Java]
* // Set the profile
* Profile profile = new Profile();
* profile.setClient("AddressSvcTest,4.0.0.0");
* svc.setProfile(profile);
* <pre>
*
*
* @return Profile object
*/
public Profile getProfile()
{
return profile;
}
/**
* Provides access to Security details (e.g., account name and license #).
* <pre>
* <b>Example:</b>
* [Java]
* // Set security
* Security security = new Security();
* security.setAccount("account");
* security.setLicense("license number");
* svc.setSecurity(security);
*
* System.out.println(svc.getSecurity().getAccount());
* System.out.println(svc.getSecurity().getLicense());
* PingResult result = svc.ping("");
* </pre>
*
* @param value
*/
public void setSecurity(Security value)
{
security = value;
String userName = security.getUserName();
String passwordText = security.getPassword();
String account = security.getAccount();
if (userName != null && userName.trim().length() != 0)
{
// If no password is given and the userName contains "@" and an account is given, then
// append the account to the username (e.g. joe@1234567890).
if (passwordText == null || passwordText.length() == 0)
{
if (userName.indexOf("@") < 0 && account != null && account.length() > 0)
{
userName += "@" + account;
}
}
}
else if (account.trim().length() != 0)
{
userName = security.getAccount().trim();
passwordText = security.getLicense().trim();
}
else
{
throw new IllegalStateException("Must supply either a " +
"valid Account or UserName in the " +
"avatax4j.properties file");
}
SecurityHeader securityHeader = new SecurityHeader();
UsernameToken usernameToken = new UsernameToken();
usernameToken.setUsername(userName);
Password password = new Password();
password.setType(PASSWORD_TEXT_TYPE);
password.set_value(passwordText);
usernameToken.setPassword(password);
securityHeader.setUsernameToken(usernameToken);
setHeader(WSSE_NAMESPACE, "Security", securityHeader);
}
/**
* Provides access to Security details (e.g., account name and license #).
* <pre>
* <b>Example:</b>
* [Java]
* // Set security
* Security security = new Security();
* security.setAccount("account");
* security.setLicense("license number");
* svc.setSecurity(security);
*
* System.out.println(svc.getSecurity().getAccount());
* System.out.println(svc.getSecurity().getLicense());
* PingResult result = svc.ping("");
* </pre>
*
* @return Security object.
*/
public Security getSecurity()
{
return security;
}
// Private members
private Profile profile;
private Security security;
}
|
package com.vetroumova.sixjars.ui.fragments;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.InputType;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.vetroumova.sixjars.R;
import com.vetroumova.sixjars.app.Prefs;
import com.vetroumova.sixjars.database.RealmManager;
import com.vetroumova.sixjars.model.Jar;
import com.vetroumova.sixjars.utils.BottleDrawableManager;
import com.vetroumova.sixjars.utils.InputSumWatcher;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import io.realm.Realm;
public class AddCashFragment extends Fragment implements View.OnClickListener,
PourToJarFragment.OnPourInJarListener {
public static final String ARG_JAR_ID = "jarID";
private static final int POUR_RQ_CODE = 6;
private static final List<String> jarIDs
= Arrays.asList("NEC", "PLAY", "GIVE", "EDU", "LTSS", "FFA");
EditText sumEditText;
TextView getCurrBalanceJars;
TextView currBalanceNEC;
TextView currBalancePLAY;
TextView currBalanceGIVE;
TextView currBalanceEDU;
TextView currBalanceLTSS;
TextView currBalanceFFA;
ImageView bottlesAll;
ImageView bottleNEC;
ImageView bottlePLAY;
ImageView bottleGIVE;
ImageView bottleEDU;
ImageView bottleLTSS;
ImageView bottleFFA;
RelativeLayout allJars;
RelativeLayout jarNEC;
RelativeLayout jarPLAY;
RelativeLayout jarGIVE;
RelativeLayout jarEDU;
RelativeLayout jarLTSS;
RelativeLayout jarFFA;
Button saveButton;
private String jarID;
private float sum;
private int currPercent;
private List<Jar> jars; //to add in all by percentage
private Realm realm;
private float sumOfJars;
public AddCashFragment() {
// Required empty public constructor
}
public static AddCashFragment newInstance() {
AddCashFragment fragment = new AddCashFragment();
Bundle args = new Bundle();
fragment.setArguments(args);
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//get realm instance
this.realm = RealmManager.with(this).getRealm();
if (savedInstanceState == null) {
jarID = "NoID";
} else {
jarID = savedInstanceState.getString(ARG_JAR_ID, "NoID");
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_add_cash, container, false);
sumEditText = (EditText) view.findViewById(R.id.cashAddEdit);
sumEditText.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL);
sumEditText.setText("");
sumEditText.addTextChangedListener(new InputSumWatcher(sumEditText));
getCurrBalanceJars = (TextView) view.findViewById(R.id.currBalanceJars);
currBalanceNEC = (TextView) view.findViewById(R.id.currBalanceNECJar);
currBalancePLAY = (TextView) view.findViewById(R.id.currBalancePLAYJar);
currBalanceGIVE = (TextView) view.findViewById(R.id.currBalanceGIVEJar);
currBalanceEDU = (TextView) view.findViewById(R.id.currBalanceEDUJar);
currBalanceLTSS = (TextView) view.findViewById(R.id.currBalanceLTSSJar);
currBalanceFFA = (TextView) view.findViewById(R.id.currBalanceFFAJar);
bottlesAll = (ImageView) view.findViewById(R.id.addAllJars_imageView);
bottleNEC = (ImageView) view.findViewById(R.id.addNECJar_imageView);
bottlePLAY = (ImageView) view.findViewById(R.id.addPLAYJar_imageView);
bottleGIVE = (ImageView) view.findViewById(R.id.addGIVEJar_imageView);
bottleEDU = (ImageView) view.findViewById(R.id.addEDUJar_imageView);
bottleLTSS = (ImageView) view.findViewById(R.id.addLTSSJar_imageView);
bottleFFA = (ImageView) view.findViewById(R.id.addFFAJar_imageView);
allJars = (RelativeLayout) view.findViewById(R.id.addAllJars);
jarNEC = (RelativeLayout) view.findViewById(R.id.addNECJar);
jarPLAY = (RelativeLayout) view.findViewById(R.id.addPLAYJar);
jarGIVE = (RelativeLayout) view.findViewById(R.id.addGIVEJar);
jarEDU = (RelativeLayout) view.findViewById(R.id.addEDUJar);
jarLTSS = (RelativeLayout) view.findViewById(R.id.addLTSSJar);
jarFFA = (RelativeLayout) view.findViewById(R.id.addFFAJar);
allJars.setClickable(true);
jarNEC.setClickable(true);
jarPLAY.setClickable(true);
jarGIVE.setClickable(true);
jarEDU.setClickable(true);
jarLTSS.setClickable(true);
jarFFA.setClickable(true);
allJars.setOnClickListener(this);
jarNEC.setOnClickListener(this);
jarPLAY.setOnClickListener(this);
jarGIVE.setOnClickListener(this);
jarEDU.setOnClickListener(this);
jarLTSS.setOnClickListener(this);
jarFFA.setOnClickListener(this);
saveButton = (Button) view.findViewById(R.id.saveCashAddButton);
saveButton.setOnClickListener(this);
setBalance();
return view;
}
private void setBottles() {
bottlesAll.setImageResource(BottleDrawableManager.setDrawableJar(Prefs.with(getContext()), "AllJars"));
bottleNEC.setImageResource(BottleDrawableManager.setDrawableJar(Prefs.with(getContext()), "NEC"));
bottlePLAY.setImageResource(BottleDrawableManager.setDrawableJar(Prefs.with(getContext()), "PLAY"));
bottleGIVE.setImageResource(BottleDrawableManager.setDrawableJar(Prefs.with(getContext()), "GIVE"));
bottleEDU.setImageResource(BottleDrawableManager.setDrawableJar(Prefs.with(getContext()), "EDU"));
bottleLTSS.setImageResource(BottleDrawableManager.setDrawableJar(Prefs.with(getContext()), "LTSS"));
bottleFFA.setImageResource(BottleDrawableManager.setDrawableJar(Prefs.with(getContext()), "FFA"));
setCheckedJar();
}
private void setCheckedJar() {
allJars.setBackgroundResource(jarID.equals("AllJars") ? R.drawable.jar_widget_selected_bg
: R.drawable.jar_widget_bg);
jarNEC.setBackgroundResource(jarID.equals("NEC") ? R.drawable.jar_widget_selected_bg
: R.drawable.jar_widget_bg);
jarPLAY.setBackgroundResource(jarID.equals("PLAY") ? R.drawable.jar_widget_selected_bg
: R.drawable.jar_widget_bg);
jarGIVE.setBackgroundResource(jarID.equals("GIVE") ? R.drawable.jar_widget_selected_bg
: R.drawable.jar_widget_bg);
jarEDU.setBackgroundResource(jarID.equals("EDU") ? R.drawable.jar_widget_selected_bg
: R.drawable.jar_widget_bg);
jarLTSS.setBackgroundResource(jarID.equals("LTSS") ? R.drawable.jar_widget_selected_bg
: R.drawable.jar_widget_bg);
jarFFA.setBackgroundResource(jarID.equals("FFA") ? R.drawable.jar_widget_selected_bg
: R.drawable.jar_widget_bg);
}
private void setBalance() {
// get all Jars
jars = RealmManager.with(this).getJars();
Log.d("VOlga", "Getting jars elements: " + jars.size());
//Set the text
DecimalFormatSymbols s = new DecimalFormatSymbols();
DecimalFormat f = new DecimalFormat("##,##0.00", s);
currBalanceNEC.setText(getString(R.string.cash_balance_text, f.format(jars.get(0).getTotalCash())));
currBalancePLAY.setText(getString(R.string.cash_balance_text, f.format(jars.get(1).getTotalCash())));
currBalanceGIVE.setText(getString(R.string.cash_balance_text, f.format(jars.get(2).getTotalCash())));
currBalanceEDU.setText(getString(R.string.cash_balance_text, f.format(jars.get(3).getTotalCash())));
currBalanceLTSS.setText(getString(R.string.cash_balance_text, f.format(jars.get(4).getTotalCash())));
currBalanceFFA.setText(getString(R.string.cash_balance_text, f.format(jars.get(5).getTotalCash())));
sumOfJars = 0;
for (Jar jar : jars) {
sumOfJars += jar.getTotalCash();
}
getCurrBalanceJars.setText(getString(R.string.cash_balance_text, f.format(sumOfJars)));
setBottles();
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.addAllJars: {
jarID = (jarID.equals("AllJars") ? "NoID" : "AllJars");
//jarID = "AllJars"; //TODO IN here
break;
}
case R.id.addNECJar: {
jarID = (jarID.equals(jarIDs.get(0)) ? "NoID" : jarIDs.get(0));
break;
}
case R.id.addPLAYJar: {
jarID = (jarID.equals(jarIDs.get(1)) ? "NoID" : jarIDs.get(1));
break;
}
case R.id.addGIVEJar: {
jarID = (jarID.equals(jarIDs.get(2)) ? "NoID" : jarIDs.get(2));
break;
}
case R.id.addEDUJar: {
jarID = (jarID.equals(jarIDs.get(3)) ? "NoID" : jarIDs.get(3));
break;
}
case R.id.addLTSSJar: {
jarID = (jarID.equals(jarIDs.get(4)) ? "NoID" : jarIDs.get(4));
break;
}
case R.id.addFFAJar: {
jarID = (jarID.equals(jarIDs.get(5)) ? "NoID" : jarIDs.get(5));
break;
}
case R.id.saveCashAddButton: {
if (sumEditText.getText().toString().equals("")) {
Toast.makeText(getContext(), R.string.enter_sum_text, Toast.LENGTH_SHORT).show();
} else {
// add to one jar or to all
sum = Float.parseFloat(sumEditText.getText().toString());
if (sum > 10_000_000 || (sumOfJars + sum) > 60_000_000) {
Toast.makeText(getContext(), R.string.too_much_text, Toast.LENGTH_SHORT).show();
break;
}
//GLOBAL INCOME
if (jarID.equals("AllJars")) {
if (sumOfJars > 0) {
//CHOOSE if pour to FFA or LTSS jar needed
PourToJarFragment pourFragment = new PourToJarFragment();
// SETS the target fragment for use later when sending results
pourFragment.setTargetFragment(AddCashFragment.this, POUR_RQ_CODE);
pourFragment.show(getFragmentManager(), "choosePourInJar");
//see onChooseToPour()
} else {
onChooseToPour("NoJar");
}
} else if (jarID.equals("NoID")) {
Toast.makeText(getContext(), R.string.choose_jar_text, Toast.LENGTH_SHORT).show();
} else {
currPercent = Prefs.with(getContext()).getPercentJar(jarID);
//adding in DB
boolean resultAdd = RealmManager.with(this).addCashToJar(jarID, sum,
new Date(System.currentTimeMillis()), currPercent, getString(R.string.new_income_text));
Log.d("VOlga", "add to " + jarID + " new Cashflow "
+ sum + " - " + resultAdd);
Toast.makeText(getContext(), getString(resultAdd ? R.string.added_sum_text
: R.string.not_added_sum_text), Toast.LENGTH_SHORT).show();
if (resultAdd) {
sumEditText.setText("");
//new MaxVolume for bottle
Prefs.with(getContext()).setMaxVolumeInJar(RealmManager.with(this)
.getJar(jarID).getTotalCash(), jarID);
//save new prefs to user in realm
RealmManager.setUserPrefsFromSharedPrefs(getContext(),
RealmManager.with(this).getJar(jarID).getUser());
}
setBalance();
}
}
}
jarID = "NoID";
break;
}
setCheckedJar(); //to other cases different from save
}
@Override
public void onSaveInstanceState(Bundle outState) {
outState.putString(ARG_JAR_ID, jarID);
}
@Override
public void onChooseToPour(String jarIdToPour) {
boolean resultAdd = false;
for (String jarID : jarIDs) {
currPercent = Prefs.with(getContext()).getPercentJar(jarID);
Log.d("VOlga", "perc in jar before adding sum " + jarID + " " + currPercent);
float sumInJar = sum * ((float) currPercent / 100);
//adding in DB
resultAdd = RealmManager.with(this).addCashToJar(jarID, sumInJar,
new Date(System.currentTimeMillis()), currPercent, getString(R.string.new_income_text));
Log.d("VOlga", "add to " + jarID + " new Cashflow "
+ sumInJar + " - " + resultAdd);
if (resultAdd) {
sumEditText.setText("");
//new MaxVolume for bottle
Prefs.with(getContext()).setMaxVolumeInJar(RealmManager.with(this)
.getJar(jarID).getTotalCash(), jarID);
//save new prefs to user in realm
RealmManager.setUserPrefsFromSharedPrefs(getContext(),
RealmManager.with(this).getJar(jarID).getUser());
}
}
Toast.makeText(getContext(), getString(resultAdd ? R.string.added_sum_text
: R.string.not_added_sum_text), Toast.LENGTH_SHORT).show();
if (jarIdToPour.equals("NoJar")) {
Toast.makeText(getContext(), getString(R.string.no_poured_text),
Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getContext(), getString(R.string.poured_text) + jarIdToPour,
Toast.LENGTH_SHORT).show();
}
jarID = "NoID";
setBalance();
}
}
|
package com.yunussandikci.GithubImporter.Models.Response;
public class ImportUserRepositoriesResponse extends BaseResponse {
public ImportUserRepositoriesResponse(Integer importedRepositoryCount,String message){
this.importedRepositoryCount = importedRepositoryCount;
this.setMessage(message);
}
private Integer importedRepositoryCount;
public Integer getImportedRepositoryCount() {
return importedRepositoryCount;
}
public void setImportedRepositoryCount(Integer importedRepositoryCount) {
this.importedRepositoryCount = importedRepositoryCount;
}
}
|
package capitulo07;
public class Exercicio703 {
public static void main(String[] args) {
final int ARRAY_SIZE = 10;
double[] fractions = new double[ARRAY_SIZE];
fractions[9] = 1.667;
fractions[6] = 3.333;
double total = 0;
for (int j = 0; j < fractions.length; j++) {
total += fractions[j];
System.out.printf("%.3f%n",fractions[j]);
}
}
}
|
package com.heartmarket.model.dao;
import org.springframework.data.domain.Pageable;
import java.util.List;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import com.heartmarket.model.dto.Trade;
import com.heartmarket.model.dto.User;
import com.heartmarket.model.dto.response.OtherTrade;
@Repository
public interface TradeRepository extends JpaRepository<Trade, Integer> {
// 거래글 하나를 조회 ( 상세 페이지 조회 )
// 메인페이지에서 게시글 하나를 선택 했을 때 사용
Trade findByTradeNo(Integer tradeNo);
List<Trade> findAllByTradeArea(String tradeArea);
List<Trade> findAllBytUserUserNo(int userNo);
List<Trade> findAllBytUserUserNoOrderByTradeNoDesc(int userNo);
List<Trade> findAllBybUserUserNo(int userNo);
// 검색 결과
// List<TradeResponse> findAllBy();
Page<Trade> findAllByTradeAreaAndTradeCategory(String tradeArea, String tradeCategory, Pageable req);
Page<Trade> findAllByTradeCategory(String tradeCategory, Pageable req);
Page<Trade> findAllByTradeAreaAndTradeCategoryAndBUserUserNoIsNull(String tradeArea, String tradeCategory, Pageable req);
Page<Trade> findAllByTradeAreaAndTradeCategoryAndBUserUserNoIsNotNull(String tradeArea, String tradeCategory, Pageable req);
// 페이지 기능
// 가져 옵시다. 구매 목록, 판매 목록
// 페이지 기능 -> 검색 기능
// 현재 데이터 수
// 지역별 데이터 수
Integer countByTradeArea(String area);
@Query("Select count(t) from Trade t")
int countAll();
// getList에서 사용되는 전체 조회
Page<Trade> findAll(Pageable req);
// 판매중
Page<Trade> findBybUserUserNoIsNull(Pageable req);
Page<Trade> findBybUserUserNoIsNotNull(Pageable req);
Page<Trade> findByTradeArea(String area,Pageable req);
Page<Trade> findAll(Specification<Trade> specification, Pageable of);
// 판매내역 일부만가져오기 --> 상대방 프로필에 띄울거
List<Trade> findTop4BytUserUserNo(int userNo);
// 인기매물 ( 찜한 순서대로 )
@Query("select t from Cart c right join Trade t on c.cTrade.tradeNo = t.tradeNo"
+ " and t.bUser.userNo is null"
+ " group by t.tradeNo "
+ " having count(c.cTrade.tradeNo) > 0"
+ "order by count(c.cTrade.tradeNo) desc"
)
Page<Trade> findTop8All(Pageable req);
}
|
package pooproject.servico;
import java.util.Vector;
import pooproject.exception.*;
import pooproject.usuario.*;
public class Repositorio implements IRepositorio{
protected Vector<Perfil> usersvector= new <Perfil>Vector();
@Override
//Resposável por cadastrar usuário no vetor;
public void cadastrar(Perfil usuario)throws UJCException{
if(buscar(usuario.getUsuario())!=null){
throw new UJCException();
}
else{
this.usersvector.add(usuario);
}
}
//busca usuário dentro do repositório
@Override
public Perfil buscar(String usuario){
int i =0;
while(i<usersvector.size()){
if((this.usersvector.get(i)).getUsuario().equals(usuario)){
return usersvector.get(i);
}
i = i+1;
}
return null;
}
//atuzaliza o perfil do usuário;
@Override
public void atualizar(Perfil perfilatualizado)throws UNCException{
Perfil perfilatual = this.buscar(perfilatualizado.getUsuario());
if(perfilatual == null){
throw new UNCException();
}
else{
if(perfilatual instanceof PessoaFisica && perfilatualizado instanceof PessoaFisica){
((PessoaFisica)perfilatual).setCpf(((PessoaFisica)perfilatualizado).getCpf());
}
else{
((PessoaJuridica)perfilatual).setCnpj(((PessoaJuridica)perfilatualizado).getCnpj());
}
}
}
}
|
package com.tencent.mm.modelvoiceaddr.ui;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
class VoiceSearchLayout$2 implements OnCompletionListener {
final /* synthetic */ VoiceSearchLayout erE;
final /* synthetic */ a erF = null;
VoiceSearchLayout$2(VoiceSearchLayout voiceSearchLayout) {
this.erE = voiceSearchLayout;
}
public final void onCompletion(MediaPlayer mediaPlayer) {
mediaPlayer.release();
}
}
|
import java.util.Scanner;
public class Hangman {
private static void setGame(Scanner sc, CommandOpts opts) {
boolean correct;
GameState state;
if (opts.wordSource.equals("")) {
System.out.println(" 1. Counties");
System.out.println(" 2. Countries");
System.out.println(" 3. Cities");
System.out.print("Pick a category:");
state = new GameState(Words.randomWord(sc.nextInt()), opts.maxGuesses, opts.maxHints);
} else {
state = new GameState(Words.randomWord(opts.wordSource), opts.maxGuesses, opts.maxHints);
}
while (!state.won() && !state.lost()) {
state.showWord(state.word);
System.out.println("Guesses remaining: " + state.guessRemain);
correct = state.guessLetter();
if (correct) System.out.println("Good guess!");
if (!correct) System.out.println("Wrong guess!");
}
if (state.won()) {
System.out.println("Well done!");
System.out.println("You took " + state.guessTime + " guesses");
} else {
System.out.println("You lost! The word was " + state.word);
}
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// GameState state = null;
CommandOpts opts;
opts = new CommandOpts(args);
setGame(sc, opts);
}
}
|
/*
* 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 View;
import javax.swing.table.DefaultTableModel;
import javax.swing.JOptionPane;
import Model.*;
/**
*
* @author Lapankha
*/
public class DataKategori extends javax.swing.JFrame {
/**
* Creates new form DataKategori
*/
int baris = 0;
static Object kolom[] = {"No", "Kode Kategori Buku", "Kategori Buku"};
DefaultTableModel tbl = new DefaultTableModel(kolom,baris);
public DataKategori() {
initComponents();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jLabel2 = new javax.swing.JLabel();
BEdit = new javax.swing.JButton();
jLabel3 = new javax.swing.JLabel();
BHapus = new javax.swing.JButton();
TKode = new javax.swing.JTextField();
TKategori = new javax.swing.JTextField();
BTambah = new javax.swing.JButton();
BSimpan = new javax.swing.JButton();
BReset = new javax.swing.JButton();
TCari = new javax.swing.JTextField();
BCari = new javax.swing.JButton();
jScrollPane1 = new javax.swing.JScrollPane();
TblKategori = new javax.swing.JTable();
jLabel1 = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
addComponentListener(new java.awt.event.ComponentAdapter() {
public void componentShown(java.awt.event.ComponentEvent evt) {
formComponentShown(evt);
}
});
jLabel2.setText("Kode Kategori");
BEdit.setText("Edit");
BEdit.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
BEditActionPerformed(evt);
}
});
jLabel3.setText("Kategori");
BHapus.setText("Hapus");
BHapus.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
BHapusActionPerformed(evt);
}
});
BTambah.setText("Tambah");
BTambah.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
BTambahActionPerformed(evt);
}
});
BSimpan.setText("Simpan");
BSimpan.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
BSimpanActionPerformed(evt);
}
});
BReset.setText("Reset");
BReset.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
BResetActionPerformed(evt);
}
});
BCari.setText("Cari");
BCari.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
BCariActionPerformed(evt);
}
});
TblKategori.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{null, null, null, null},
{null, null, null, null},
{null, null, null, null},
{null, null, null, null}
},
new String [] {
"Title 1", "Title 2", "Title 3", "Title 4"
}
));
jScrollPane1.setViewportView(TblKategori);
jLabel1.setFont(new java.awt.Font("Ubuntu", 1, 36)); // NOI18N
jLabel1.setForeground(new java.awt.Color(0, 51, 204));
jLabel1.setText("DATA KATEGORI");
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(23, 23, 23)
.addComponent(jLabel1))
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel2)
.addGap(18, 18, 18)
.addComponent(TKode))
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel3)
.addComponent(BTambah))
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(18, 18, 18)
.addComponent(BSimpan)
.addGap(18, 18, 18)
.addComponent(BReset))
.addGroup(layout.createSequentialGroup()
.addGap(38, 38, 38)
.addComponent(TKategori, javax.swing.GroupLayout.PREFERRED_SIZE, 179, javax.swing.GroupLayout.PREFERRED_SIZE))))))
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(TCari, javax.swing.GroupLayout.PREFERRED_SIZE, 168, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(BCari))
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(12, 12, 12)
.addComponent(BEdit, javax.swing.GroupLayout.PREFERRED_SIZE, 66, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(39, 39, 39)
.addComponent(BHapus))
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel1)
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel2)
.addComponent(TKode, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel3)
.addComponent(TKategori, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(BTambah)
.addComponent(BSimpan)
.addComponent(BReset))
.addGap(46, 46, 46)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(TCari, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(BCari))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 120, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(BEdit)
.addComponent(BHapus))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void BEditActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BEditActionPerformed
KategoriBuku obj = new KategoriBuku();
int Pilihbaris = TblKategori.getSelectedRow();
String kodekategoribuku = tbl.getValueAt(Pilihbaris, 1).toString();
String kategoribuku = obj.getDataKategori(kodekategoribuku);
TKode.setText(kodekategoribuku);
TKode.setEditable(false);
TKategori.setText(kategoribuku);
}//GEN-LAST:event_BEditActionPerformed
private void BHapusActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BHapusActionPerformed
KategoriBuku obj = new KategoriBuku();
int Pilihbaris = TblKategori.getSelectedRow();
String kodekategoribuku = tbl.getValueAt(Pilihbaris, 1).toString();
obj.HapusDataKategori(kodekategoribuku);
tbl.removeRow(Pilihbaris);
JOptionPane.showMessageDialog(this, "Data berhasil dihapus",
"Pesan konfirmasi", JOptionPane.INFORMATION_MESSAGE);
}//GEN-LAST:event_BHapusActionPerformed
private void BTambahActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BTambahActionPerformed
KategoriBuku obj = new KategoriBuku();
String kodekategori = TKode.getText();
String kategoribuku = TKategori.getText();
if(kodekategori.isEmpty()){
JOptionPane.showMessageDialog(this, "Kode kategori buku harus diisi",
"Pesan Kesalahan", JOptionPane.INFORMATION_MESSAGE);
}else if(kategoribuku.isEmpty()){
JOptionPane.showMessageDialog(this, "Nama kategori buku harus diisi",
"Pesan Kesalahan", JOptionPane.INFORMATION_MESSAGE);
}else{
int No = obj.TambahDataKategori(kodekategori, kategoribuku);
tbl.addRow(new Object[]{No, kodekategori, kategoribuku});
TblKategori.setModel(tbl);
TKode.setText("");
TKategori.setText("");
}
}//GEN-LAST:event_BTambahActionPerformed
private void BSimpanActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BSimpanActionPerformed
KategoriBuku obj = new KategoriBuku();
String kodekategoribuku = TKode.getText();
String kategoribuku = TKategori.getText();
obj.UpdateDataKategori(kodekategoribuku, kategoribuku);
tbl.getDataVector().removeAllElements();
String[][] data = obj.getKategoriBuku();
for(int i=0; i<data.length; i++){
int no = i + 1;
tbl.addRow(new Object[]{no, data[i][0], data[i][1]});
}
TblKategori.setModel(tbl);
JOptionPane.showMessageDialog(this, "Data Berhasil diedit",
"Pesan Konfirmasi", JOptionPane.INFORMATION_MESSAGE);
TKode.setEditable(true);
TKode.setText("");
TKategori.setText("");
}//GEN-LAST:event_BSimpanActionPerformed
private void BResetActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BResetActionPerformed
TKode.setEditable(true);
TKode.setText("");
TKategori.setText("");
}//GEN-LAST:event_BResetActionPerformed
private void BCariActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BCariActionPerformed
KategoriBuku obj1 = new KategoriBuku();
String katakunci = TCari.getText();
tbl.getDataVector().removeAllElements();
String [][] data = obj1.CariDataKategori(katakunci);
for(int i=0; i<data.length; i++){
int no = i+1;
tbl.addRow(new Object[]{no, data[i][0], data[i][1]});
}
TblKategori.setModel(tbl);
TCari.setText("");
}//GEN-LAST:event_BCariActionPerformed
private void formComponentShown(java.awt.event.ComponentEvent evt) {//GEN-FIRST:event_formComponentShown
// TODO add your handling code here:
KategoriBuku obj = new KategoriBuku();
String [][]data = obj.getKategoriBuku();
for(int i=0; i<data.length; i++){
int no = (i+1);
tbl.addRow(new Object[]{data[i][0], data[i][1], data[i][2]});
}
TblKategori.setModel(tbl);
}//GEN-LAST:event_formComponentShown
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(DataKategori.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(DataKategori.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(DataKategori.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(DataKategori.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new DataKategori().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton BCari;
private javax.swing.JButton BEdit;
private javax.swing.JButton BHapus;
private javax.swing.JButton BReset;
private javax.swing.JButton BSimpan;
private javax.swing.JButton BTambah;
private javax.swing.JTextField TCari;
private javax.swing.JTextField TKategori;
private javax.swing.JTextField TKode;
private javax.swing.JTable TblKategori;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JScrollPane jScrollPane1;
// End of variables declaration//GEN-END:variables
}
|
package com.github.agmcc.slate.bytecode;
import static com.github.agmcc.slate.test.FileUtils.readResourceAsString;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import com.github.agmcc.slate.ast.CompilationUnit;
import com.github.agmcc.slate.ast.MethodDeclaration;
import com.github.agmcc.slate.ast.Parameter;
import com.github.agmcc.slate.ast.expression.BooleanLit;
import com.github.agmcc.slate.ast.expression.DecLit;
import com.github.agmcc.slate.ast.expression.IntLit;
import com.github.agmcc.slate.ast.expression.PostDecrement;
import com.github.agmcc.slate.ast.expression.PostIncrement;
import com.github.agmcc.slate.ast.expression.PreDecrement;
import com.github.agmcc.slate.ast.expression.PreIncrement;
import com.github.agmcc.slate.ast.expression.StringLit;
import com.github.agmcc.slate.ast.expression.VarReference;
import com.github.agmcc.slate.ast.expression.binary.AdditionExpression;
import com.github.agmcc.slate.ast.expression.binary.DivisionExpression;
import com.github.agmcc.slate.ast.expression.binary.MultiplicationExpression;
import com.github.agmcc.slate.ast.expression.binary.SubtractionExpression;
import com.github.agmcc.slate.ast.expression.binary.logic.AndExpression;
import com.github.agmcc.slate.ast.expression.binary.logic.GreaterExpression;
import com.github.agmcc.slate.ast.expression.binary.logic.LessExpression;
import com.github.agmcc.slate.ast.expression.binary.logic.OrExpression;
import com.github.agmcc.slate.ast.statement.Assignment;
import com.github.agmcc.slate.ast.statement.Block;
import com.github.agmcc.slate.ast.statement.Condition;
import com.github.agmcc.slate.ast.statement.ForTraditional;
import com.github.agmcc.slate.ast.statement.Print;
import com.github.agmcc.slate.ast.statement.Statement;
import com.github.agmcc.slate.ast.statement.VarDeclaration;
import com.github.agmcc.slate.ast.statement.While;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.List;
import java.util.NoSuchElementException;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.Type;
import org.objectweb.asm.util.CheckClassAdapter;
import org.objectweb.asm.util.TraceClassVisitor;
class JvmCompilerTest {
private static final String CLASS_NAME = "Test";
private static JvmCompiler compiler;
@BeforeAll
static void setup() {
compiler = new JvmCompiler();
}
/* Var Declaration */
@Test
void testCompile_varDeclaration_nullExpression() {
// Given
final var compilationUnit =
createCompilationUnitWithMethod(List.of(new VarDeclaration("count", null)));
// When Then
assertThrows(NoSuchElementException.class, () -> compiler.compile(compilationUnit, CLASS_NAME));
}
@ParameterizedTest
@ValueSource(strings = {"5", "-5", "0146", "0X123Face", "0x123", "0b1111", "0B1111", "1_000_000"})
void testCompile_varDeclaration_int_valid(String value) {
// Given
final var compilationUnit =
createCompilationUnitWithMethod(List.of(new VarDeclaration("count", new IntLit(value))));
// When
final var actual = compiler.compile(compilationUnit, CLASS_NAME);
// Then
assertTrue(verifyByteCode(actual).isEmpty());
}
@ParameterizedTest
@ValueSource(strings = {"abc", "15.5", "10L", "10f"})
void testCompile_varDeclaration_int_invalidFormat(String value) {
// Given
final var compilationUnit =
createCompilationUnitWithMethod(List.of(new VarDeclaration("count", new IntLit(value))));
// When Then
assertThrows(NumberFormatException.class, () -> compiler.compile(compilationUnit, CLASS_NAME));
}
@Test
void testCompile_varDeclaration_int_nullValue() {
// Given
final var compilationUnit =
createCompilationUnitWithMethod(List.of(new VarDeclaration("count", new IntLit(null))));
// When Then
assertThrows(NullPointerException.class, () -> compiler.compile(compilationUnit, CLASS_NAME));
}
@Test
void testCompile_varDeclaration_int() {
// Given
final var compilationUnit =
createCompilationUnitWithMethod(List.of(new VarDeclaration("count", new IntLit("100"))));
// When
final var actual = compiler.compile(compilationUnit, CLASS_NAME);
// Then
assertTrue(verifyByteCode(actual).isEmpty());
assertEquals(readResourceAsString("bytecode/vardec/varDec_int.txt"), readByteCode(actual));
}
@ParameterizedTest
@ValueSource(
strings = {
"5",
"-5",
"5.0",
"-5.0",
"5.5",
"5f",
"-5f",
"5.0f",
"-5.0f",
"1_000.00",
"100.00_00"
})
void testCompile_varDeclaration_decimal_valid(String value) {
// Given
final var compilationUnit =
createCompilationUnitWithMethod(List.of(new VarDeclaration("price", new DecLit(value))));
// When
final var actual = compiler.compile(compilationUnit, CLASS_NAME);
// Then
assertTrue(verifyByteCode(actual).isEmpty());
}
@ParameterizedTest
@ValueSource(strings = {"abc", "15L", "0146.5", "0X123Face.123"})
void testCompile_varDeclaration_decimal_invalidFormat(String value) {
// Given
final var compilationUnit =
createCompilationUnitWithMethod(List.of(new VarDeclaration("price", new IntLit(value))));
// When Then
assertThrows(NumberFormatException.class, () -> compiler.compile(compilationUnit, CLASS_NAME));
}
@Test
void testCompile_varDeclaration_decimal_nullValue() {
// Given
final var compilationUnit =
createCompilationUnitWithMethod(List.of(new VarDeclaration("price", new DecLit(null))));
// When Then
assertThrows(NullPointerException.class, () -> compiler.compile(compilationUnit, CLASS_NAME));
}
@Test
void testCompile_varDeclaration_decimal() {
// Given
final var compilationUnit =
createCompilationUnitWithMethod(List.of(new VarDeclaration("count", new DecLit("99.99"))));
// When
final var actual = compiler.compile(compilationUnit, CLASS_NAME);
// Then
assertTrue(verifyByteCode(actual).isEmpty());
assertEquals(readResourceAsString("bytecode/vardec/varDec_decimal.txt"), readByteCode(actual));
}
@Test
void testCompile_varDeclaration_string() {
// Given
final var compilationUnit =
createCompilationUnitWithMethod(
List.of(new VarDeclaration("message", new StringLit("Hello"))));
// When
final var actual = compiler.compile(compilationUnit, CLASS_NAME);
// Then
assertTrue(verifyByteCode(actual).isEmpty());
assertEquals(readResourceAsString("bytecode/vardec/varDec_string.txt"), readByteCode(actual));
}
@Test
void testCompile_varDeclaration_string_nullValue() {
// Given
final var compilationUnit =
createCompilationUnitWithMethod(
List.of(new VarDeclaration("message", new StringLit(null))));
// When Then
assertThrows(
IllegalArgumentException.class, () -> compiler.compile(compilationUnit, CLASS_NAME));
}
@Test
void testCompile_varDeclaration_boolean_true() {
// Given
final var compilationUnit =
createCompilationUnitWithMethod(
List.of(new VarDeclaration("valid", new BooleanLit("true"))));
// When
final var actual = compiler.compile(compilationUnit, CLASS_NAME);
// Then
assertTrue(verifyByteCode(actual).isEmpty());
assertEquals(
readResourceAsString("bytecode/vardec/varDec_boolean_true.txt"), readByteCode(actual));
}
@Test
void testCompile_varDeclaration_boolean_false() {
// Given
final var compilationUnit =
createCompilationUnitWithMethod(
List.of(new VarDeclaration("valid", new BooleanLit("false"))));
// When
final var actual = compiler.compile(compilationUnit, CLASS_NAME);
// Then
assertTrue(verifyByteCode(actual).isEmpty());
assertEquals(
readResourceAsString("bytecode/vardec/varDec_boolean_false.txt"), readByteCode(actual));
}
@Test
void testCompile_varDeclaration_boolean_invalid() {
// Given
final var compilationUnit =
createCompilationUnitWithMethod(
List.of(new VarDeclaration("valid", new BooleanLit("invalid"))));
// When Then
final var e =
assertThrows(
UnsupportedOperationException.class,
() -> compiler.compile(compilationUnit, CLASS_NAME));
assertEquals("Invalid boolean value: invalid", e.getMessage());
}
@Test
void testCompile_varDeclaration_addition() {
// Given
final var compilationUnit =
createCompilationUnitWithMethod(
List.of(
new VarDeclaration(
"result", new AdditionExpression(new IntLit("1"), new IntLit("3")))));
// When
final var actual = compiler.compile(compilationUnit, CLASS_NAME);
// Then
assertTrue(verifyByteCode(actual).isEmpty());
assertEquals(readResourceAsString("bytecode/vardec/varDec_addition.txt"), readByteCode(actual));
}
@Test
void testCompile_varDeclaration_addition_mixedTypes() {
// Given
final var compilationUnit =
createCompilationUnitWithMethod(
List.of(
new VarDeclaration(
"result", new AdditionExpression(new IntLit("1"), new DecLit("3.5")))));
// When
final var actual = compiler.compile(compilationUnit, CLASS_NAME);
// Then
assertTrue(verifyByteCode(actual).isEmpty());
assertEquals(
readResourceAsString("bytecode/vardec/varDec_addition_mixed.txt"), readByteCode(actual));
}
@Test
void testCompile_varDeclaration_addition_string() {
// Given
final var compilationUnit =
createCompilationUnitWithMethod(
List.of(
new VarDeclaration(
"result",
new AdditionExpression(new StringLit("Hello, "), new StringLit("World!")))));
// When
final var actual = compiler.compile(compilationUnit, CLASS_NAME);
// Then
assertTrue(verifyByteCode(actual).isEmpty());
assertEquals(
readResourceAsString("bytecode/vardec/varDec_addition_string.txt"), readByteCode(actual));
}
@Test
void testCompile_varDeclaration_subtraction() {
// Given
final var compilationUnit =
createCompilationUnitWithMethod(
List.of(
new VarDeclaration(
"result", new SubtractionExpression(new IntLit("10"), new IntLit("3")))));
// When
final var actual = compiler.compile(compilationUnit, CLASS_NAME);
// Then
assertTrue(verifyByteCode(actual).isEmpty());
assertEquals(
readResourceAsString("bytecode/vardec/varDec_subtraction.txt"), readByteCode(actual));
}
@Test
void testCompile_varDeclaration_subtraction_mixedTypes() {
// Given
final var compilationUnit =
createCompilationUnitWithMethod(
List.of(
new VarDeclaration(
"result", new SubtractionExpression(new IntLit("10"), new DecLit("3")))));
// When
final var actual = compiler.compile(compilationUnit, CLASS_NAME);
// Then
assertTrue(verifyByteCode(actual).isEmpty());
assertEquals(
readResourceAsString("bytecode/vardec/varDec_subtraction_mixed.txt"), readByteCode(actual));
}
@Test
void testCompile_varDeclaration_multiplication() {
// Given
final var compilationUnit =
createCompilationUnitWithMethod(
List.of(
new VarDeclaration(
"result", new MultiplicationExpression(new IntLit("10"), new IntLit("2")))));
// When
final var actual = compiler.compile(compilationUnit, CLASS_NAME);
// Then
assertTrue(verifyByteCode(actual).isEmpty());
assertEquals(
readResourceAsString("bytecode/vardec/varDec_multiplication.txt"), readByteCode(actual));
}
@Test
void testCompile_varDeclaration_multiplication_mixedTypes() {
// Given
final var compilationUnit =
createCompilationUnitWithMethod(
List.of(
new VarDeclaration(
"result",
new MultiplicationExpression(new DecLit("10.0101"), new IntLit("2")))));
// When
final var actual = compiler.compile(compilationUnit, CLASS_NAME);
// Then
assertTrue(verifyByteCode(actual).isEmpty());
assertEquals(
readResourceAsString("bytecode/vardec/varDec_multiplication_mixed.txt"),
readByteCode(actual));
}
@Test
void testCompile_varDeclaration_division() {
// Given
final var compilationUnit =
createCompilationUnitWithMethod(
List.of(
new VarDeclaration(
"result", new DivisionExpression(new IntLit("10"), new IntLit("2")))));
// When
final var actual = compiler.compile(compilationUnit, CLASS_NAME);
// Then
assertTrue(verifyByteCode(actual).isEmpty());
assertEquals(readResourceAsString("bytecode/vardec/varDec_division.txt"), readByteCode(actual));
}
@Test
void testCompile_varDeclaration_division_mixedTypes() {
// Given
final var compilationUnit =
createCompilationUnitWithMethod(
List.of(
new VarDeclaration(
"result", new DivisionExpression(new IntLit("10"), new DecLit("0.5")))));
// When
final var actual = compiler.compile(compilationUnit, CLASS_NAME);
// Then
assertTrue(verifyByteCode(actual).isEmpty());
assertEquals(
readResourceAsString("bytecode/vardec/varDec_division_mixed.txt"), readByteCode(actual));
}
@Test
void testCompile_varDeclaration_greater() {
// Given
final var compilationUnit =
createCompilationUnitWithMethod(
List.of(
new VarDeclaration(
"valid", new GreaterExpression(new IntLit("5"), new IntLit("3")))));
// When
final var actual = compiler.compile(compilationUnit, CLASS_NAME);
// Then
assertTrue(verifyByteCode(actual).isEmpty());
assertEquals(readResourceAsString("bytecode/vardec/varDec_greater.txt"), readByteCode(actual));
}
/* Assignment */
// TODO: Assignment null expression
@Test
void testCompile_assignment_int_valid() {
// Given
final var compilationUnit =
createCompilationUnitWithMethod(
List.of(
new VarDeclaration("value", new IntLit("0")),
new Assignment("value", new IntLit("1"))));
// When
final var actual = compiler.compile(compilationUnit, CLASS_NAME);
// Then
assertTrue(verifyByteCode(actual).isEmpty());
assertEquals(
readResourceAsString("bytecode/assignment/assignment_int.txt"), readByteCode(actual));
}
@Test
void testCompile_assignment_int_convertType() {
// Given
final var compilationUnit =
createCompilationUnitWithMethod(
List.of(
new VarDeclaration("value", new DecLit("1.5")),
new Assignment("value", new IntLit("1"))));
// When
final var actual = compiler.compile(compilationUnit, CLASS_NAME);
// Then
assertTrue(verifyByteCode(actual).isEmpty());
assertEquals(
readResourceAsString("bytecode/assignment/assignment_mixed.txt"), readByteCode(actual));
}
@Test
void testCompile_assignment_missingVarName() {
// Given
final var compilationUnit =
createCompilationUnitWithMethod(List.of(new Assignment("value", new IntLit("1"))));
// When Then
assertThrows(NoSuchElementException.class, () -> compiler.compile(compilationUnit, CLASS_NAME));
}
@Test
void testCompile_assignment_validVarRef() {
// Given
final var compilationUnit =
createCompilationUnitWithMethod(
List.of(
new VarDeclaration("a", new StringLit("Hello")),
new VarDeclaration("b", new StringLit("Goodbye")),
new Assignment("a", new VarReference("b"))));
// When
final var actual = compiler.compile(compilationUnit, CLASS_NAME);
// Then
assertTrue(verifyByteCode(actual).isEmpty());
assertEquals(
readResourceAsString("bytecode/assignment/assignment_varRef.txt"), readByteCode(actual));
}
@Test
void testCompile_assignment_invalidVarRef() {
// Given
final var compilationUnit =
createCompilationUnitWithMethod(
List.of(
new VarDeclaration("a", new StringLit("Hello")),
new Assignment("a", new VarReference("unknown"))));
// When Then
final var e =
assertThrows(RuntimeException.class, () -> compiler.compile(compilationUnit, CLASS_NAME));
assertEquals("Variable 'unknown' doesn't exist in scope", e.getMessage());
}
@Test
void testCompile_assignment_invalidConversion() {
// Given
final var compilationUnit =
createCompilationUnitWithMethod(
List.of(
new VarDeclaration("value", new StringLit("Hello")),
new Assignment("value", new IntLit("1"))));
// When Then
final var e =
assertThrows(
UnsupportedOperationException.class,
() -> compiler.compile(compilationUnit, CLASS_NAME));
assertEquals("Unable to convert type I to java/lang/String", e.getMessage());
}
/* Print */
// TODO: Print null expression
@Test
void testCompile_print_int_valid() {
// Given
final var compilationUnit =
createCompilationUnitWithMethod(List.of(new Print(new IntLit("10"))));
// When
final var actual = compiler.compile(compilationUnit, CLASS_NAME);
// Then
assertTrue(verifyByteCode(actual).isEmpty());
assertEquals(readResourceAsString("bytecode/print/print_int.txt"), readByteCode(actual));
}
/* Block */
@Test
void testCompile_block() {
// Given
final var compilationUnit =
createCompilationUnitWithMethod(
List.of(
new VarDeclaration("outer", new IntLit("3")),
new Block(List.of(new VarDeclaration("inner1", new IntLit("5")))),
new Block(List.of(new VarDeclaration("inner2", new DecLit("2.5"))))));
// When
final var actual = compiler.compile(compilationUnit, CLASS_NAME);
// Then
assertTrue(verifyByteCode(actual).isEmpty());
assertEquals(readResourceAsString("bytecode/block/block.txt"), readByteCode(actual));
}
@Test
void testCompile_condition_and_boolean() {
// Given
final var compilationUnit =
createCompilationUnitWithMethod(
List.of(
new Condition(
new AndExpression(new BooleanLit("true"), new BooleanLit("true")),
new Print(new StringLit("msg")))));
// When
final var actual = compiler.compile(compilationUnit, CLASS_NAME);
// Then
assertTrue(verifyByteCode(actual).isEmpty());
assertEquals(
readResourceAsString("bytecode/condition/condition_and_boolean.txt"), readByteCode(actual));
}
@Test
void testCompile_condition_and_boolean_greater() {
// Given
final var compilationUnit =
createCompilationUnitWithMethod(
List.of(
new Condition(
new AndExpression(
new BooleanLit("true"),
new GreaterExpression(new IntLit("5"), new IntLit("3"))),
new Print(new StringLit("msg")))));
// When
final var actual = compiler.compile(compilationUnit, CLASS_NAME);
// Then
assertTrue(verifyByteCode(actual).isEmpty());
assertEquals(
readResourceAsString("bytecode/condition/condition_and_boolean_greater.txt"),
readByteCode(actual));
}
@Test
void testCompile_condition_and_varRef() {
// Given
final var compilationUnit =
createCompilationUnitWithMethod(
List.of(
new VarDeclaration("check", new BooleanLit("true")),
new Condition(
new AndExpression(new BooleanLit("true"), new VarReference("check")),
new Print(new StringLit("msg")))));
// When
final var actual = compiler.compile(compilationUnit, CLASS_NAME);
// Then
assertTrue(verifyByteCode(actual).isEmpty());
assertEquals(
readResourceAsString("bytecode/condition/condition_and_boolean_varRef.txt"),
readByteCode(actual));
}
@Test
void testCompile_condition_or_boolean() {
// Given
final var compilationUnit =
createCompilationUnitWithMethod(
List.of(
new Condition(
new OrExpression(new BooleanLit("true"), new BooleanLit("false")),
new Print(new StringLit("msg")))));
// When
final var actual = compiler.compile(compilationUnit, CLASS_NAME);
// Then
assertTrue(verifyByteCode(actual).isEmpty());
assertEquals(
readResourceAsString("bytecode/condition/condition_or_boolean.txt"), readByteCode(actual));
}
@Test
void testCompile_while() {
// Given
final var compilationUnit =
createCompilationUnitWithMethod(
List.of(new While(new BooleanLit("true"), new Print(new StringLit("Looping")))));
// When
final var actual = compiler.compile(compilationUnit, CLASS_NAME);
// Then
assertTrue(verifyByteCode(actual).isEmpty());
assertEquals(readResourceAsString("bytecode/while/while.txt"), readByteCode(actual));
}
@Test
void testCompile_postIncrement() {
// Given
final var compilationUnit =
createCompilationUnitWithMethod(
List.of(
new VarDeclaration("count", new IntLit("5")),
new VarDeclaration("result", new PostIncrement("count"))));
// When
final var actual = compiler.compile(compilationUnit, CLASS_NAME);
// Then
assertTrue(verifyByteCode(actual).isEmpty());
assertEquals(readResourceAsString("bytecode/vardec/varDec_postInc.txt"), readByteCode(actual));
}
@Test
void testCompile_preIncrement() {
// Given
final var compilationUnit =
createCompilationUnitWithMethod(
List.of(
new VarDeclaration("count", new IntLit("5")),
new VarDeclaration("result", new PreIncrement("count"))));
// When
final var actual = compiler.compile(compilationUnit, CLASS_NAME);
// Then
assertTrue(verifyByteCode(actual).isEmpty());
assertEquals(readResourceAsString("bytecode/vardec/varDec_preInc.txt"), readByteCode(actual));
}
@Test
void testCompile_postDecrement() {
// Given
final var compilationUnit =
createCompilationUnitWithMethod(
List.of(
new VarDeclaration("count", new IntLit("5")),
new VarDeclaration("result", new PostDecrement("count"))));
// When
final var actual = compiler.compile(compilationUnit, CLASS_NAME);
// Then
assertTrue(verifyByteCode(actual).isEmpty());
assertEquals(readResourceAsString("bytecode/vardec/varDec_postDec.txt"), readByteCode(actual));
}
@Test
void testCompile_preDecrement() {
// Given
final var compilationUnit =
createCompilationUnitWithMethod(
List.of(
new VarDeclaration("count", new IntLit("5")),
new VarDeclaration("result", new PreDecrement("count"))));
// When
final var actual = compiler.compile(compilationUnit, CLASS_NAME);
// Then
assertTrue(verifyByteCode(actual).isEmpty());
assertEquals(readResourceAsString("bytecode/vardec/varDec_preDec.txt"), readByteCode(actual));
}
@Test
void testCompile_forTraditional() {
// Given
final var compilationUnit =
createCompilationUnitWithMethod(
List.of(
new ForTraditional(
new VarDeclaration("i", new IntLit("0")),
new LessExpression(new VarReference("i"), new IntLit("10")),
new PostIncrement("i"),
new Print(new VarReference("i")))));
// When
final var actual = compiler.compile(compilationUnit, CLASS_NAME);
// Then
assertTrue(verifyByteCode(actual).isEmpty());
assertEquals(readResourceAsString("bytecode/for/for_traditional.txt"), readByteCode(actual));
}
/*
Helper methods
*/
private String readByteCode(byte[] bytes) {
final var stringWriter = new StringWriter();
new ClassReader(bytes).accept(new TraceClassVisitor(new PrintWriter(stringWriter)), 0);
return stringWriter.toString();
}
private String verifyByteCode(byte[] bytes) {
final var stringWriter = new StringWriter();
CheckClassAdapter.verify(new ClassReader(bytes), false, new PrintWriter(stringWriter));
return stringWriter.toString();
}
private CompilationUnit createCompilationUnitWithMethod(List<Statement> statements) {
return new CompilationUnit(
List.of(
new MethodDeclaration(
"main",
List.of(new Parameter(Type.getType(String[].class), "args")),
Type.VOID_TYPE,
new Block(statements))));
}
}
|
package helloworld;
import java.util.Scanner;
public class gugudan {
public static void main(String[] args) {
int j;
System.out.println("구구단 중 출력할 단은?:");
Scanner scanner = new Scanner(System.in);
int number =scanner.nextInt();
for(j=1; j<10; j++)
System.out.println(number + "*" + j + "=" + number * j);
}
}
|
/*******************************************************************************
* Copyright 2011 See AUTHORS file.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package com.badlogic.gdx.scenes.scene2d.ui;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.g2d.NinePatch;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
import com.badlogic.gdx.math.Interpolation;
import com.badlogic.gdx.math.MathUtils;
import com.badlogic.gdx.scenes.scene2d.InputEvent;
import com.badlogic.gdx.scenes.scene2d.InputListener;
import com.badlogic.gdx.scenes.scene2d.utils.ChangeListener.ChangeEvent;
import com.badlogic.gdx.scenes.scene2d.utils.Disableable;
import com.badlogic.gdx.scenes.scene2d.utils.Drawable;
import com.badlogic.gdx.utils.Pools;
/** A slider is a horizontal indicator that allows a user to set a value. The slider has a range (min, max) and a stepping between
* each value the slider represents.
* <p>
* {@link ChangeEvent} is fired when the slider knob is moved. Cancelling the event will move the knob to where it was previously.
* <p>
* The preferred height of a slider is determined by the larger of the knob and background. The preferred width of a slider is
* 140, a relatively arbitrary size.
* @author mzechner
* @author Nathan Sweet */
public class Slider extends Widget implements Disableable {
private SliderStyle style;
private float min, max, stepSize;
private float value, animateFromValue;
private float sliderPos;
private final boolean vertical;
int draggingPointer = -1;
private float animateDuration, animateTime;
private Interpolation animateInterpolation = Interpolation.linear;
private float[] snapValues;
private float threshold;
boolean disabled;
public Slider (float min, float max, float stepSize, boolean vertical, Skin skin) {
this(min, max, stepSize, vertical, skin.get("default-" + (vertical ? "vertical" : "horizontal"), SliderStyle.class));
}
public Slider (float min, float max, float stepSize, boolean vertical, Skin skin, String styleName) {
this(min, max, stepSize, vertical, skin.get(styleName, SliderStyle.class));
}
/** Creates a new slider. It's width is determined by the given prefWidth parameter, its height is determined by the maximum of
* the height of either the slider {@link NinePatch} or slider handle {@link TextureRegion}. The min and max values determine
* the range the values of this slider can take on, the stepSize parameter specifies the distance between individual values.
* E.g. min could be 4, max could be 10 and stepSize could be 0.2, giving you a total of 30 values, 4.0 4.2, 4.4 and so on.
* @param min the minimum value
* @param max the maximum value
* @param stepSize the step size between values
* @param style the {@link SliderStyle} */
public Slider (float min, float max, float stepSize, boolean vertical, SliderStyle style) {
if (min > max) throw new IllegalArgumentException("min must be > max: " + min + " > " + max);
if (stepSize <= 0) throw new IllegalArgumentException("stepSize must be > 0: " + stepSize);
setStyle(style);
this.min = min;
this.max = max;
this.stepSize = stepSize;
this.vertical = vertical;
this.value = min;
setWidth(getPrefWidth());
setHeight(getPrefHeight());
addListener(new InputListener() {
public boolean touchDown (InputEvent event, float x, float y, int pointer, int button) {
if (disabled) return false;
if (draggingPointer != -1) return false;
draggingPointer = pointer;
calculatePositionAndValue(x, y);
return true;
}
public void touchUp (InputEvent event, float x, float y, int pointer, int button) {
if (pointer != draggingPointer) return;
draggingPointer = -1;
if (!calculatePositionAndValue(x, y)) {
// Fire an event on touchUp even if the value didn't change, so listeners can see when a drag ends via isDragging.
ChangeEvent changeEvent = Pools.obtain(ChangeEvent.class);
fire(changeEvent);
Pools.free(changeEvent);
}
}
public void touchDragged (InputEvent event, float x, float y, int pointer) {
calculatePositionAndValue(x, y);
}
});
}
public void setStyle (SliderStyle style) {
if (style == null) throw new IllegalArgumentException("style cannot be null.");
this.style = style;
invalidateHierarchy();
}
/** Returns the slider's style. Modifying the returned style may not have an effect until {@link #setStyle(SliderStyle)} is
* called. */
public SliderStyle getStyle () {
return style;
}
public void act (float delta) {
super.act(delta);
animateTime -= delta;
}
@Override
public void draw (SpriteBatch batch, float parentAlpha) {
SliderStyle style = this.style;
boolean disabled = this.disabled;
final Drawable knob = (disabled && style.disabledKnob != null) ? style.disabledKnob : style.knob;
final Drawable bg = (disabled && style.disabledBackground != null) ? style.disabledBackground : style.background;
final Drawable knobBefore = (disabled && style.disabledKnobBefore != null) ? style.disabledKnobBefore : style.knobBefore;
final Drawable knobAfter = (disabled && style.disabledKnobAfter != null) ? style.disabledKnobAfter : style.knobAfter;
Color color = getColor();
float x = getX();
float y = getY();
float width = getWidth();
float height = getHeight();
float knobHeight = knob == null ? 0 : knob.getMinHeight();
float knobWidth = knob == null ? 0 : knob.getMinWidth();
float value = getVisualValue();
batch.setColor(color.r, color.g, color.b, color.a * parentAlpha);
if (vertical) {
bg.draw(batch, x + (int)((width - bg.getMinWidth()) * 0.5f), y, bg.getMinWidth(), height);
float sliderPosHeight = height - (bg.getTopHeight() + bg.getBottomHeight());
if (min != max) {
sliderPos = (value - min) / (max - min) * (sliderPosHeight - knobHeight);
sliderPos = Math.max(0, sliderPos);
sliderPos = Math.min(sliderPosHeight - knobHeight, sliderPos) + bg.getBottomHeight();
}
float knobHeightHalf = knobHeight * 0.5f;
if (knobBefore != null) {
knobBefore.draw(batch, x + (int)((width - knobBefore.getMinWidth()) * 0.5f), y, knobBefore.getMinWidth(),
(int)(sliderPos + knobHeightHalf));
}
if (knobAfter != null) {
knobAfter.draw(batch, x + (int)((width - knobAfter.getMinWidth()) * 0.5f), y + (int)(sliderPos + knobHeightHalf),
knobAfter.getMinWidth(), height - (int)(sliderPos + knobHeightHalf));
}
if (knob != null) knob.draw(batch, x + (int)((width - knobWidth) * 0.5f), (int)(y + sliderPos), knobWidth, knobHeight);
} else {
bg.draw(batch, x, y + (int)((height - bg.getMinHeight()) * 0.5f), width, bg.getMinHeight());
float sliderPosWidth = width - (bg.getLeftWidth() + bg.getRightWidth());
if (min != max) {
sliderPos = (value - min) / (max - min) * (sliderPosWidth - knobWidth);
sliderPos = Math.max(0, sliderPos);
sliderPos = Math.min(sliderPosWidth - knobWidth, sliderPos) + bg.getLeftWidth();
}
float knobHeightHalf = knobHeight * 0.5f;
if (knobBefore != null) {
knobBefore.draw(batch, x, y + (int)((height - knobBefore.getMinHeight()) * 0.5f), (int)(sliderPos + knobHeightHalf),
knobBefore.getMinHeight());
}
if (knobAfter != null) {
knobAfter.draw(batch, x + (int)(sliderPos + knobHeightHalf), y + (int)((height - knobAfter.getMinHeight()) * 0.5f),
width - (int)(sliderPos + knobHeightHalf), knobAfter.getMinHeight());
}
if (knob != null)
knob.draw(batch, (int)(x + sliderPos), (int)(y + (height - knobHeight) * 0.5f), knobWidth, knobHeight);
}
}
boolean calculatePositionAndValue (float x, float y) {
final Drawable knob = (disabled && style.disabledKnob != null) ? style.disabledKnob : style.knob;
final Drawable bg = (disabled && style.disabledBackground != null) ? style.disabledBackground : style.background;
float value;
float oldPosition = sliderPos;
if (vertical) {
float height = getHeight() - bg.getTopHeight() - bg.getBottomHeight();
float knobHeight = knob == null ? 0 : knob.getMinHeight();
sliderPos = y - bg.getBottomHeight() - knobHeight * 0.5f;
value = min + (max - min) * (sliderPos / (height - knobHeight));
sliderPos = Math.max(0, sliderPos);
sliderPos = Math.min(height - knobHeight, sliderPos);
} else {
float width = getWidth() - bg.getLeftWidth() - bg.getRightWidth();
float knobWidth = knob == null ? 0 : knob.getMinWidth();
sliderPos = x - bg.getLeftWidth() - knobWidth * 0.5f;
value = min + (max - min) * (sliderPos / (width - knobWidth));
sliderPos = Math.max(0, sliderPos);
sliderPos = Math.min(width - knobWidth, sliderPos);
}
float oldValue = value;
boolean valueSet = setValue(value);
if (value == oldValue) sliderPos = oldPosition;
return valueSet;
}
/** Returns true if the slider is being dragged. */
public boolean isDragging () {
return draggingPointer != -1;
}
public float getValue () {
return value;
}
/** If {@link #setAnimateDuration(float) animating} the slider value, this returns the value current displayed. */
public float getVisualValue () {
if (animateTime > 0) return animateInterpolation.apply(animateFromValue, value, 1 - animateTime / animateDuration);
return value;
}
/** Sets the slider position, rounded to the nearest step size and clamped to the minumum and maximim values.
* {@link #clamp(float)} can be overidden to allow values outside of the sliders min/max range.
* @return false if the value was not changed because the slider already had the value or it was canceled by a listener. */
public boolean setValue (float value) {
value = snap(clamp(Math.round(value / stepSize) * stepSize));
float oldValue = this.value;
if (value == oldValue) return false;
float oldVisualValue = getVisualValue();
this.value = value;
ChangeEvent changeEvent = Pools.obtain(ChangeEvent.class);
boolean cancelled = fire(changeEvent);
if (cancelled)
this.value = oldValue;
else if (animateDuration > 0) {
animateFromValue = oldVisualValue;
animateTime = animateDuration;
}
Pools.free(changeEvent);
return !cancelled;
}
/** Clamps the value to the sliders min/max range. This can be overidden to allow a range different from the slider knob's
* range. */
protected float clamp (float value) {
return MathUtils.clamp(value, min, max);
}
/** Sets the range of this slider. The slider's current value is reset to min. */
public void setRange (float min, float max) {
if (min > max) throw new IllegalArgumentException("min must be <= max");
this.min = min;
this.max = max;
if (value < min)
setValue(min);
else if (value > max) setValue(max);
}
/** Sets the step size of the slider */
public void setStepSize (float stepSize) {
if (stepSize <= 0) throw new IllegalArgumentException("steps must be > 0: " + stepSize);
this.stepSize = stepSize;
}
public float getPrefWidth () {
if (vertical) {
final Drawable knob = (disabled && style.disabledKnob != null) ? style.disabledKnob : style.knob;
final Drawable bg = (disabled && style.disabledBackground != null) ? style.disabledBackground : style.background;
return Math.max(knob == null ? 0 : knob.getMinWidth(), bg.getMinWidth());
} else
return 140;
}
public float getPrefHeight () {
if (vertical)
return 140;
else {
final Drawable knob = (disabled && style.disabledKnob != null) ? style.disabledKnob : style.knob;
final Drawable bg = (disabled && style.disabledBackground != null) ? style.disabledBackground : style.background;
return Math.max(knob == null ? 0 : knob.getMinHeight(), bg.getMinHeight());
}
}
public float getMinValue () {
return this.min;
}
public float getMaxValue () {
return this.max;
}
public float getStepSize () {
return this.stepSize;
}
/** If > 0, changes to the slider value via {@link #setValue(float)} will happen over this duration in seconds. */
public void setAnimateDuration (float duration) {
this.animateDuration = duration;
}
/** Sets the interpolation to use for {@link #setAnimateDuration(float)}. */
public void setAnimateInterpolation (Interpolation animateInterpolation) {
if (animateInterpolation == null) throw new IllegalArgumentException("animateInterpolation cannot be null.");
this.animateInterpolation = animateInterpolation;
}
/** Will make this slider snap to the specified values, if the knob is within the threshold */
public void setSnapToValues (float[] values, float threshold) {
this.snapValues = values;
this.threshold = threshold;
}
/** Returns a snapped value, or the original value */
private float snap (float value) {
if (snapValues == null) return value;
for (int i = 0; i < snapValues.length; i++) {
if (Math.abs(value - snapValues[i]) <= threshold) return snapValues[i];
}
return value;
}
public void setDisabled (boolean disabled) {
this.disabled = disabled;
}
public boolean isDisabled () {
return disabled;
}
/** The style for a slider, see {@link Slider}.
* @author mzechner
* @author Nathan Sweet */
static public class SliderStyle {
/** The slider background, stretched only in one direction. */
public Drawable background;
/** Optional. **/
public Drawable disabledBackground;
/** Optional, centered on the background. */
public Drawable knob, disabledKnob;
/** Optional. */
public Drawable knobBefore, knobAfter, disabledKnobBefore, disabledKnobAfter;
public SliderStyle () {
}
public SliderStyle (Drawable background, Drawable knob) {
this.background = background;
this.knob = knob;
}
public SliderStyle (SliderStyle style) {
this.background = style.background;
this.knob = style.knob;
}
}
}
|
package com.yinghai.a24divine_user.wxapi.wechatLogin;
import android.app.Activity;
import android.os.Bundle;
import com.tencent.mm.opensdk.modelbase.BaseReq;
import com.tencent.mm.opensdk.modelbase.BaseResp;
import com.tencent.mm.opensdk.openapi.IWXAPIEventHandler;
/**
* Created by chenjianrun on 2017/5/4.
*/
public abstract class WXEntryBaseActivity extends Activity implements IWXAPIEventHandler {
private static final String TAG = "WXEntryBaseActivity";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
WechatLogin.getInstance().getIwxapi().handleIntent(getIntent(),this);
}
/**
* 设置 APPID
* @return
*/
// public abstract String getAppId();
@Override
public void onReq(BaseReq baseReq) {
}
@Override
public void onResp(BaseResp baseResp) {
WechatLogin.getInstance().onResp(baseResp);
finish();
}
}
|
package com.yeahbunny.stranger.server.controller.dto.request;
import java.util.Calendar;
import javax.validation.constraints.NotNull;
import org.hibernate.validator.constraints.NotBlank;
import org.hibernate.validator.constraints.NotEmpty;
import io.swagger.annotations.ApiModelProperty;
/**
* Created by kroli on 30.05.2017.
*/
public class RegistrationRequest {
@ApiModelProperty(required = true)
@NotNull
@NotBlank
private String login;
@ApiModelProperty(required = true)
@NotNull
@NotBlank
private String hashedPw;
private Calendar birthdate;
@NotNull
private boolean female;
public String getLogin() {
return login;
}
public void setLogin(String login) {
this.login = login;
}
public String getHashedPw() {
return hashedPw;
}
public void setHashedPw(String hashedPw) {
this.hashedPw = hashedPw;
}
public Calendar getBirthdate() {
return birthdate;
}
public void setBirthdate(Calendar birthdate) {
this.birthdate = birthdate;
}
public boolean isFemale() {
return female;
}
public void setFemale(boolean female) {
this.female = female;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.