text stringlengths 10 2.72M |
|---|
package com.example.dtps.dtpsforum;
import android.content.Intent;
import android.graphics.Paint;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.toolbox.Volley;
import org.json.JSONException;
import org.json.JSONObject;
import org.w3c.dom.Text;
public class PostsActivity extends AppCompatActivity { /*implements View.OnClickListener*/
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_posts);
/*old GUI for postsActivity*/
final EditText tvPost1 = (EditText) findViewById(R.id.tvPost1);
final EditText tvPost2 = (EditText) findViewById(R.id.tvPost2);
final EditText tvPost3 = (EditText) findViewById(R.id.tvPost3);
final TextView tvMember1 = (TextView) findViewById(R.id.tvMember1);
final TextView tvMember2 = (TextView) findViewById(R.id.tvMember2);
final TextView tvMember3 = (TextView) findViewById(R.id.tvMember3);
/* final TextView tpc_name = (TextView) findViewById(R.id.tpc_name);*/
final TextView top_tlt = (TextView)findViewById(R.id.top_tlt);
/* set text username in txv in posted by*/
/*For Topic Android Tutorial get username and topic_title*/
Intent AndroidPosts= getIntent();
String UserName = AndroidPosts.getStringExtra("username");
String message = "Posted by " + UserName;
tvMember1.setText(message);
tvMember1.setPaintFlags(tvMember1.getPaintFlags() | Paint.UNDERLINE_TEXT_FLAG);
tvMember1.setVisibility(tvMember1.INVISIBLE);
tvMember2.setText(message);
tvMember2.setPaintFlags(tvMember2.getPaintFlags() | Paint.UNDERLINE_TEXT_FLAG);
tvMember2.setVisibility(tvMember2.INVISIBLE);
tvMember3.setText(UserName);
tvMember3.setVisibility(tvMember3.INVISIBLE);
String tpc_nm = AndroidPosts.getStringExtra("topic_title");
top_tlt.setText(tpc_nm);
/*For topic Cellular Networks*/
Intent NetPosts= getIntent();
String UrName = NetPosts.getStringExtra("username");
String msg = "Posted by " + UrName;
tvMember1.setText(msg);
tvMember1.setPaintFlags(tvMember1.getPaintFlags() | Paint.UNDERLINE_TEXT_FLAG);
tvMember1.setVisibility(tvMember1.INVISIBLE);
tvMember2.setText(msg);
tvMember2.setPaintFlags(tvMember2.getPaintFlags() | Paint.UNDERLINE_TEXT_FLAG);
tvMember2.setVisibility(tvMember2.INVISIBLE);
String tpc_name = NetPosts.getStringExtra("topic_title");
top_tlt.setText(tpc_name);
/*For new topic*/
Intent posts= getIntent();
final String UsrNm = posts.getStringExtra("username");
String mesag = "Posted by " + UsrNm;
tvMember1.setText(mesag);
tvMember1.setPaintFlags(tvMember1.getPaintFlags() | Paint.UNDERLINE_TEXT_FLAG);
tvMember1.setVisibility(tvMember1.INVISIBLE);
tvMember2.setText(mesag);
tvMember2.setPaintFlags(tvMember2.getPaintFlags() | Paint.UNDERLINE_TEXT_FLAG);
tvMember2.setVisibility(tvMember2.INVISIBLE);
/*Get newtopicTitle from topicActivity*/
String Topic_name = posts.getStringExtra("topic_title");
top_tlt.setText(Topic_name);
top_tlt.setVisibility(top_tlt.INVISIBLE);
ImageView return_to_mainpage = (ImageView) findViewById(R.id.return_to_mainpage);
return_to_mainpage.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent return_to_main = new Intent(PostsActivity.this, MainActivity.class);
startActivity(return_to_main);
}
});
Button post1But = (Button) findViewById(R.id.post1But);
post1But.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String username = tvMember3.getText().toString();
String topic_title = top_tlt.getText().toString();
String post_text = tvPost1.getText().toString();
tvMember1.setVisibility(tvMember1.VISIBLE);
Response.Listener<String> responseListener = new Response.Listener<String>() {
@Override
public void onResponse(String response) {
try {
JSONObject jsonResponse = new JSONObject(response);
boolean success = jsonResponse.getBoolean("success");
if (success) {
String topic_title = jsonResponse.getString("post_subject");
String post_text = jsonResponse.getString("post_text");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
};
PostRequest postRequest = new PostRequest(username,topic_title,post_text, responseListener);
RequestQueue queue = Volley.newRequestQueue(PostsActivity.this);
queue.add(postRequest);
}
});
/*Button post2But = (Button) findViewById(R.id.post2But);
post2But.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String post_text = tvPost2.getText().toString();
tvMember2.setVisibility(tvMember2.VISIBLE);
Response.Listener<String> responseListener = new Response.Listener<String>() {
@Override
public void onResponse(String response) {
try {
JSONObject jsonResponse = new JSONObject(response);
boolean success = jsonResponse.getBoolean("success");
if (success) {
String post_text = jsonResponse.getString("post_text");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
};
PostRequest postRequest = new PostRequest(topic_title,post_text, responseListener);
RequestQueue queue = Volley.newRequestQueue(PostsActivity.this);
queue.add(postRequest);
}
});
Button post3But = (Button) findViewById(R.id.post3But);
post3But.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String post_text = tvPost3.getText().toString();
Response.Listener<String> responseListener = new Response.Listener<String>() {
@Override
public void onResponse(String response) {
try {
JSONObject jsonResponse = new JSONObject(response);
boolean success = jsonResponse.getBoolean("success");
if (success) {
String post_text = jsonResponse.getString("post_text");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
};
PostRequest postRequest = new PostRequest(topic_title,post_text, responseListener);
RequestQueue queue = Volley.newRequestQueue(PostsActivity.this);
queue.add(postRequest);
}
});
*/
}
}
|
package com.ranpeak.ProjectX.activity.lobby.forGuestUsers.fragments;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import com.baoyz.widget.PullRefreshLayout;
import com.ranpeak.ProjectX.R;
import com.ranpeak.ProjectX.activity.interfaces.Activity;
import com.ranpeak.ProjectX.activity.lobby.commands.ResumeNavigator;
import com.ranpeak.ProjectX.activity.lobby.forAuthorizedUsers.navigationFragment.resumesNavFragment.adapter.ResumeListAdapter;
import com.ranpeak.ProjectX.activity.lobby.viewModel.ResumeViewModel;
import com.ranpeak.ProjectX.dto.ResumeDTO;
import java.util.ArrayList;
import java.util.List;
public class FragmentResumes extends Fragment implements Activity, ResumeNavigator {
private View view;
private RecyclerView recyclerView;
private ResumeListAdapter resumeListAdapter;
private List<ResumeDTO> data = new ArrayList<>();
private ArrayList<String> imageUrls = new ArrayList<>();
private ResumeViewModel resumeViewModel;
PullRefreshLayout pullRefreshLayout;
public FragmentResumes() {
}
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fargment_lobby_list_resume,container,false);
resumeViewModel = new ResumeViewModel(getContext());
resumeViewModel.setNavigator(this);
findViewById();
typeRefresh();
onListener();
initImageBitmaps();
setupAdapter();
getResumes();
return view;
}
private void typeRefresh() {
pullRefreshLayout.setRefreshStyle(PullRefreshLayout.STYLE_SMARTISAN);
}
@Override
public void findViewById() {
pullRefreshLayout = view.findViewById(R.id.refresh_resumes);
recyclerView = view.findViewById(R.id.recycler_resumes);
}
@Override
public void onListener() {
pullRefreshLayout.setOnRefreshListener(() -> {
final Handler handler = new Handler();
handler.postDelayed(() -> {
getResumes();
pullRefreshLayout.setRefreshing(false);
}, 1000);
});
}
@Override
public void handleError(Throwable throwable) {
Toast.makeText(getContext(),"Resumes don`t upload",Toast.LENGTH_LONG).show();
}
@Override
public void getDataInAdapter(List<ResumeDTO> resumeDTOS) {
data.clear();
data.addAll(resumeDTOS);
resumeListAdapter.notifyDataSetChanged();
}
private void initImageBitmaps() {
imageUrls.add("https://cdn.fishki.net/upload/post/2017/03/19/2245758/01-beautiful-white-cat-imagescar-wallpaper.jpg");
imageUrls.add("https://usionline.com/wp-content/uploads/2016/02/12-4.jpg");
imageUrls.add("http://bm.img.com.ua/nxs/img/prikol/images/large/1/2/308321_879390.jpg");
imageUrls.add("http://bm.img.com.ua/nxs/img/prikol/images/large/1/2/308321_879389.jpg");
imageUrls.add("http://www.radionetplus.ru/uploads/posts/2013-05/1369460621_panda-26.jpg");
imageUrls.add("http://v.img.com.ua/b/1100x999999/1/fc/409a3eebc81a4d8dc4a2437cbe07afc1.jpg");
imageUrls.add("http://ztb.kz/media/imperavi/59cb70c479d20.jpg");
imageUrls.add("https://bryansktoday.ru/uploads/common/dcbf021231e742e6_XL.jpg");
imageUrls.add("https://ki.ill.in.ua/m/670x450/24227758.jpg");
imageUrls.add("https://cs9.pikabu.ru/post_img/2017/10/06/7/1507289738144386744.jpg");
imageUrls.add("https://placepic.ru/uploads/posts/2014-03/1396234652_podborka-realnyh-pacanov-2.jpg");
imageUrls.add("http://2queens.ru/Uploads/Yelizaveta/%D1%80%D0%B5%D0%B0%D0%BB%D1%8C%D0%BD%D1%8B%D0%B9%20%D0%BF%D0%B0%D1%86%D0%B0%D0%BD%20%D1%80%D0%B6%D0%B0%D0%B2%D1%8B%D0%B9.jpg");
imageUrls.add("http://bidla.net/uploads/posts/2017-06/thumbs/1496943807_urodru20170608ku7564.jpeg");
imageUrls.add("https://www.baikal-daily.ru/upload/resize_cache/iblock/ca6/600_500_1/vovan.png");
imageUrls.add("https://www.vokrug.tv/pic/person/b/3/6/d/b36d3d2f4c263fc18eba1a464eb942d2.jpeg");
imageUrls.add("https://i.mycdn.me/image?id=877079192648&t=35&plc=WEB&tkn=*85PLfcQAXU8Glv9V8-xzIyJxZF4");
}
private void setupAdapter(){
resumeListAdapter = new ResumeListAdapter(data,imageUrls,recyclerView,getActivity());
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
recyclerView.setAdapter(resumeListAdapter);
}
private void getResumes(){
resumeViewModel.getResumesFromServer();
}
}
|
package com.lenovohit.hcp.test.db.model;
import com.lenovohit.core.utils.StringUtils;
public class Column {
public Column(Object obj){
Object[] array = (Object[])obj;
this.setColumnName(array[0].toString());
this.setDataType(array[1].toString());
this.setColumnComment(array[2].toString());
}
public Column(String columnName,String dataType,String columnComment){
this.columnName =columnName;
this.dataType =dataType;
this.columnComment =columnComment;
}
private String columnName;
private String dataType;
private String columnComment;
public String getColumnName() {
return columnName;
}
public void setColumnName(String columnName) {
this.columnName = columnName;
}
public String getDataType() {
return dataType;
}
public void setDataType(String dataType) {
this.dataType = dataType;
}
public String getColumnComment() {
return columnComment;
}
public void setColumnComment(String columnComment) {
this.columnComment = columnComment;
}
public String toModel(){
StringBuilder sb = new StringBuilder();
sb.append("private ");
sb.append(getType(this.dataType)).append(" ");
sb.append(getName(this.columnName));
sb.append(";");
if(!StringUtils.isEmpty(this.columnComment))
sb.append(" //").append(this.columnComment);
return sb.toString();
}
private String getType(String type){
if("char".equals(type.toLowerCase())
||"varchar".equals(type.toLowerCase())
||"varchar2".equals(type.toLowerCase())
){
return "String";
}else if("datetime".equals(type.toLowerCase())) {
return "Date";
}else {
return "String";
}
}
private String getName(String name){
String low = name.toLowerCase();
String[] ns = low.split("_");
StringBuilder sb=new StringBuilder();
for(int i=0 ; i < ns.length;i++){
if(i==0)sb.append( ns[i]);
else{
String v = ns[i];
sb.append( v.substring(0, 1).toUpperCase());
sb.append( v.substring(1));
}
}
return sb.toString();
}
}
|
package com.xbang.bootdemo.controller;
import com.xbang.bootdemo.dao.entity.TMoney;
import com.xbang.bootdemo.service.face.ITMoneyService;
import com.xbang.bootdemo.utils.DistributedLockUtils;
import com.xbang.bootdemo.utils.TOOL;
import com.xbang.commons.exception.BaseException;
import com.xbang.commons.vo.result.BaseResult;
import com.xbang.commons.vo.result.Result;
import com.xbang.commons.vo.result.ResultEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
/**
* <p>
* 前端控制器
* </p>
*
* @author xbang
* @since 2019-09-20
*/
@RestController
@RequestMapping("/tMoney")
public class TMoneyController {
private final ITMoneyService itMoneyService;
@Autowired
public TMoneyController(ITMoneyService itMoneyService) {
this.itMoneyService = itMoneyService;
}
@RequestMapping("increase")
public Result increase(@RequestParam("id") Long id){
itMoneyService.increase(id);
return Result.getResult(ResultEnum.RESULT_SUCCESS);
}
@RequestMapping("decrease")
public Result decrease(@RequestParam("id") Long id){
itMoneyService.decrease(id);
return Result.getResult(ResultEnum.RESULT_SUCCESS);
}
@RequestMapping("/increase/optimisticlock")
public Result increaseOptimisticlock(@RequestParam("id") Long id){
itMoneyService.increaseWithOptimisticLock(id);
return Result.getResult(ResultEnum.RESULT_SUCCESS);
}
@RequestMapping("/decrease/optimisticlock")
public Result decreaseOptimisticlock(@RequestParam("id") Long id){
itMoneyService.decreaseWithOptimisticLock(id);
return Result.getResult(ResultEnum.RESULT_SUCCESS);
}
@RequestMapping("statistical")
public Result statistical(){
Map<String,Long> resultMap = new HashMap<>();
resultMap.put("success", TOOL.getSuccessCount());
resultMap.put("fail",TOOL.getFailCount());
resultMap.put("total",TOOL.getTotal());
return BaseResult.getResult(ResultEnum.RESULT_SUCCESS,resultMap);
}
@RequestMapping("clear")
public Result clear(){
Result result = statistical();
TOOL.clear();
return result;
}
@RequestMapping("/increaseWithDistributedLock")
public Result increaseWithDistributedLock(@RequestParam("id") Long id , HttpServletRequest request){
request.setAttribute("requestId",UUID.randomUUID().toString());
itMoneyService.increaseWithDistributedLock(id);
return Result.getResult(ResultEnum.RESULT_SUCCESS);
}
@RequestMapping("decreaseWithDistributedLock")
public Result decreaseWithDistributedLock(@RequestParam("id") Long id){
itMoneyService.decreaseWithDistributedLock(id);
return Result.getResult(ResultEnum.RESULT_SUCCESS);
}
@Autowired
DistributedLockUtils distributedLockUtils;
@RequestMapping("getStatisticalInfo")
public Result getStatisticalInfo(){
return BaseResult.getResult(ResultEnum.RESULT_SUCCESS,distributedLockUtils.getStatisticalInfo());
}
@RequestMapping("clearStatisticalInfo")
public Result clearStatisticalInfo(){
return BaseResult.getResult(ResultEnum.RESULT_SUCCESS,distributedLockUtils.clearStatisticalInfo());
}
@ExceptionHandler(BaseException.class)
public Result exception(BaseException baseException){
return BaseResult.getResult(ResultEnum.RESULT_EXCEPTION,baseException.getError_msg());
}
}
|
package trunk.Model;
/**
* Created by sadaf345 on 4/14/2016.
*/
public interface WatchlistVisitor {
public void visit(Portfolio p);
}
|
package fmi;
public class Lamborghini implements Car {
@Override
public void create() {
System.out.println("Car: Lambo");
}
}
|
package fr.univsavoie.istoage.clienttri;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.annotation.XmlElementDecl;
import javax.xml.bind.annotation.XmlRegistry;
import javax.xml.namespace.QName;
/**
* This object contains factory methods for each
* Java content interface and Java element interface
* generated in the fr.univsavoie.istoage.soaptri package.
* <p>An ObjectFactory allows you to programatically
* construct new instances of the Java representation
* for XML content. The Java representation of XML
* content can consist of schema derived interfaces
* and classes representing the binding of schema
* type definitions, element declarations and model
* groups. Factory methods for each of these are
* provided in this class.
*
*/
@XmlRegistry
public class ObjectFactory {
private final static QName _StageSortResponse_QNAME = new QName("http://soaptri.istoage.univsavoie.fr/", "stageSortResponse");
private final static QName _StageSort_QNAME = new QName("http://soaptri.istoage.univsavoie.fr/", "stageSort");
/**
* Create a new ObjectFactory that can be used to create new instances of schema derived classes for package: fr.univsavoie.istoage.soaptri
*
*/
public ObjectFactory() {
}
/**
* Create an instance of {@link StageSortResponse }
*
*/
public StageSortResponse createStageSortResponse() {
return new StageSortResponse();
}
/**
* Create an instance of {@link StageSort_Type }
*
*/
public StageSort_Type createStageSort_Type() {
return new StageSort_Type();
}
/**
* Create an instance of {@link JAXBElement }{@code <}{@link StageSortResponse }{@code >}}
*
*/
@XmlElementDecl(namespace = "http://soaptri.istoage.univsavoie.fr/", name = "stageSortResponse")
public JAXBElement<StageSortResponse> createStageSortResponse(StageSortResponse value) {
return new JAXBElement<StageSortResponse>(_StageSortResponse_QNAME, StageSortResponse.class, null, value);
}
/**
* Create an instance of {@link JAXBElement }{@code <}{@link StageSort_Type }{@code >}}
*
*/
@XmlElementDecl(namespace = "http://soaptri.istoage.univsavoie.fr/", name = "stageSort")
public JAXBElement<StageSort_Type> createStageSort(StageSort_Type value) {
return new JAXBElement<StageSort_Type>(_StageSort_QNAME, StageSort_Type.class, null, value);
}
}
|
/**
* Created with IntelliJ IDEA.
* User: dexctor
* Date: 12-11-26
* Time: 下午1:47
* To change this template use File | Settings | File Templates.
*/
public class p2_1_12 {
public static double time(String alg, Comparable[] a)
{
Stopwatch timer = new Stopwatch();
ShellSort.sort(a);
return timer.elapsedTime();
}
public static double timeRandomInput(String alg, int N, int T)
{
double total = 0.0;
Double[] a = new Double[N];
for(int t = 0; t < T; ++t)
{
for(int i = 0; i < N; ++i)
a[i] = StdRandom.uniform();
total += time(alg, a);
}
return total / T;
}
public static void main(String[] args)
{
for(int N = 100; true; N *= 10)
{
StdOut.println(timeRandomInput(null, N, 10));
}
}
}
|
package com.github.fierioziy.particlenativetest.command;
import com.github.fierioziy.particlenativeapi.api.ParticleNativeAPI;
import com.github.fierioziy.particlenativeapi.api.packet.ParticlePacket;
import com.github.fierioziy.particlenativetest.ParticleNativeTestPlugin;
import com.github.fierioziy.particlenativetest.command.utils.*;
import org.bukkit.ChatColor;
import org.bukkit.Location;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.scheduler.BukkitRunnable;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
public class CommandPNAT implements CommandExecutor {
private final ParticleNativeTestPlugin plugin;
private final ParticleNativeAPI particleApi;
public CommandPNAT(ParticleNativeTestPlugin plugin) {
this.plugin = plugin;
this.particleApi = plugin.getAPI();
}
public boolean onCommand(CommandSender sender, Command cmd, String s, String[] args) {
if (!(sender instanceof Player)) {
sender.sendMessage(ChatColor.RED + "This command is designed for players!");
return true;
}
Player p = (Player) sender;
if (!p.isOp()) {
sender.sendMessage(ChatColor.RED + "This is command for OP users only!");
return true;
}
if (args.length != 2) {
p.sendMessage(ChatColor.RED + "Wrong syntax, use /pnat <1.8/1.13/1.19> <speed>");
p.sendMessage(ChatColor.RED + "To cancel particles, tap 3 times crouch.");
return true;
}
double speed;
try {
speed = Double.parseDouble(args[1]);
}
catch (NumberFormatException e) {
p.sendMessage(ChatColor.RED + "Its not a number!");
return true;
}
if (speed < 0.0) {
p.sendMessage(ChatColor.RED + "Number must be positive!");
return true;
}
// this is hard-coded because reflected elements doesn't have strict order
switch (args[0]) {
case "1.8": {
testParticles(p, speed, particleApi.LIST_1_8, ParticleListFields_1_8.FIELDS);
break;
}
case "1.13": {
testParticles(p, speed, particleApi.LIST_1_13, ParticleListFields_1_13.FIELDS);
break;
}
case "1.19": {
testParticles(p, speed, particleApi.LIST_1_19_PART, ParticleListFields_1_19.FIELDS);
break;
}
default: {
p.sendMessage(ChatColor.RED + "Wrong syntax, use /pnat <1.8/1.13/1.19>");
break;
}
}
return true;
}
private void testParticles(final Player player, final double speed,
final Object particleListObj, final String[] particleTypeFieldNames) {
final List<Player> players = player.getWorld().getPlayers();
new BukkitRunnable() {
private final Location startLoc = player.getLocation().add(0D, 0.5D, 0D);
private final SneakToggle sneakToggle = new SneakToggle();
private int ticks = 0;
private final int waitPeriod = 10;
@Override
public void run() {
if (!player.isOnline())
this.cancel();
sneakToggle.tick(player.isSneaking());
if (sneakToggle.isFinished()) {
this.cancel();
return;
}
if (ticks < waitPeriod) {
++ticks;
return;
}
else {
ticks = 0;
}
int packetsGroupsLen = 6;
List<PacketFactory> packetFactories = new ArrayList<>(packetsGroupsLen);
for (int i = 0; i < packetsGroupsLen; ++i) {
packetFactories.add(new PacketFactory(
player,
new Location(startLoc.getWorld(), startLoc.getX(), startLoc.getY() + i, startLoc.getZ()),
speed
));
}
for (String particleTypeFieldName : particleTypeFieldNames) {
Field particleTypeField;
try {
particleTypeField = particleListObj
.getClass()
.getField(particleTypeFieldName);
}
catch (NoSuchFieldException e) {
player.sendMessage(ChatColor.RED + "Field " + particleTypeFieldName + " does not exist");
this.cancel();
return;
}
try {
// this looks awful, but I want it that way
List<List<ParticlePacket>> packetsGroups = new ArrayList<>(packetsGroupsLen);
for (PacketFactory packetFactory : packetFactories) {
packetsGroups.add(packetFactory.createPackets(
particleListObj, particleTypeField
));
}
packetsGroups.get(0).forEach(packet -> packet.sendTo(player));
packetsGroups.get(1).forEach(packet -> packet.sendTo(players));
packetsGroups.get(2).forEach(packet -> packet.sendTo(players, Player::isSneaking));
packetsGroups.get(3).forEach(packet -> packet.sendInRadiusTo(player, 5D));
packetsGroups.get(4).forEach(packet -> packet.sendInRadiusTo(players, 5D));
packetsGroups.get(5).forEach(packet -> packet.sendInRadiusTo(players, 5D, Player::isSneaking));
}
catch (IllegalAccessException e) {
player.sendMessage(ChatColor.RED + "Cast error on particle " + particleTypeField.getName());
this.cancel();
return;
}
for (PacketFactory packetFactory : packetFactories) {
packetFactory.getSpawnLocation().add(1D, 0D, 0D);
}
}
}
}.runTaskTimer(plugin, 0L, 1L);
}
}
|
package com.example.narubibi.findate._Chat.ViewHolder;
import android.view.View;
import android.widget.ImageView;
import com.bumptech.glide.Glide;
import com.example.narubibi.findate.R;
import com.example.narubibi.findate._Chat.Message;
public class StickerHolder extends ChatObjectHolder {
ImageView stickerImg;
StickerHolder(View itemView) {
super(itemView);
stickerImg = itemView.findViewById(R.id.text_message_body);
stickerImg.setOnClickListener(this);
}
void bind(Message message) {
super.bind(message);
Glide.with(stickerImg.getContext()).load(message.getMessage()).into(stickerImg);
}
}
|
package us.ihmc.euclid.referenceFrame.interfaces;
import us.ihmc.euclid.geometry.interfaces.BoundingBox3DBasics;
import us.ihmc.euclid.referenceFrame.FramePoint3D;
import us.ihmc.euclid.referenceFrame.ReferenceFrame;
import us.ihmc.euclid.referenceFrame.exceptions.ReferenceFrameMismatchException;
import us.ihmc.euclid.referenceFrame.tools.EuclidFrameShapeTools;
import us.ihmc.euclid.shape.primitives.interfaces.Capsule3DReadOnly;
/**
* Read-only interface for a capsule 3D expressed in given reference frame.
* <p>
* A capsule 3D is represented by its length, i.e. the distance separating the center of the two
* half-spheres, its radius, the position of its center, and its axis of revolution.
* </p>
*
* @author Sylvain Bertrand
*/
public interface FrameCapsule3DReadOnly extends Capsule3DReadOnly, FrameShape3DReadOnly
{
/** {@inheritDoc} */
@Override
FramePoint3DReadOnly getPosition();
/** {@inheritDoc} */
@Override
FrameUnitVector3DReadOnly getAxis();
/**
* {@inheritDoc}
* <p>
* Note that the centroid is also the position of this capsule.
* </p>
*/
@Override
default FramePoint3DReadOnly getCentroid()
{
return getPosition();
}
/** {@inheritDoc} */
@Override
default FramePoint3DReadOnly getTopCenter()
{
FramePoint3D topCenter = new FramePoint3D(getReferenceFrame());
topCenter.scaleAdd(getHalfLength(), getAxis(), getPosition());
return topCenter;
}
/** {@inheritDoc} */
@Override
default FramePoint3DReadOnly getBottomCenter()
{
FramePoint3D bottomCenter = new FramePoint3D(getReferenceFrame());
bottomCenter.scaleAdd(-getHalfLength(), getAxis(), getPosition());
return bottomCenter;
}
/** {@inheritDoc} */
@Override
default void getBoundingBox(BoundingBox3DBasics boundingBoxToPack)
{
FrameShape3DReadOnly.super.getBoundingBox(boundingBoxToPack);
}
/** {@inheritDoc} */
@Override
default void getBoundingBox(ReferenceFrame destinationFrame, BoundingBox3DBasics boundingBoxToPack)
{
EuclidFrameShapeTools.boundingBoxCapsule3D(this, destinationFrame, boundingBoxToPack);
}
/**
* Returns {@code null} as this shape is not defined by a pose.
*/
@Override
default FrameShape3DPoseReadOnly getPose()
{
return null;
}
/** {@inheritDoc} */
@Override
FixedFrameCapsule3DBasics copy();
/**
* Tests on a per component basis if this capsule and {@code other} are equal to an {@code epsilon}.
* <p>
* If the two capsules have different frames, this method returns {@code false}.
* </p>
*
* @param other the other capsule to compare against this. Not modified.
* @param epsilon tolerance to use when comparing each component.
* @return {@code true} if the two capsules are equal component-wise and are expressed in the same
* reference frame, {@code false} otherwise.
*/
default boolean epsilonEquals(FrameCapsule3DReadOnly other, double epsilon)
{
if (getReferenceFrame() != other.getReferenceFrame())
return false;
else
return Capsule3DReadOnly.super.epsilonEquals(other, epsilon);
}
/**
* Compares {@code this} to {@code other} to determine if the two capsules are geometrically
* similar.
*
* @param other the other capsule to compare against this. Not modified.
* @param epsilon the tolerance of the comparison.
* @return {@code true} if the two capsules represent the same geometry, {@code false} otherwise.
* @throws ReferenceFrameMismatchException if {@code this} and {@code other} are not expressed in
* the same reference frame.
*/
default boolean geometricallyEquals(FrameCapsule3DReadOnly other, double epsilon)
{
checkReferenceFrameMatch(other);
return Capsule3DReadOnly.super.geometricallyEquals(other, epsilon);
}
/**
* Tests on a per component basis, if this capsule 3D is exactly equal to {@code other}.
* <p>
* If the two capsules have different frames, this method returns {@code false}.
* </p>
*
* @param other the other capsule 3D to compare against this. Not modified.
* @return {@code true} if the two capsules are exactly equal component-wise and are expressed in
* the same reference frame, {@code false} otherwise.
*/
default boolean equals(FrameCapsule3DReadOnly other)
{
if (other == this)
{
return true;
}
else if (other == null)
{
return false;
}
else
{
if (getReferenceFrame() != other.getReferenceFrame())
return false;
if (getLength() != other.getLength())
return false;
if (getRadius() != other.getRadius())
return false;
if (!getPosition().equals(other.getPosition()))
return false;
if (!getAxis().equals(other.getAxis()))
return false;
return true;
}
}
}
|
package co.company.spring;
import java.sql.Date;
import java.util.List;
import java.util.Map;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import co.company.spring.config.DBConfiguration;
import co.company.spring.config.MybatisConfiguration;
import co.company.spring.dao.Emp;
import co.company.spring.dao.EmpDAO;
import co.company.spring.dao.EmpMapper;
import co.company.spring.dao.EmpSearch;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = { DBConfiguration.class, MybatisConfiguration.class })
public class EmpDAOMapperClient {
@Autowired
EmpMapper empDAO;
@Test
public void getStatDeptTest() {
List<Map<String,Object>> list = empDAO.getStatDept();
System.out.println(list.get(0));
System.out.println(list.get(0).get("deptName"));
}
//@Test
public void countTest() {
EmpSearch emp = new EmpSearch();
int count = empDAO.getCount(emp);
System.out.println(count);
}
//@Test
public void insertProcTest() {
Emp emp = new Emp();
emp.setLastName("pong");
emp.setJobId("IT_PROG");
emp.setEmail("a@a.h");
empDAO.insertEmpProc(emp);
System.out.println(emp.getEmployeeId() + " : " + emp.getMsg());
}
//@Test
public void insertTest() {
Emp emp = new Emp();
emp.setFirstName("dongon");
emp.setLastName("park");
emp.setJobId("IT_PROG");
emp.setEmail("a@a.c");
emp.setHireDate(new Date(System.currentTimeMillis()));
empDAO.insertEmp(emp);
System.out.println(emp.getEmployeeId());
}
// @Test
public void deleteMultiTest() {
EmpSearch emp = new EmpSearch();
emp.setList(new String[] {"1000","1001"});
empDAO.deleteMultiEmp(emp);
}
// @Test
public void updateTest() {
Emp emp = new Emp();
emp.setEmployeeId("102");
System.out.println(empDAO.getEmp(emp));
emp.setFirstName("honggg");
empDAO.updateEmp(emp);
System.out.println(empDAO.getEmp(emp));
}
// @Test
public void MapperTest() {
EmpSearch empvo = new EmpSearch();
empvo.setFirstName("NI");
empvo.setDepartmentId("80");
empvo.setMinSalary(5000);
empvo.setMaxSalary(10000);
List<Emp> list =empDAO.getEmpList(empvo);
for (Emp emp : list) {
System.out.println(emp.getEmployeeId() + " : " + emp.getFirstName() + " : " + emp.getDepartmentId() + " : "
+ emp.getJobId() + " : " +emp.getSalary());
}
}
}
|
package io.twasyl.demo.fx.controllers;
import io.twasyl.demo.core.Generator;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.CheckBox;
import javafx.scene.control.TextField;
import javafx.scene.control.skin.TitledPaneSkin;
import javafx.scene.input.Clipboard;
import javafx.scene.input.ClipboardContent;
import javafx.scene.text.Text;
import java.net.URL;
import java.util.ResourceBundle;
/**
* @author Thierry Wasylczenko
* @version 1.0
*/
public class DemoFXController implements Initializable {
@FXML private CheckBox allowNumbers;
@FXML private CheckBox allowLowerCaseLetters;
@FXML private CheckBox allowUpperCaseLetters;
@FXML private TextField length;
@FXML private Text generatedPasswordText;
private final StringProperty generatedPassword = new SimpleStringProperty();
private Generator generator;
@FXML
private void exitApplication(final ActionEvent event) {
System.exit(0);
}
@FXML private void allowNumbersAction(final ActionEvent event) {
this.generator.setNumberAllowed(this.allowNumbers.isSelected());
}
@FXML private void allowLowerCaseLettersAction(final ActionEvent event) {
this.generator.setLowerCaseAllowed(this.allowLowerCaseLetters.isSelected());
}
@FXML private void allowUpperCaseLettersAction(final ActionEvent event) {
this.generator.setUpperCaseAllowed(this.allowUpperCaseLetters.isSelected());
}
@FXML private void generatePasswordAction(final ActionEvent event) {
this.generator.setLength(Integer.parseInt(this.length.getText()));
final String password = this.generator.generate();
this.generatedPasswordText.setText(password);
this.generatedPassword.set(password);
}
@FXML private void copyGeneratedPasswordToClipboardAction(final ActionEvent event) {
if(this.generatedPassword.isNotEmpty().get()) {
final ClipboardContent content = new ClipboardContent();
content.putString(this.generatedPassword.get());
Clipboard.getSystemClipboard().setContent(content);
}
}
@FXML private void clearPasswordAction(final ActionEvent event) {
this.generatedPasswordText.setText("");
this.generatedPassword.set("");
}
public String getGeneratedPassword() { return generatedPassword.get(); }
public StringProperty generatedPasswordProperty() { return generatedPassword; }
@Override
public void initialize(URL url, ResourceBundle resourceBundle) {
initializeGenerator();
}
private void initializeGenerator() {
this.generator = new Generator();
this.generator.setNumberAllowed(this.allowNumbers.isSelected());
this.generator.setLowerCaseAllowed(this.allowLowerCaseLetters.isSelected());
this.generator.setUpperCaseAllowed(this.allowUpperCaseLetters.isSelected());
}
}
|
package co.sblock.users;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import co.sblock.Sblock;
import co.sblock.chat.Color;
import co.sblock.chat.Language;
import co.sblock.module.Module;
import co.sblock.utilities.CollectionConversions;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import com.google.common.cache.RemovalListener;
import com.google.common.cache.RemovalNotification;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.Statistic;
import org.bukkit.entity.Player;
import org.bukkit.scoreboard.DisplaySlot;
import org.bukkit.scoreboard.Objective;
import org.bukkit.scoreboard.Score;
import org.bukkit.scoreboard.Scoreboard;
import org.bukkit.scoreboard.Team;
/**
* Class that keeps track of players currently logged on to the game.
*
* @author FireNG, Jikoo
*/
public class Users extends Module {
/* The Cache of Player UUID and relevant Users. */
private final LoadingCache<UUID, User> userCache;
public Users(Sblock plugin) {
super(plugin);
this.userCache = CacheBuilder.newBuilder()
.expireAfterAccess(30L, TimeUnit.MINUTES)
.removalListener(new RemovalListener<UUID, User>() {
@Override
public void onRemoval(RemovalNotification<UUID, User> notification) {
User user = notification.getValue();
user.save();
unteam(user.getPlayerName());
}
}).build(new CacheLoader<UUID, User>() {
@Override
public User load(UUID uuid) {
User user = User.load(getPlugin(), uuid);
team(user.getPlayer(), null);
return user;
}
});
}
@Override
protected void onEnable() {
for (Player player : Bukkit.getOnlinePlayers()) {
getUser(player.getUniqueId());
team(player, null);
}
}
@Override
protected void onDisable() {
// Invalidating and cleaning up causes our removal listener to save all cached users.
userCache.invalidateAll();
userCache.cleanUp();
}
@Override
public boolean isRequired() {
return true;
}
@Override
public String getName() {
return "Users";
}
/**
* Fetch a User. A User is always returned, even if the Player by the given UUID is not online.
*
* @param uuid
*
* @return the User
*/
public User getUser(UUID uuid) {
return userCache.getUnchecked(uuid);
}
public Set<User> getOnlineUsers() {
return CollectionConversions.toSet(Bukkit.getOnlinePlayers(), player -> getUser(player.getUniqueId()));
}
/**
* Add a Player to a Team colored based on permissions.
*
* @param player the Player
*/
public static void team(Player player, String prefix) {
if (player == null) {
return;
}
StringBuilder prefixBuilder = new StringBuilder();
if (prefix != null && !prefix.isEmpty()) {
prefixBuilder.append(prefix);
}
for (net.md_5.bungee.api.ChatColor color : Color.COLORS) {
if (player.hasPermission("sblock.chat.color." + color.name().toLowerCase())) {
prefixBuilder.append(color);
break;
}
}
if (prefixBuilder.length() > (prefix == null ? 0 : prefix.length())) {
// Do nothing, we've got a fancy override going on
} else if (player.hasPermission("sblock.chat.color.horrorterror")) {
prefixBuilder.append(Language.getColor("rank.horrorterror"));
} else if (player.hasPermission("sblock.chat.color.denizen")) {
prefixBuilder.append(Language.getColor("rank.denizen"));
} else if (player.hasPermission("sblock.chat.color.felt")) {
prefixBuilder.append(Language.getColor("rank.felt"));
} else if (player.hasPermission("sblock.chat.color.helper")) {
prefixBuilder.append(Language.getColor("rank.helper"));
} else if (player.hasPermission("sblock.chat.color.donator")) {
prefixBuilder.append(Language.getColor("rank.donator"));
} else if (player.hasPermission("sblock.chat.color.godtier")) {
prefixBuilder.append(Language.getColor("rank.godtier"));
} else {
prefixBuilder.append(Language.getColor("rank.hero"));
}
for (net.md_5.bungee.api.ChatColor color : Color.FORMATS) {
if (player.hasPermission("sblock.chat.color." + color.name().toLowerCase())) {
prefixBuilder.append(color);
}
}
Scoreboard board = Bukkit.getScoreboardManager().getMainScoreboard();
String teamName = player.getName();
Team team = board.getTeam(teamName);
if (team == null) {
team = board.registerNewTeam(teamName);
}
prefix = prefixBuilder.length() <= 16 ? prefixBuilder.toString()
: prefixBuilder.substring(prefixBuilder.length() - 16, prefixBuilder.length());
team.setPrefix(prefix);
team.addEntry(player.getName());
team.addEntry(player.getPlayerListName());
Objective objective = board.getObjective("deaths");
if (objective == null) {
objective = board.registerNewObjective("deaths", "deathCount");
objective.setDisplaySlot(DisplaySlot.PLAYER_LIST);
}
// Since Mojang doesn't, we'll force deathcount to persist - it's been a feature for ages
Score score = objective.getScore(player.getName());
score.setScore(player.getStatistic(Statistic.DEATHS));
}
public static void unteam(Player player) {
unteam(player.getName());
}
private static void unteam(String teamName) {
if (teamName == null) {
return;
}
Team team = Bukkit.getScoreboardManager().getMainScoreboard().getTeam(teamName);
if (team != null) {
team.unregister();
}
}
public static Location getSpawnLocation() {
return new Location(Bukkit.getWorld("Earth"), -3.5, 20, 6.5, 179.99F, 1F);
}
}
|
package examples;
public class StackTest {
public static void main(String[] args) {
double[] doubleElements = {1.1, 2.2, 3.3, 4.4, 5.5};
int[] integerElements = {1, 2, 3, 4, 5};
Stack<Double> doubleStack = new Stack<Double>(5);
Stack<Integer> integerStack = new Stack<Integer>();
testPushDouble(doubleStack, doubleElements);
testPopDouble(doubleStack);
testPushInteger(integerStack, integerElements);
testPopInteger(integerStack);
}
private static void testPushDouble(Stack<Double>someDouble, double[] someArray) {
System.out.printf("%nPushing elements into stack%n");
for(double value : someArray) {
System.out.printf("%.1f ", value);
someDouble.push(value);
}
}
private static void testPopDouble(Stack<Double> someDouble) {
try {
System.out.printf("%nPopping elements from stack%n");
double popValue;
while(true) {
popValue = someDouble.pop();
System.out.printf("%.1f ", popValue);
}
}catch(EmptyStackException ex) {
System.err.println();
ex.printStackTrace();
}
}
private static void testPushInteger(Stack<Integer>someDouble, int[] someArray) {
System.out.printf("%nPushing elements into stack%n");
for(int value : someArray) {
System.out.printf("%d ", value);
someDouble.push(value);
}
}
private static void testPopInteger(Stack<Integer> someDouble) {
try {
System.out.printf("%nPopping elements from stack%n");
int popValue;
while(true) {
popValue = someDouble.pop();
System.out.printf("%d ", popValue);
}
}catch(EmptyStackException ex) {
System.err.println();
ex.printStackTrace();
}
}
}
|
package com.example.ryokun.helloandroid;
import java.util.ArrayList;
import java.util.List;
/**
* Created by taka on 2016/05/24.
*/
public class ImageidSlotReel extends SlotReel{
List<Integer> symbols;
public ImageidSlotReel(){
super(0);
symbols = new ArrayList<Integer>();
}
public ImageidSlotReel(int[] s0){
this();
addSymbols(s0);
}
public ImageidSlotReel(int gap) {
super(0, DEFAULT_INTERVAL, gap);
symbols = new ArrayList<Integer>();
}
public ImageidSlotReel(int[] s0, int gap){
this(gap);
addSymbols(s0);
}
public void addSymbol(int iid){
symbols.add(iid);
setCount(symbols.size());
}
public void addSymbols(int[] iid){
for(int v : iid){
addSymbol(v);
}
}
public void clearSymbols(){
symbols.clear();
setCount(symbols.size());
}
public int getSymbolId(int defaultValue){
if( !symbols.isEmpty() ){
return symbols.get(getValue());
}else{
return defaultValue;
}
}
public int getSymbolId(){
return getSymbolId(-1);
}
}
|
package com.cbs.edu.spring.decoupled_runtime;
public class HelloWorldDecoupledApp {
public static void main(String[] args) {
DecoupledMessageFactory messageFactory = DecoupledMessageFactory.getInstance();
MessageProvider messageProvider = messageFactory.getMessageProvider();
MessageRenderer messageRenderer = messageFactory.getMessageRenderer();
messageRenderer.setMessageProvider(messageProvider);
messageRenderer.render();
}
}
|
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import com.test.dubbo.ApiResponse;
import com.test.dubbo.DubboClient;
import com.test.dubbo.ParameterUtil;
import com.test.dubbo.SpringConfiguration;
/**
*
* @author wangpeihu
* @date 2017/10/13 10:30
*
*/
public class MainTest {
public static void main(String[] args) {
AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(
SpringConfiguration.class);
DubboClient client = applicationContext.getBean("dubboClient", DubboClient.class);
String ip = "10.148.181.141dd";
String parameter = "{'biz': '123'}";
String service = "com.hpay.risk.limit.api.LimitCheckServiceApi";
String method = "check";
int port = 50131;
String url = "dubbo://" + ip + ":" + port;
ApiResponse response = client.invoke(url, service, method,
ParameterUtil.getRequestBodyList(parameter));
System.out.println("client = " + response);
}
}
|
package com.sample.controller;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import com.sample.form.SignupForm;
import com.sample.service.AccountService;
@Controller
public class AccountController {
@Autowired
AccountService accountService;
@RequestMapping(value = "/signin", method = RequestMethod.GET)
public String signin(
Model model,
@RequestParam(name = "username", required = false)
String username,
@RequestParam
Optional<String> error
) {
if(error.isPresent()) {
model.addAttribute("messageType", "danger");
model.addAttribute("message", "Cannot Authentication...Please check username and password");
}
model.addAttribute("username", username);
return "account/signin";
}
@RequestMapping(value = "/signup", method = RequestMethod.GET)
public String singup(
Model model,
@ModelAttribute("signupForm")
SignupForm signupForm
) {
model.addAttribute("signupForm", signupForm);
return "account/signup";
}
@RequestMapping(value = "/signup", method = RequestMethod.POST)
public String doSingup(
Model model,
@ModelAttribute("signupForm")
@Validated
SignupForm signupForm,
BindingResult result
) {
if(result.hasErrors()) {
model.addAttribute("messageType", "danger");
model.addAttribute("message", "Please check error message");
model.addAttribute("postForm", signupForm);
return "account/signup";
}
accountService.signupUser(signupForm.getUser());
return "redirect:/signin?username=" + signupForm.getUser().getUsername();
}
}
|
/*
* Copyright 2021 Vincenzo De Notaris
*
* 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.vdenotaris.spring.boot.security.saml.web.core;
import com.vdenotaris.spring.boot.security.saml.web.CommonTestSupport;
import com.vdenotaris.spring.boot.security.saml.web.TestConfig;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.opensaml.saml2.core.NameID;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.saml.SAMLCredential;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import java.util.ArrayList;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
@ExtendWith(SpringExtension.class)
@ContextConfiguration(classes= TestConfig.class)
public class SAMLUserDetailsServiceImplTest extends CommonTestSupport {
@Autowired
private SAMLUserDetailsServiceImpl userDetailsService;
@Test
public void testLoadUserBySAML() {
// given
NameID mockNameID = mock(NameID.class);
when(mockNameID.getValue()).thenReturn(USER_NAME);
SAMLCredential credentialsMock = mock(SAMLCredential.class);
when(credentialsMock.getNameID()).thenReturn(mockNameID);
// when
Object actual = userDetailsService.loadUserBySAML(credentialsMock);
// / then
assertNotNull(actual);
assertTrue(actual instanceof User);
User user = (User)actual;
assertEquals(USER_NAME, user.getUsername());
assertEquals(USER_PASSWORD, user.getPassword());
assertTrue(user.isEnabled());
assertTrue(user.isAccountNonExpired());
assertTrue(user.isCredentialsNonExpired());
assertTrue(user.isAccountNonLocked());
assertEquals(1, user.getAuthorities().size());
List<GrantedAuthority> authorities = new ArrayList<>(user.getAuthorities());
Object authority = authorities.get(0);
assertTrue(authority instanceof SimpleGrantedAuthority);
assertEquals(USER_ROLE, ((SimpleGrantedAuthority)authority).getAuthority());
}
}
|
/*
*
* This software is the confidential and proprietary information of
* shall not disclose such Confidential Information and shall use
* it only in accordance with the terms of the license agreement
*/
package com.sshfortress.common.util;
import java.lang.reflect.Field;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/** <p class="detail">
* 功能:用于渲染Json前端 枚举的下拉菜单
* 备注:仅支持枚举参数名 为 code、detail的枚举
* </p>
* @ClassName: ReflectUtils
* @version V1.0
*/
public class ReflectUtils {
private static final Log logger = LogFactory.getLog(ReflectUtils.class);
/**
* <p class="detail">
* 功能:获取属性值
* </p>
* @param obj 目标对象
* @param name 属性名
* @return
*/
public static Object getProperty(Object obj, String name){
if(obj != null){
Class<?> clazz = obj.getClass();
while(clazz != null){
Field field = null;
try {
field = clazz.getDeclaredField(name);
} catch (Exception e) {
clazz = clazz.getSuperclass();
continue;
}
try {
field.setAccessible(true);
return field.get(obj);
} catch (Exception e) {
return null;
}finally{
field.setAccessible(false);
}
}
}
return null;
}
/**
* <p class="detail">
* 功能:设置属性值
* </p>
* @param obj 目标对象
* @param name 属性名
* @param value 属性值(可为空),当属性类型不一致,目标属性为基本类型且该参数为字符串则进行转化(转化失败返回false)
* @return
*/
public static boolean setProperty(Object obj, String name, Object value){
if(obj != null){
Class<?> clazz = obj.getClass();
while(clazz != null){
Field field = null;
try {
field = clazz.getDeclaredField(name);
} catch (Exception e) {
clazz = clazz.getSuperclass();
continue;
}
try {
Class<?> type = field.getType();
if(type.isPrimitive() == true && value != null){
if(value instanceof String){
if(type.equals(int.class) == true){
value = Integer.parseInt((String)value);
}else if(type.equals(double.class) == true){
value = Double.parseDouble((String)value);
}else if(type.equals(boolean.class) == true){
value = Boolean.parseBoolean((String)value);
}else if(type.equals(long.class) == true){
value = Long.parseLong((String)value);
}else if(type.equals(byte.class) == true){
value = Byte.parseByte((String)value);
}else if(type.equals(char.class) == true){
value = Character.valueOf(((String)value).charAt(0));
}else if(type.equals(float.class) == true){
value = Float.parseFloat((String)value);
}else if(type.equals(short.class) == true){
value = Short.parseShort((String)value);
}
}
field.setAccessible(true);
field.set(obj, value);
field.setAccessible(false);
}
if(value == null || type.equals(value.getClass()) == true){
field.setAccessible(true);
field.set(obj, value);
field.setAccessible(false);
}
return true;
} catch (Exception e) {
return false;
}
}
}
return false;
}
/**
* <p class="detail">
* 功能:获取当前方法的全路径
* </p>
* @return
*/
public static String getCurrentClassMethodName(){
return Thread.currentThread().getStackTrace()[2].getClassName()+"."+Thread.currentThread().getStackTrace()[2].getMethodName();
}
}
|
/*
* 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 aTPeopleCOS730;
import javax.persistence.*;
/**
* Defines an entity (any being with substance, such as a Person or Group)
*/
public interface Entity
{
}
|
package mistaomega.jahoot.lib;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;
/**
* Configuration class for the program.
* Singleton pattern to allow only 1 instance of the class to exist.
*/
public class Config extends Properties {
private static Config instance = null;
private Config() {
}
public static Config getInstance() {
if (instance == null) {
try {
instance = new Config();
FileInputStream in = new FileInputStream("jahoot.properties");
instance.load(in);
in.close();
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
return instance;
}
}
|
package dev.fujioka.eltonleite.infrastructure.persistence.hibernate.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import dev.fujioka.eltonleite.domain.model.warehouse.Warehouse;
public interface WarehouseRepository extends JpaRepository<Warehouse, Long>{
}
|
/**
*
*/
package de.jaroso.example.cxf;
import java.util.HashMap;
import java.util.Map;
import org.apache.cxf.binding.BindingFactoryManager;
import org.apache.cxf.jaxrs.JAXRSBindingFactory;
import org.apache.cxf.jaxrs.JAXRSServerFactoryBean;
import org.apache.cxf.jaxrs.lifecycle.SingletonResourceProvider;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.fasterxml.jackson.jaxrs.json.JacksonJaxbJsonProvider;
import de.jaroso.example.cxf.exceptions.AFJobNotFoundExceptionHandler;
/**
* Server für den REST-Test-Service
*
* <p>
* <i><small>Copyright (c) 2015 Jaroso GmbH</small></i> <br>
* <i><small>http://www.jaroso.de </small></i>
* <p>
*
* @author Marco Nitschke (m.nitschke@jaroso.de)
* @version $Revision: $ $Date: $ $Id: $
*/
public class ServerApp {
private final static Logger logger = LoggerFactory.getLogger(ServerApp.class);
/**
* Main
*
* @param args
*/
public static void main(String[] args) {
logger.info("server starting");
JAXRSServerFactoryBean sf = new JAXRSServerFactoryBean();
sf.setProvider(new JacksonJaxbJsonProvider());
sf.setProvider(new AFJobNotFoundExceptionHandler());
sf.setResourceClasses(AFService.class);
sf.setResourceProvider(AFService.class, new SingletonResourceProvider(new AFServiceImpl()));
sf.setAddress("http://localhost:4444/");
Map<String, Object> properties = new HashMap<>();
properties.put("single.multipart.is.collection", true);
sf.setProperties(properties);
BindingFactoryManager manager = sf.getBus().getExtension(BindingFactoryManager.class);
JAXRSBindingFactory factory = new JAXRSBindingFactory();
factory.setBus(sf.getBus());
manager.registerBindingFactory(JAXRSBindingFactory.JAXRS_BINDING_ID, factory);
sf.create();
}
}
|
package bookmanager.main;
import boookaager.database.DatabaseHandler;
import com.jfoenix.controls.JFXTextField;
import java.io.IOException;
import java.net.URL;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Optional;
import java.util.ResourceBundle;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Node;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Alert;
import javafx.scene.control.ButtonType;
import javafx.scene.control.Label;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.AnchorPane;
import javafx.scene.text.Text;
import javafx.stage.Stage;
import javafx.stage.StageStyle;
/**
* FXML Controller class
*
* @author mustafa
*/
public class Main_Controller implements Initializable {
private DatabaseHandler handler;
@FXML
private Label message;
@FXML
private JFXTextField bid;
@FXML
private JFXTextField mid;
@FXML
private Text bookName;
@FXML
private Text bAuthor;
@FXML
private Text bStatus;
@FXML
private Text mName;
@FXML
private Text mMobile;
@FXML
private AnchorPane pane;
@Override
public void initialize(URL url, ResourceBundle rb) {
handler = DatabaseHandler.getInstance();
}
@FXML
private void loadAddMember(ActionEvent event) throws IOException {
loadWindow("/boookmanager/addmember/addmember.fxml","Add Member Window");
}
@FXML
private void loadAddBook(ActionEvent event) throws IOException {
loadWindow("/boookmanager/addbook/FXMLDocument.fxml","Add Book Window");
}
@FXML
private void loadShowMember(ActionEvent event) throws IOException {
loadWindow("/boookmanager/listbook/book_list.fxml","Show Book Window");
}
@FXML
private void loadShowBooks(ActionEvent event) throws IOException {
loadWindow("/boookmanager/listmembers/listmember.fxml","Show Member Window");
}
@FXML
private void loadSettings(ActionEvent event) throws IOException {
loadWindow("/bookmanger/settings/settings.fxml","Setting Window");
}
private void loadWindow(String loc, String title) throws IOException{
AnchorPane pane=FXMLLoader.load(getClass().getResource(loc));
Stage stage = new Stage(StageStyle.DECORATED);
stage.setTitle(title);
stage.setScene(new Scene(pane));
stage.show();
}
@FXML
private void laodBookInfo(ActionEvent event) throws SQLException {
clearBookCache();
String id = bid.getText();
String qu= "SELECT * FROM BOOK WHERE id = '"+id +"'";
ResultSet rs = handler.execQuery(qu);
Boolean flag=false;
while(rs.next()){
String bName=rs.getString("title");
String Author=rs.getString("author");
Boolean Status=rs.getBoolean("isAvail");
bookName.setText(bName);
bAuthor.setText(Author);
String status=(Status)?"Available" : "Not Available";
bStatus.setText(status);
flag=true;
}
if(!flag)
bookName.setText("No such book is Available");
}
@FXML
private void loadMemberInfo(ActionEvent event) throws SQLException {
clearMemberCache();
String Mid=mid.getText();
String qu="SELECT * FROM MEMBER WHERE id='"+Mid +"'";
ResultSet rs = handler.execQuery(qu);
Boolean flag=false;
while(rs.next()){
String mname= rs.getString("name");
String mmobile= rs.getString("mobile");
mName.setText(mname);
mMobile.setText(mmobile);
flag=true;
}
if(!flag)
mName.setText("No such member is Available");
}
void clearBookCache() {
bookName.setText("");
bAuthor.setText("");
bStatus.setText("");
}
void clearMemberCache() {
mName.setText("");
mMobile.setText("");
}
@FXML
private void loadIssueOperation(ActionEvent event) {
String mID= mid.getText();
String bID=bid.getText();
Alert alert= new Alert(Alert.AlertType.CONFIRMATION);
alert.setTitle("Confirm issue operation");
alert.setHeaderText(null);
alert.setContentText("Are you sure want to issue book " + bookName.getText()+ " to \n the " +mName.getText());
Optional<ButtonType> response= alert.showAndWait();
if(response.get()==ButtonType.OK){ //must specified
String str = "INSERT INTO ISSUE(memberID,bookID) VALUES ("
+ "'" + mID + "',"
+ "'" + bID + "')";
String str2 = "UPDATE BOOK SET isAvail = false WHERE id = '" + bID + "'";
System.out.println(str + " and " + str2);
if (handler.execAction(str) && handler.execAction(str2)){
Alert alert1= new Alert(Alert.AlertType.INFORMATION);
alert1.setTitle("Success");
alert1.setHeaderText(null);
alert1.setContentText("Book Issue complete");
alert1.showAndWait();
}else
{
Alert alert1= new Alert(Alert.AlertType.ERROR);
alert.setTitle("Failed");
alert.setHeaderText(null);
alert.setContentText("Book Issue Failed");
alert.showAndWait();
}
}else
{
Alert alert1= new Alert(Alert.AlertType.INFORMATION);
alert.setTitle("Cancelled");
alert.setHeaderText(null);
alert.setContentText("Book Issue Cancelled");
alert.showAndWait();
}
bookName.setText("");
bAuthor.setText("");
bStatus.setText("");
mName.setText("");
mMobile.setText("");
}
@FXML
private void loadRenew(MouseEvent event) throws IOException {
Node source =(Node) event.getSource();
Stage stage = (Stage) source.getScene().getWindow() ;
Parent root = FXMLLoader.load(getClass().getResource("/boookmanager/renew/renew.fxml"));
Scene scene = new Scene(root);
stage.setScene(scene);
}
}
|
package commands;
import java.io.IOException;
import org.newdawn.slick.SlickException;
import actionEngines.ActionEngine;
public interface GenericCommand {
public void execute(ActionEngine actionEngine) throws SlickException, IOException;
}
|
/**Bootstrap server
*
* @author rushabhmehta
*/
import java.awt.*;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
public class Bootstrap extends Thread {
int count_join, count_delete, current_count;
ArrayList<Peer> listOfPeers;
ServerSocket serverSoc;
int port;
/*
* Constructor
*/
public Bootstrap() {
try {
count_delete = 0;
count_join = 0;
current_count = 0;
listOfPeers = new ArrayList<>();
port = 5000;
serverSoc = new ServerSocket();
serverSoc.setReuseAddress(true);
serverSoc.bind(new InetSocketAddress(port));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/*
* This method creates server socket and will run till program is terminated. This method will provide booting node for new peers.
*/
public void run() {
try {
while (true) {
System.out.println("waiting for peer");
Socket peer_join = serverSoc.accept();
System.out.println("Peer joined");
ObjectInputStream din = new ObjectInputStream(peer_join.getInputStream());
String workToDo = (String) din.readObject();
Peer p = (Peer) din.readObject();
if (workToDo.equals("join")) {
p.portout = 5000 + count_join + 1;
if (listOfPeers.size() == 0) {
System.out.println("in if");
p.z = new Zone(new Point(0, 0), new Point(1000, 1000));
ObjectOutputStream out = new ObjectOutputStream(peer_join.getOutputStream());
out.writeObject(p);
out.writeObject(p.portout);
System.out.println("if over");
} else {
System.out.println("in else");
ObjectOutputStream out = new ObjectOutputStream(peer_join.getOutputStream());
out.writeObject(listOfPeers.get(0));
out.writeObject(p.portout);
}
listOfPeers.add(p);
count_join++;
}
if (workToDo.equals("delete")) {
int del;
for (int index = 0; index < listOfPeers.size(); index++) {
if (p.equals(listOfPeers.get(index))) {
del = index;
listOfPeers.remove(del);
break;
}
}
}
peer_join.close();
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* this is the main method
*
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
new Bootstrap().start();
}
}
|
package be.dpms.medwan.webapp.wl.servlets.filters;
/*
* (c) 2004, Kevin Chipalowsky (kevin@farwestsoftware.com) and
* Ivelin Ivanov (ivelin@apache.org)
*
* Released under terms of the Artistic License
* http://www.opensource.org/licenses/artistic-license.php
*/
import be.mxs.common.util.db.MedwanQuery;
import be.mxs.common.util.system.Debug;
import be.dpms.medwan.common.model.IConstants;
import java.io.IOException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
/**
* Use this filter to synchronize requests to your web application and
* reduce the maximum load that each individual user can put on your
* web application. Requests will be synchronized per session. When more
* than one additional requests are made while a request is in process,
* only the most recent of the additional requests will actually be
* processed.
* <p>
* If a user makes two requests, A and B, then A will be processed first
* while B waits. When A finishes, B will be processed.
* <p>
* If a user makes three or more requests (e.g. A, B, and C), then the
* first will be processed (A), and then after it finishes the last will
* be processed (C), and any intermediate requests will be skipped (B).
* <p>
* There are two additional limitiations:
* <ul>
* <li>Requests will be excluded from filtering if their URI matches
* one of the exclusion patterns. There will be no synchronization
* performed if a request matches one of those patterns.</li>
* <li>Requests wait a maximum of 5 seconds, which can be overridden
* per URI pattern in the filter's configuration.</li>
* </ul>
*
* @author Kevin Chipalowsky and Ivelin Ivanov
*/
public class RequestControlFilter implements Filter
{
private ServletResponse response;
/**
* Initialize this filter by reading its configuration parameters
*
* @param config Configuration from web.xml file
*/
public void init( FilterConfig config ) throws ServletException
{
// parse all of the initialization parameters, collecting the exclude
// patterns and the max wait parameters
Enumeration e = config.getInitParameterNames();
excludePatterns = new LinkedList();
maxWaitDurations = new HashMap();
String paramName, paramValue, durationString;
Pattern excludePattern;
int endDuration;
Long duration;
Pattern waitPattern;
while( e.hasMoreElements() )
{
paramName = ( String )e.nextElement();
paramValue = config.getInitParameter( paramName );
if( paramName.startsWith( "excludePattern" ) )
{
// compile the pattern only this once
excludePattern = Pattern.compile( paramValue );
excludePatterns.add( excludePattern );
}
else if( paramName.startsWith( "maxWaitMilliseconds." ) )
{
// the delay gets parsed from the parameter name
durationString = paramName.substring( "maxWaitMilliseconds.".length() );
endDuration = durationString.indexOf( '.' );
if( endDuration != -1 )
{
durationString = durationString.substring( 0, endDuration );
}
duration = new Long( durationString );
// compile the corresponding pattern, and store it with this delay in the map
waitPattern = Pattern.compile( paramValue );
maxWaitDurations.put( waitPattern, duration );
}
}
}
/**
* Called with the filter is no longer needed.
*/
public void destroy()
{
// there is nothing to do
}
/**
* Synchronize the request and then either process it or skip it,
* depending on what other requests current exist for this session.
* See the description of this class for more details.
*/
public void doFilter(
ServletRequest request,
ServletResponse response,
FilterChain chain )
throws IOException, ServletException
{
this.response = response;
HttpServletRequest httpRequest = (HttpServletRequest)request;
HttpSession session = httpRequest.getSession();
// if this request is excluded from the filter, then just process it
if( !isFilteredRequest( httpRequest ) ){
Debug.println(httpRequest.getRequestURI()+" excluded from filter");
chain.doFilter( request, response );
return;
}
synchronized( getSynchronizationObject( session ) ){
// if another request is being processed, then wait
if( isRequestInProcess( session ) ){
Debug.println(httpRequest.getRequestURI()+" queued");
// Put this request in the queue and wait
enqueueRequest( httpRequest );
if( !waitForRelease( httpRequest ) ){
Debug.println(httpRequest.getRequestURI()+" abandoned");
// this request was replaced in the queue by another request,
// so it need not be processed
return;
}
}
// lock the session, so that no other requests are processed until this one finishes
setRequestInProgress( httpRequest );
}
// process this request, and then release the session lock regardless of
// any exceptions thrown farther down the chain.
try{
chain.doFilter( request, response );
}
finally{
releaseQueuedRequest( httpRequest );
}
}
/**
* Get a synchronization object for this session
*
* @param session
*/
private static synchronized Object getSynchronizationObject(HttpSession session)
{
// get the object from the session. If it does not yet exist,
// then create one.
Object syncObj = session.getAttribute( SYNC_OBJECT_KEY );
if( syncObj == null ){
syncObj = new Object();
session.setAttribute( SYNC_OBJECT_KEY, syncObj );
}
return syncObj;
}
/**
* Record that a request is in process so that the filter blocks additional
* requests until this one finishes.
*
* @param request
*/
private void setRequestInProgress(HttpServletRequest request){
HttpSession session = request.getSession();
session.setAttribute( REQUEST_IN_PROCESS, request );
}
/**
* Release the next waiting request, because the current request
* has just finished.
*
* @param request The request that just finished
*/
private void releaseQueuedRequest( HttpServletRequest request ){
HttpSession session;
try{
session = request.getSession();
synchronized( getSynchronizationObject( session ) )
{
// if this request is still the current one (i.e., it didn't run for too
// long and result in another request being processed), then clear it
// and thus release the lock
if( session.getAttribute( REQUEST_IN_PROCESS ) == request )
{
session.removeAttribute( REQUEST_IN_PROCESS );
getSynchronizationObject( session ).notify();
}
}
}
catch(IllegalStateException e){
try{
request.getRequestDispatcher(IConstants.MEDWAN_LOGIN_PAGE).forward(request,response);
}
catch(Exception ex){}
}
}
/**
* Is this server currently processing another request for this session?
*
* @param session The request's session
* @return true if the server is handling another request for this session
*/
private boolean isRequestInProcess( HttpSession session )
{
return session.getAttribute( REQUEST_IN_PROCESS ) != null;
}
/**
* Wait for this server to finish with its current request so that
* it can begin processing our next request. This method also detects if
* its request is replaced by another request in the queue.
*
* @param request Wait for this request to be ready to run
* @return true if this request may be processed, or false if this
* request was replaced by another in the queue.
*/
private boolean waitForRelease( HttpServletRequest request )
{
HttpSession session = request.getSession();
// wait for the currently running request to finish, or until this
// thread has waited the maximum amount of time
try
{
getSynchronizationObject( session ).wait( getMaxWaitTime( request ) );
}
catch( InterruptedException ie )
{
return false;
}
// This request can be processed now if it hasn't been replaced
// in the queue
return request == session.getAttribute( REQUEST_QUEUE );
}
/**
* Put a new request in the queue. This new request will replace
* any other requests that were waiting.
*
* @param request The request to queue
*/
private void enqueueRequest( HttpServletRequest request )
{
HttpSession session = request.getSession();
// Put this request in the queue, replacing whoever was there before
session.setAttribute( REQUEST_QUEUE, request );
// if another request was waiting, notify it so it can discover that
// it was replaced
getSynchronizationObject( session ).notify();
}
/**
* What is the maximum wait time (in milliseconds) for this request
*
* @param request
* @return Maximum number of milliseconds to hold this request in the queue
*/
private long getMaxWaitTime( HttpServletRequest request )
{
// look for a Pattern that matches the request's path
String path = request.getRequestURI();
Iterator patternIter = maxWaitDurations.keySet().iterator();
Pattern p;
Matcher m;
Long maxDuration;
while( patternIter.hasNext() )
{
p = (Pattern)patternIter.next();
m = p.matcher( path );
if( m.matches() )
{
// this pattern matches. At most, how long can this request wait?
maxDuration = (Long)maxWaitDurations.get( p );
return maxDuration.longValue();
}
}
// If no pattern matches the path, return the default value
return DEFAULT_DURATION;
}
/**
* Look through the filter's configuration, and determine whether or not it
* should synchronize this request with others.
*
* @return
*/
private boolean isFilteredRequest(HttpServletRequest request)
{
if(request.getParameter("excludeFromFilter")!=null){
return false;
}
// iterate through the exclude patterns. If one matches this path,
// then the request is excluded.
String path = request.getRequestURI();
Iterator patternIter = excludePatterns.iterator();
Pattern p;
Matcher m;
while( patternIter.hasNext() )
{
p = (Pattern)patternIter.next();
m = p.matcher( path );
if( m.matches() )
{
// at least one of the patterns excludes this request
return false;
}
}
// this path is not excluded
return true;
}
/** A list of Pattern objects that match paths to exclude */
private LinkedList excludePatterns;
/** A map from Pattern to max wait duration (Long objects) */
private HashMap maxWaitDurations;
/** The session attribute key for the request currently being processed */
private final static String REQUEST_IN_PROCESS
= "RequestControlFilter.requestInProcess";
/** The session attribute key for the request currently waiting in the queue */
private final static String REQUEST_QUEUE
= "RequestControlFilter.requestQueue";
/** The session attribute key for the synchronization object */
private final static String SYNC_OBJECT_KEY = "RequestControlFilter.sessionSync";
/** The default maximum number of milliseconds to wait for a request */
private final static long DEFAULT_DURATION = 5000;
}
|
package com.gyorog.filepusher;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;
import java.io.File;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class BrowseLocalPathActivity extends AppCompatActivity {
public static final String TAG = "com.gyorog.filepusher.BrowseLocalPathActivity";
String localpath;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent args_intent = getIntent();
String intent_path = args_intent.getStringExtra("str-localpath");
if (intent_path == null) {
ShowPath("/");
} else {
ShowPath(intent_path);
}
}
private void ShowPath(String path) {
localpath = path;
setContentView(R.layout.activity_browse_path);
LinearLayout layout = findViewById(R.id.layout_browse);
Context context = layout.getContext();
if ("/".equals(localpath) ) {
// Unfortunately, listing directories is a pain with Android. From ADB shell, I can see these, but not from an app:
// SD cards at /storage/8va9-ava09
// CARD_NAMES=$(ls /storage | grep -v "emulated\|self")
TextView textview;
File[] media_dirs = context.getExternalMediaDirs();
if( media_dirs != null) {
Log.d(TAG, "Found " + media_dirs.length + " dirs from context.getExternalMediaDirs()");
Pattern pattern = Pattern.compile("/storage/(.*?)/Android.*");
for (int i = 0; i < media_dirs.length; i++) {
if ( media_dirs[i] != null) {
Matcher matcher = pattern.matcher( media_dirs[i].getAbsolutePath() );
if (matcher.find()) {
if ("emulated/0".equals( matcher.group(1) ) ){
textview = MakePathItem(context, "Internal Storage", "/storage/emulated/0");
} else {
textview = MakePathItem(context, "Device " + matcher.group(1), "/storage/" + matcher.group(1));
}
layout.addView(textview);
}
}
}
}
/*
// This is also returned by getExternalMediaDirs() above.
TextView textview = MakePathItem(context, "Internal Storage", "/storage/emulated/0");
layout.addView(textview);
*/
/*
// This one captured "ES: /sdcard"
try {
final String ExternalStorage = System.getenv("EXTERNAL_STORAGE");
textview = MakePathItem(context, "ES: " + ExternalStorage, ExternalStorage);
layout.addView(textview);
final String SecondaryStorage = System.getenv("SECONDARY_STORAGE");
if (SecondaryStorage != null ) {
final String[] SecondaryStorageList = SecondaryStorage.split(File.pathSeparator);
for (int i = 0; i < SecondaryStorageList.length; i++) {
textview = MakePathItem(context, "SS: " + SecondaryStorageList[i], SecondaryStorageList[i]);
layout.addView(textview);
}
}
} catch(Exception e){
Log.e(TAG, "Exception: " + e);
}
*/
/*
// This seems to simply not be allowed by Android
File directory = new File("/storage/");
File[] files = directory.listFiles();
if( files != null) {
Log.d(TAG, "Found " + files.length + " files in /storage/");
for (int i = 0; i < files.length; i++) {
if (files[i].isDirectory()) {
String file_name_lcase = files[i].getName().toLowerCase();
if ((!"emulated".equals(file_name_lcase)) && (!"self".equals(file_name_lcase))) {
textview = MakePathItem(context, "External Storage (SD?) " + files[i].getName(), "/storage/" + files[i].getName());
layout.addView(textview);
}
}
}
}
*/
} else {
TextView choose_text = new TextView(context);
choose_text.setText(localpath);
layout.addView(choose_text);
Button choose_this = new Button(context);
choose_this.setText(R.string.choose_path);
choose_this.setTag(localpath);
choose_this.setOnClickListener(v -> {
Log.d(TAG, "Choose path " + localpath);
Intent returnIntent = new Intent();
returnIntent.putExtra("str-localpath", localpath);
setResult(MainActivity.CODE_SUCCESS, returnIntent);
finish();
});
layout.addView(choose_this);
Button go_up = new Button(context);
go_up.setText(R.string.go_up);
go_up.setOnClickListener(v -> {
// Paths are assumed to always be directories and have no leading slash and no trailing slash.
int index = localpath.lastIndexOf('/');
String newpath = localpath.substring(0, index);
if ( "/storage".equals(newpath) || "/storage/emulated".equals(newpath) ) {
ShowPath("/");
} else {
ShowPath(localpath.substring(0, index));
}
});
layout.addView(go_up);
File directory = new File(localpath);
File[] files = directory.listFiles();
if (files != null) {
Log.d(TAG, "Found " + files.length + " files in " + localpath);
for (int i = 0; i < files.length; i++) {
if (files[i].isDirectory()) {
TextView textview = MakePathItem(context, files[i].getName(), localpath + "/" + files[i].getName());
layout.addView(textview);
//Log.d(TAG, "added " + files[i].getName());
}
}
} else {
Log.e(TAG, "Found no files in " + localpath);
}
}
}
TextView MakePathItem(Context context, String item_name, String browse_path) {
TextView textview = new TextView(context);
textview.setText( item_name );
textview.setBackground(ContextCompat.getDrawable(context, R.drawable.textview_border));
textview.setPadding(10, 10, 10, 10);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
params.setMargins(10, 10, 10, 10);
textview.setLayoutParams(params);
textview.setTag(browse_path);
textview.setOnClickListener(v -> {
TextView tv = (TextView) v;
ShowPath( (String) tv.getTag() );
});
return textview;
}
}
|
package negocio.beans;
import java.io.Serializable;
public class Habilidade implements Serializable {
/// Atributos
private String nome;
private String tipo;
private String categoria;
private String requisito;
private int mana;
private int dificuldade;
private String[] classes;
private String[] racas;
private String descricao;
/// Construtores
public Habilidade(String nome, String tipo, String categoria, String requisito, int mana, int dificuldade,
String[] classes, String[] racas, String descricao) {
this.nome = nome;
this.tipo = tipo;
this.categoria = categoria;
this.requisito = requisito;
this.mana = mana;
this.dificuldade = dificuldade;
this.classes = classes;
this.racas = racas;
this.descricao = descricao;
}
/// Metodos
public boolean equals(Habilidade another)
{
boolean ret = false;
if(this.getNome().equals(another.getNome()))
{
ret = true;
}
return ret;
}
public String toString()
{
return this.nome;
}
public String descricaoCompleta()
{
String str = String.format("%s\n" + "Habilidade ", this.nome);
if (categoria != null && !categoria.equals("-"))
{
str += String.format("(%s) ", this.categoria);
}
str += String.format("- %s\n", this.tipo);
if (requisito != null && !requisito.equals("-"))
{
str += String.format("Requisito: %s\n", this.requisito);
}
if (mana >= 0)
{
if (mana == 0)
{
str += "Mana: Varia\n";
}
else
{
str += String.format("Mana: %d\n", this.mana);
}
}
if (dificuldade >= 0)
{
str += String.format("Dificuldade da Magia: %d\n", this.dificuldade);
}
str += String.format("Descricao: %s\n", this.descricao);
return str;
}
public boolean containsClasse(String classe)
{
boolean ret = false;
for(String str : classes)
{
if(str.equals(classe))
{
ret = true;
}
}
return ret;
}
public boolean containsRaca(String raca)
{
boolean ret = false;
for(String str : racas)
{
if(str.equals(raca))
{
ret = true;
}
}
return ret;
}
/// Gets e sets
public String getNome() {
return this.nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public String[] getClasses() {
return this.classes;
}
public void setClasses(String[] classes) {
this.classes = classes;
}
public String[] getRacas() {
return this.racas;
}
public void setRacas(String[] racas) {
this.racas = racas;
}
public String getTipo() {
return tipo;
}
public void setTipo(String tipo) {
this.tipo = tipo;
}
public String getCategoria() {
return categoria;
}
public void setCategoria(String categoria) {
this.categoria = categoria;
}
public String getRequisito() {
return requisito;
}
public void setRequisito(String requisito) {
this.requisito = requisito;
}
public int getMana() {
return mana;
}
public void setMana(int mana) {
this.mana = mana;
}
public int getDificuldade() {
return dificuldade;
}
public void setDificuldade(int dificuldade) {
this.dificuldade = dificuldade;
}
public String getDescricao() {
return descricao;
}
public void setDescricao(String descricao) {
this.descricao = descricao;
}
public static Habilidade habildade = new Habilidade(null, null, null, null, 0, 0, null, null, null);
}
|
package com.lsjr.callback;
import android.text.TextUtils;
import android.util.Log;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.lsjr.bean.ArrayResult;
import com.lsjr.bean.ObjectResult;
import com.lsjr.bean.Result;
import com.lsjr.exception.ApiException;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.net.ConnectException;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
import rx.exceptions.CompositeException;
public abstract class ChatArrayCallBack<T> extends BaseCallBack<String> {
private Class<T> mClazz;
public ChatArrayCallBack(Class<T> clazz) {
this.mClazz=clazz;
}
@Override
public void onNext(String response) {
Log.e("ChatObjectCallBack", "网络请求成功" + response);
ArrayResult<T> result = new ArrayResult<>();
try {
response = response.replace("null", "\"\"");
JSONObject jsonObject = JSON.parseObject(response);
result.setResultCode(jsonObject.getIntValue(Result.RESULT_CODE));
result.setResultMsg(jsonObject.getString(Result.RESULT_MSG));
if (result.getResultCode() == Result.CODE_SUCCESS){
String data = jsonObject.getString(Result.DATA);
Log.e("ChatArrayCallBack", "成功返回data---->:" + data );
if (!TextUtils.isEmpty(data)) {
result.setData(JSON.parseArray(data, mClazz));
}
} else {
result.setResultMsg(jsonObject.getString("detailMsg"));
Log.e("HSubscriberCallBack", "网络请求失败" + response);
}
onSuccess(result);
} catch (Exception e) {
e.printStackTrace();
onXError(e.getMessage());
}
}
@Override
public void onError(final Throwable e) {
if (e instanceof CompositeException) {
CompositeException compositeE = (CompositeException) e;
for (Throwable throwable : compositeE.getExceptions()) {
if (throwable instanceof SocketTimeoutException) {
onXError(ApiException.SOCKET_TIMEOUT_EXCEPTION);
} else if (throwable instanceof ConnectException) {
onXError(ApiException.CONNECT_EXCEPTION);
} else if (throwable instanceof UnknownHostException) {
onXError(ApiException.CONNECT_EXCEPTION);
}else {
onXError(ApiException.CONNECT_EXCEPTION);
}
}
} else {
onXError(ApiException.CONNECT_EXCEPTION);
}
}
@Override
public void onStart() {
super.onStart();
}
@Override
public void onCompleted() {
}
protected abstract void onXError(String exception);
protected abstract void onSuccess(ArrayResult<T> result);
} |
package com.jgw.supercodeplatform.trace.service.tracefun;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.jgw.supercodeplatform.exception.SuperCodeException;
import com.jgw.supercodeplatform.pojo.cache.AccountCache;
import com.jgw.supercodeplatform.trace.common.util.CommonUtil;
import com.jgw.supercodeplatform.trace.common.util.RestTemplateUtil;
import com.jgw.supercodeplatform.trace.exception.SuperCodeTraceException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;
/**
* 设备信息
*
* @author wzq
* @date: 2019-03-29
*/
@Service
public class DeviceService extends CommonUtil {
@Autowired
private RestTemplateUtil restTemplateUtil;
@Value("${rest.user.url}")
private String restUserUrl;
/**
* 添加设备使用记录
* @param deviceId
* @return
*/
public JsonNode insertUsageInfo(String deviceId,String operationalContent) {
Map<String, Object> params = new HashMap<String, Object>();
Map<String, String> headerMap = new HashMap<String, String>();
LocalDateTime time = LocalDateTime.now();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("YYYY-MM-dd HH:mm:ss");
try {
AccountCache userAccount = getUserLoginCache();
params.put("deviceId", deviceId);
params.put("usageTime", time.format(formatter));
params.put("userId", userAccount.getUserId());
params.put("userName", userAccount.getUserName());
params.put("operationalContent", operationalContent);
headerMap.put("super-token", getSuperToken());
ResponseEntity<String> rest = restTemplateUtil.postJsonDataAndReturnJosn(restUserUrl + "/device/usage-record", JSONObject.toJSONString( params), headerMap);
if (rest.getStatusCode().value() == 200) {
String body = rest.getBody();
JsonNode node = new ObjectMapper().readTree(body);
if (200 == node.get("state").asInt()) {
return node.get("results");
}
}
} catch (SuperCodeTraceException | IOException | SuperCodeException e) {
e.printStackTrace();
}
return null;
}
}
|
package sun.study.java;
import sun.study.java.tree.BinaryTree;
public class TreeTest {
public static void main(String[] args) {
BinaryTree.TreeNode<Integer> root= new BinaryTree.TreeNode<Integer>(1);
BinaryTree.TreeNode<Integer> l1= new BinaryTree.TreeNode<Integer>(2);
BinaryTree.TreeNode<Integer> r1= new BinaryTree.TreeNode<Integer>(3);
BinaryTree.TreeNode<Integer> ll2= new BinaryTree.TreeNode<Integer>(4);
BinaryTree.TreeNode<Integer> rr2= new BinaryTree.TreeNode<Integer>(5);
BinaryTree.TreeNode<Integer> llr3= new BinaryTree.TreeNode<Integer>(6);
BinaryTree.TreeNode<Integer> llrl4= new BinaryTree.TreeNode<Integer>(7);
BinaryTree.TreeNode<Integer> llrr4= new BinaryTree.TreeNode<Integer>(8);
root.setlChild(l1);
root.setrChild(r1);
l1.setlChild(ll2);
r1.setlChild(rr2);
ll2.setrChild(llr3);
llr3.setlChild(llrl4);
llr3.setrChild(llrr4);
BinaryTree.leftTraversal(root);
}
}
|
package com.example.apprunner.Organizer.menu4_check_distance.Activity;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.example.apprunner.Login.LoginActivity;
import com.example.apprunner.Login.RegisterappActivity;
import com.example.apprunner.Organizer.menu1_home.Activity.MainActivity;
import com.example.apprunner.Organizer.menu3_check_payment.Activity.DetailSubmitPaymentActivity;
import com.example.apprunner.Organizer.menu3_check_payment.Activity.Select_user_paymentActivity;
import com.example.apprunner.OrganizerAPI;
import com.example.apprunner.R;
import com.example.apprunner.ResultQuery;
import com.example.apprunner.User.menu1_home.Fragment.SecondFragment;
import com.example.apprunner.User.menu2_profile_event.Activity.ShowDistanceEventActivity;
import com.example.apprunner.User.menu2_profile_event.Adapter.ShowStatUserAdapter;
import com.example.apprunner.addressQuery;
import java.util.List;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
public class DetailDistanceUserActivity extends AppCompatActivity {
TextView id,event,FName,LName,distance_user,distance_event,type_tv,address;
String name_event,first_name,last_name,type;
int id_user,id_add,status_reward,id_organizer;
Button btn_submit;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail_distance_user);
first_name = getIntent().getExtras().getString("first_name");
last_name = getIntent().getExtras().getString("last_name");
id_user = getIntent().getExtras().getInt("id_user");
id_organizer = getIntent().getExtras().getInt("id_organizer");
name_event = getIntent().getExtras().getString("name_event");
id_add = getIntent().getExtras().getInt("id_add");
status_reward = getIntent().getExtras().getInt("status_reward");
type = getIntent().getExtras().getString("type");
id = findViewById(R.id.id);
event = findViewById(R.id.event);
FName = findViewById(R.id.FName);
LName = findViewById(R.id.LName);
distance_user = findViewById(R.id.distance_user);
distance_event = findViewById(R.id.distance_event);
address = findViewById(R.id.address);
type_tv = findViewById(R.id.type_tv);
btn_submit = findViewById(R.id.btn_submit);
if(status_reward == 0){
type_tv.setText("รออนุมัติ");
}
if(status_reward == 1){
type_tv.setText("อนุมัติ");
}
id.setText(Integer.toString(id_user));
event.setText(name_event);
FName.setText(first_name);
LName.setText(last_name);
showdetail_address();
setDetailRegEvent();
setProfileDistance();
btn_submit.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
showAlertDialog(view);
}
});
}
public void showAlertDialog(View view) {
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setTitle("ยืนยันการอนุมัติระยะทางวิ่ง");
alert.setMessage("คุณต้องการอนุมัติระยะทางวิ่งใช่หรือไม่");
alert.setPositiveButton("ใช่", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
Toast.makeText(DetailDistanceUserActivity.this, "อนุมติสำเร็จ", Toast.LENGTH_SHORT).show();
Submit_type();
}
});
alert.setNegativeButton("ไม่", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
}
});
alert.create().show();
}
private void Submit_type() {
MainActivity mainActivity = new MainActivity();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(mainActivity.url)
.addConverterFactory(GsonConverterFactory.create())
.build();
OrganizerAPI services = retrofit.create(OrganizerAPI.class);
Call<ResultQuery> call = services.submit_type_distance(id_add,id_user);
call.enqueue(new Callback<ResultQuery>() {
@Override
public void onResponse(Call<ResultQuery> call, Response<ResultQuery> response) {
Intent intent = new Intent(DetailDistanceUserActivity.this, MainActivity.class);
intent.putExtra("first_name", first_name);
intent.putExtra("last_name", last_name);
intent.putExtra("type", type);
intent.putExtra("id_user", id_organizer);
startActivity(intent);
Toast.makeText(DetailDistanceUserActivity.this,"อนุมัติแล้ว",Toast.LENGTH_LONG).show();
}
@Override
public void onFailure(Call<ResultQuery> call, Throwable t) {
}
});
}
private void showdetail_address() {
MainActivity mainActivity = new MainActivity();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(mainActivity.url)
.addConverterFactory(GsonConverterFactory.create())
.build();
OrganizerAPI services = retrofit.create(OrganizerAPI.class);
Call<addressQuery> call = services.show_address(id_user,id_add);
call.enqueue(new Callback<addressQuery>() {
@Override
public void onResponse(Call<addressQuery> call, Response<addressQuery> response) {
addressQuery addressQuery = (addressQuery) response.body();
address.setText(addressQuery.getAddress() + "\t\t" + addressQuery.getDistrict() + "\t\t" + addressQuery.getMueangDistrict()
+ "\t\t" + addressQuery.getProvince() + "\t\t" + addressQuery.getCountry_number());
}
@Override
public void onFailure(Call<addressQuery> call, Throwable t) {
}
});
}
private void setDetailRegEvent(){
MainActivity mainActivity = new MainActivity();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(mainActivity.url)
.addConverterFactory(GsonConverterFactory.create())
.build();
OrganizerAPI services = retrofit.create(OrganizerAPI.class);
Call<ResultQuery> call = services.user_detail_reg_event(id_user,id_add);
call.enqueue(new Callback<ResultQuery>() {
@Override
public void onResponse(Call<ResultQuery> call, Response<ResultQuery> response) {
ResultQuery resultQuery = (ResultQuery) response.body();
String distance = resultQuery.getDistance();
distance_event.setText(distance);
}
@Override
public void onFailure(Call<ResultQuery> call, Throwable t) {
}
});
}
private void setProfileDistance() {
MainActivity mainActivity = new MainActivity();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(mainActivity.url)
.addConverterFactory(GsonConverterFactory.create())
.build();
OrganizerAPI services = retrofit.create(OrganizerAPI.class);
Call<List<ResultQuery>> call = services.show_stat_distance(id_user,id_add);
call.enqueue(new Callback<List<ResultQuery>>() {
@Override
public void onResponse(Call<List<ResultQuery>> call, Response<List<ResultQuery>> response) {
List<ResultQuery> resultQueries = (List<ResultQuery>) response.body();
double x = 0.00;
for(int i =0;i<resultQueries.size();i++){
String cal = resultQueries.get(i).getDistance();
Float y = Float.valueOf(cal);
x = x + y;
//Toast.makeText(ShowDistanceEventActivity.this,cal, Toast.LENGTH_SHORT).show();
}
distance_user.setText(String.format("%.2f",x));
}
@Override
public void onFailure(Call<List<ResultQuery>> call, Throwable t) {
Toast.makeText(DetailDistanceUserActivity.this,"ไม่พบสถิติวิ่งของคุณ", Toast.LENGTH_SHORT).show();
}
});
}
} |
package utils;
import java.awt.Component;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.sql.Connection;
import java.util.Map;
import java.util.TreeMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import db.JtdsDriver;
import db.SQL;
import file.FileUtils;
import gui.ComponentTools;
import gui.comp.FileChooser;
/**
* Provides a means to store and retrieve persistent default configuration
* settings using a simple property (key = value) file.
*/
public class Options extends TreeMap<String, String>
{
public static final String DBMS_HOST = "DBMSHost";
public static final String DBMS_PORT = "DBMSPort";
public static final String DATABASE = "Database";
private static final long serialVersionUID = 1L;
private static final Pattern OPT_PATTERN = Pattern.compile ("([^=]+)=(.+)");
private String optionsFile;
public Options (final String dir)
{
String home = System.getProperty ("user.home");
String path = home + "/Local Settings/Application Data/" + dir;
optionsFile = path + File.separator + "options.txt";
// set default values
put (DBMS_HOST, "ob03");
put (DBMS_PORT, "1433");
}
public String getOptionsFile()
{
return optionsFile;
}
public void setOptionsFile (final String optionsFile)
{
this.optionsFile = optionsFile;
}
public void read()
{
BufferedReader br = null;
try
{
FileInputStream fis = new FileInputStream (optionsFile);
InputStreamReader isr = new InputStreamReader (fis);
br = new BufferedReader (isr);
String line = null;
while ((line = br.readLine()) != null)
parseOption (line);
}
catch (IOException x)
{
System.err.println (x);
}
finally
{
FileUtils.close (br);
}
}
public String get (final String key, final String defaultValue)
{
String value = get (key);
if (value == null)
value = defaultValue;
return value;
}
public int getInt (final String key, final int defaultValue)
{
String value = get (key);
return value != null ? Integer.parseInt (value) : defaultValue;
}
public File getFile (final String key)
{
String value = get (key);
return value != null ? new File (value) : null;
}
private void parseOption (final String line)
{
Matcher m = OPT_PATTERN.matcher (line);
if (m.matches())
put (m.group (1), m.group (2));
}
public void write()
{
PrintStream out = null;
try
{
FileUtils.makeDir (new File (optionsFile).getParent());
out = new PrintStream (optionsFile);
write (out);
}
catch (IOException x)
{
System.err.println (x);
}
finally
{
FileUtils.close (out);
}
}
public void write (final PrintStream out)
{
for (Map.Entry<String, String> entry : this.entrySet())
out.println (entry.getKey() + "=" + entry.getValue());
out.flush();
}
public void warn (final Component owner, final String title,
final String message, final Exception x)
{
System.err.println (message);
if (x != null)
System.err.println (x);
if (title != null)
JOptionPane.showMessageDialog (owner, message + "\n" + x, title,
JOptionPane.ERROR_MESSAGE, null);
}
public SQL connect()
{
SQL sql = null;
final String host = get (DBMS_HOST);
final int port = getInt (DBMS_PORT, 1433);
final String db = get (DATABASE);
JtdsDriver dd = new JtdsDriver(); // supports Windows Authentication SSO
final Connection conn = dd.connect (host, port + "", db);
if (conn != null)
sql = new SQL (db, conn);
return sql;
}
public String getDatabase() // used in warnings
{
return get (DBMS_HOST) + ":" + get (DBMS_PORT) + " " + get (DATABASE);
}
public File selectFile (final Component owner, final String title,
final String regex, final String description,
final String pathOption, final int mode)
{
File choice = null;
FileChooser fc = new FileChooser (title, get (pathOption));
fc.setFileSelectionMode (mode);
fc.setRegexFilter (regex, description);
// cf.setSelectedFile (new File (defaultName));
if (fc.showOpenDialog (owner) == JFileChooser.APPROVE_OPTION)
{
choice = fc.getSelectedFile();
put (pathOption, choice.isDirectory() ? choice.getPath() : choice.getParent());
write();
}
return choice;
}
public static void main (final String[] args)
{
ComponentTools.setDefaults();
Options options = new Options ("Oberon/HR");
options.read();
System.out.println (options.optionsFile);
options.write (System.out);
}
}
|
package com.trannguyentanthuan2903.yourfoods.favorites.model;
import android.support.v7.widget.CardView;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.trannguyentanthuan2903.yourfoods.R;
/**
* Created by Administrator on 10/31/2017.
*/
public class FavoriteViewHolder extends RecyclerView.ViewHolder {
public TextView txtStoreName, txtSumfavorite, txtSumShipped, txtAddress, txtTimeWork, txtDistance, txtSumProduct, txtStatus,txtEmailStore,txtSumComment;
public ImageView imgHeart, imgPhotoStore;
public LinearLayout linearLayout,imgComment;
public CardView cardView;
public Button btnViewProfileStore, btnViewOrder;
public FavoriteViewHolder(View itemView) {
super(itemView);
txtStoreName = (TextView) itemView.findViewById(R.id.txtStoreName_itemstore);
txtSumfavorite = (TextView) itemView.findViewById(R.id.txtHeart);
txtSumShipped = (TextView) itemView.findViewById(R.id.txtSumShipped);
txtAddress = (TextView) itemView.findViewById(R.id.txtAddress_itemstore);
txtTimeWork = (TextView) itemView.findViewById(R.id.txtTimeWork_itemstore);
txtDistance = (TextView) itemView.findViewById(R.id.txtDistanceFromUserToStore);
txtSumProduct = (TextView) itemView.findViewById(R.id.txtSumProduct);
txtStatus = (TextView) itemView.findViewById(R.id.txtStatus_itemStore);
txtEmailStore =(TextView) itemView.findViewById(R.id.txtEmail_itemStore);
txtSumComment = (TextView) itemView.findViewById(R.id.txtSumShipped_itemstore);
linearLayout = (LinearLayout) itemView.findViewById(R.id.layoutInfo);
cardView = (CardView) itemView.findViewById(R.id.cardView);
btnViewProfileStore = (Button) itemView.findViewById(R.id.btnViewProfileStore);
btnViewOrder = (Button) itemView.findViewById(R.id.btnViewOrder);
imgHeart = (ImageView) itemView.findViewById(R.id.imgHeart);
imgComment= (LinearLayout) itemView.findViewById(R.id.imgComment) ;
imgPhotoStore = (ImageView) itemView.findViewById(R.id.imgPhotoStore_itemStore);
}
}
|
/* BindingNode.java
{{IS_NOTE
Purpose:
Description:
History:
Thu Feb 1 16:16:54 2007, Created by Henri
}}IS_NOTE
Copyright (C) 2006 Potix Corporation. All Rights Reserved.
{{IS_RIGHT
}}IS_RIGHT
*/
package org.zkoss.zkplus.databind;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.zkoss.zk.ui.UiException;
/**
* BindingNode that forms a databinding bean path dependant tree.
*
* @author Henri
*/
/*package*/ class BindingNode implements java.io.Serializable {
private static final long serialVersionUID = 200808191424L;
private LinkedHashSet _bindingSet = new LinkedHashSet(); //(Binding set of this expression BindingNode)
private Map _kids = new LinkedHashMap(7); //(nodeid, BindingNode)
private String _path; //path of this BindingNode
private Set _sameNodes = new HashSet(); //BindingNode Set that refer to the same object
private boolean _var; //a var node
private String _nodeId; //node id of this BindingNode
private boolean _root; //whether root node of a path
private boolean _innerCollectionNode; //whether a collection in collection item node
/** Constructor.
* @param path the path of this node in the expression dependant tree.
* @param var whether a _var variable binding node.
*/
public BindingNode(String path, boolean var, String id, boolean root) {
_path = path;
_sameNodes.add(this);
_var = var;
_nodeId = id;
_root = root;
}
public LinkedHashSet getBindings() {
return _bindingSet;
}
/** Get all Bindings below the given nodes (deepth first traverse).
*/
public LinkedHashSet getAllBindings() {
Set walkedNodes = new HashSet(23);
LinkedHashSet all = new LinkedHashSet(23*2);
myGetAllBindings(all, walkedNodes);
return all;
}
private void myGetAllBindings(LinkedHashSet all, Set walkedNodes) {
if (walkedNodes.contains(this)) {
return; //already walked, skip
}
//mark as walked already
walkedNodes.add(this);
for(final Iterator it = _kids.values().iterator(); it.hasNext();) {
((BindingNode) it.next()).myGetAllBindings(all, walkedNodes); //recursive
}
for(final Iterator it = _sameNodes.iterator(); it.hasNext();) {
final Object obj = it.next();
if (obj instanceof BindingNode) {
((BindingNode) obj).myGetAllBindings(all, walkedNodes); //recursive
}
}
all.addAll(getBindings());
}
public String getPath() {
return _path;
}
public String getNodeId() {
return _nodeId;
}
public boolean isVar() {
return _var;
}
public boolean isRoot() {
return _root;
}
/** Add a binding in the BindingNode of the specified path.
* @param path the path of the specified BindingNode in the tree.
* @param binding the binding to be added to the specified BindingNode.
* @param varnameSet set with all _var names
*/
public void addBinding(String path, Binding binding, Set varnameSet) {
final List nodeids = DataBinder.parseExpression(path, ".");
if (nodeids.size() <= 0) {
throw new UiException("Incorrect bean expression: "+path);
}
boolean var = varnameSet.contains(nodeids.get(0));
BindingNode currentNode = this;
for(final Iterator it = nodeids.iterator(); it.hasNext();) {
final String nodeid = (String) it.next();
if (nodeid == null) {
throw new UiException("Incorrect bean expression: "+path);
}
BindingNode kidNode = (BindingNode) currentNode.getKidNode(nodeid);
if (kidNode == null) { //if not found, then add one
if ("/".equals(currentNode._path)) {
kidNode = new BindingNode(nodeid, var, nodeid, true);
} else {
kidNode = new BindingNode(currentNode._path + "." + nodeid, var, nodeid, false);
}
currentNode.addKidNode(nodeid, kidNode);
} else {
var = var || kidNode._var;
}
currentNode = kidNode;
}
if (currentNode == this) {
throw new UiException("Incorrect bean expression: "+path);
}
currentNode.addBinding(binding);
if ("_var".equals(binding.getAttr())) {
currentNode._innerCollectionNode = DataBinder.hasTemplateOwner(binding.getComponent());
}
}
public boolean isInnerCollectionNode() {
return _innerCollectionNode;
}
/** Add a binding to this BindingNode.
* @param binding the binding to be added to this node.
*/
public void addBinding(Binding binding) {
_bindingSet.add(binding);
}
/** Locate the BindingNode of the specified path.
* @param path the path of the specified BindingNode in the tree.
*/
public BindingNode locate(String path) {
BindingNode currentNode = this;
final List nodeids = DataBinder.parseExpression(path, ".");
for(final Iterator it = nodeids.iterator(); it.hasNext(); ) {
final String nodeid = (String) it.next();
if (nodeid == null) {
throw new UiException("Incorrect format of bean expression: "+path);
}
currentNode = (BindingNode) currentNode.getKidNode(nodeid);
if (currentNode == null) {
return null;
}
}
return currentNode == this ? null : currentNode;
}
/** Get root node of this node.
*/
public BindingNode getRootNode(BindingNode superNode) {
if (isRoot()) {
return this;
}
final int j = getPath().indexOf(".");
final String path = (j < 0) ? getPath() : getPath().substring(0, j);
return superNode.locate(path);
}
/** get the sameNodes of this BindingNode.
*/
public Set getSameNodes() {
return _sameNodes;
}
/** merge and set the given other sameNodes as sameNodes of this BindingNode.
*/
public void mergeAndSetSameNodes(Set other) {
if (other == _sameNodes) { //same set, no need to merge
return;
}
if (_sameNodes != null) {
other.addAll(_sameNodes);
}
_sameNodes = other;
}
public String toString() {
return _path;
}
// Get kid nodes
/*package*/ Collection getKidNodes() {
return _kids.values();
}
// Get kid nodes of the specified nodeid.
/*package*/ BindingNode getKidNode(String nodeid) {
return (BindingNode) _kids.get(nodeid);
}
private void addKidNode(String nodeid, BindingNode kid) {
_kids.put(nodeid, kid);
}
}
|
package mavenproject1.testng;
import org.testng.annotations.Test;
public class mavenTest {
@Test(priority=7)
public void Test1()
{
System.out.println("1st test");
}
@Test(priority=6)
public void Test2()
{
System.out.println("2nd test");
}
@Test(priority=5)
public void Test3()
{
System.out.println("3rd test");
}
@Test(priority=4)
public void Test4()
{
System.out.println("4th test");
}
@Test(priority=3)
public void Test5()
{
System.out.println("5rd test");
}
@Test(priority=2)
public void Test6()
{
System.out.println("6nd test");
}
@Test(priority=1)
public void Test7()
{
System.out.println("7rd test");
}
}
|
package com.sample.myapplication;
import android.app.Activity;
import android.content.DialogInterface;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
import com.sample.myapplication.adapter.FlickrImagesAdapter;
import com.sample.myapplication.base.BaseActivity;
import com.sample.myapplication.display_model.FlickrImagesDisplayModel;
import com.sample.myapplication.network.service.client.FlickrImagesRestClient;
import com.sample.myapplication.network.service.event.FlickrImagesResponseEvent;
import com.sample.myapplication.network.service.model.FlickrImages;
import com.sample.myapplication.network.service.model.Photo;
import org.greenrobot.eventbus.Subscribe;
import java.util.ArrayList;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import timber.log.Timber;
public class MainActivity extends BaseActivity {
@BindView(R.id.searchText)
EditText searchEditTextView;
@BindView(R.id.flickr_images_recycler_view)
android.support.v7.widget.RecyclerView recyclerView;
@BindView(R.id.noResultsTextView)
TextView resultTextView;
private FlickrImagesAdapter flickrImagesAdapter;
private ArrayList<FlickrImagesDisplayModel> displayList = new ArrayList<>();
private int page = 1;
private int perPage = 30;
private Handler handler;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
recyclerView.setHasFixedSize(true);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(MainActivity.this);
linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
recyclerView.setLayoutManager(linearLayoutManager);
handler = new Handler();
captureDone();
}
@Override
protected void onPause() {
super.onPause();
FlickrImagesRestClient.getInstance().cancelFlickrImagesRestCall();
}
@Override
public void onCancel(DialogInterface dialogInterface) {
FlickrImagesRestClient.getInstance().cancelFlickrImagesRestCall();
}
@Override
public void onResume() {
super.onResume();
if(flickrImagesAdapter != null) {
flickrImagesAdapter.refreshAdapter();
}
}
@OnClick(R.id.button)
public void onClickButton() {
if(displayList != null) {
displayList.clear();
}
if(flickrImagesAdapter != null) {
flickrImagesAdapter.notifyDataSetChanged();
}
page = 1;
hideKeyboard(MainActivity.this);
showProgressDialog(getString(R.string.fetching) + " " + searchEditTextView.getText().toString());
FlickrImagesRestClient.getInstance().getFlickrImages(searchEditTextView.getText().toString(), perPage, page);
Log.d("Flickr Images, Text",searchEditTextView.getText().toString());
}
public void hideKeyboard(Activity activity) {
InputMethodManager imm = (InputMethodManager) activity.getSystemService(Activity.INPUT_METHOD_SERVICE);
//Find the currently focused view, so we can grab the correct window token from it.
View view = activity.getCurrentFocus();
//If no view currently has focus, create a new one, just so we can grab a window token from it
if (view == null) {
view = new View(activity);
}
imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
private void captureDone() {
searchEditTextView.setOnEditorActionListener(new EditText.OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if (actionId == EditorInfo.IME_ACTION_NEXT) {
onClickButton();
return true;
}
return false;
}
});
}
@Subscribe
public void onFlickrImagesResponseEvent(FlickrImagesResponseEvent event) {
closeProgressDialog();
if (!event.isCanceled()) {
if (event.hasResponse()) {
if(flickrImagesAdapter == null) {
FlickrImages flickrImages = event.getResponse();
Log.i("FlickrImages", "Received");
resultTextView.setVisibility(View.GONE);
resultTextView.setText(flickrImages.toString());
recyclerView.setVisibility(View.VISIBLE);
setFlickrImagesAdapter(flickrImages);
Log.d("FlickrImages", "Received Flickr Images.");
} else {
final FlickrImages flickrImages = event.getResponse();
handler.post(new Runnable() {
@Override
public void run() {
if(displayList.size() > 0) {
displayList.remove(displayList.size() - 1);
flickrImagesAdapter.notifyItemRemoved(displayList.size());
}
flickrImagesAdapter.setResultListSize(flickrImages.getPhotos().getPhoto().size());
for(int i=0; i<flickrImages.getPhotos().getPhoto().size(); i=i+3) {
addItemToList(i, flickrImages);
flickrImagesAdapter.notifyItemInserted(displayList.size());
}
flickrImagesAdapter.setLoaded();
}
});
}
} else {
resultTextView.setText(getString(R.string.no_data));
recyclerView.setVisibility(View.GONE);
Log.d("FlickrImages","Error getting Flickr Images.");
}
} else {
resultTextView.setVisibility(View.GONE);
recyclerView.setVisibility(View.GONE);
Log.d("FlickrImages","Canceled getting Flickr Images.");
}
}
private void setFlickrImagesAdapter(FlickrImages flickrImages) {
flickrImagesAdapter = new FlickrImagesAdapter(
MainActivity.this,
getDisplayList(flickrImages),
recyclerView,
flickrImages.getPhotos().getPhoto().size());
flickrImagesAdapter.setOnLoadMoreListener(new OnLoadMoreListener() {
@Override
public void onLoadMore() {
displayList.add(null);
flickrImagesAdapter.notifyItemInserted(displayList.size() - 1);
page++;
makeRequest(page);
}
});
recyclerView.setAdapter(flickrImagesAdapter);
}
private void makeRequest(int page) {
FlickrImagesRestClient.getInstance().getFlickrImages(searchEditTextView.getText().toString(), perPage, page);
}
private ArrayList<FlickrImagesDisplayModel> getDisplayList(FlickrImages flickrImages) {
for(int i=0; i<flickrImages.getPhotos().getPhoto().size(); i=i+3) {
addItemToList(i, flickrImages);
}
return displayList;
}
private void addItemToList(int i, FlickrImages flickrImages) {
int index = i;
Photo photo1 = null;
Photo photo2 = null;
Photo photo3 = null;
if(index < flickrImages.getPhotos().getPhoto().size()) {
photo1 = flickrImages.getPhotos().getPhoto().get(index);
index++;
}
if(index < flickrImages.getPhotos().getPhoto().size()) {
photo2 = flickrImages.getPhotos().getPhoto().get(index);
index++;
}
if(index < flickrImages.getPhotos().getPhoto().size()) {
photo3 = flickrImages.getPhotos().getPhoto().get(index);
}
StringBuilder urlOne = null;
if(photo1 != null) {
urlOne = new StringBuilder("http://farm")
.append(photo1.getFarm())
.append(".static.flickr.com/")
.append(photo1.getServer())
.append("/")
.append(photo1.getId())
.append("_")
.append(photo1.getSecret())
.append(".jpg");
}
StringBuilder urlTwo = null;
if(photo2 != null) {
urlTwo = new StringBuilder("http://farm")
.append(photo2.getFarm())
.append(".static.flickr.com/")
.append(photo2.getServer())
.append("/")
.append(photo2.getId())
.append("_")
.append(photo2.getSecret())
.append(".jpg");
}
StringBuilder urlThree = null;
if(photo3 != null) {
urlThree = new StringBuilder("http://farm")
.append(photo3.getFarm())
.append(".static.flickr.com/")
.append(photo3.getServer())
.append("/")
.append(photo3.getId())
.append("_")
.append(photo3.getSecret())
.append(".jpg");
}
displayList.add(new FlickrImagesDisplayModel(urlOne.toString(), urlTwo.toString(), urlThree.toString()));
}
}
|
package ffm.slc.model.enums;
/**
* Specifies whether the course was defined by the SEA, LEA, School, or national organization.
*/
public enum CourseDefinedByType {
LEA("LEA"),
NATIONAL_ORGANIZATION("National Organization"),
SEA("SEA"),
SCHOOL("School");
private String prettyName;
CourseDefinedByType(String prettyName) {
this.prettyName = prettyName;
}
@Override
public String toString() {
return prettyName;
}
}
|
package models;
import javax.persistence.*;
import java.util.List;
@Entity
@Table(name = "owners_and_animals")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
@Column
private String name;
@Column
private int age;
@OneToMany
@JoinTable(name = "pets",
joinColumns =
@JoinColumn(name = "owner_id"),
inverseJoinColumns =
@JoinColumn(name = "id"))
private List<Pet> pets;
public User() {
}
public User(int id, String name, int age) {
this.id = id;
this.name = name;
this.age = age;
}
public User(String name, int age) {
this.name = name;
this.age = age;
}
public int getId() {
return id;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
public void setId(int id) {
this.id = id;
}
public void setName(String name) {
this.name = name;
}
public void setAge(int age) {
this.age = age;
}
public List<Pet> getPets() {
return pets;
}
public void setPets(List<Pet> pets) {
this.pets = pets;
}
@Override
public String toString() {
return id + " " + name + " " + age;
}
@Override
public boolean equals(Object object) {
if (this == object) {
return true;
}
if (object == null || !(object instanceof User)) {
return false;
}
User that = (User) object;
return this.id == that.id &&
this.age == that.age &&
this.name.equals(that.name);
}
} |
package com.wacai.springboot_demo.service;
import javax.servlet.http.HttpServletRequest;
public interface GetipService {
void getip(HttpServletRequest request);
}
|
package com.share.util;
import java.io.File;
import java.io.FileInputStream;
import org.apache.commons.io.IOUtils;
import org.apache.commons.net.ftp.FTPClient;
public class FtpUtil {
private String url;
private String username;
private String passwd;
private String workSpace;
public FtpUtil(String url, String username, String passwd, String workSpace) {
this.url = url;
this.username = username;
this.passwd = passwd;
this.workSpace = workSpace;
}
public void setUrl(String url) {
this.url = url;
}
public void setUsername(String username) {
this.username = username;
}
public void setPasswd(String passwd) {
this.passwd = passwd;
}
public void setWorkSpace(String workSpace) {
this.workSpace = workSpace;
}
public void upload(File srcFile){
FTPClient client = new FTPClient();
FileInputStream fis = null;
try {
client.connect(url);
client.login(username, passwd);
fis = new FileInputStream(srcFile);
// 设置上传目录
if (workSpace != null && !"".equals(workSpace)) {
client.changeWorkingDirectory(workSpace);
}
client.setBufferSize(1024);
client.setControlEncoding("UTF-8");
// 设置文件类型
client.setFileType(FTPClient.BINARY_FILE_TYPE);
client.storeFile(srcFile.getName(), fis);
System.out.println("ftp upload file successful!");
} catch (Exception e) {
e.printStackTrace();
} finally{
IOUtils.closeQuietly(fis);
try {
client.disconnect();
} catch (Exception e) {
e.printStackTrace();
}
}
}
public void upload(String filepath) {
upload(new File(filepath));
}
}
|
package com.brichri.howTiredAmI.ui;
import java.util.Date;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.text.format.DateFormat;
import android.util.Log;
import android.widget.TextView;
import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuInflater;
import com.actionbarsherlock.view.MenuItem;
import com.brichri.howTiredAmI.R;
import com.brichri.howTiredAmI.pvt.Result;
public class ResultDetailActivity extends SherlockFragmentActivity {
private static final String TAG = "Result Activity";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.v(TAG, "onCreate");
if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE
&& getResources().getBoolean(R.bool.wideEnoughForDualPane)) {
// If the screen is now in landscape mode and this screen size
// is wide enough to support dual pane results, finish this activity.
finish();
return;
}
// TODO move this stuff into styles
ActionBar actionBar = getSupportActionBar();
actionBar.setDisplayOptions(
ActionBar.DISPLAY_SHOW_HOME
| ActionBar.DISPLAY_SHOW_CUSTOM
| ActionBar.DISPLAY_HOME_AS_UP);
actionBar.setCustomView(R.layout.date_and_duration);
getWindow().setBackgroundDrawableResource(R.color.dark_grey);
Result result = (Result) getIntent().getExtras().getSerializable(Result.TAG);
final long resultsId = result.getId();
// When this activity is created for the first time
if (savedInstanceState == null) {
final ResultFragment resultFrag = ResultFragment.newInstance(result, false);
Log.v(TAG, "adding fragment for resultsId " + resultsId);
getSupportFragmentManager().beginTransaction().add(android.R.id.content, resultFrag).commit();
}
// TODO fix layout to ensure duration doesn't get pushed out
TextView dateView = (TextView) findViewById(R.id.ab_date);
if(dateView != null) {
Date date = new Date();
date.setTime(result.getStartDate());
dateView.setText(DateFormat.format(getResources().getString(R.string.date_format), date));
}
TextView durationView = (TextView) findViewById(R.id.ab_duration);
if(durationView != null){
durationView.setText(result.getLevel().getLabel(this));
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getSupportMenuInflater();
inflater.inflate(R.menu.results, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
Intent intent = new Intent(this, ResultsActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
} |
package com.siicanada.article.repository;
import com.siicanada.article.repository.entity.TagEntity;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
/**
* Tag Repository.
*/
@Repository
public interface TagRepository extends JpaRepository<TagEntity, Integer> {
TagEntity getByDescription(String description);
}
|
package com.muhardin.endy.training;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
@Repository
public class JenisProdukDao {
@Autowired private DataSource dataSource;
private String sqlInsert = "insert into jenis_produk (kode, nama) "
+ "values (?,?)";
private String sqlUpdate = "update jenis_produk set kode=?, nama=? "
+ "where id = ?";
private String sqlCariSemuaJenisProduk = "select * from jenis_produk order by kode";
public void simpan(JenisProduk jp) throws Exception {
Connection c = dataSource.getConnection();
if (jp.getId() == null) {
PreparedStatement psInsert = c.prepareStatement(sqlInsert);
psInsert.setString(1, jp.getKode());
psInsert.setString(2, jp.getNama());
psInsert.executeUpdate();
} else {
PreparedStatement psUpdate = c.prepareStatement(sqlUpdate);
psUpdate.setString(1, jp.getKode());
psUpdate.setString(2, jp.getNama());
psUpdate.setInt(5, jp.getId());
psUpdate.executeUpdate();
}
c.close();
}
public List<JenisProduk> cariSemuaJenisProduk() throws Exception {
List<JenisProduk> hasil = new ArrayList<JenisProduk>();
Connection c = dataSource.getConnection();
PreparedStatement psCariSemua = dataSource.getConnection().prepareStatement(sqlCariSemuaJenisProduk);
ResultSet rs = psCariSemua.executeQuery();
while (rs.next()) {
JenisProduk jp = new JenisProduk();
jp.setId(rs.getInt("id"));
jp.setKode(rs.getString("kode"));
jp.setNama(rs.getString("nama"));
hasil.add(jp);
}
c.close();
return hasil;
}
}
|
package edu.neu.ccs.cs5010;
import java.util.ArrayList;
/**
* Created by xwenfei on 10/22/17.
*/
public class Mansion implements INeighborhood {
public ArrayList<Candy> candyList;
/**
* General mansion constructor.
* add all the candy from historical data
*/
public Mansion() {
candyList = new ArrayList<Candy>();
candyList.add(new Candy("Twix", "Super"));
candyList.add(new Candy("Snickers", "Super"));
candyList.add(new Candy("Mars", "Super"));
candyList.add(new Candy("Kit Kat", "King"));
candyList.add(new Candy("Whoopers", "King"));
candyList.add(new Candy("Crunch", "King"));
candyList.add(new Candy("Toblerone", "Fun"));
candyList.add(new Candy("Baby Ruth", "Fun"));
candyList.add(new Candy("Almond Joy", "Fun"));
}
@Override
public void accept(INeighborhoodVisitor INeighborhoodVisitor){
INeighborhoodVisitor.visit(this);
}
}
|
package com.clever.presenter.impl;
import com.clever.presenter.SplashPresenter;
import com.clever.ui.interf.SplashView;
/**
* @author liuhea
* @date 2016-12-29</p>
*/
public class SplashPresenterImpl implements SplashPresenter {
private SplashView mSplashView;
public SplashPresenterImpl(SplashView splashView) {
mSplashView = splashView;
}
@Override
public void isFirstLogin() {
// if (EMClient.getInstance().isConnected() && EMClient.getInstance().isLoggedInBefore()) {
// // 已登录,暂时替代sp .
mSplashView.onFirstLogin(false);
// } else {
// // 未登录 .
// mSplashView.onFirstLogin(true);
// }
}
}
|
/*
* 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 tugas2;
/*
* 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.
*/
import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.TextArea;
import javafx.scene.layout.GridPane;
import javafx.scene.text.Text;
import javafx.scene.control.TextField;
import javafx.stage.Stage;
public class Tugas2 extends Application {
@Override
public void start(Stage stage) {
//creating label email
Text text1 = new Text("Nama");
//creating label password
Text text2 = new Text("Telepon");
Text text3 = new Text("Alamat");
//Creating Text Filed for email
TextField textField1 = new TextField();
//Creating Text Filed for password
TextField textField2 = new TextField();
TextArea textArea1 = new TextArea();
//Creating Buttons
Button button1 = new Button("Kirim");
Button button2 = new Button("Hapus");
//Creating a Grid Pane
GridPane gridPane = new GridPane();
//Setting size for the pane
gridPane.setMinSize(800, 400);
//Setting the padding
gridPane.setPadding(new Insets(10, 10, 10, 10));
//Setting the vertical and horizontal gaps between the columns
gridPane.setVgap(5);
gridPane.setHgap(5);
//Setting the Grid alignment
gridPane.setAlignment(Pos.CENTER);
//Arranging all the nodes in the grid
gridPane.add(text1, 0, 0);
gridPane.add(textField1, 1, 0);
gridPane.add(text2, 0, 1);
gridPane.add(textField2, 1, 1);
gridPane.add(text3, 0, 2);
gridPane.add(textArea1, 1, 2);
gridPane.add(button1, 0, 3);
gridPane.add(button2, 1, 3);
//Creating a scene object
Scene scene = new Scene(gridPane);
//Setting title to the Stage
stage.setTitle("Form");
//Adding scene to the stage
stage.setScene(scene);
//Displaying the contents of the stage
stage.show();
}
public static void main(String args[]){
launch(args);
}
} |
package blackjack;
public class Kortti {
String maa;
int arvo;
String kuvapolku;
public Kortti (String maa, int arvo, String kuvapolku) {
this.maa = maa;
this.arvo = arvo;
this.kuvapolku = kuvapolku;
}
public void setMaa(String maa) {
this.maa = maa;
}
public void setArvo() {
this.arvo = arvo;
}
public String getKuvaPolku() {
return kuvapolku;
}
public String getMaa() {
return maa;
}
public int getArvo() {
return arvo;
}
public String toString() {
String tulostettavaArvo = "";
if (arvo == 11) {
tulostettavaArvo = "j";
} else if (arvo == 12) {
tulostettavaArvo = "q";
} else if (arvo == 13) {
tulostettavaArvo = "k";
} else if (arvo == 1) {
tulostettavaArvo = "1";
} else {
tulostettavaArvo = arvo + "";
}
return maa + tulostettavaArvo;
}
}
|
package edu.weber.edu.matchgame;
import javafx.application.Application;
import javafx.event.EventHandler;
import javafx.geometry.Insets;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.SceneAntialiasing;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.*;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
import javafx.stage.Stage;
import java.util.ArrayList;
/**
* Created by Scott on 11/4/2014.
*/
public class Game extends Application {
private Stage primaryStage;
private Scene primaryScene;
private Pane root;
private int numberOfCards = 16;
private int boardSize = 800;
private ArrayList<Card> cardsArray;
@Override
public void start(Stage primaryStage) throws Exception {
this.primaryStage = primaryStage;
primaryScene = new Scene(getRoot(), boardSize, boardSize, true, SceneAntialiasing.BALANCED);
this.primaryStage.setScene(primaryScene);
cardsArray = new ArrayList<>();
FlowPane cardsLayout = new FlowPane();
ArrayList<Card> deck = buildDeck();
for(Card card: deck){
cardsLayout.setPadding(new Insets(10,10,10,10));
cardsLayout.setVgap(40);
cardsLayout.setHgap(40);
cardsLayout.setPrefWrapLength(boardSize);
card.addEventHandler(MouseEvent.MOUSE_CLICKED, event -> card.toggleSelect());
cardsLayout.getChildren().add(card);
}
getRoot().getChildren().addAll(cardsLayout);
this.primaryStage.show();
}
private ArrayList buildDeck() {
ArrayList<Card> cards = new ArrayList<>();
cards.add(new Card("images/bird.png"));
cards.add(new Card("images/cat.png"));
cards.add(new Card("images/dog.png"));
cards.add(new Card("images/duck.png"));
cards.add(new Card("images/elephant.png"));
cards.add(new Card("images/fish.png"));
cards.add(new Card("images/frog.png"));
cards.add(new Card("images/tiger.png"));
cards.add(new Card("images/bird.png"));
cards.add(new Card("images/cat.png"));
cards.add(new Card("images/dog.png"));
cards.add(new Card("images/duck.png"));
cards.add(new Card("images/elephant.png"));
cards.add(new Card("images/fish.png"));
cards.add(new Card("images/frog.png"));
cards.add(new Card("images/tiger.png"));
return cards;
}
private Pane getRoot() {
if (null == root) {
root = new Pane();
}
return root;
}
}
|
/*
* 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 hdfcraft;
/**
*
* @author SchmitzP
*/
public class HeightFilter implements Filter {
public HeightFilter(int maxHeight, int startHeight, int stopHeight, boolean feather) {
this.startHeight = startHeight;
this.stopHeight = stopHeight;
this.feather = feather;
if (feather) {
if (startHeight > 0) {
start = Math.max(startHeight - 2, 0);
fullStart = startHeight + 2;
} else {
start = 0;
fullStart = 0;
}
if (stopHeight < (maxHeight - 1)) {
fullEnd = stopHeight - 2;
end = Math.min(stopHeight + 2, maxHeight - 1);
} else {
fullEnd = maxHeight - 1;
end = maxHeight - 1;
}
} else {
start = fullStart = startHeight;
end = fullEnd = stopHeight;
}
}
@Override
public int getLevel(int x, int y, int z, int inputLevel) {
if ((z < start) || (z > end)) {
return 0;
} else if (z < fullStart) {
// Lower feathering
return inputLevel - (fullStart - z) * inputLevel / (fullStart - start + 1);
} else if (z <= fullEnd) {
// Full strength
return inputLevel;
} else {
// Upper feathering
return inputLevel - (z - fullEnd) * inputLevel / (end - fullEnd + 1);
}
}
public int getStartHeight() {
return startHeight;
}
public int getStopHeight() {
return stopHeight;
}
public boolean isFeather() {
return feather;
}
private final int start, fullStart, end, fullEnd, startHeight, stopHeight;
private final boolean feather;
private static final long serialVersionUID = 1L;
} |
package com.encounterfitness.musicapp;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ListView;
import java.util.ArrayList;
public class Country extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.song_list);
//create an arraylist and add the Artist and Title
ArrayList <MusicDetails> music = new ArrayList <>();
music.add(new MusicDetails(R.drawable.garthbrooks,"Garth Brooks", "Friends In Low Places", R.drawable.playbutton));
music.add(new MusicDetails(R.drawable.railroad,"Confederate Railroad", "Trashy Women", R.drawable.playbutton));
music.add(new MusicDetails(R.drawable.johnmichael,"John Michael Montgomery", "Sold (The Grundy County Auction Incident)", R.drawable.playbutton));
music.add(new MusicDetails(R.drawable.kennyroger,"Kenny Rogers", "The Gambler", R.drawable.playbutton));
music.add(new MusicDetails(R.drawable.clintblack,"Clint Black", "A Better Man", R.drawable.playbutton));
music.add(new MusicDetails(R.drawable.alanjackson,"Alan Jackson", "Gone Country", R.drawable.playbutton));
music.add(new MusicDetails(R.drawable.brooksanddunn,"Brooks and Dunn", "Neon Moon", R.drawable.playbutton));
music.add(new MusicDetails(R.drawable.timmcgraw,"Tim McGraw", "Where The Green Grass Grows", R.drawable.playbutton));
music.add(new MusicDetails(R.drawable.kennychesney,"Kenny Chesney", "She's Got It All", R.drawable.playbutton));
music.add(new MusicDetails(R.drawable.rebamcentire,"Reba McEntire", "Fancy", R.drawable.playbutton));
MusicDetailsAdapter adapter = new MusicDetailsAdapter(this, music);
ListView listView = findViewById(R.id.list);
listView.setAdapter(adapter);
}
}
|
package com.platform.interceptor;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import com.platform.session.CustomSessionContext;
import com.platform.session.SessionVariable;
import com.platform.util.ConfigLoadUtil;
import com.platform.util.LoginInitUtil;
/**
*
* ClassName:LoginValidationFilter Function:
* 登录验证过滤器 ,判断是否存在默认职责,判断用户密码是否重置
*
*
*/
public class LoginValidationInterceptor implements HandlerInterceptor {
//private static Logger logger = Logger.getLogger(LoginValidationInterceptor.class);
private static List<String> noFilterUrlList = null; // 不拦截的url页面
private static List<String> nolyPfUseUrlList = null; // 只有平台可以使用页面
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
request.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("UTF-8");
noFilterUrlList = ConfigLoadUtil.getFilterExclusion();
nolyPfUseUrlList = ConfigLoadUtil.getOnlyAcUseUrl();
String requestUrl = request.getRequestURL().toString();
String queryStr = request.getQueryString();
if (queryStr != null) {
requestUrl = requestUrl.concat("?").concat(queryStr);
}
String lowerUrl = requestUrl.toLowerCase();
if (lowerUrl.endsWith(".css") || lowerUrl.endsWith(".js") || lowerUrl.endsWith(".gif") || lowerUrl.endsWith(".jpg")
|| lowerUrl.endsWith(".jpeg") || lowerUrl.endsWith(".png") || lowerUrl.endsWith(".ico") || lowerUrl.indexOf("fonts") > 0) {
return true;
}
HttpSession session = request.getSession();
CustomSessionContext.setCurrentSession(session);
// 如果是Web Service(url中包含/services/的请求URL)都不校验登录信息
if (requestUrl.indexOf("/services/") > 0) {
return true;
}
HashMap<String, String> sessionVars = (HashMap<String, String>) session.getAttribute(SessionVariable.SESSION_VARS);
String secCode = request.getParameter("secCode");
// 如果有安全码,并且安全码有效,则模拟登录
if ((secCode != null) && (secCode.length() > 0)) {
//do....授权码待配置
if ("activity-bpm".equals(secCode)) {
String userCode = request.getParameter("userCode");
LoginInitUtil.initSession(request, response, null, userCode, "sec", true);
return true;
}
}
for (String filterUrl : noFilterUrlList) {
if (requestUrl.indexOf(filterUrl) >= 0) {
return true;
}
}
for (String authUrl : nolyPfUseUrlList) {
if (requestUrl.indexOf(authUrl) >= 0) {
return true;
}
}
// 如果不存在userId的话说明还未登录
if ((sessionVars == null) || (sessionVars.get(SessionVariable.userId) == null)) {
// 如果是登录页面,则跳过,否则跳转到登录页面
if (request.getRequestURI().indexOf(("/login.html")) >= 0) {
return true;
}
String serverUrl = ConfigLoadUtil.getServer();
sendRedirect(response,serverUrl + "/login.html");
}
return true;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
}
//对于请求是ajax请求重定向问题的处理方法
private static void sendRedirect(HttpServletResponse response, String redirectUrl){
try {
//这里并不是设置跳转页面,而是将重定向的地址发给前端,让前端执行重定向
//设置跳转地址
response.setHeader("redirectUrl", redirectUrl);
//设置跳转使能
response.setHeader("enableRedirect","true");
response.flushBuffer();
} catch (IOException ex) {
// logger.error("Could not redirect to: " + redirectUrl, ex);
ex.printStackTrace();
}
}
}
|
package msip.go.kr.common.entity;
import java.io.Serializable;
@SuppressWarnings("serial")
public class CommonVO implements Serializable {
/** 검색조건 */
private String searchCondition = "";
/** 검색Keyword */
private String searchKeyword = "";
/** 검색사용여부 */
private String searchUseYn = "";
/** 현재페이지 */
private int pageIndex = 1;
/** 페이지갯수 */
private int pageUnit = 10;
/** 페이지사이즈 */
private int pageSize = 10;
/** firstIndex */
private int firstIndex = 1;
/** lastIndex */
private int lastIndex = 1;
/** recordCountPerPage */
private int recordCountPerPage = 10;
/** 유저 esntl_id */
private String paramEsntlId;
/** 주소록 - 부서코드, 기관코드, 나의그룹코드 */
private Long nodeId;
public CommonVO() {
}
public CommonVO(String param) {
String[] params = param.split("&");
if(params.length == 0) {
this.nodeId = new Long(-1);
this.pageIndex = 1;
} else if(params.length == 1) {
this.pageIndex = Integer.parseInt(params[0]);
this.nodeId = new Long(-1);
} else if(params.length == 2) {
this.pageIndex = Integer.parseInt(params[0]);
this.nodeId = new Long(params[1]);
}
}
public String getSearchCondition() {
return searchCondition;
}
public void setSearchCondition(String searchCondition) {
this.searchCondition = searchCondition;
}
public String getSearchKeyword() {
return searchKeyword;
}
public void setSearchKeyword(String searchKeyword) {
this.searchKeyword = searchKeyword;
}
public String getSearchUseYn() {
return searchUseYn;
}
public void setSearchUseYn(String searchUseYn) {
this.searchUseYn = searchUseYn;
}
public int getPageIndex() {
return pageIndex;
}
public void setPageIndex(int pageIndex) {
this.pageIndex = pageIndex;
}
public int getPageUnit() {
return pageUnit;
}
public void setPageUnit(int pageUnit) {
this.pageUnit = pageUnit;
}
public int getPageSize() {
return pageSize;
}
public void setPageSize(int pageSize) {
this.pageSize = pageSize;
}
public int getFirstIndex() {
return firstIndex;
}
public void setFirstIndex(int firstIndex) {
this.firstIndex = firstIndex;
}
public int getLastIndex() {
return lastIndex;
}
public void setLastIndex(int lastIndex) {
this.lastIndex = lastIndex;
}
public int getRecordCountPerPage() {
return recordCountPerPage;
}
public void setRecordCountPerPage(int recordCountPerPage) {
this.recordCountPerPage = recordCountPerPage;
}
public String getParamEsntlId() {
return paramEsntlId;
}
public void setParamEsntlId(String paramEsntlId) {
this.paramEsntlId = paramEsntlId;
}
public Long getNodeId() {
return nodeId;
}
public void setNodeId(Long nodeId) {
this.nodeId = nodeId;
}
}
|
package modele.exceptions.ExceptionConnexion;
/**
* Created by alucard on 04/11/2016.
*/
public class ExceptionLoginDejaPris extends Exception {
}
|
package po;
import java.util.ArrayList;
import java.util.Iterator;
public class MatchTeamPO {
private MatchPlayerPO[] players;
private int[] scores;
private int totalScores;
private String name;
private int time;
public MatchTeamPO(MatchPlayerPO[] player,int [] scores,int totalScores,String name, int time)
{
this.players = player;
this.scores = scores;
this.totalScores = totalScores;
this.name = name;
this.time = time;
if (name.equals("NOH"))
{
this.name = "NOP";
}
if (player != null)
{
for (MatchPlayerPO p : player)
{
p.setTeamnameAbridge(name);
}
}
}
public int getTime()
{
return time;
}
public MatchPlayerPO[] getPlayers()
{
return players;
}
public int[] getScores()
{
return scores;
}
public int getTotalScores() {
return totalScores;
}
public String getName() {
return name;
}
public String toString()
{
StringBuilder sb = new StringBuilder();
sb.append(name + "---");
sb.append(totalScores);
for (int score : scores)
{
sb.append(score);
sb.append(" ");
}
sb.append(" ");
sb.append("\n");
for (MatchPlayerPO player : players)
{
sb.append(player.toString());
}
return sb.toString();
}
}
|
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class TestIoc {
public static void main(String[] args) {
ApplicationContext applicationContext =
new ClassPathXmlApplicationContext("applicationContext.xml");
UserDao userDao = (UserDao) applicationContext.getBean("userDao");
userDao.say();
System.out.println("userDao = " + userDao);
UserService userService = (UserService) applicationContext.getBean("userService");
userService.say();
userService.printInfo();
System.out.println();
System.out.println("TestIoc.main");
System.out.println("userService = " + userService);
System.out.println("args = [" + args + "]");
System.out.println("TestIoc.main");
}
}
|
package fj.swsk.cn.eqapp.main.Common;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.drawable.Drawable;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;
import fj.swsk.cn.eqapp.R;
import fj.swsk.cn.eqapp.util.ResUtil;
public class Topbar extends RelativeLayout {
public Button leftButton;
public Button rightButton;
public TextView titleTextView;
private String leftButtonText;
private String rightButtonText;
private String titleTextViewText;
private float leftButtonTextSize;
private float rightButtonTextSize;
private float titleTextViewTextSize;
private Drawable leftButtonBackground;
private Drawable rightButtonBackground;
private int titleTextViewTextColor;
private LayoutParams leftButtonLayoutParams;
private LayoutParams rightButtonLayoutParams;
private LayoutParams titleTextViewLayoutParams;
public OnClickListener letfListener,rightListener;
public Topbar(final Context context, AttributeSet attrs) {
super(context, attrs);
TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.Topbar);
leftButtonText = typedArray.getString(R.styleable.Topbar_leftButtonText);
rightButtonText = typedArray.getString(R.styleable.Topbar_rightButtonText);
titleTextViewText = typedArray.getString(R.styleable.Topbar_titleText);
titleTextViewTextColor = typedArray.getColor(R.styleable.Topbar_titleColor, 0);
leftButtonBackground = typedArray.getDrawable(R.styleable.Topbar_leftButtonBackground);
rightButtonBackground = typedArray.getDrawable(R.styleable.Topbar_rightButtonBackground);
titleTextViewTextSize = typedArray.getDimension(R.styleable.Topbar_titleSize, 14);
leftButtonTextSize = typedArray.getDimension(R.styleable.Topbar_leftButtonSize, 14);
rightButtonTextSize = typedArray.getDimension(R.styleable.Topbar_rightButtonSize, 14);
typedArray.recycle();
//setBackgroundColor(0x80000000); //设置标题栏背景透明
// setBackgroundColor(Color.parseColor("#4C627D"));
leftButton = new Button(context);
rightButton = new Button(context);
titleTextView = new TextView(context);
leftButtonLayoutParams = new LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
leftButtonLayoutParams.addRule(RelativeLayout.ALIGN_PARENT_LEFT, RelativeLayout.TRUE);
leftButtonLayoutParams.addRule(RelativeLayout.CENTER_VERTICAL, RelativeLayout.TRUE);
addView(leftButton, leftButtonLayoutParams);
rightButtonLayoutParams = new LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
rightButtonLayoutParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT, RelativeLayout.TRUE);
rightButtonLayoutParams.addRule(RelativeLayout.CENTER_VERTICAL, RelativeLayout.TRUE);
addView(rightButton, rightButtonLayoutParams);
titleTextViewLayoutParams = new LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
titleTextViewLayoutParams.addRule(RelativeLayout.CENTER_VERTICAL, RelativeLayout.TRUE);
titleTextViewLayoutParams.addRule(RelativeLayout.CENTER_IN_PARENT, RelativeLayout.TRUE);
titleTextView.setGravity(Gravity.CENTER);
addView(titleTextView, titleTextViewLayoutParams);
leftButton.setText(leftButtonText);
leftButton.setBackgroundDrawable(leftButtonBackground);
leftButton.setTextSize(leftButtonTextSize);
leftButton.setTextColor(getResources().getColorStateList(R.color.topbar_btn_state));
leftButton.setMinWidth(180);
leftButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (letfListener != null) {
letfListener.onClick(v);
}
}
});
rightButton.setText(rightButtonText);
rightButton.setBackgroundDrawable(rightButtonBackground);
rightButton.setTextSize(rightButtonTextSize);
rightButton.setTextColor(getResources().getColorStateList(R.color.topbar_btn_state));
rightButton.setMinWidth(180);
rightButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (rightListener != null) {
rightListener.onClick(v);
}
}
});
/*RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams)rightButton.getLayoutParams();
layoutParams.setMargins(10,0,10,0);
rightButton.setLayoutParams(layoutParams);*/
titleTextView.setEllipsize(TextUtils.TruncateAt.MIDDLE);
titleTextView.setGravity(Gravity.CENTER_HORIZONTAL | Gravity.CENTER_VERTICAL);
titleTextView.setSingleLine(true);
titleTextView.setText(titleTextViewText);
titleTextView.setTextSize(titleTextViewTextSize);
titleTextView.setTextColor(titleTextViewTextColor);
LayoutParams lp = new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ResUtil.dp2Intp(1));
lp.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM, RelativeLayout.TRUE);
View line = new View(getContext());
line.setBackgroundColor(0xaaaaaaaa);
addView(line,lp);
}
public void setLeftButtonIsvisable(boolean flag) {
if (leftButton == null) {
return;
}
leftButton.setVisibility(flag?View.VISIBLE:View.GONE);
}
public void setRightButtonIsvisable(boolean flag) {
if (rightButton == null) {
return;
}
rightButton.setVisibility(flag?View.VISIBLE:View.GONE);
}
public void setTitleTextViewIsvisable(boolean flag) {
if (titleTextView == null) {
return;
}
titleTextView.setVisibility(flag?View.VISIBLE:View.GONE);
}
public void setTitleText(String title) {
if (titleTextView == null) {
return;
}
titleTextView.setText(title);
}
}
|
package net.kkolyan.elements.engine.utils;
import net.kkolyan.elements.engine.core.ResourceManager;
import net.kkolyan.elements.engine.core.graphics.Drawable;
import net.kkolyan.elements.engine.core.templates.Sprite;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
/**
* @author nplekhanov
*/
public class TileSetConverter {
public static void convert(File input, File output) throws FileNotFoundException, UnsupportedEncodingException {
Scanner scanner = new Scanner(input);
PrintStream writer = new PrintStream(output, "utf8");
try {
String imageSetId = scanner.nextLine();
if (!scanner.nextLine().isEmpty()) {
throw new IllegalStateException();
}
int w = 0;
int h = 0;
List<Integer> indexes = new ArrayList<Integer>();
while (scanner.hasNextLine()) {
String line = scanner.nextLine().replace(" ","");
w = Math.max(w, line.length());
h ++;
for (char c: line.toCharArray()) {
indexes.add(c - 'a');
}
}
ResourceManager resourceManager = new ResourceManager();
BufferedImage firstFrame = resourceManager.getImageSet(imageSetId).getFrame(0);
for (int i = 0; i < indexes.size(); i++) {
writer.println("Tile");
int x = firstFrame.getWidth() * (i % w) - 1024;
int y = firstFrame.getHeight() * (i / w) - 1024;
Integer index = indexes.get(i);
writer.println("\tx = " + x);
writer.println("\ty = " + y);
writer.println("\timageSetId = " + imageSetId + "#" + index);
writer.flush();
}
} finally {
writer.close();
}
}
public static void main(String[] args) throws FileNotFoundException, UnsupportedEncodingException {
File dir = new File("D:\\dev\\elements\\src\\main\\resources\\game");
convert(new File(dir, "demo2.tiles.txt"), new File(dir, "demo2.tiles"));
}
}
|
/**
*/
package iso20022;
import java.util.Map;
import org.eclipse.emf.common.util.DiagnosticChain;
/**
* <!-- begin-user-doc -->
* A representation of the model object '<em><b>Choice Component</b></em>'.
* <!-- end-user-doc -->
*
* <!-- begin-model-doc -->
* re-usable Dictionary Item that is a building block for assembling MessageDefinitions, composed of a choice of MessageElements
* <!-- end-model-doc -->
*
*
* @see iso20022.Iso20022Package#getChoiceComponent()
* @model annotation="urn:iso:std:iso:20022:2013:ecore:extension basis='IMPLEMENTATION_ENHANCEMENT' description='The property element is moved from MessageComponentType to the new abstract Meta Class MessageElementContainer so that only such MessageElementContainer may own MessageElements. This MessageElementContainer class is the super class of MessageComponent and ChoiceComponent. As such, it is constrained directly in the MOF MetaClass structure that an ExternalSchema may not contain MessageElement; instead of constraining this with an OCL rule.'"
* @generated
*/
public interface ChoiceComponent extends MessageElementContainer {
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* <!-- begin-model-doc -->
* A MessageComponent or ChoiceComponent must have at least one MessageElement
* messageElement->notEmpty( )
* <!-- end-model-doc -->
* @model required="true" ordered="false" contextRequired="true" contextOrdered="false" diagnosticsRequired="true" diagnosticsOrdered="false"
* @generated
*/
boolean AtLeastOneProperty(Map context, DiagnosticChain diagnostics);
} // ChoiceComponent
|
package es.codeurjc.gameweb.controllers;
import java.security.Principal;
import java.util.HashMap;
import java.util.Optional;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.core.io.InputStreamResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import es.codeurjc.gameweb.models.Chat;
import es.codeurjc.gameweb.models.Game;
import es.codeurjc.gameweb.models.Message;
import es.codeurjc.gameweb.models.User;
import es.codeurjc.gameweb.services.AlgorithmService;
import es.codeurjc.gameweb.services.ChatService;
import es.codeurjc.gameweb.services.GameService;
import es.codeurjc.gameweb.services.ScoresService;
import es.codeurjc.gameweb.services.SubscriptionsService;
import es.codeurjc.gameweb.services.UserService;
import java.sql.SQLException;
@Controller
public class GamePageController {
@Autowired
private GameService gamePostService;
@Autowired
private ChatService chatService;
@Autowired
private UserService userService;
@Autowired
private ScoresService scoresService;
@Autowired
private SubscriptionsService subService;
@ModelAttribute
public void addAttributes(Model model, HttpServletRequest request) {
Principal principal = request.getUserPrincipal();
if (principal != null) {
model.addAttribute("logged", true);
model.addAttribute("userName", principal.getName());
model.addAttribute("admin", request.isUserInRole("ADMIN"));
} else {
model.addAttribute("logged", false);
}
}
@RequestMapping("/gamePage/{id}")
public String showGame(Model model, @PathVariable Long id, HttpServletRequest request) {
Principal principal = request.getUserPrincipal();
try{
Optional<User> myUser= userService.findByName(principal.getName());
User user =myUser.get();
Optional<Game> myGame = gamePostService.findById(id);
Optional<Chat> myChat = chatService.findById(id+1);
Game game = myGame.get();
Chat chat;
chat = myChat.get();
model.addAttribute("game", game);
for (Integer i = 0; i <= chat.getListMessages().size() - 1; i++) {
if (user.getInfo().equals(chat.getListMessages().get(i).getNameUser()))
chat.getListMessages().get(i).setMessageWriter(true);
else
chat.getListMessages().get(i).setMessageWriter(false);
}
if(principal != null){
try {
model.addAttribute("canSub", !user.getMyGames().contains(game.getId()));
} catch (Exception e) {
model.addAttribute("canSub", true);
}
model.addAttribute("Messages", chat.getListMessages());
}
return "gamePage";
} catch (Exception e){
Optional<Game> myGame = gamePostService.findById(id);
Game game = myGame.get();
model.addAttribute("game", game);
return "gamePage";
}
}
@RequestMapping("/gamePage/{id}/subButton")
public String subButton(Model model,@PathVariable Long id, HttpServletRequest request){
Principal principal = request.getUserPrincipal();
Optional<Game> myGame=gamePostService.findById(id);
Game game=myGame.get();
Optional<User> myUser= userService.findByName(principal.getName());
User user =myUser.get();
if(!user.getMyGames().contains(id)){
userService.save(subService.subscriptionFunction(id, user));
model.addAttribute("game", myGame);
model.addAttribute("customMessage", "Suscripción realizada con éxito");
return "successPage";
}
else{
model.addAttribute("game", myGame);
model.addAttribute("customMessage", "Ya te has subscrito a ese juego");
return "successPage";
}
}
@RequestMapping("/gamePage/{id}/unsubButton")
public String unsubButton(Model model, @PathVariable Long id,HttpServletRequest request){
Principal principal = request.getUserPrincipal();
Optional<User> myUser= userService.findByName(principal.getName());
User user =myUser.get();
String gameTitle=gamePostService.findById(id).get().getGameTitle();
userService.save(subService.unsubscriptionFunction(id, user));
model.addAttribute("customMessage", "Desuscripción realizada con éxito");
return "successPage";
}
@GetMapping("/gamePage/{id}/image")
public ResponseEntity<Object> downloadImage(@PathVariable long id) throws SQLException {
Optional<Game> game = gamePostService.findById(id);
if (game.isPresent() && game.get().getImageFile() != null) {
Resource file = new InputStreamResource(game.get().getImageFile().getBinaryStream());
return ResponseEntity.ok().header(HttpHeaders.CONTENT_TYPE, "image/jpeg")
.contentLength(game.get().getImageFile().length()).body(file);
} else {
return ResponseEntity.notFound().build();
}
}
@RequestMapping("/rate/{id}")
public String ValorarGame(Model model, @PathVariable Long id, @RequestParam Integer stars,HttpServletRequest request) {
gamePostService.save(scoresService.putScore(request, id, stars));
model.addAttribute("customMessage", "Juego valorado con un " + stars + " con éxito");
return "successPage";
}
@PostMapping("/agregarChat/{id}")
public String newChat(Model model, @PathVariable Long id, @RequestParam String sentChat,HttpServletRequest request) {
Optional<Game> game = gamePostService.findById(id);
Game myGame = game.get();
model.addAttribute("game", myGame);
Principal principal = request.getUserPrincipal();
Optional<User> myUser= userService.findByName(principal.getName());
User user =myUser.get();
//iterate the chat messages to allign them to the right or to the left
for (Integer i=0;i<=myGame.getChat().getListMessages().size()-1;i++){
if(user.getInfo().equals(myGame.getChat().getListMessages().get(i).getNameUser()))
myGame.getChat().getListMessages().get(i).setMessageWriter(true);
else
myGame.getChat().getListMessages().get(i).setMessageWriter(false);
}
model.addAttribute("Messages", myGame.getChat().getListMessages());
//Create the message and add it to the chat of the game
Message MyMessage = new Message(user.getInfo(), sentChat,true);
myGame.getChat().getListMessages().add(MyMessage);
model.addAttribute("Messages", myGame.getChat().getListMessages());
gamePostService.save(myGame);
if(principal!=null){
model.addAttribute("canSub", !user.getMyGames().contains(myGame.getId()));
//model.addAttribute("Messages", chat.getListMessages());
}
return "gamePage";
}
@RequestMapping("/statistics/{id}")
public String showGameStats(Model model, @PathVariable Long id) {
Optional<Game> myGame = gamePostService.findById(id);
Game game = myGame.get();
model.addAttribute("game", game);
Integer int1=scoresService.doAverageRatio(game.getMapScores(),1);
Integer int2=scoresService.doAverageRatio(game.getMapScores(),2);
Integer int3=scoresService.doAverageRatio(game.getMapScores(),3);
Integer int4=scoresService.doAverageRatio(game.getMapScores(),4);
Integer int5=scoresService.doAverageRatio(game.getMapScores(),5);
model.addAttribute("gamestars1", int1);
model.addAttribute("gamestars2", int2);
model.addAttribute("gamestars3", int3);
model.addAttribute("gamestars4", int4);
model.addAttribute("gamestars5", int5);
return "gameStadistics";
}
}
|
/*
* Copyright 2019 WeBank
*
* 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.webank.wedatasphere.qualitis.rule.service.impl;
import com.webank.wedatasphere.qualitis.rule.constant.FunctionTypeEnum;
import com.webank.wedatasphere.qualitis.rule.constant.RuleTemplateTypeEnum;
import com.webank.wedatasphere.qualitis.rule.constant.TemplateActionTypeEnum;
import com.webank.wedatasphere.qualitis.rule.constant.TemplateDataSourceTypeEnum;
import com.webank.wedatasphere.qualitis.rule.entity.TemplateStatisticsInputMeta;
import com.webank.wedatasphere.qualitis.rule.request.AddCustomRuleRequest;
import com.webank.wedatasphere.qualitis.rule.request.AddRuleTemplateRequest;
import com.webank.wedatasphere.qualitis.rule.request.ModifyRuleTemplateRequest;
import com.webank.wedatasphere.qualitis.rule.request.TemplateMidTableInputMetaRequest;
import com.webank.wedatasphere.qualitis.rule.request.TemplateOutputMetaRequest;
import com.webank.wedatasphere.qualitis.rule.request.TemplateStatisticsInputMetaRequest;
import com.webank.wedatasphere.qualitis.rule.response.TemplateMidTableInputMetaResponse;
import com.webank.wedatasphere.qualitis.rule.response.TemplateOutputMetaResponse;
import com.webank.wedatasphere.qualitis.rule.response.TemplateStatisticsInputMetaResponse;
import com.webank.wedatasphere.qualitis.rule.service.RuleService;
import com.webank.wedatasphere.qualitis.rule.service.RuleTemplateService;
import com.webank.wedatasphere.qualitis.exception.UnExpectedRequestException;
import com.webank.wedatasphere.qualitis.request.PageRequest;
import com.webank.wedatasphere.qualitis.response.GeneralResponse;
import com.webank.wedatasphere.qualitis.response.GetAllResponse;
import com.webank.wedatasphere.qualitis.rule.dao.RuleTemplateDao;
import com.webank.wedatasphere.qualitis.rule.dao.TemplateMidTableInputMetaDao;
import com.webank.wedatasphere.qualitis.rule.dao.TemplateOutputMetaDao;
import com.webank.wedatasphere.qualitis.rule.dao.UserRuleTemplateDao;
import com.webank.wedatasphere.qualitis.rule.dao.repository.RegexpExprMapperRepository;
import com.webank.wedatasphere.qualitis.rule.entity.Template;
import com.webank.wedatasphere.qualitis.rule.entity.TemplateMidTableInputMeta;
import com.webank.wedatasphere.qualitis.rule.entity.TemplateOutputMeta;
import com.webank.wedatasphere.qualitis.rule.response.RuleTemplateResponse;
import com.webank.wedatasphere.qualitis.rule.response.TemplateInputDemandResponse;
import com.webank.wedatasphere.qualitis.rule.response.TemplateMetaResponse;
import com.webank.wedatasphere.qualitis.rule.service.TemplateMidTableInputMetaService;
import com.webank.wedatasphere.qualitis.rule.service.TemplateOutputMetaService;
import com.webank.wedatasphere.qualitis.rule.service.TemplateStatisticsInputMetaService;
import com.webank.wedatasphere.qualitis.util.HttpUtils;
import java.lang.reflect.InvocationTargetException;
import java.util.HashSet;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.core.Context;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
/**
* @author howeye
*/
@Service
public class RuleTemplateServiceImpl implements RuleTemplateService {
@Autowired
private RuleTemplateDao ruleTemplateDao;
@Autowired
private TemplateMidTableInputMetaDao templateMidTableInputMetaDao;
@Autowired
private TemplateOutputMetaDao templateOutputMetaDao;
@Autowired
private UserRuleTemplateDao userRuleTemplateDao;
@Autowired
private RegexpExprMapperRepository regexpExprMapperRepository;
@Autowired
private TemplateStatisticsInputMetaService templateStatisticsInputMetaService;
@Autowired
private TemplateMidTableInputMetaService templateMidTableInputMetaService;
@Autowired
private TemplateOutputMetaService templateOutputMetaService;
@Autowired
private RuleService ruleService;
private HttpServletRequest httpServletRequest;
private static final Logger LOGGER = LoggerFactory.getLogger(RuleTemplateServiceImpl.class);
public RuleTemplateServiceImpl(@Context HttpServletRequest httpServletRequest) {
this.httpServletRequest = httpServletRequest;
}
@Override
public GeneralResponse<GetAllResponse<RuleTemplateResponse>> getCustomRuleTemplateByUser(PageRequest request) throws UnExpectedRequestException {
// Check Arguments
PageRequest.checkRequest(request);
// Get userId
Long userId = HttpUtils.getUserId(httpServletRequest);
int size = request.getSize();
int page = request.getPage();
List<Template> templates = userRuleTemplateDao.findByUserId(userId, page, size);
long total = userRuleTemplateDao.countByUserId(userId);
GetAllResponse<RuleTemplateResponse> response = new GetAllResponse<>();
response.setTotal(total);
List<RuleTemplateResponse> responseList = new ArrayList<>();
for (Template template : templates) {
responseList.add(new RuleTemplateResponse(template));
}
response.setData(responseList);
LOGGER.info("Succeed to get custom rule_template. response: {}", response);
return new GeneralResponse<>("200", "{&GET_CUSTOM_RULE_TEMPLATE_SUCCESSFULLY}", response);
}
@Override
public GeneralResponse<GetAllResponse<RuleTemplateResponse>> getDefaultRuleTemplate(PageRequest request) throws UnExpectedRequestException {
// Check Arguments
PageRequest.checkRequest(request);
int size = request.getSize();
int page = request.getPage();
List<Template> templates = ruleTemplateDao.findAllDefaultTemplate(page, size);
long total = ruleTemplateDao.countAllDefaultTemplate();
GetAllResponse<RuleTemplateResponse> response = new GetAllResponse<>();
response.setTotal(total);
List<RuleTemplateResponse> responseList = new ArrayList<>();
for (Template template : templates) {
responseList.add(new RuleTemplateResponse(template));
}
response.setData(responseList);
LOGGER.info("Succeed to find default rule_template. response: {}", response);
return new GeneralResponse<>("200", "{&GET_RULE_TEMPLATE_SUCCESSFULLY}", response);
}
@Override
public GeneralResponse<TemplateMetaResponse> getRuleTemplateMeta(Long ruleTemplateId) throws UnExpectedRequestException {
// Find rule template by id
Template templateInDb = ruleTemplateDao.findById(ruleTemplateId);
if (null == templateInDb) {
throw new UnExpectedRequestException("rule_template_id {&CAN_NOT_BE_NULL_OR_EMPTY}");
}
// Find input meta data by template
List<TemplateMidTableInputMeta> templateMidTableInputMetas = templateMidTableInputMetaDao.findByRuleTemplate(templateInDb);
List<TemplateOutputMeta> templateOutputMetas = templateOutputMetaDao.findByRuleTemplate(templateInDb);
TemplateMetaResponse response = new TemplateMetaResponse(templateInDb, templateMidTableInputMetas, templateOutputMetas);
LOGGER.info("Succeed to get rule_template. rule_template_id: {}", ruleTemplateId);
return new GeneralResponse<>("200", "{&GET_RULE_TEMPLATE_META_SUCCESSFULLY}", response);
}
@Override
public GeneralResponse<TemplateInputDemandResponse> getRuleTemplateInputMeta(Long ruleTemplateId) throws UnExpectedRequestException {
// Check existence of rule template
Template templateInDb = ruleTemplateDao.findById(ruleTemplateId);
if (null == templateInDb) {
throw new UnExpectedRequestException("rule_template_id {&DOES_NOT_EXIST}");
}
TemplateInputDemandResponse templateInputDemandResponse = new TemplateInputDemandResponse(templateInDb, regexpExprMapperRepository);
LOGGER.info("Succeed to get the input of rule_template. rule_template_id: {}", ruleTemplateId);
return new GeneralResponse<>("200", "{&GET_TEMPLATE_RULE_DEMAND_SUCCESSFULLY}", templateInputDemandResponse);
}
@Override
public Template checkRuleTemplate(Long ruleTemplateId) throws UnExpectedRequestException {
Template template = ruleTemplateDao.findById(ruleTemplateId);
if (template == null) {
throw new UnExpectedRequestException("rule_template_id {&DOES_NOT_EXIST}");
}
return template;
}
@Override
@Transactional(rollbackFor = {RuntimeException.class, UnExpectedRequestException.class})
public Template addCustomTemplate(AddCustomRuleRequest request) {
Template newTemplate = new Template();
newTemplate.setName(request.getProjectId() + "_" + request.getRuleName() + "_template");
newTemplate.setDatasourceType(TemplateDataSourceTypeEnum.HIVE.getCode());
newTemplate.setSaveMidTable(request.getSaveMidTable());
newTemplate.setMidTableAction(getMidTableAction(request));
newTemplate.setTemplateType(RuleTemplateTypeEnum.CUSTOM.getCode());
newTemplate.setActionType(TemplateActionTypeEnum.SQL.getCode());
Template savedTemplate = ruleTemplateDao.saveTemplate(newTemplate);
LOGGER.info("Succeed to save custom template, template_id: {}", savedTemplate.getId());
Set<TemplateStatisticsInputMeta> templateStatisticsInputMetas = templateStatisticsInputMetaService.getAndSaveTemplateStatisticsInputMeta(
request.getOutputName(), request.getFunctionType(), request.getFunctionContent(), request.getSaveMidTable(), savedTemplate);
savedTemplate.setStatisticAction(templateStatisticsInputMetas);
Set<TemplateOutputMeta> templateOutputMetas = templateOutputMetaService.getAndSaveTemplateOutputMeta(request.getOutputName(),
request.getFunctionType(), request.getSaveMidTable(), savedTemplate);
savedTemplate.setTemplateOutputMetas(templateOutputMetas);
return savedTemplate;
}
private String getMidTableAction(AddCustomRuleRequest request) {
StringBuilder sb = new StringBuilder("SELECT ");
if (request.getFunctionContent().equals("*")) {
sb.append(request.getFunctionContent());
} else {
sb.append(request.getFunctionContent()).append(" AS ").append(getFunctionAlias(request.getFunctionType()));
}
//
// if (request.getSaveMidTable()) {
// } else {
// sb.append(FunctionTypeEnum.getByCode(request.getFunctionType()).getFunction())
// .append("(")
// .append(request.getFunctionContent())
// .append(") AS ")
// .append(getFunctionAlias(request.getFunctionType()));
// }
sb.append(" FROM ").append(request.getFromContent()).append(" WHERE ").append("${filter}");
// Check SQL grammar
String sql = sb.toString();
return sql;
}
@Override
public String getFunctionAlias(Integer code) {
return "my" + FunctionTypeEnum.getByCode(code).getFunction();
}
@Override
public void deleteCustomTemplate(Template template) throws UnExpectedRequestException {
if (template == null) {
throw new UnExpectedRequestException("Template {&DOES_NOT_EXIST}");
}
if (!template.getTemplateType().equals(RuleTemplateTypeEnum.CUSTOM.getCode())) {
throw new UnExpectedRequestException("Template(id:[" + template.getId() + "]) {&IS_NOT_A_CUSTOM_TEMPLATE}");
}
ruleTemplateDao.deleteTemplate(template);
}
@Override
public GeneralResponse<?> getMultiSourceTemplateMeta(Long templateId) throws UnExpectedRequestException {
// Check existence of template and if multi-table rule template
Template templateInDb = checkRuleTemplate(templateId);
if (!templateInDb.getTemplateType().equals(RuleTemplateTypeEnum.MULTI_SOURCE_TEMPLATE.getCode())) {
throw new UnExpectedRequestException("Template : [" + templateId + "] {&IS_NOT_A_MULTI_TEMPLATE}");
}
// return show_sql of template and template output
TemplateInputDemandResponse templateInputDemandResponse = new TemplateInputDemandResponse(templateInDb, RuleTemplateTypeEnum.MULTI_SOURCE_TEMPLATE.getCode());
LOGGER.info("Succeed to get the meta of multi_rule_template. rule_template_id: {}", templateId);
return new GeneralResponse<>("200", "{&GET_META_OF_MULTI_RULE_TEMPLATE_SUCCESSFULLY}", templateInputDemandResponse);
}
/**
* Paging get template
* @param request
* @return
*/
@Override
public GeneralResponse<GetAllResponse<RuleTemplateResponse>> getMultiRuleTemplate(
PageRequest request) throws UnExpectedRequestException {
// Check Arguments
PageRequest.checkRequest(request);
int size = request.getSize();
int page = request.getPage();
List<Template> templates = ruleTemplateDao.findAllMultiTemplate(page, size);
long total = ruleTemplateDao.countAllMultiTemplate();
GetAllResponse<RuleTemplateResponse> response = new GetAllResponse<>();
response.setTotal(total);
List<RuleTemplateResponse> responseList = new ArrayList<>();
for (Template template : templates) {
responseList.add(new RuleTemplateResponse(template));
}
response.setData(responseList);
LOGGER.info("Succeed to find multi rule_template. response: {}", response);
return new GeneralResponse<>("200", "{&GET_MULTI_RULE_TEMPLATE_SUCCESSFULLY}", response);
}
/**
* Get meta data information by template_id
* @param ruleTemplateId
* @return
* @throws UnExpectedRequestException
*/
@Override
public GeneralResponse<TemplateMetaResponse> getRuleMultiTemplateMeta(Long ruleTemplateId)
throws UnExpectedRequestException {
// Find rule template by rule template id
Template templateInDb = ruleTemplateDao.findById(ruleTemplateId);
if (null == templateInDb) {
throw new UnExpectedRequestException("rule_template_id {&CAN_NOT_BE_NULL_OR_EMPTY}");
}
// Find meta data of template
List<TemplateOutputMeta> templateOutputMetas = templateOutputMetaDao.findByRuleTemplate(templateInDb);
// Add child template
if (templateInDb.getChildTemplate() != null) {
templateOutputMetas.addAll(templateOutputMetaDao.findByRuleTemplate(templateInDb.getChildTemplate()));
}
TemplateMetaResponse response = new TemplateMetaResponse(templateInDb, templateOutputMetas);
LOGGER.info("Succeed to get rule_template. rule_template_id: {}", ruleTemplateId);
return new GeneralResponse<>("200", "{&GET_RULE_TEMPLATE_META_SUCCESSFULLY}", response);
}
@Override
@Transactional(rollbackFor = {RuntimeException.class, UnExpectedRequestException.class}, propagation = Propagation.REQUIRED)
public RuleTemplateResponse addRuleTemplate(AddRuleTemplateRequest request)
throws UnExpectedRequestException {
AddRuleTemplateRequest.checkRequest(request, false);
LOGGER.info("Add default rule template request detail: {}", request.toString());
// Save template.
checkTemplateName(request.getTemplateName());
Template newTemplate = new Template();
newTemplate.setName(request.getTemplateName());
newTemplate.setClusterNum(request.getClusterNum());
newTemplate.setDbNum(request.getDbNum());
newTemplate.setTableNum(request.getTableNum());
newTemplate.setFieldNum(request.getFieldNum());
newTemplate.setActionType(request.getActionType());
newTemplate.setDatasourceType(request.getDatasourceType());
newTemplate.setMidTableAction(request.getMidTableAction());
newTemplate.setSaveMidTable(request.getSaveMidTable());
newTemplate.setShowSql(request.getMidTableAction());
newTemplate.setTemplateType(request.getTemplateType());
Template savedTemplate = ruleTemplateDao.saveTemplate(newTemplate);
LOGGER.info("Succeed to save rule template, template_id: {}", savedTemplate.getId());
createAndSaveTemplateInfo(savedTemplate, request);
return new RuleTemplateResponse(savedTemplate);
}
private void createAndSaveTemplateInfo(Template savedTemplate, AddRuleTemplateRequest request) {
// Save template output meta.
Set<TemplateOutputMeta> templateOutputMetas = new HashSet<>();
for (TemplateOutputMetaRequest templateOutputMetaRequest : request.getTemplateOutputMetaRequests()) {
templateOutputMetas.addAll(templateOutputMetaService.getAndSaveTemplateOutputMeta(templateOutputMetaRequest.getOutputName(),
FunctionTypeEnum.getFunctionTypeByName(templateOutputMetaRequest.getFieldName()),
request.getSaveMidTable(), savedTemplate));
}
savedTemplate.setTemplateOutputMetas(templateOutputMetas);
LOGGER.info("Success to save template output meta. TemplateOutputMetas: {}", savedTemplate.getTemplateOutputMetas());
// Save template mid_table input meta
List<TemplateMidTableInputMeta> templateMidTableInputMetas = new ArrayList<>();
for (TemplateMidTableInputMetaRequest templateMidTableInputMetaRequest : request.getTemplateMidTableInputMetaRequests()) {
TemplateMidTableInputMeta templateMidTableInputMeta = new TemplateMidTableInputMeta();
templateMidTableInputMeta.setName(templateMidTableInputMetaRequest.getName());
templateMidTableInputMeta.setFieldType(templateMidTableInputMetaRequest.getFieldType());
templateMidTableInputMeta.setInputType(templateMidTableInputMetaRequest.getInputType());
templateMidTableInputMeta.setPlaceholder(templateMidTableInputMetaRequest.getPlaceholder());
templateMidTableInputMeta.setPlaceholderDescription(templateMidTableInputMetaRequest.getPlaceholderDescription());
templateMidTableInputMeta.setRegexpType(templateMidTableInputMetaRequest.getRegexpType());
templateMidTableInputMeta.setReplaceByRequest(templateMidTableInputMetaRequest.getReplaceByRequest());
templateMidTableInputMeta.setTemplate(savedTemplate);
templateMidTableInputMetas.add(templateMidTableInputMeta);
}
savedTemplate.setTemplateMidTableInputMetas(templateMidTableInputMetaService.saveAll(templateMidTableInputMetas));
LOGGER.info("Success to save template mid_table input meta. TemplateMidTableInputMetas: {}", savedTemplate.getTemplateMidTableInputMetas());
// Save template statistics input meta
List<TemplateStatisticsInputMeta> templateStatisticsInputMetas = new ArrayList<>();
for (TemplateStatisticsInputMetaRequest templateStatisticsInputMetaRequest : request.getTemplateStatisticsInputMetaRequests()) {
TemplateStatisticsInputMeta templateStatisticsInputMeta = new TemplateStatisticsInputMeta();
templateStatisticsInputMeta.setName(templateStatisticsInputMetaRequest.getName());
templateStatisticsInputMeta.setFuncName(templateStatisticsInputMetaRequest.getFuncName());
templateStatisticsInputMeta.setResultType(templateStatisticsInputMetaRequest.getResultType());
templateStatisticsInputMeta.setValue(templateStatisticsInputMetaRequest.getValue());
templateStatisticsInputMeta.setValueType(templateStatisticsInputMetaRequest.getValueType());
templateStatisticsInputMeta.setTemplate(savedTemplate);
templateStatisticsInputMetas.add(templateStatisticsInputMeta);
}
savedTemplate.setStatisticAction(templateStatisticsInputMetaService.saveAll(templateStatisticsInputMetas));
LOGGER.info("Success to save template statistics input meta. templateStatisticsInputMetas: {}", savedTemplate.getStatisticAction());
}
private void checkTemplateName(String templateName) throws UnExpectedRequestException {
List<Template> templates = ruleTemplateDao.getAllTemplate();
LOGGER.info("Number of templates in database is {}", templates.size());
for (Template template : templates) {
if (templateName.equals(template.getName())) {
throw new UnExpectedRequestException("Template name {&ALREADY_EXIST}");
}
}
}
@Override
@Transactional(rollbackFor = {RuntimeException.class, UnExpectedRequestException.class})
public RuleTemplateResponse modifyRuleTemplate(ModifyRuleTemplateRequest request)
throws UnExpectedRequestException, InvocationTargetException, IllegalAccessException {
AddRuleTemplateRequest addRuleTemplateRequest = ModifyRuleTemplateRequest.checkRequest(request, "modifyDefaultRuleTemplateRequest");
// Check template existence
Template templateInDb = checkRuleTemplate(request.getTemplateId());
// delete output meta
templateOutputMetaService.deleteByTemplate(templateInDb);
// delete mid_table input meta
templateMidTableInputMetaService.deleteByTemplate(templateInDb);
// delete statistics input meta
templateStatisticsInputMetaService.deleteByTemplate(templateInDb);
// Save template.
templateInDb.setClusterNum(request.getClusterNum());
templateInDb.setDbNum(request.getDbNum());
templateInDb.setTableNum(request.getTableNum());
templateInDb.setFieldNum(request.getFieldNum());
templateInDb.setActionType(request.getActionType());
templateInDb.setDatasourceType(request.getDatasourceType());
templateInDb.setMidTableAction(request.getMidTableAction());
templateInDb.setSaveMidTable(request.getSaveMidTable());
templateInDb.setShowSql(request.getMidTableAction());
templateInDb.setTemplateType(request.getTemplateType());
Template savedTemplate = ruleTemplateDao.saveTemplate(templateInDb);
LOGGER.info("Succeed to save rule template, template_id: {}", savedTemplate.getId());
createAndSaveTemplateInfo(savedTemplate, addRuleTemplateRequest);
return new RuleTemplateResponse(savedTemplate);
}
@Override
public void deleteRuleTemplate(Long templateId) throws UnExpectedRequestException {
// Check template existence
Template templateInDb = checkRuleTemplate(templateId);
// Check rules of template
ruleService.checkRuleOfTemplate(templateInDb);
ruleTemplateDao.deleteTemplate(templateInDb);
}
@Override
public RuleTemplateResponse getModifyRuleTemplateDetail(Long templateId) throws UnExpectedRequestException {
// Check template existence
Template templateInDb = checkRuleTemplate(templateId);
RuleTemplateResponse response = new RuleTemplateResponse(templateInDb);
response.setClusterNum(templateInDb.getClusterNum());
response.setDbNum(templateInDb.getDbNum());
response.setTableNum(templateInDb.getTableNum());
response.setFieldNum(templateInDb.getFieldNum());
response.setDatasourceType(templateInDb.getDatasourceType());
response.setActionType(templateInDb.getActionType());
response.setMidTableAction(templateInDb.getMidTableAction());
response.setSaveMidTable(templateInDb.getSaveMidTable());
List<TemplateOutputMetaResponse> outputMetaResponses = new ArrayList<>(1);
List<TemplateMidTableInputMetaResponse> midTableInputMetaResponses = new ArrayList<>(2);
List<TemplateStatisticsInputMetaResponse> statisticsInputMetaResponses = new ArrayList<>(1);
for (TemplateOutputMeta templateOutputMeta : templateInDb.getTemplateOutputMetas()) {
TemplateOutputMetaResponse templateOutputMetaResponse = new TemplateOutputMetaResponse();
templateOutputMetaResponse.setOutputName(templateOutputMeta.getOutputName());
outputMetaResponses.add(templateOutputMetaResponse);
}
response.setTemplateOutputMetaResponses(outputMetaResponses);
for (TemplateMidTableInputMeta templateMidTableInputMeta : templateInDb.getTemplateMidTableInputMetas()) {
TemplateMidTableInputMetaResponse templateMidTableInputMetaResponse = new TemplateMidTableInputMetaResponse();
templateMidTableInputMetaResponse.setName(templateMidTableInputMeta.getName());
templateMidTableInputMetaResponse.setPlaceholder(templateMidTableInputMeta.getPlaceholder());
templateMidTableInputMetaResponse.setPlaceholderDescription(templateMidTableInputMeta.getPlaceholderDescription());
templateMidTableInputMetaResponse.setInputType(templateMidTableInputMeta.getInputType());
midTableInputMetaResponses.add(templateMidTableInputMetaResponse);
}
response.setTemplateMidTableInputMetaResponses(midTableInputMetaResponses);
for (TemplateStatisticsInputMeta templateStatisticsInputMeta : templateInDb.getStatisticAction()) {
TemplateStatisticsInputMetaResponse templateStatisticsInputMetaResponse = new TemplateStatisticsInputMetaResponse();
templateStatisticsInputMetaResponse.setName(templateStatisticsInputMeta.getName());
templateStatisticsInputMetaResponse.setFuncName(templateStatisticsInputMeta.getFuncName());
templateStatisticsInputMetaResponse.setValue(templateStatisticsInputMeta.getValue());
templateStatisticsInputMetaResponse.setValueType(templateStatisticsInputMeta.getValueType());
statisticsInputMetaResponses.add(templateStatisticsInputMetaResponse);
}
response.setTemplateStatisticsInputMetaResponses(statisticsInputMetaResponses);
return response;
}
}
|
package ai.cheap.petbot.tracking;
import org.opencv.core.Mat;
/**
* Created by GraOOu on 13/02/2016.
*/
public abstract class TrackingStrategy
{
protected TrackingContext _context = null;
public void Initialize ( TrackingContext context )
{
_context = context;
}
public abstract Mat Process ( Mat img );
}
|
package com.dbs.portal.ui.component.type;
public class LayoutPermissionType {
public static final String REPORT_SUBSCRIPTION = "REPORT";
}
|
package lib;
/**
* Implementation of the PRG described in problem 252
*/
public class PseudoRandomGenerator {
private long seed = 290797;
private long divisor = 50515093;
public PseudoRandomGenerator() {
this(290797, 50515093);
}
public PseudoRandomGenerator(long seed, long divisor) {
this.seed = seed;
this.divisor = divisor;
}
public long next() {
long newSeed = (seed * seed) % divisor;
long random = (newSeed % 2000) - 1000;
seed = newSeed;
return random;
}
public long[] get(int q) {
long batch[] = new long[q];
for (int i = 0; i < q; i++) {
batch[i] = next();
}
return batch;
}
}
|
package com.cheese.radio.util;
import android.Manifest;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.pm.PackageManager;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.support.v4.app.ActivityCompat;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import com.binding.model.App;
import com.cheese.radio.ui.CheeseApplication;
public class NetUtil {
static WifiManager wifiManager;
private static String macAddress = CheeseApplication.getUser().getMac();
public static String getMacAddress() {
if (!TextUtils.isEmpty(macAddress)) return macAddress;
if (TextUtils.isEmpty(macAddress)) {
if (ActivityCompat.checkSelfPermission(App.getCurrentActivity(), Manifest.permission.READ_PHONE_STATE) == PackageManager.PERMISSION_GRANTED) {
TelephonyManager telephonyManager = (TelephonyManager) App.getCurrentActivity().getSystemService(Context.TELEPHONY_SERVICE);
if (telephonyManager != null) {
macAddress = telephonyManager.getDeviceId();
if(!TextUtils.isEmpty(macAddress))return macAddress;
}
}
}
if (wifiManager == null) wifiManager =
(WifiManager) App.getCurrentActivity().getApplicationContext().getSystemService(Context.WIFI_SERVICE);
WifiInfo info = (null == wifiManager ? null : wifiManager.getConnectionInfo());
if (!wifiManager.isWifiEnabled()) {
//必须先打开,才能获取到MAC地址
wifiManager.setWifiEnabled(true);
wifiManager.setWifiEnabled(false);
}
if (null != info) {
CheeseApplication.getUser().setMac(info.getMacAddress());
macAddress = CheeseApplication.getUser().getMac();
}
return macAddress;
}
public static void checkNetType(Context context) {
if (wifiManager == null) wifiManager =
(WifiManager) App.getCurrentActivity().getApplicationContext().getSystemService(Context.WIFI_SERVICE);
WifiInfo info = (null == wifiManager ? null : wifiManager.getConnectionInfo());
if (!wifiManager.isWifiEnabled())
new AlertDialog.Builder(context)
.setCancelable(false)
.setTitle("温馨提示")
.setMessage("你没有开启无线网络,这将会消耗你大量的流量")
.setPositiveButton("去打开", (dialog1, which) -> {
wifiManager.setWifiEnabled(true);
})
.setNegativeButton("任性!", null)
.show()
.setOnDismissListener(DialogInterface::dismiss);
}
}
|
package com.joaosakai.easybillings.enumerations;
public enum Sensation {
DRY("Seco"),
STICKY("Elástico"),
DAMP("Úmido"),
WET("Molhado"),
LUBRIFICATED("Lubrificado"),
SLIPPERY("Escorregadio");
private final String value;
Sensation(String value) {
this.value = value;
}
public String getValue() {
return value;
}
}
|
package com.irfanstore.product.service;
import com.irfanstore.product.dto.ProductResponseDto;
import com.irfanstore.product.entity.Product;
import com.irfanstore.product.dto.ProductDto;
import com.irfanstore.product.repository.ProductRepository;
import org.modelmapper.ModelMapper;
import org.modelmapper.TypeToken;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.lang.reflect.Type;
import java.util.List;
@Service
public class ProductService {
@Autowired
private ProductRepository productRepository;
private ModelMapper modelMapper = new ModelMapper();
public List<ProductResponseDto> getProducts()
{
List<Product> products = productRepository.findAll();
Type listType = new TypeToken<List<ProductResponseDto>>() {}.getType();
List<ProductResponseDto> productsResponseDto = modelMapper.map(products, listType);
return productsResponseDto;
}
public ProductResponseDto getProduct(long id) {
Product product = productRepository.findOne(id);
ProductResponseDto productResponseDto = modelMapper.map(product, ProductResponseDto.class);
return productResponseDto;
}
public ProductResponseDto getProduct(String productCode) {
Product product = productRepository.findByProductCode(productCode);
ProductResponseDto productResponseDto = modelMapper.map(product, ProductResponseDto.class);
return productResponseDto;
}
public ProductResponseDto createOrUpdateProduct(ProductDto productDto) {
Product product = modelMapper.map(productDto, Product.class);
Product productCreated = productRepository.save(product);
ProductResponseDto productResponseDto = modelMapper.map(productCreated, ProductResponseDto.class);
return productResponseDto;
}
public void deleteProduct(Long id) {
productRepository.delete(id);
}
}
|
package com.example.api;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.view;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.test.web.servlet.MockMvc;
/**
* @Componentなどはスキャンされない。
* MockMvc を自動構成する。
*
*/
@WebMvcTest(AuthenticationController.class)
public class AuthenticationControllerTest {
@Autowired
private MockMvc mockMvc;
@Test
public void testContoller() throws Exception {
//whenb
System.out.println("test start");
mockMvc.perform(get("/loginForm"))
.andExpect(status().isOk())
.andExpect(view().name("Login"));
}
}
|
package pipeline.messages;
public class SimpleMessage implements PipelineMessage
{
private String _message;
public SimpleMessage(String message)
{
_message = message;
}
public String getMessage()
{
return _message;
}
}
|
package com.example.user.javaolympics;
/**
* Created by user on 15/09/2017.
*/
public class Athlete extends Competitor{
String name;
int skill;
public Athlete(int goldMedalCount,
int silverMedalCount,
int bronzeMedalCount,
Enum<Country> country,
String name,
int skill,
Enum<Discipline> discipline) {
super(goldMedalCount,
silverMedalCount,
bronzeMedalCount,
country,
discipline);
this.name = name;
this.skill = skill;
}
public String getName() {
return name;
}
public double getSkill() {
return skill;
}
} |
package com.spr.model;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
/**
* Created by Dan on 26.03.2017.
*/
@Entity
@Table(name = "user")
public class User {
@Id
@GeneratedValue
private Integer id;
private String name;
private String username;
private String password;
private String type;
private String description;
private String birthDate;
private String email;
public User() {
}
public User(String username, String password) {
this.username = username;
this.password = password;
}
public User(String name, String username, String password, String type) {
this.name = name;
this.username = username;
this.password = password;
this.type = type;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getBirthDate() {
return birthDate;
}
public void setBirthDate(String birthDate) {
this.birthDate = birthDate;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getRole() {
return type;
}
public void setRole(String type) {
this.type = type;
}
}
|
/**
* FileName: LoginDto
* Author: yangqinkuan
* Date: 2019-3-21 17:15
* Description:
*/
package com.ice.find.utils.enums.dto;
import java.io.Serializable;
/**
* 登录用实体
*/
public class LoginReqDto implements Serializable {
private static final long serialVersionUID = 702016414931860178L;
private String user_name;
private String password;
private String instanse;
public String getUser_name() {
return user_name;
}
public void setUser_name(String user_name) {
this.user_name = user_name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getInstanse() {
return instanse;
}
public void setInstanse(String instanse) {
this.instanse = instanse;
}
}
|
package br.com.clean.arch.domain.usecase.multiply;
import br.com.clean.arch.domain.dto.GivenParamDTO;
import br.com.clean.arch.domain.entity.ResultHistoryEntity;
public interface MultiplyHundredToFifteenOnZeroGivenUseCase {
ResultHistoryEntity calculate(GivenParamDTO firstParam);
}
|
package com.lamdevops.annotation.maxlength;
import java.lang.annotation.*;
/**
* Created by lam.nm on 6/27/2017.
*/
@Documented
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface MaxLength {
int maxLength();
}
|
package fr.cea.nabla.interpreter.nodes.instruction;
import com.oracle.truffle.api.Assumption;
import com.oracle.truffle.api.CompilerDirectives;
import com.oracle.truffle.api.Truffle;
import com.oracle.truffle.api.dsl.NodeChild;
import com.oracle.truffle.api.dsl.Specialization;
import com.oracle.truffle.api.frame.VirtualFrame;
import com.oracle.truffle.api.nodes.ExplodeLoop;
import com.oracle.truffle.api.nodes.RepeatingNode;
import fr.cea.nabla.interpreter.nodes.expression.NablaExpressionNode;
import fr.cea.nabla.interpreter.values.NV0Bool;
@NodeChild(value = "conditionNode", type = NablaExpressionNode.class)
public abstract class NablaWhileRepeatingNode extends NablaInstructionNode implements RepeatingNode {
@Child
private NablaInstructionNode body;
protected final Assumption lengthUnchanged = Truffle.getRuntime().createAssumption();
public NablaWhileRepeatingNode(NablaInstructionNode body) {
this.body = body;
}
/**
* Necessary to avoid errors in generated class.
*/
@Override
public final Object executeRepeatingWithValue(VirtualFrame frame) {
if (executeRepeating(frame)) {
return CONTINUE_LOOP_STATUS;
} else {
return BREAK_LOOP_STATUS;
}
}
@ExplodeLoop
@Specialization
public boolean doLoop(VirtualFrame frame, NV0Bool shouldContinue) {
final boolean continueLoop = shouldContinue.isData();
if (CompilerDirectives.injectBranchProbability(0.9, continueLoop)) {
body.executeGeneric(frame);
}
return continueLoop;
}
}
|
package com.company;
import java.util.ArrayList;
/**
* Created by Casey on 8/12/16.
*/
public class Board {
int[] b;
int size;
// /* Reference:
// UP_LT | UP_CT | UP_RT
// CT_LT | | CT_RT
// DN_LT | DN_CT | DN_RT*/
// protected static final int UP_LT = 0;
// protected static final int UP_CT = 1;
// protected static final int UP_RT = 2;
// protected static final int CT_LT = 3;
// protected static final int CT_RT = 4;
// protected static final int DN_LT = 5;
// protected static final int DN_CT = 6;
// protected static final int DN_RT = 7;
// protected static final int numDirections = 8;
protected static final int LT = 0;
protected static final int RT = 1;
protected static final int numDirections = 2;
public Board(int size){
this.size = size;
b = new int[size];
//all position equal Othello.empty since default value of int is 0
b[size/2-1] = Othello.BLACK;
b[size/2] = Othello.WHITE;
}
public int[] getBoard(){
return b;
}
public int getSize(){
return size;
}
/**
* for testing purposes only
*/
public void setPosition(int player, int position){
b[position] = player;
}
/**
* needs testing
* @return
*
*
*/
public Boolean isFull(){
for(int i = 0; i < b.length; i++){
if(b[i] == Othello.EMPTY){
return true;
}
}
return false;
}
/**
*
* @return
*/
public ArrayList<Integer> getEmpties(){
ArrayList<Integer> empties = new ArrayList<>();
for (int j = 0; j < b.length ; j++) {
if(b[j] == Othello.EMPTY){
empties.add(j);
}
}
return empties;
}
//check if it's valid move
public boolean addPiece(int player, int position){
//return false if position is already taken
if(b[position] != 0){
return false;
}
//check if pieces will be flipped, if yes, flip them
boolean flipped = false; //flag to see if any pieces heed to be flipped. If never true,-> invalid move
//loop through directions looking for the one that the player wanted to flip
for(int i = 0; i < numDirections; i++){
ArrayList<Integer> dirArr = getDirectionArray(position, i);
flipDirection(player, dirArr);
}
//return true if "any pieces r flipped"
return flipped;
}
private boolean flipDirection(int player, ArrayList<Integer> directionArray){
int otherPlayer = ( player == 1 ) ? 2 : 1;
//check if the adjacent position is of opposite color
if(directionArray.get(0) == player) return false;
//find next of same color to flip toward
for(int i = 1; i < directionArray.size(); i++){
if(directionArray.get(i) == player){
//flip(directionArray, i)
return true;
}
}
return false;
}
//flip pieces in directionArray from 0 to index
private void flip(ArrayList directionArray, int index){
}
private ArrayList getDirectionArray(int pos, int dir){
return null;
}
}
|
package ffm.slc.model.resources;
/**
* The public web site address (URL) for the educational organization.
*/
public class WebSite extends StringResource{}
|
package com.lesports.albatross.fragment;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.TextView;
import com.facebook.drawee.view.SimpleDraweeView;
import com.lesports.albatross.R;
import com.lesports.albatross.activity.race.RaceDetailActivity;
import com.lesports.albatross.adapter.learn.BannerViewPagerAdapter;
import com.lesports.albatross.entity.learn.BannerEntity;
import com.lesports.albatross.utils.Utils;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
/**
* 首页Banner条父类
*
* @author andye
*/
public class BannerViewPageFragment extends BaseFragment implements OnPageChangeListener {
/**
* ViewPager相关控件
**/
public ViewPager vp;
public BannerViewPagerAdapter vpAdapter;
// public TextView tv_pager_text; //ViewPager底部文字
public List<View> viewPages; // ViewPager内容
public int currentIndex; // 当前广告的索引号
public ImageView[] dots; // 底部小点
public ScheduledExecutorService scheduledExecutorService; // 自动滚动Service
public int interval = 5; // banner条切换时间间隔,以秒为单位
private View v;
private List<BannerEntity> bannerList;
SimpleDraweeView img_focus;
LinearLayout dotlayout;
TextView banner_text;
public void initBanner(View mView) {
vp = (ViewPager) mView.findViewById(R.id.banner_pager);
dotlayout = (LinearLayout) mView.findViewById(R.id.banner_dot);
banner_text = (TextView) mView.findViewById(R.id.banner_text);
vpAdapter = new BannerViewPagerAdapter();
vp.setOnPageChangeListener(this);
vp.setAdapter(vpAdapter);
bannerList = new ArrayList<>();
this.v = mView;
}
BannerEntity bannerEntity;
/**
* 初始化上方ViewPager页面
*
* @param adList 广告集合
*/
public void updateViewPager(List<BannerEntity> adList) {
if (adList == null) {
return;
}
bannerList.clear();
bannerList.addAll(adList);
viewPages = new ArrayList<>();
for (int i = 0; i < bannerList.size(); i++) {
LayoutInflater inflater = LayoutInflater.from(getActivity());
View bannerView = inflater.inflate(R.layout.banner_imageview, null);
img_focus = (SimpleDraweeView) bannerView.findViewById(R.id.img_focus);
bannerEntity = bannerList.get(i);
String focusUrl = bannerEntity.getBaseThumbnailUri();
img_focus.setImageURI(Uri.parse(focusUrl));
bannerView.setTag(i);
bannerView.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// 广告条点击事件
// Toast.makeText(getActivity(), "viewPager:" + v.getTag(), Toast.LENGTH_SHORT).show();
Intent intent = new Intent(getActivity(), RaceDetailActivity.class);
intent.putExtra("id", bannerEntity.getContentId());
getActivity().startActivity(intent);
}
});
viewPages.add(bannerView);
}
// tv_pager_text.setText(adList.get(0).getText());
vpAdapter.updateDate(viewPages);
initDots(viewPages);
}
/**
* 初始化ViewPager底部小点
*
* @param pages
*/
private void initDots(List<View> pages) {
dots = new ImageView[pages.size()];
dotlayout.removeAllViews();
// 循环取得小点图片
for (int i = 0; i < pages.size(); i++) {
ImageView iv = new ImageView(getActivity());
LayoutParams params = new LayoutParams(Utils.getdip2px(getActivity(), 5), Utils.getdip2px(getActivity(), 5));
params.setMargins(0, 0, Utils.getdip2px(getActivity(), 10), 0);
iv.setBackgroundResource(R.drawable.banner_page_indicator_bg);
iv.setLayoutParams(params);
iv.setEnabled(true);
dotlayout.addView(iv);
dots[i] = iv;
}
dots[currentIndex].setEnabled(false);// 设置为白色,即选中状态
}
/**
* 设置ViewPager底部小点选中状态
*
* @param position
*/
private void setCurrentDot(int position) {
dots[oldPosition].setEnabled(true); // 取消选中
dots[position].setEnabled(false); // 选中
oldPosition = position;
}
@Override
public void onPageScrollStateChanged(int arg0) {
// TODO Auto-generated method stub
// 当滑动状态改变时调用
}
@Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
// TODO Auto-generated method stub
// 当前页面被滑动时调用
}
private int oldPosition = 0;
@Override
public void onPageSelected(int arg0) {
// TODO Auto-generated method stub
// 当新的页面被选中时调用
if (bannerList == null) {
return;
}
currentIndex = arg0;
banner_text.setText(bannerList.get(currentIndex).getTitle());
// tv_pager_text.setText(adList.get(arg0).getText());
setCurrentDot(arg0);
}
@Override
public void onStart() {
scheduledExecutorService = Executors.newSingleThreadScheduledExecutor();
// 当Activity显示出来后,每interval秒钟切换一次图片显示
scheduledExecutorService.scheduleAtFixedRate(new ScrollTask(), 1, interval, TimeUnit.SECONDS);
super.onStart();
}
@Override
public void onStop() {
// 当Activity不可见的时候停止切换
scheduledExecutorService.shutdown();
super.onStop();
}
@Override
public View viewBindLayout(LayoutInflater inflater) {
return v;
}
@Override
public void viewBindId(View view) {
}
@Override
public void resourcesInit(Bundle data) {
}
@Override
public void viewInit(LayoutInflater inflater) {
}
@Override
public void viewBindListener() {
}
/**
* 换行ViewPager切换事务
*
* @author Administrator
*/
private class ScrollTask implements Runnable {
public void run() {
synchronized (vp) {
// System.out.println("currentIndex: " + currentIndex);
if (bannerList == null) {
return;
}
currentIndex = (currentIndex + 1) % bannerList.size();
handler.obtainMessage().sendToTarget(); // 通过Handler切换图片
}
}
}
/**
* 切换ViewPager当前显示的图片
*/
private Handler handler = new Handler() {
public void handleMessage(android.os.Message msg) {
vp.setCurrentItem(currentIndex, true);// 切换当前显示的图片
}
;
};
}
|
package myProject.third;
public class speedMeterLevel2 {
public speedMeterLevel2() {
// TODO Auto-generated constructor stub
}
}
|
package com.corejava.java8;
public class Student implements Comparable<Student>{
private int studentNumber;
private String studentName;
private int age;
private String gender;
public Student(int studentNumber, String studentName, int age, String gender) {
super();
this.studentNumber = studentNumber;
this.studentName = studentName;
this.age = age;
this.gender = gender;
}
public int getStudentNumber() {
return studentNumber;
}
public void setStudentNumber(int studentNumber) {
this.studentNumber = studentNumber;
}
public String getStudentName() {
return studentName;
}
public void setStudentName(String studentName) {
this.studentName = studentName;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
@Override
public String toString() {
return "Student [studentNumber=" + studentNumber + ", studentName=" + studentName + ", age=" + age + ", gender="
+ gender + "]";
}
@Override
public int compareTo(Student student) {
//Ascending Order
return this.getStudentNumber()-student.getStudentNumber(); //102,103=-1
//Descending Order
//return student.getStudentNumber()-this.getStudentNumber(); //103-102=1
}
}
|
package com.iks.education.calculator.gui.buttons;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import com.iks.education.calculator.controller.CalculatorController;
@SuppressWarnings("serial")
public class CommaButton extends JButton {
public CommaButton() {
super(",");
addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
CalculatorController.getInstance().appendComma();
}
});
}
}
|
package Datos;
import java.util.ArrayList;
import java.util.List;
import Negocio.Clase;
public class TestClasesManager implements ClasesManager {
private static TestClasesManager instance = new TestClasesManager();
public static TestClasesManager getInstance() {
return instance;
}
private ArrayList<Clase> clasesBackingList = new ArrayList<Clase>();
private TestClasesManager() {
try {
clasesBackingList.add(new Clase(0, "LUNES", "18:00", TestDeportesManager.getInstance().getDeporteById(1)));
clasesBackingList.add(new Clase(1, "SÁBADO", "14:00", TestDeportesManager.getInstance().getDeporteById(2)));
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public List<Clase> getAllClases() {
List<Clase> result = new ArrayList<Clase>();
// Copiamos cada uno de los socios para simular traída de DB.
for (Clase currentClase : clasesBackingList) {
result.add(new Clase(currentClase.getCodigo(), currentClase.getDia(), currentClase.getHora(), currentClase.getDeporte()));
}
return result;
}
@Override
public void addClase(Clase newClase) {
newClase.setCodigo(getMaxId() + 1);
clasesBackingList.add(new Clase(newClase.getCodigo(), newClase.getDia(), newClase.getHora(), newClase.getDeporte()));
}
private int getMaxId() {
int maxId = 0;
for (Clase currentClase : clasesBackingList)
if (currentClase.getCodigo() > maxId)
maxId = currentClase.getCodigo();
return maxId;
}
@Override
public void editClase(int codigo, Clase modifiedClase) throws Exception {
if (codigo != modifiedClase.getCodigo())
throw new Exception();
Clase s = null;
for (Clase currentClase : clasesBackingList)
if (currentClase.getCodigo() == codigo) {
s = currentClase;
break;
}
s.setDia(modifiedClase.getDia());
s.setHora(modifiedClase.getHora());
s.setDeporte(modifiedClase.getDeporte());
}
@Override
public void deleteClase(int codigo) {
Clase s = null;
for (Clase currentClase : clasesBackingList)
if (currentClase.getCodigo() == codigo) {
s = currentClase;
break;
}
clasesBackingList.remove(s);
}
} |
package com.harshitJaiswal.Assignment4;
import java.util.Scanner;
public class HollowRhombusPatter {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
int lines = n;
int nst = n;
int nsp = n-1;
for (int i = 0; i < lines; i++) {
for (int j = 0; j < nsp; j++) {
System.out.print(" ");
}
for (int j = 0; j < nst; j++) {
if (i == 0 || i == lines-1) {
System.out.print("*");
} else {
if (!(j == 0 || j == nst-1)) {
System.out.print(" ");
} else {
System.out.print("*");
}
}
}
System.out.println();
nsp = nsp-1;
}
}
}
|
package com.github.dongchan.scheduler;
import java.time.Instant;
/**
* @author DongChan
* @date 2020/10/22
* @time 11:25 PM
*/
public interface Clock {
Instant now();
}
|
package sb.controller;
import java.io.IOException;
import java.util.List;
import java.util.Random;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import sb.model.Usuario;
import sb.model.*;
@WebServlet("/register")
public class CadastroServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private UsuarioDAO usuarioDao;
private ContaDAO contaDao;
public void init() {
usuarioDao = new UsuarioDAO();
contaDao = new ContaDAO();
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String nome = request.getParameter("nome");
String tipoPessoa = request.getParameter("tipoPessoa").toUpperCase();
String numDoc = request.getParameter("numDoc");
String score = request.getParameter("score");
String agencia = request.getParameter("agencia");
//instanciando usuário e conta
Usuario usuario = new Usuario(nome, tipoPessoa, numDoc, score);
Conta conta = new Conta();
String limite = "";
String cartao = "";
//estabelecendo número randômico de conta
Random gerador = new Random();
int random = 0 ;
for (int i = 0; i<5; i++) {
random = (int) (gerador.nextDouble() * 1000000);
}
String numero = String.valueOf(random);
conta.setNumero(numero);
//estabelecendo conta corrente ou empresaral de acordo com PF ou PJ
if (tipoPessoa.equals("PF")) {
conta.setTipoConta("Corrente");
} else {
conta.setTipoConta("Empresarial");
}
//estabelecendo limites de conta e cartão com parametrização do score
int numScore = Integer.parseInt(score);
if (numScore == 0 || numScore == 1) {
limite = "desabilitado";
}else if (numScore >= 2 && numScore <= 5) {
limite = "1000";
cartao = "200";
} else if (numScore >= 6 && numScore <= 8) {
limite = "2000";
cartao = "2000";
} else if (numScore == 9 ) {
limite = "5000";
cartao = "15000";
}
conta.setLimite(limite);
conta.setCartao(cartao);
conta.setAgencia(agencia);
conta.setNomeTitular(usuario.getNome());
//registrando conta no banco de dados
try {
contaDao.registerConta(conta);
} catch (ClassNotFoundException e1) {
e1.printStackTrace();
}
//registrando usuario no banco de dados
try {
usuarioDao.registerUsuario(usuario);
} catch (Exception e) {
e.printStackTrace();
}
//JSP com mensagem de cadastro realizado
response.sendRedirect("CadastroPronto.jsp");
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//parâmetro identificador do GET que está sendo chamado no index.
String type = request.getParameter("formType");
if (type.equals("conta")) {
try {
listConta(request, response);
} catch (Exception e) {
e.printStackTrace();
}
} else {
try {
listUser(request, response);
} catch (Exception e) {
e.printStackTrace();
}
}
}
private void listUser(HttpServletRequest request, HttpServletResponse response) throws Exception {
List < Usuario > listUser = usuarioDao.selectAllUsers();
request.setAttribute("listUser", listUser);
RequestDispatcher dispatcher = request.getRequestDispatcher("ListarUsuarios.jsp");
dispatcher.forward(request, response);
}
private void listConta(HttpServletRequest request, HttpServletResponse response) throws Exception {
List < Conta > listConta = contaDao.selectAllContas();
request.setAttribute("listConta", listConta);
RequestDispatcher dispatcher = request.getRequestDispatcher("ListarContas.jsp");
dispatcher.forward(request, response);
}
}
|
package com.gmail.filoghost.holographicdisplays.nms.interfaces.entity;
import org.bukkit.inventory.ItemStack;
public interface NMSItem extends NMSEntityBase, NMSCanMount {
// Sets the bukkit ItemStack for this item.
public void setItemStackNMS(ItemStack stack);
// Sets if this item can be picked up by players.
public void allowPickup(boolean pickup);
// The raw NMS ItemStack object.
public Object getRawItemStack();
}
|
package com.example.PesoLunar;
import android.os.Bundle;
import android.widget.TextView;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
public class DetailActivity extends AppCompatActivity {
private TextView PesoTextView;
private double Earth = 0;
private double Moon = 0;
private String strTotal;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail);
PesoTextView = (TextView) findViewById(R.id.calculateWeightTextView);
}
@Override
protected void onResume() {
super.onResume();
Earth = Double.valueOf(getIntent().getStringExtra("Peso")).doubleValue();
Moon = (Earth/9.8)*1.622;
PesoTextView.setText(getString(R.string.moon_text, String.valueOf(Moon)));
}
}
|
package net.mapthinks.web.rest;
import net.mapthinks.domain.City;
import net.mapthinks.repository.CityRepository;
import net.mapthinks.repository.search.CitySearchRepository;
import net.mapthinks.web.rest.common.AbstractPageableResource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* REST controller for managing City.
*/
@RestController
@RequestMapping("/api/cities")
public class CityResource extends AbstractPageableResource<City,CityRepository,CitySearchRepository> {
private final Logger log = LoggerFactory.getLogger(CityResource.class);
private static final String ENTITY_NAME = "city";
public CityResource(CityRepository cityRepository, CitySearchRepository citySearchRepository) {
super(cityRepository,citySearchRepository);
}
}
|
package com.avishai.MyShas;
import android.content.Intent;
import android.content.pm.ShortcutInfo;
import android.content.pm.ShortcutManager;
import android.graphics.drawable.Icon;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.ExpandableListView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
/**
* An activity for a single Masechet to show
*/
public class ShowMasechet extends AppCompatActivity {
private ImageView img;
private ExpandableListView exlv;
private List<String> listGroup; // for the parent list
private HashMap<String, List<String>> listItems; // for the child items
private MainAdapter adapter;
private Keystore store; // for shared pereferences
private HashMap<String, Boolean> stateOfPages; // to save the state before saving
private int numOfPages;
private String fileName;
private int numOfChap;
private String url;
private TextView name;
private int numMasechet;
private Boolean hasLastPage;
private ProgressBar progressBar;
private TextView progressTxt;
/**
* Method to inflate the specific menu to this form (for every Masechet)
*/
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
switch (this.numOfChap) {
case 3 :
inflater.inflate(R.menu.menu_3_chap, menu);
break;
case 4 :
inflater.inflate(R.menu.menu_4_chap, menu);
break;
case 5 :
inflater.inflate(R.menu.menu_5_chap, menu);
break;
case 6 :
inflater.inflate(R.menu.menu_6_chap, menu);
break;
case 7 :
inflater.inflate(R.menu.menu_7_chap, menu);
break;
case 8 :
inflater.inflate(R.menu.menu_8_chap, menu);
break;
case 9 :
inflater.inflate(R.menu.menu_9_chap, menu);
break;
case 10 :
inflater.inflate(R.menu.menu_10_chap, menu);
break;
case 11 :
inflater.inflate(R.menu.menu_11_chap, menu);
break;
case 12 :
inflater.inflate(R.menu.menu_12_chap, menu);
break;
case 13 :
inflater.inflate(R.menu.menu_13_chap, menu);
break;
case 14 :
inflater.inflate(R.menu.menu_14_chap, menu);
break;
case 16 :
inflater.inflate(R.menu.menu_16_chap, menu);
break;
case 24 :
inflater.inflate(R.menu.menu_24_chap, menu);
break;
case 0 :
inflater.inflate(R.menu.menu_meila_chap, menu);
break;
// if there isn't a menu to show
default:
ProgramMethods.manageHome(this, "שגיאה");
}
return true;
}
/**
* Method to to determine what happened at click on item in the menu
* @param item - the item that been clicked
*/
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.save:
disableButtonns();
ProgramMethods.manageSave(this, store, stateOfPages);
break;
case R.id.home:
disableButtonns();
ProgramMethods.manageHome(this, "השינויים לא נשמרו");
break;
// for all others options
default:
ProgramMethods.manageMenu(item, this, this.adapter, this.listGroup, this.listItems, this.fileName,
this.numOfPages, this.numMasechet, this.stateOfPages, this.exlv, this.url, this.name.getText().toString(),
this.progressBar, this.progressTxt, this.hasLastPage);
}
return super.onOptionsItemSelected(item);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.masechet);
/* The custom Toolbar */
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
this.name = toolbar.findViewById(R.id.headText);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
this.img = findViewById(R.id.imgView);
/* the specific properties of the Masechet */
Bundle extras = getIntent().getExtras();
if (extras != null) {
this.fileName = extras.getString("name");
this.numOfPages = extras.getInt("pages");
this.numOfChap = extras.getInt("chap");
this.hasLastPage = extras.getBoolean("hasLastPage");
this.numMasechet = extras.getInt("numMasechet");
this.url = "https://www.hebrewbooks.org/shas.aspx?mesechta=" + this.numMasechet + "&daf=2&format=pdf";
}
/* to create a dynamic shortcut to the last Masechet that entered */
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N_MR1) {
ShortcutManager shortcutManager = getSystemService(ShortcutManager.class);
Intent intent = new Intent(this, ShowMasechet.class);
intent.putExtra("name", this.fileName);
intent.putExtra("pages", this.numOfPages);
intent.putExtra("chap", this.numOfChap);
intent.putExtra("hasLastPage", this.hasLastPage);
intent.putExtra("numMasechet", this.numMasechet);
intent.setAction("com.android.launcher.action.INSTALL_SHORTCUT");
ShortcutInfo shortcutInfo = new ShortcutInfo.Builder(this, "shID1")
.setShortLabel("מיקום אחרון")
.setIcon(Icon.createWithResource(this, R.drawable.d_shortcut))
.setIntent(intent)
.build();
shortcutManager.setDynamicShortcuts(Collections.singletonList(shortcutInfo));
}
/* Gets the key file */
this.store = new Keystore(getApplicationContext(), this.fileName, this.numOfPages);
this.exlv = findViewById(R.id.expandableListView);
this.listGroup = new ArrayList<>();
this.listItems = new HashMap<>();
this.stateOfPages = new HashMap<>();
this.progressBar = findViewById(R.id.progressBar);
this.progressTxt = findViewById(R.id.progressTxt);
/* to set the bridge between the exlv and the UI */
this.adapter = new MainAdapter(this, this.listGroup, this.listItems, this.store, this.numOfPages,
this.stateOfPages, true, this.numMasechet, this.progressBar, this.progressTxt, this.hasLastPage);
this.exlv.setAdapter(this.adapter);
determinMasechet();
/* to set the progress of the progressbar */
ProgramMethods.determineProgress(this.progressBar, this.stateOfPages, this.numOfPages, this.progressTxt);
}
/**
* To save the progress for the future entrance
* @param view - the button that been clicked
*/
public void Save(View view) {
disableButtonns();
ProgramMethods.manageSave(this, this.store, this.stateOfPages);
}
/**
* To return to the homepage without saving
* @param view - the button that been clicked
*/
public void Home(View view) {
disableButtonns();
ProgramMethods.manageHome(this, "השינויים לא נשמרו");
}
/**
* Help method to disable the "save" and "home" button after a click on one of them
*/
private void disableButtonns() {
ImageButton home = findViewById(R.id.homeWithoutSave);
home.setEnabled(false);
ImageButton save = findViewById((R.id.saveChanges));
save.setEnabled((false));
}
/**
* Help Method to determine which Masechet to show (by the name of the file)
*/
private void determinMasechet() {
switch (this.fileName) {
case "brachotFile" :
DataMethods.initListDataBrachot(this, this.listGroup, this.adapter, this.listItems);
this.name.setText(R.string.brachot);
this.img.setImageResource(R.drawable.brachot);
break;
case "shabatFile" :
DataMethods.initListDataShabat(this, this.listGroup, this.adapter, this.listItems);
this.name.setText(R.string.shabat);
this.img.setImageResource(R.drawable.shabat);
break;
case "eruvinFile" :
DataMethods.initListDataEruvin(this, this.listGroup, this.adapter, this.listItems);
this.name.setText(R.string.eruvin);
this.img.setImageResource(R.drawable.eruvin);
break;
case "psachimFile" :
DataMethods.initListDataPsachim(this, this.listGroup, this.adapter, this.listItems);
this.name.setText(R.string.psachim);
this.img.setImageResource(R.drawable.psachim);
break;
case "shkalimFile" :
DataMethods.initListDataShkalim(this, this.listGroup, this.adapter, this.listItems);
this.name.setText(R.string.shkalim);
this.img.setImageResource(R.drawable.shkalim);
break;
case "yomaFile" :
DataMethods.initListDataYoma(this, this.listGroup, this.adapter, this.listItems);
this.name.setText(R.string.yoma);
this.img.setImageResource(R.drawable.yoma);
break;
case "sukaFile" :
DataMethods.initListDataSuka(this, this.listGroup, this.adapter, this.listItems);
this.name.setText(R.string.suka);
this.img.setImageResource(R.drawable.suka);
break;
case "beitzaFile" :
DataMethods.initListDataBeitza(this, this.listGroup, this.adapter, this.listItems);
this.name.setText(R.string.beitza);
this.img.setImageResource(R.drawable.beitza);
break;
case "roshHashanaFile" :
DataMethods.initListDataRoshHashana(this, this.listGroup, this.adapter, this.listItems);
this.name.setText(R.string.roshHashana);
this.img.setImageResource(R.drawable.rosh_hashana);
break;
case "taanitFile" :
DataMethods.initListDataTaanit(this, this.listGroup, this.adapter, this.listItems);
this.name.setText(R.string.taanit);
this.img.setImageResource(R.drawable.taanit);
break;
case "megilaFile" :
DataMethods.initListDataMegila(this, this.listGroup, this.adapter, this.listItems);
this.name.setText(R.string.megila);
this.img.setImageResource(R.drawable.megila);
break;
case "moedKatanFile" :
DataMethods.initListDataMoedKatan(this, this.listGroup, this.adapter, this.listItems);
this.name.setText(R.string.moedKatan);
this.img.setImageResource(R.drawable.moed_katan);
break;
case "hagigaFile" :
DataMethods.initListDataHagiga(this, this.listGroup, this.adapter, this.listItems);
this.name.setText(R.string.hagiga);
this.img.setImageResource(R.drawable.hagiga);
break;
case "yevamotFile" :
DataMethods.initListDataYevamot(this, this.listGroup, this.adapter, this.listItems);
this.name.setText(R.string.yevamot);
this.img.setImageResource(R.drawable.yevamot);
break;
case "ktubotFile" :
DataMethods.initListDataKtubot(this, this.listGroup, this.adapter, this.listItems);
this.name.setText(R.string.ktubot);
this.img.setImageResource(R.drawable.ktubot);
break;
case "nedarimFile" :
DataMethods.initListDataNedarim(this, this.listGroup, this.adapter, this.listItems);
this.name.setText(R.string.nedarim);
this.img.setImageResource(R.drawable.nedarim);
break;
case "nazirFile" :
DataMethods.initListDataNazir(this, this.listGroup, this.adapter, this.listItems);
this.name.setText(R.string.nazir);
this.img.setImageResource(R.drawable.nazir);
break;
case "sotaFile" :
DataMethods.initListDataSota(this, this.listGroup, this.adapter, this.listItems);
this.name.setText(R.string.sota);
this.img.setImageResource(R.drawable.sota);
break;
case "gitinFile" :
DataMethods.initListDataGitin(this, this.listGroup, this.adapter, this.listItems);
this.name.setText(R.string.gitin);
this.img.setImageResource(R.drawable.gitin);
break;
case "kidushinFile" :
DataMethods.initListDataKidushin(this, this.listGroup, this.adapter, this.listItems);
this.name.setText(R.string.kidushin);
this.img.setImageResource(R.drawable.kidushin);
break;
case "babaKamaFile" :
DataMethods.initListDataBabaKama(this, this.listGroup, this.adapter, this.listItems);
this.name.setText(R.string.babaKama);
this.img.setImageResource(R.drawable.baba_kama);
break;
case "babaMetziaFile" :
DataMethods.initListDataBabaMetzia(this, this.listGroup, this.adapter, this.listItems);
this.name.setText(R.string.babaMetzia);
this.img.setImageResource(R.drawable.baba_metzia);
break;
case "babaBatraFile" :
DataMethods.initListDataBabaBatra(this, this.listGroup, this.adapter, this.listItems);
this.name.setText(R.string.babaBatra);
this.img.setImageResource(R.drawable.baba_batra);
break;
case "sanhedrinFile" :
DataMethods.initListDataSanhedrin(this, this.listGroup, this.adapter, this.listItems);
this.name.setText(R.string.sanhedrin);
this.img.setImageResource(R.drawable.sanhedrin);
break;
case "makotFile" :
DataMethods.initListDataMakot(this, this.listGroup, this.adapter, this.listItems);
this.name.setText(R.string.makot);
this.img.setImageResource(R.drawable.makot);
break;
case "shvuotFile" :
DataMethods.initListDataShvuot(this, this.listGroup, this.adapter, this.listItems);
this.name.setText(R.string.shvuot);
this.img.setImageResource(R.drawable.shvuot);
break;
case "avodaZaraFile" :
DataMethods.initListDataAvodaZara(this, this.listGroup, this.adapter, this.listItems);
this.name.setText(R.string.avodaZara);
this.img.setImageResource(R.drawable.avoda_zara);
break;
case "horayotFile" :
DataMethods.initListDataHorayot(this, this.listGroup, this.adapter, this.listItems);
this.name.setText(R.string.horayot);
this.img.setImageResource(R.drawable.horayot);
break;
case "zvachimFile" :
DataMethods.initListDataZvachim(this, this.listGroup, this.adapter, this.listItems);
this.name.setText(R.string.zvachim);
this.img.setImageResource(R.drawable.zvachim);
break;
case "menachotFile" :
DataMethods.initListDataMenachot(this, this.listGroup, this.adapter, this.listItems);
this.name.setText(R.string.menachot);
this.img.setImageResource(R.drawable.menachot);
break;
case "chulinFile" :
DataMethods.initListDataChulin(this, this.listGroup, this.adapter, this.listItems);
this.name.setText(R.string.chulin);
this.img.setImageResource(R.drawable.chulin);
break;
case "bechorotFile" :
DataMethods.initListDataBechorot(this, this.listGroup, this.adapter, this.listItems);
this.name.setText(R.string.bechorot);
this.img.setImageResource(R.drawable.bechorot);
break;
case "arachinFile" :
DataMethods.initListDataArachin(this, this.listGroup, this.adapter, this.listItems);
this.name.setText(R.string.arachin);
this.img.setImageResource(R.drawable.arachin);
break;
case "tmuraFile" :
DataMethods.initListDataTmura(this, this.listGroup, this.adapter, this.listItems);
this.name.setText(R.string.tmura);
this.img.setImageResource(R.drawable.tmura);
break;
case "kritutFile" :
DataMethods.initListDataKritut(this, this.listGroup, this.adapter, this.listItems);
this.img.setImageResource(R.drawable.kritut);
this.name.setText(R.string.kritut);
break;
case "meilaFile" :
DataMethods.initListDataMeila(this, this.listGroup, this.adapter, this.listItems);
this.name.setText(R.string.meila);
this.img.setImageResource(R.drawable.meila);
break;
case "nidaFile" :
DataMethods.initListDataNida(this, this.listGroup, this.adapter, this.listItems);
this.name.setText(R.string.nida);
this.img.setImageResource(R.drawable.nida);
break;
// if the name is not fit to any file
default:
ProgramMethods.manageHome(this, "שגיאה");
}
}
} |
package BatailleNavale;
/**
* Created by fabie_000 on 01/05/2017.
*/
public class Coordonnee {
private int ligne;
private int colone;
public Coordonnee(int ligne, int colone) { // OUAIISS !!!
this.ligne = ligne;
this.colone = colone;
}
public int getLigne() {
return ligne;
}
public int getColone() {
return colone;
}
@Override
public String toString() {
return "Coordonnee{" +
"ligne=" + ligne +
", colone=" + colone +
'}';
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Coordonnee that = (Coordonnee) o;
if (ligne != that.ligne) return false;
return colone == that.colone;
}
} |
package org.juxtasoftware.dao;
import java.io.IOException;
import java.io.Reader;
import java.util.List;
import javax.xml.stream.XMLStreamException;
import org.juxtasoftware.model.ResourceInfo;
import org.juxtasoftware.model.Source;
import org.juxtasoftware.model.Usage;
import org.juxtasoftware.model.Workspace;
public interface SourceDao {
/**
* Create a source in the specified workspace using the supplied name
* and content reader
* @param ws Workspace in which to add the source
* @param name Name for the new source
* @param type The source content type
* @param contentReader Content reader
* @return The ID of the newly created source
* @throws XMLStreamException
* @throws IOException
*/
Long create(final Workspace ws, final String name, final Source.Type type, Reader contentReader) throws IOException, XMLStreamException;
/**
* Get brief info on this source: name and dates
* @param sourceId
* @return
*/
ResourceInfo getInfo(final Long sourceId);
/**
* Update the source name
* @param src
* @param newName
*/
void update(Source src, final String newName);
/**
* Update th name and content of the specified source
* @param src
* @param newName
* @param contentReader
* @throws XMLStreamException
* @throws IOException
*/
void update(Source src, final String newName, Reader contentReader) throws IOException, XMLStreamException;
/**
* Delete the specifed source
* @param src
*/
void delete(Source src);
/**
* Find a source by ids ID
* @param id
* @return
*/
Source find( final Long workspaceId, Long id );
Source find( final Long workspaceId, String name );
/**
* Given a source, find its root element
* @param src
* @return
*/
String getRootElement( final Source src );
/**
* Get a reader for the content of the source
* @param src
* @return
*/
Reader getContentReader( final Source src );
/**
* List all of the sources in a workspace
* @param ws
* @return
*/
List<Source> list( final Workspace ws);
/**
* Check if a named source exists in the workspace
* @param ws
* @param name
* @return
*/
boolean exists( final Workspace ws, final String name);
/**
* Transform the non-unique <code>origName</code> into a name that
* is unique for workspace <code>ws</code>. Uniqne names are generated
* by adding a '-#' extension to the end, where # is an sequentially increasing
* number
* @param ws
* @param origName
* @return
*/
String makeUniqueName(final Workspace ws, final String origName);
/**
* Get a list of usage information for this source. The list
* details all of the witnesses based upon this source, and
* all of the sets using these witnesses
* @param src
* @return
*/
List<Usage> getUsage( final Source src );
}
|
package com.sha.springbootmongo.repository;
import com.sha.springbootmongo.model.User;
import com.sha.springbootmongo.projection.CountryAggregation;
import com.sha.springbootmongo.projection.UserAggregation;
import org.springframework.data.mongodb.repository.Aggregation;
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.data.mongodb.repository.Query;
import java.util.List;
import java.util.Optional;
/**
* @author sa
* @date 1/10/21
* @time 11:59 AM
*/
public interface IUserRepository extends MongoRepository<User, String> {
// findBy + fieldName
Optional<User> findByUsername(String username);
// value: where condition
// fields: select items: 1 => include, 0 => exclude
// sort: 1 => ASC, -1 => DESC
@Query(value = "{ country: ?0 }", fields = "{ name: 1, _id: 0 }", sort = "{ name: -1 }")
List<User> findByCountryAsCustom(String country);
// select country, sum(1) = count(*) from users group by country
@Aggregation("{ $group: { _id : $country, total : { $sum : 1 } } }")
List<CountryAggregation> countByCountry();
// select country, [names] from user group by country
@Aggregation("{ $group: { _id : $country, names : { $addToSet : $name } } }")
List<UserAggregation> groupByCounty();
}
|
package com.sshfortress.controller.system;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import com.sshfortress.common.beans.SysUser;
import com.sshfortress.common.beans.SysUserForm;
import com.sshfortress.common.enums.UserStatus;
import com.sshfortress.common.enums.UserTypeEnums;
import com.sshfortress.common.enums.ViewShowEnums;
import com.sshfortress.common.util.PageModel;
import com.sshfortress.common.util.Pager;
import com.sshfortress.common.util.ResponseObj;
import com.sshfortress.common.util.StringUtil;
import com.sshfortress.dao.system.mapper.SysUserMapper;
import com.sshfortress.service.system.SysUserService;
@Controller
@RequestMapping("web/sysUser")
public class SysUserWeb {
@Autowired
SysUserMapper sysUserMapper;
@Autowired
SysUserService sysUserService;
/** <p class="detail">
* 功能:获取系统用户
* </p>
* @param user
* @param page
* @return
*/
@RequestMapping(value = "/getList.web",produces = { "application/json;charset=UTF-8" }, method = RequestMethod.POST)
@ResponseBody
public ResponseObj getList(SysUser user, Pager page) {
ResponseObj obj = new ResponseObj(ViewShowEnums.INFO_SUCCESS.getStatus(),
ViewShowEnums.INFO_SUCCESS.getDetail());
Map<String, Object> map = new HashMap<String, Object>();
map.put("record", user);
map.put("page", page);
List<SysUser> list = sysUserMapper.queryByParamsListPager(map);
obj.setData(new PageModel(page, list));
return obj;
}
/** <p class="detail">
* 功能:根据用户ID获取系统用户
* </p>
* @param userId
* @return
*/
@RequestMapping(value = "/getSysUser.web", produces = { "application/json;charset=UTF-8" }, method = RequestMethod.POST)
@ResponseBody
public ResponseObj getSysUser(String userId) {
SysUser selectByPrimaryKey = sysUserMapper.selectByPrimaryKey(userId);
ResponseObj obj = new ResponseObj(ViewShowEnums.INFO_SUCCESS.getStatus(),
ViewShowEnums.INFO_SUCCESS.getDetail());
obj.setData(selectByPrimaryKey);
return obj;
}
/** <p class="detail">
* 功能:更新系统用户
* </p>
* @param form
* @return
*/
@RequestMapping(value = "/update.web", method = RequestMethod.POST)
@ResponseBody
public ResponseObj update(@Valid SysUserForm form) {
ResponseObj obj = new ResponseObj(ViewShowEnums.INFO_SUCCESS.getStatus(),
ViewShowEnums.INFO_SUCCESS.getDetail());
if(StringUtil.isNullOrEmpty(form.getUserId()))
{
obj.setStatus(ViewShowEnums.ERROR_FAILED.getStatus());
obj.setShowMessage("用户Id不能为空");
return obj;
}
SysUser sysUser = sysUserMapper.selectByPrimaryKey(form.getUserId());
if(sysUser==null)
{
obj.setStatus(ViewShowEnums.ERROR_FAILED.getStatus());
obj.setShowMessage("用户不存在!");
return obj;
}
try {
sysUserService.updateUser(form.getUserId(),form.getUserName(), form.getPassWord(),form.getRoleId());
obj.setShowMessage("修改成功");
obj.setStatus(ViewShowEnums.INFO_SUCCESS.getStatus());
} catch (Exception e) {
e.printStackTrace();
obj.setShowMessage("修改失败");
obj.setStatus(ViewShowEnums.ERROR_FAILED.getStatus());
}
return obj;
}
/** <p class="detail">
* 功能:添加系统用户
* </p>
* @param request
* @param response
* @param form
* @param result
* @return
*/
@RequestMapping(value = "/add.web",produces = { "application/json;charset=UTF-8" }, method = RequestMethod.POST)
@ResponseBody
public ResponseObj add(HttpServletRequest request, HttpServletResponse response, @Valid SysUserForm form,
BindingResult result) {
ResponseObj obj = new ResponseObj(ViewShowEnums.INFO_SUCCESS.getStatus(),
ViewShowEnums.INFO_SUCCESS.getDetail());
if (result.hasErrors()) {
obj.setShowMessage(result.getAllErrors().get(0).getDefaultMessage());
obj.setStatus(ViewShowEnums.ERROR_FAILED.getStatus());
return obj;
}
if (form != null && form.getRoleId() == null) {
obj.setShowMessage("角色ID不能为空");
obj.setStatus(ViewShowEnums.ERROR_FAILED.getStatus());
return obj;
}
//判断用户是否存在
SysUser queryByUserNameAndUserType = sysUserService.queryByUserNameAndUserType(form.getUserName(), UserTypeEnums.SYSTEM_MANAGER.getCode());
if(queryByUserNameAndUserType!=null)
{
if(queryByUserNameAndUserType.getStatus()==UserStatus.VOID.getCode())
{
obj.setShowMessage("账户被禁用!");
obj.setStatus(ViewShowEnums.ERROR_FAILED.getStatus());
}
else
{
obj.setShowMessage("账户已经存在");
obj.setStatus(ViewShowEnums.ERROR_FAILED.getStatus());
}
obj.setData("");
return obj;
}
try {
sysUserService.addUser(form.getUserName(), form.getPassWord(), form.getRoleId());
obj.setShowMessage("添加成功");
obj.setStatus(ViewShowEnums.INFO_SUCCESS.getStatus());
} catch (Exception e) {
e.printStackTrace();
obj.setShowMessage("添加失败");
obj.setStatus(ViewShowEnums.ERROR_FAILED.getStatus());
}
obj.setData("");
return obj;
}
/** <p class="detail">
* 功能:删除系统用户
* </p>
* @param userId
* @return
*/
@RequestMapping(value = "/del.web",produces = { "application/json;charset=UTF-8" }, method = RequestMethod.POST)
@ResponseBody
public ResponseObj del(String userId)
{
ResponseObj obj = new ResponseObj(ViewShowEnums.INFO_SUCCESS.getStatus(),
ViewShowEnums.INFO_SUCCESS.getDetail());
try {
sysUserService.delUser(userId);
obj.setShowMessage("删除成功");
obj.setStatus(ViewShowEnums.INFO_SUCCESS.getStatus());
} catch (Exception e) {
e.printStackTrace();
obj.setShowMessage("删除失败");
obj.setStatus(ViewShowEnums.ERROR_FAILED.getStatus());
}
return obj;
}
/** <p class="detail">
* 功能:查询系统权限列表
* </p>
* @param userId
* @return
*/
@RequestMapping(value = "/selectUser.web",produces = { "application/json;charset=UTF-8" }, method = RequestMethod.POST)
@ResponseBody
public ResponseObj selectUser(String userName,String roleName,Pager pager)
{
ResponseObj obj = new ResponseObj(ViewShowEnums.INFO_SUCCESS.getStatus(),
ViewShowEnums.INFO_SUCCESS.getDetail());
Map<String,Object> params=new HashMap<String,Object>();
params.put("userName", userName);
params.put("roleName", roleName);
params.put("pager", pager);
List<Map<String,Object>> l=sysUserService.selectUser(params);
obj.setData(new PageModel(pager, l));
return obj;
}
/**
* <p class="detail">
* 功能:冻结解冻会员
* </p>
* @param sysUser
* @return
*/
@RequestMapping(value = "/freezeUser.web",produces = { "application/json;charset=UTF-8" }, method = RequestMethod.POST)
@ResponseBody
public ResponseObj freezeUser(SysUser sysUser){
ResponseObj obj = new ResponseObj(ViewShowEnums.INFO_SUCCESS.getStatus(),
ViewShowEnums.INFO_SUCCESS.getDetail());
int freezeUser = sysUserMapper.updateByPrimaryKeySelective(sysUser);
if(freezeUser<=0){
obj.setStatus(ViewShowEnums.ERROR_FAILED.getStatus());
obj.setShowMessage(ViewShowEnums.ERROR_FAILED.getDetail());
obj.setData(freezeUser);
return obj;
}
obj.setData(freezeUser);
return obj;
}
}
|
package com.juancrud.miscontactos.fragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.juancrud.miscontactos.R;
import com.juancrud.miscontactos.adapter.ContactoAdaptador;
import com.juancrud.miscontactos.pojo.Contacto;
import com.juancrud.miscontactos.presentador.IRecyclerViewFragmentPresenter;
import com.juancrud.miscontactos.presentador.RecyclerViewFragmentPresenter;
import java.util.ArrayList;
public class RecyclerViewFragment extends Fragment implements IRecyclerViewFragmentView {
private ArrayList<Contacto> contactos;
private RecyclerView rvContactos;
private IRecyclerViewFragmentPresenter presenter;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_recyclerview, container, false);
rvContactos = (RecyclerView)view.findViewById(R.id.rvContactos);
presenter = new RecyclerViewFragmentPresenter(this, getContext());
return view;
}
@Override
public void generarGridLayout() {
GridLayoutManager glm = new GridLayoutManager(getActivity(), 2);
rvContactos.setLayoutManager(glm);
}
@Override
public void generarLinearLayoutVertical() {
LinearLayoutManager llm = new LinearLayoutManager(getActivity());
llm.setOrientation(LinearLayoutManager.VERTICAL);
rvContactos.setLayoutManager(llm);
}
@Override
public ContactoAdaptador crearAdaptador(ArrayList<Contacto> contactos) {
return new ContactoAdaptador(contactos, getActivity());
}
@Override
public void inicializarAdaptador(ContactoAdaptador adaptador) {
rvContactos.setAdapter(adaptador);
}
}
|
// Decompiled by Jad v1.5.8e. Copyright 2001 Pavel Kouznetsov.
// Jad home page: http://www.geocities.com/kpdus/jad.html
// Decompiler options: braces fieldsfirst space lnc
package com.neuron.mytelkom;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.neuron.mytelkom.base.BaseActivity;
import com.neuron.mytelkom.utils.Utils;
import org.apache.http.Header;
import org.json.JSONObject;
// Referenced classes of package com.neuron.mytelkom:
// LoginActivity
public class ActivationActivity extends BaseActivity
{
private Button btnActivate;
private EditText edtCode;
private EditText edtUsername;
public ActivationActivity()
{
}
private void postActivation(String s, String s1)
{
if (s.equals("") || s1.equals(""))
{
Utils.showToast(this, "Fields can not be empty");
return;
}
final ProgressDialog dialog = new ProgressDialog(this);
dialog.setMessage("Harap tunggu...");
dialog.show();
try
{
JSONObject jsonobject = new JSONObject();
jsonobject.put("regusername", s);
jsonobject.put("activation_code", s1);
String s2 = jsonobject.toString();
Utils.printLog(s2);
RequestParams requestparams = new RequestParams();
requestparams.put("param", s2);
asyncHttpClient.post("https://my.telkom.co.id/api/MTActivation.php?api=", requestparams, new AsyncHttpResponseHandler() {
final ActivationActivity this$0;
private final ProgressDialog val$dialog;
public void onFailure(int i, Header aheader[], byte abyte0[], Throwable throwable)
{
super.onFailure(i, aheader, abyte0, throwable);
dialog.dismiss();
Utils.showToast(ActivationActivity.this, "Gagal melakukan aktivasi. Silakan coba lagi");
}
public void onSuccess(int i, Header aheader[], byte abyte0[])
{
super.onSuccess(i, aheader, abyte0);
dialog.dismiss();
String s3 = new String(abyte0);
fetchResponse(s3);
}
{
this$0 = ActivationActivity.this;
dialog = progressdialog;
super();
}
});
return;
}
catch (Exception exception)
{
Utils.printLog(exception.getMessage());
}
}
public static void toActivationActivity(Activity activity)
{
activity.startActivity(new Intent(activity, com/neuron/mytelkom/ActivationActivity));
}
public void fetchResponse(String s)
{
super.fetchResponse(s);
JSONObject jsonobject;
jsonobject = new JSONObject(s);
if (jsonobject.getString("rescode").equals("00"))
{
Utils.showToast(this, jsonobject.getString("resmsg"));
LoginActivity.toLoginActivity(this);
finish();
return;
}
try
{
Utils.showToast(this, jsonobject.getString("resmsg"));
return;
}
catch (Exception exception)
{
Utils.printLog(exception.getMessage());
}
return;
}
public void initializeActions()
{
super.initializeActions();
btnActivate.setOnClickListener(new android.view.View.OnClickListener() {
final ActivationActivity this$0;
public void onClick(View view)
{
postActivation(edtUsername.getText().toString().trim(), edtCode.getText().toString().trim());
}
{
this$0 = ActivationActivity.this;
super();
}
});
}
public void initializeViews()
{
super.initializeViews();
edtUsername = (EditText)findViewById(0x7f0a0000);
edtCode = (EditText)findViewById(0x7f0a0001);
btnActivate = (Button)findViewById(0x7f0a0002);
}
protected void onCreate(Bundle bundle)
{
super.onCreate(bundle);
setContentView(0x7f030000);
initializeViews();
initializeActions();
}
}
|
package com.example.NFEspring.entity;
import javax.persistence.*;
import javax.persistence.Entity;
import javax.validation.constraints.NotEmpty;
import java.io.Serializable;
@Entity
@Table(name = "link")
public class Link implements Serializable {
@Id
@Column(name = "lk_id")
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
@Column(name = "lk_referent_description")
@NotEmpty
private String referentDescription;
@Column(name = "lk_reference_description")
@NotEmpty
private String referenceDescription;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getReferentDescription() {
return referentDescription;
}
public void setReferentDescription(String referentDescription) {
this.referentDescription = referentDescription;
}
public String getReferenceDescription() {
return referenceDescription;
}
public void setReferenceDescription(String referenceDescription) {
this.referenceDescription = referenceDescription;
}
}
|
package cardGames;
import java.util.Collections;
import java.util.EmptyStackException;
import java.util.Stack;
public class DeckStack<E> implements DeckADT<E>{
private Stack <E> cards;
private int items;
public DeckStack() {
cards = new Stack <E> ();
items = 0;
}
public DeckStack(Stack<E> cards) {
this.cards = cards;
}
public void insert52() {
for (int i = 1; i < 14; i++) {
for (int j = 1; j < 5; j++) {
@SuppressWarnings("unchecked")
E newCard = (E) new Card(i,j);
// throws exception if not valid card
addCard(newCard);
items++;
}
}
}
public void addCard(E e) {
if (e == null) {
throw new IllegalArgumentException();
}
if (((Card) e).getRank() > 13 || ((Card) e).getRank() < 1) {
throw new IllegalArgumentException();
}
if (((Card) e).getSuit() > 4 || ((Card) e).getSuit() < 1) {
throw new IllegalArgumentException();
}
cards.push(e);
items++;
}
public E removeCard() {
if (isEmpty()) {
throw new IllegalArgumentException();
}
E curr = null;
try {
curr = cards.pop();
} catch (EmptyStackException e) {
e.getStackTrace();
}
items--;
return curr;
}
public void randomShuffle() {
Collections.shuffle(cards);
}
// need to use sorting algorithm, Can implement later
public void shuffleInOrder() {
}
public boolean isEmpty() {
return items == 0;
}
public int getNumItems() {
return items;
}
//public int countRank
// return copy of the deck
public DeckADT<E> getDeck() {
DeckADT <E> copy = new DeckStack <E> (cards);
return copy;
}
public int compareTo(DeckStack <Card> e) {
// TODO: Compare rank. Similar to toString();
return 0;
}
public int size() {
return items;
}
public String toString() {
String ret = "";
Stack <E> temp = cards;
SimpleQueue<E> writeBack = new SimpleQueue <E> ();
while (!temp.isEmpty()) {
writeBack.enqueue(temp.pop());
}
while (!writeBack.isEmpty()){
E curr = null;
try {
curr = temp.push(writeBack.dequeue());
ret += curr;
if (!writeBack.isEmpty()){
ret += ", ";
}
} catch (EmptyQueueException e) {
e.printStackTrace();
}
}
return ret;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.