text stringlengths 10 2.72M |
|---|
package com.smartup.shippingapplication.mappers;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletRequest;
import org.springframework.context.MessageSource;
import org.springframework.context.support.DefaultMessageSourceResolvable;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.MethodArgumentNotValidException;
import com.smartup.shippingapplication.dto.ApiErrorDto;
@Component
public class ApiErrorDtoMapper {
private MessageSource messageSource;
public ApiErrorDtoMapper(MessageSource messageSource) {
this.messageSource=messageSource;
}
public ApiErrorDto runtimeException2Dto(RuntimeException ex){
return ApiErrorDto.builder()
.errorCode("000")
.message(ex.getMessage())
.build();
}
public ApiErrorDto constraintViolationException2Dto(MethodArgumentNotValidException ex, HttpServletRequest request){
return ApiErrorDto.builder()
.errorCode("999")
.message(messageSource.getMessage("validation.errors", null, request.getLocale()))
.validationErrors(ex.getBindingResult().getAllErrors().stream().map(DefaultMessageSourceResolvable::getDefaultMessage).collect(Collectors.toList()))
.build();
}
}
|
package com.mes.old.meta;
// Generated 2017-5-22 1:25:24 by Hibernate Tools 5.2.1.Final
import java.math.BigDecimal;
/**
* BRoutineGroupId generated by hbm2java
*/
public class BRoutineGroupId implements java.io.Serializable {
private String uniqueid;
private String routing;
private BigDecimal opuid;
private String routineGroupid;
private Byte routineGrouptype;
private String deptid;
private String partuid;
private String positionname;
public BRoutineGroupId() {
}
public BRoutineGroupId(String uniqueid, String routineGroupid) {
this.uniqueid = uniqueid;
this.routineGroupid = routineGroupid;
}
public BRoutineGroupId(String uniqueid, String routing, BigDecimal opuid, String routineGroupid,
Byte routineGrouptype, String deptid, String partuid, String positionname) {
this.uniqueid = uniqueid;
this.routing = routing;
this.opuid = opuid;
this.routineGroupid = routineGroupid;
this.routineGrouptype = routineGrouptype;
this.deptid = deptid;
this.partuid = partuid;
this.positionname = positionname;
}
public String getUniqueid() {
return this.uniqueid;
}
public void setUniqueid(String uniqueid) {
this.uniqueid = uniqueid;
}
public String getRouting() {
return this.routing;
}
public void setRouting(String routing) {
this.routing = routing;
}
public BigDecimal getOpuid() {
return this.opuid;
}
public void setOpuid(BigDecimal opuid) {
this.opuid = opuid;
}
public String getRoutineGroupid() {
return this.routineGroupid;
}
public void setRoutineGroupid(String routineGroupid) {
this.routineGroupid = routineGroupid;
}
public Byte getRoutineGrouptype() {
return this.routineGrouptype;
}
public void setRoutineGrouptype(Byte routineGrouptype) {
this.routineGrouptype = routineGrouptype;
}
public String getDeptid() {
return this.deptid;
}
public void setDeptid(String deptid) {
this.deptid = deptid;
}
public String getPartuid() {
return this.partuid;
}
public void setPartuid(String partuid) {
this.partuid = partuid;
}
public String getPositionname() {
return this.positionname;
}
public void setPositionname(String positionname) {
this.positionname = positionname;
}
public boolean equals(Object other) {
if ((this == other))
return true;
if ((other == null))
return false;
if (!(other instanceof BRoutineGroupId))
return false;
BRoutineGroupId castOther = (BRoutineGroupId) other;
return ((this.getUniqueid() == castOther.getUniqueid()) || (this.getUniqueid() != null
&& castOther.getUniqueid() != null && this.getUniqueid().equals(castOther.getUniqueid())))
&& ((this.getRouting() == castOther.getRouting()) || (this.getRouting() != null
&& castOther.getRouting() != null && this.getRouting().equals(castOther.getRouting())))
&& ((this.getOpuid() == castOther.getOpuid()) || (this.getOpuid() != null
&& castOther.getOpuid() != null && this.getOpuid().equals(castOther.getOpuid())))
&& ((this.getRoutineGroupid() == castOther.getRoutineGroupid())
|| (this.getRoutineGroupid() != null && castOther.getRoutineGroupid() != null
&& this.getRoutineGroupid().equals(castOther.getRoutineGroupid())))
&& ((this.getRoutineGrouptype() == castOther.getRoutineGrouptype())
|| (this.getRoutineGrouptype() != null && castOther.getRoutineGrouptype() != null
&& this.getRoutineGrouptype().equals(castOther.getRoutineGrouptype())))
&& ((this.getDeptid() == castOther.getDeptid()) || (this.getDeptid() != null
&& castOther.getDeptid() != null && this.getDeptid().equals(castOther.getDeptid())))
&& ((this.getPartuid() == castOther.getPartuid()) || (this.getPartuid() != null
&& castOther.getPartuid() != null && this.getPartuid().equals(castOther.getPartuid())))
&& ((this.getPositionname() == castOther.getPositionname())
|| (this.getPositionname() != null && castOther.getPositionname() != null
&& this.getPositionname().equals(castOther.getPositionname())));
}
public int hashCode() {
int result = 17;
result = 37 * result + (getUniqueid() == null ? 0 : this.getUniqueid().hashCode());
result = 37 * result + (getRouting() == null ? 0 : this.getRouting().hashCode());
result = 37 * result + (getOpuid() == null ? 0 : this.getOpuid().hashCode());
result = 37 * result + (getRoutineGroupid() == null ? 0 : this.getRoutineGroupid().hashCode());
result = 37 * result + (getRoutineGrouptype() == null ? 0 : this.getRoutineGrouptype().hashCode());
result = 37 * result + (getDeptid() == null ? 0 : this.getDeptid().hashCode());
result = 37 * result + (getPartuid() == null ? 0 : this.getPartuid().hashCode());
result = 37 * result + (getPositionname() == null ? 0 : this.getPositionname().hashCode());
return result;
}
}
|
package com.kgitbank.spring.domain.follow.mapper;
import java.util.List;
import com.kgitbank.spring.domain.follow.FollowDto;
import com.kgitbank.spring.domain.model.FollowVO;
import com.kgitbank.spring.domain.myprofile.dto.ProfileDto;
public interface FollowMapper {
public void following(FollowVO vo);
public void ufollow(FollowVO vo);
public ProfileDto seqsearch(Integer id);
public List<Integer> selectFollow(ProfileDto vo);
public List<Integer> selectFollower(ProfileDto vo);
public List<ProfileDto> selectProfileOfFollow(int seqId);
public List<FollowDto> selectTop5Follows();
public int checkFollow(FollowVO vo);
} |
package view;
import java.awt.Button;
import java.awt.EventQueue;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import potentialtrain.Main;
public class MainView extends JFrame {
/**
*
*/
private static final long serialVersionUID = 1L;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
MainView frame = new MainView();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public MainView() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
Image image = Toolkit.getDefaultToolkit().createImage(Main.LOGO_PATH);
JLabel btBild = new JLabel(new ImageIcon(image));
btBild.setBounds(70, 50, 460, 100);
btBild.setText("JLabel");
add(btBild);
Button b = new Button("Start");
b.setBounds(260, 200, 80, 30);// setting button position
b.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
GameView game = new GameView();
game.setVisible(true);
MainView.this.setVisible(false);
MainView.this.dispose();
}
});
add(b);//adding button into frame
Button a = new Button("Optionen");
a.setBounds(273, 250, 55, 25);// setting button position
a.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
PreferencesView prefs = new PreferencesView();
prefs.setVisible(true);
MainView.this.setVisible(false);
MainView.this.dispose();
}
});
add(a);//adding button into frame
setSize(600, 400);//frame size 300 width and 300 height
setLayout(null);//no layout manager
setVisible(true);//now frame will be visible, by default not visible
}
}
|
package com.mes.old.meta;
// Generated 2017-5-22 1:25:24 by Hibernate Tools 5.2.1.Final
import java.util.Date;
/**
* CActivityAccount generated by hbm2java
*/
public class CActivityAccount implements java.io.Serializable {
private String activityAccountId;
private String superActivityAccountId;
private String activityAccountName;
private String costCenterId;
private Date createTime;
private String creator;
private String costDriverId;
private String notes;
private Long isBasicActivityAccount;
public CActivityAccount() {
}
public CActivityAccount(String activityAccountId) {
this.activityAccountId = activityAccountId;
}
public CActivityAccount(String activityAccountId, String superActivityAccountId, String activityAccountName,
String costCenterId, Date createTime, String creator, String costDriverId, String notes,
Long isBasicActivityAccount) {
this.activityAccountId = activityAccountId;
this.superActivityAccountId = superActivityAccountId;
this.activityAccountName = activityAccountName;
this.costCenterId = costCenterId;
this.createTime = createTime;
this.creator = creator;
this.costDriverId = costDriverId;
this.notes = notes;
this.isBasicActivityAccount = isBasicActivityAccount;
}
public String getActivityAccountId() {
return this.activityAccountId;
}
public void setActivityAccountId(String activityAccountId) {
this.activityAccountId = activityAccountId;
}
public String getSuperActivityAccountId() {
return this.superActivityAccountId;
}
public void setSuperActivityAccountId(String superActivityAccountId) {
this.superActivityAccountId = superActivityAccountId;
}
public String getActivityAccountName() {
return this.activityAccountName;
}
public void setActivityAccountName(String activityAccountName) {
this.activityAccountName = activityAccountName;
}
public String getCostCenterId() {
return this.costCenterId;
}
public void setCostCenterId(String costCenterId) {
this.costCenterId = costCenterId;
}
public Date getCreateTime() {
return this.createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public String getCreator() {
return this.creator;
}
public void setCreator(String creator) {
this.creator = creator;
}
public String getCostDriverId() {
return this.costDriverId;
}
public void setCostDriverId(String costDriverId) {
this.costDriverId = costDriverId;
}
public String getNotes() {
return this.notes;
}
public void setNotes(String notes) {
this.notes = notes;
}
public Long getIsBasicActivityAccount() {
return this.isBasicActivityAccount;
}
public void setIsBasicActivityAccount(Long isBasicActivityAccount) {
this.isBasicActivityAccount = isBasicActivityAccount;
}
}
|
package instructable.server.senseffect;
import instructable.server.hirarchy.EmailInfo;
/**
* Created by Amos Azaria on 28-Apr-15.
*/
public interface IIncomingEmailControlling
{
void addEmailMessageToInbox(EmailInfo emailMessage);
}
|
package pt.ua.nextweather.ui;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import pt.ua.nextweather.R;
import pt.ua.nextweather.fragments.CitiesHolderFragment;
import pt.ua.nextweather.fragments.ForecastResultsFragment;
public class CityForecast extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_city_forecast);
String city_name = getIntent().getStringExtra("cityname");
int city_code= getIntent().getIntExtra("citycode",0);
TextView title=findViewById(R.id.city_title);
title.setText(city_name);
//Generate Fragment and get Forecast
getForecast(city_code);
}
private void getForecast(int city_code) {
ForecastResultsFragment fragment = ForecastResultsFragment.newInstance(city_code);
// Get FragmentManager and start transaction.
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager
.beginTransaction();
// Add the new fragment for the current broadcast request
fragmentTransaction.add(R.id.fragment_container,
fragment).addToBackStack(null).commit();
}
} |
/* This file was generated by SableCC (http://www.sablecc.org/). */
package node;
import analysis.*;
@SuppressWarnings("nls")
public final class TSection extends Token
{
public TSection()
{
super.setText("¤");
}
public TSection(int line, int pos)
{
super.setText("¤");
setLine(line);
setPos(pos);
}
@Override
public Object clone()
{
return new TSection(getLine(), getPos());
}
@Override
public void apply(Switch sw)
{
((Analysis) sw).caseTSection(this);
}
@Override
public void setText(@SuppressWarnings("unused") String text)
{
throw new RuntimeException("Cannot change TSection text.");
}
}
|
package com.example.ming.controller;
import com.example.ming.entry.Student;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* Created by jamy on 2020-04-22
*/
@RestController
public class HelloWorld {
@RequestMapping("/hello1")
public String sayHello(){
Student stud = new Student();
stud.setName("jamy");
stud.setSex("男");
stud.setAge(24);
stud.setAddress("上海");
return stud.toString();
}
}
|
package example.com.nammamysuru.model;
public class Event {
private String name;
private String place;
private String time;
private String date;
private String url;
public Event(String name, String place, String time, String date, String url) {
this.name = name;
this.place = place;
this.time = time;
this.date = date;
this.url = url;
}
public String getName() {
return name;
}
public String getPlace() {
return place;
}
public String getTime() {
return time;
}
public String getDate() {
return date;
}
public String getUrl() {
return url;
}
}
|
package org.grizz.service.collectors;
import com.beust.jcommander.internal.Maps;
import org.grizz.config.Configuration;
import org.grizz.service.collectors.helpers.Ranking;
import org.grizz.service.collectors.helpers.SummingRanking;
import org.joda.time.DateTime;
import org.springframework.stereotype.Service;
import pl.grizwold.microblog.model.Entry;
import java.util.Map;
import java.util.Optional;
@Service
public class TagUsageCounter implements StatisticsCollector {
private Map<String, Object> stats = Maps.newHashMap();
private Ranking ranking = new SummingRanking();
@Override
public void collect(Entry entry, Configuration configuration) {
DateTime timeOffset = DateTime.now().minusMinutes(configuration.getCountLastMinutes());
Optional.of(entry)
.filter(e -> e.getDateAdded().isAfter(timeOffset))
.ifPresent(e -> e.getTags()
.forEach(t -> ranking.add(t.getName())));
entry.getComments().stream()
.filter(c -> c.getDateAdded().isAfter(timeOffset))
.forEach(c -> c.getTags()
.forEach(t -> ranking.add(t.getName())));
}
@Override
public Map<String, Object> getStats() {
stats.put("tag_usage", ranking.asMap());
return stats;
}
}
|
package com.ci.loader;
import javax.annotation.Nullable;
import com.ci.ModMain;
import com.ci.gui.*;
import com.ci.container.*;
import com.ci.tileentity.TileEntityElectronicProcessing;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
import net.minecraftforge.fml.common.network.IGuiHandler;
import net.minecraftforge.fml.common.network.NetworkRegistry;
public class GuiElementLoader implements IGuiHandler{
public GuiElementLoader()
{
NetworkRegistry.INSTANCE.registerGuiHandler(ModMain.instance, this);
}
@Nullable
@Override
public Object getServerGuiElement(int ID, EntityPlayer player, World world, int x, int y, int z) {
BlockPos pos = new BlockPos(x, y, z);
TileEntity tileEntity = world.getTileEntity(pos);
if (ID == 2){
TileEntityElectronicProcessing tile = (TileEntityElectronicProcessing)tileEntity;
return new ContainerElectronicProcessing(player.inventory, tile);
}
System.out.print("NULL");
return null;
}
@Nullable
@Override
public Object getClientGuiElement(int ID, EntityPlayer player, World world, int x, int y, int z) {
BlockPos pos = new BlockPos(x, y, z);
TileEntity tileEntity = world.getTileEntity(pos);
if (ID == 2){
TileEntityElectronicProcessing tile = (TileEntityElectronicProcessing)tileEntity;
return new GuiElectronicProcessing(player.inventory, tile);
}
System.out.print("NULL");
return null;
}
}
|
package rent.common.repository;
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.data.repository.query.Param;
import org.springframework.data.rest.core.annotation.RepositoryRestResource;
import rent.common.entity.DocumentTypeEntity;
import rent.common.projection.DocumentTypeBasic;
import java.util.List;
@RepositoryRestResource(
collectionResourceRel = "document-types",
path = "document-type",
itemResourceRel = "document-type",
excerptProjection = DocumentTypeBasic.class)
public interface DocumentTypeRepository extends PagingAndSortingRepository<DocumentTypeEntity, String> {
List<DocumentTypeEntity> findByNameContainingOrderByName(@Param("name") String name);
}
|
package com.jst.myservice;
import java.util.List;
import java.util.Map;
import com.jst.model.Sys_user;
public interface LoginService {
public Sys_user getUpwd(String uname);
// //查询所有用户(加分页)
public List<Sys_user> listAll(Map map);
public void addUser(Sys_user users);
// //通过id删除用户
public void deleteById(int uid);
// //查询共有多少条数据
// int listAllRows();
// //通过用户id查询用户
Sys_user selectUserById(int uid);
// //通过用户id修改用户信息
void updateUser(Sys_user users);
}
|
package com.dinu;
import java.util.Arrays;
public class SetMismatch {
public static void main(String[] args) {
int[] arr= {1,2,2,4};
System.out.println(Arrays.toString(find(arr)));
}
static int[] find(int[] nums) {
int i=0;
while(i<nums.length) {
int element=i;
int pos=nums[i]-1;
if(nums[element]!=nums[pos]) {
swap(nums,element,pos);
}else {
i++;
}
}
int[] ans=new int[2];
for(int j=0;j<nums.length;j++) {
if(j+1!=nums[j]) {
ans[0]=nums[j];
ans[1]=j+1;
}
}
return ans;
}
static void swap(int arr[], int f,int s) {
int temp=arr[f];
arr[f]=arr[s];
arr[s]=temp;
}
}
|
package com.tencent.mm.ui.chatting;
import android.view.View.OnLayoutChangeListener;
import android.view.animation.Animation;
import android.view.animation.LinearInterpolator;
import android.view.animation.Transformation;
import com.tencent.mm.sdk.platformtools.x;
import com.tencent.mm.ui.c.a.a;
import com.tencent.mm.ui.c.a.b;
class ChattingAnimFrame$b extends Animation {
private int fi = 0;
private float hkl;
private float hkm;
private float hkn;
private float hko;
private float hkp;
private float hkq;
final /* synthetic */ ChattingAnimFrame tIp;
private float tIq;
private float tIr;
private float tIs;
private float tIt;
private int tIu = 0;
private boolean tIv = false;
private OnLayoutChangeListener tjG = new 1(this);
public ChattingAnimFrame$b(ChattingAnimFrame chattingAnimFrame, int i, int i2) {
this.tIp = chattingAnimFrame;
this.tIu = i;
this.fi = i2;
this.tIv = false;
}
public ChattingAnimFrame$b(ChattingAnimFrame chattingAnimFrame, int i, int i2, boolean z) {
this.tIp = chattingAnimFrame;
this.tIu = i;
this.fi = i2;
this.tIv = z;
}
public final void initialize(int i, int i2, int i3, int i4) {
super.initialize(i, i2, i3, i4);
switch (this.tIu) {
case 1:
this.tIq = ChattingAnimFrame.E(0.1f, 0.9f);
this.tIr = ChattingAnimFrame.E(this.tIq - 0.25f, this.tIq + 0.25f);
this.tIs = 1.5f;
this.tIt = -0.2f;
setInterpolator(new LinearInterpolator());
break;
case 2:
this.tIq = 0.0f;
this.tIr = 0.0f;
this.tIs = 0.0f;
this.tIt = 1.0f;
setInterpolator(new a());
break;
case 3:
this.tIq = 0.0f;
this.tIr = 0.0f;
this.tIs = 1.5f;
if (this.tIv) {
this.tIt = ChattingAnimFrame.E(0.4f, 0.55f);
} else {
this.tIt = ChattingAnimFrame.E(0.54999995f, 0.85f);
}
setInterpolator(new b());
break;
case 999:
this.tIq = ChattingAnimFrame.E(0.1f, 0.9f);
this.tIr = ChattingAnimFrame.E(this.tIq - 0.5f, this.tIq + 0.5f);
this.tIs = 0.0f;
this.tIt = 0.0f;
this.hkl = 0.8f;
this.hkm = 1.1f;
setInterpolator(new LinearInterpolator());
break;
default:
this.tIq = ChattingAnimFrame.E(0.1f, 0.9f);
this.tIr = ChattingAnimFrame.E(this.tIq - 0.5f, this.tIq + 0.5f);
this.tIs = -0.2f;
this.tIt = 1.2f;
setInterpolator(new LinearInterpolator());
break;
}
if (!(this.tIu == 0 || this.tIu == 1)) {
this.tIp.addOnLayoutChangeListener(this.tjG);
}
aum();
}
protected final void applyTransformation(float f, Transformation transformation) {
float f2 = this.hkn;
float f3 = this.hkp;
if (this.hkn != this.hko) {
f2 = this.hkn + ((this.hko - this.hkn) * f);
}
if (this.hkp != this.hkq) {
f3 = this.hkp + ((this.hkq - this.hkp) * f);
if (this.tIu == 2) {
f3 -= (float) this.fi;
}
}
transformation.getMatrix().setTranslate(f2, f3);
if (this.hkl != this.hkm && 3 == this.tIu) {
f2 = this.hkl + ((this.hkm - this.hkl) * f);
transformation.getMatrix().postScale(f2, f2);
}
}
protected final void finalize() {
super.finalize();
x.i("MicroMsg.ChattingAnimFrame", "finalize!");
this.tIp.removeOnLayoutChangeListener(this.tjG);
}
public final void aum() {
this.hkn = this.tIq * ((float) ChattingAnimFrame.a(this.tIp));
this.hko = this.tIr * ((float) ChattingAnimFrame.a(this.tIp));
if (this.tIu == 2) {
this.hkp = this.tIs * ((float) ChattingAnimFrame.b(this.tIp));
this.hkq = this.tIt * ((float) ChattingAnimFrame.b(this.tIp));
} else if (this.tIu == 3) {
this.hkp = this.tIs * ((float) ChattingAnimFrame.c(this.tIp));
this.hkq = this.tIt * ((float) ChattingAnimFrame.c(this.tIp));
if (ChattingAnimFrame.d(this.tIp)) {
this.hkp = (this.tIs * ((float) ChattingAnimFrame.c(this.tIp))) - ((float) ChattingAnimFrame.e(this.tIp));
this.hkq = (this.tIt * ((float) ChattingAnimFrame.c(this.tIp))) - ((float) ChattingAnimFrame.e(this.tIp));
}
if (this.hkq < 0.0f) {
this.hkq = 0.0f;
}
} else {
this.hkp = this.tIs * ((float) ChattingAnimFrame.c(this.tIp));
this.hkq = this.tIt * ((float) ChattingAnimFrame.c(this.tIp));
}
}
}
|
package com.youthchina.domain.tianjian;
public class JobInfo {
private String job_id;
private String company_id;
private String job_name;
private String job_class;
private String job_time;
private String job_description;
private String job_duty;
public String getJob_id() {
return job_id;
}
public void setJob_id(String job_id) {
this.job_id = job_id;
}
public String getCompany_id() {
return company_id;
}
public void setCompany_id(String company_id) {
this.company_id = company_id;
}
public String getJob_name() {
return job_name;
}
public void setJob_name(String job_name) {
this.job_name = job_name;
}
public String getJob_class() {
return job_class;
}
public void setJob_class(String job_class) {
this.job_class = job_class;
}
public String getJob_time() {
return job_time;
}
public void setJob_time(String job_time) {
this.job_time = job_time;
}
public String getJob_description() {
return job_description;
}
public void setJob_description(String job_description) {
this.job_description = job_description;
}
public String getJob_duty() {
return job_duty;
}
public void setJob_duty(String job_duty) {
this.job_duty = job_duty;
}
public String getJob_edu_req() {
return job_edu_req;
}
public void setJob_edu_req(String job_edu_req) {
this.job_edu_req = job_edu_req;
}
public String getJob_location() {
return job_location;
}
public void setJob_location(String job_location) {
this.job_location = job_location;
}
public String getJob_highlight() {
return job_highlight;
}
public void setJob_highlight(String job_highlight) {
this.job_highlight = job_highlight;
}
public String getJob_salary() {
return job_salary;
}
public void setJob_salary(String job_salary) {
this.job_salary = job_salary;
}
public String getJob_recei_mail() {
return job_recei_mail;
}
public void setJob_recei_mail(String job_recei_mail) {
this.job_recei_mail = job_recei_mail;
}
private String job_edu_req;
private String job_location;
private String job_highlight;
private String job_salary;
private String job_recei_mail;
}
|
package org.sscraper.model;
import java.io.Serializable;
public class Actor implements Serializable {
private String name;
private String role;
public Actor(String name, String role) {
this.name = name;
this.role = role;
}
public String getName() {
return this.name;
}
public String getRole() {
return this.role;
}
public String toString() {
return "Actor : name(" + this.name + "), role(" + this.role + ")";
}
}
|
package com.mobica.rnd.parking.parkingbe.exception;
import com.mobica.rnd.parking.parkingbe.model.MarkAvailableSlotsExceptionCode;
import lombok.AllArgsConstructor;
import lombok.Getter;
@Getter
@AllArgsConstructor
public class MarkAvailableSlotsException extends Exception {
private MarkAvailableSlotsExceptionCode code;
}
|
package com.supconit.kqfx.web.fxzf.search.services;
import hc.base.domains.Pageable;
import hc.orm.BasicOrmService;
import java.util.List;
import com.supconit.kqfx.web.fxzf.search.entities.FxzfStatic;
/**
*
* @author JNJ
* @time 2016年12月8日10:01:09
*
*/
public interface FxzfStaticService extends BasicOrmService<FxzfStatic, String> {
/**
* 分页查询信息列表,实时过车记录页面(含有车牌号模糊查询)
*
* @param pager
* @param condition
* @return
*/
Pageable<FxzfStatic> findByPager(Pageable<FxzfStatic> pager, FxzfStatic condition);
/**
* 分页查询信息列表(违章过车和黑名单过车轨迹,使用车牌号和车牌颜色进行精确查询)
*
* @param pager
* @param condition
* @return
*/
Pageable<FxzfStatic> findByPagerDetail(Pageable<FxzfStatic> pager, FxzfStatic condition);
/**
* 批量新增
*
* @param fxzfList
*/
void batchInsert(List<FxzfStatic> fxzfStaticList);
/**
* 告警触发接口(判断是否超过告警阀值)
*
* @param fxzfStatic
* @return
*/
Boolean warnTrigger(FxzfStatic fxzfStatic);
/**
* 审核信息
*/
void checkFxzfMessage(FxzfStatic condition);
/**
* 获取某个超限状态的数目
*/
int getOverLoadStatusCount(FxzfStatic fxzfStatic);
/**
* 获取所有超限状态的数目
*/
int getIllegalLevelCount(FxzfStatic fxzfStatic);
/**
* 获取治超站过车数量、违法过车数量、治超站当天违法过车数量(监控系统调用)
*
* @param fxzfStatic
* @return
*/
Integer getCountByCondition(FxzfStatic fxzfStatic);
/**
* 获取某违法程度过车数量(监控系统调用)
*
* @param fxzfStatic
* @return
*/
Integer getOverLoadCount(FxzfStatic fxzfStatic);
/**
* 根据过车记录ID删除该记录信息
*
* @param id
*/
void deleteById(String id);
/**
* 获取没有被上传的前10条信息
*/
List<FxzfStatic> getFxzfToTransport();
/**
* 更新过车数据
*
* @param fxzfStatic
*/
void upDateFxzftransport(FxzfStatic fxzfStatic);
}
|
package com.example.hp.bookshop;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.support.v4.app.Fragment;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import java.util.ArrayList;
import java.util.List;
public class BiographyFragment extends Fragment {
public CustomAdapter customAdapter;
public String url = "https://www.googleapis.com/books/v1/volumes?q=biography";
ProgressDialog progressDialog;
ListView listView;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View rootView = inflater.inflate(R.layout.fragment_biography,container,false);
listView = (ListView)rootView.findViewById(R.id.list_view_bio);
populate();
return rootView;
}
public void populate()
{
customAdapter = new CustomAdapter(getContext(),new ArrayList<Books>());
listView.setAdapter(customAdapter);
BackgroundTask backgroundTask = new BackgroundTask();
backgroundTask.execute(url);
}
public class BackgroundTask extends AsyncTask<String,Void,List<Books>>
{
@Override
protected List<Books> doInBackground(String... urls) {
if (urls.length<1 || urls[0]==null) {
return null;
}
List<Books> booksList = QueryUtils.fetchFeatures(urls[0]);
return booksList;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = ProgressDialog.show(getContext(),"Please Wait","Loading");
}
@Override
protected void onPostExecute(List<Books> bookses) {
super.onPostExecute(bookses);
customAdapter.clear();
if (bookses != null && !bookses.isEmpty())
{
customAdapter.addAll(bookses);
progressDialog.dismiss();
}
}
}
}
|
package com.tencent.mm.plugin.appbrand.jsapi.g;
import com.tencent.mm.plugin.appbrand.jsapi.h;
import com.tencent.mm.plugin.appbrand.l;
import com.tencent.mm.sdk.platformtools.x;
import java.util.HashMap;
import java.util.Map;
import org.json.JSONObject;
public class a$a extends h {
public static final int CTRL_INDEX = 468;
public static final String NAME = "onLoadSubPackageTaskStateChange";
static /* synthetic */ void a(l lVar, String str, String str2, String str3, int i, long j, long j2) {
x.i("MicroMsg.JsApiCreateLoadSubPackageTask", "hy: formatEventCallback taskId: %s, state: %s, progress: %d, currentWritten: %d, totalWritten: %d", new Object[]{str, str2, Integer.valueOf(i), Long.valueOf(j), Long.valueOf(j2)});
Map hashMap = new HashMap();
hashMap.put("taskId", str);
hashMap.put("state", str2);
hashMap.put("moduleName", str3);
hashMap.put("progress", Integer.valueOf(i));
hashMap.put("totalBytesWritten", Long.valueOf(j));
hashMap.put("totalBytesExpectedToWrite", Long.valueOf(j2));
String jSONObject = new JSONObject(hashMap).toString();
h a = new a$a().a(lVar);
a.mData = jSONObject;
a.ahM();
}
}
|
package ast.expressions;
import ast.LhsNode;
import ast.Node;
import ast.types.TypeNode;
import exceptions.TypeException;
import semanticAnalysis.Effect;
import semanticAnalysis.Environment;
import semanticAnalysis.SemanticError;
import java.util.ArrayList;
import java.util.List;
public class DerExpNode extends ExpNode{
final private LhsNode lhs;
public DerExpNode(LhsNode lhs){
this.lhs = lhs;
}
@Override
public String toPrint(String indent) {
return indent + lhs.toPrint(indent);
}
@Override
public TypeNode typeCheck() throws TypeException {
return lhs.typeCheck();
}
@Override
public String codeGeneration() {
return lhs.codeGeneration();
}
@Override
public ArrayList<SemanticError> checkSemantics(Environment env) {
ArrayList<SemanticError> res = new ArrayList<>();
res.addAll(lhs.checkSemantics(env));
return res;
}
@Override
public ArrayList<SemanticError> checkEffects(Environment env) {
ArrayList<SemanticError> res = new ArrayList<>();
res.addAll(lhs.checkEffects(env));
// we are processing a dereferentiation Node lhs -> lhs^ -> id^
if (lhs.getLhsId().getSTentry().getVarStatus().equals(Effect.BOT)) {
res.add(new SemanticError(lhs + " is used prior to initialization."));
}
return res;
}
@Override
public List<LhsNode> getExpVar() {
List<LhsNode> var = new ArrayList<>();
if(!( lhs == null)) {
var.add(lhs);
}
return var;
}
public LhsNode getLhs() {
return this.lhs;
}
}
|
package com.tencent.mm.plugin.appbrand.widget.f;
import com.tencent.mm.plugin.appbrand.page.p;
public final class b {
public final p gOQ;
public c gOR;
public b(p pVar) {
this.gOQ = pVar;
}
}
|
package com.wzy.service;
import org.springframework.context.annotation.Conditional;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
/**
* @ClassName Example2
* @Desc TODO
* @Author Administrator
* @Date 2019/6/24 15:32
**/
@Component
@Conditional(LinuxCondition.class)
public class Example2 {
public Example2() {
System.out.println("example2 init");
}
}
|
import java.util.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.sql.*;
import javax.swing.BorderFactory;
import java.awt.BorderLayout;
class admin
{
static JFrame jf;
JRadioButton r1,r2,r3,r4;
ButtonGroup bg;
String y;
static JLabel jl1,jl2,jl3,jl4,jl5,jl6,jl7,jl8,jl9,jl10,jl11,jl12,jl13,jl14,jl15;
String ques,opt1,opt2,opt3,opt4,ans,val1,val2,val3,val4,non;
JButton b1,b2;
JPanel jp,jp1,jp2,jp3;
int x=1,k,j,f,n=1,z=0;
int i=1;
admin()
{
jf=new JFrame();
jf.setBounds(100,100,1200,600);
jf.setLayout(null);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jf.setUndecorated(true);
ImageIcon ic=new ImageIcon("1.png");
Image im=ic.getImage().getScaledInstance(1200,600,Image.SCALE_SMOOTH);
ic=new ImageIcon(im);
JLabel l=new JLabel(ic);
l.setBounds(0,0,1200,600);
jf.add(l);
l.setBorder(BorderFactory.createLineBorder(Color.black));
jl2=new JLabel();
jl2.setBounds(0,60,1200,2);
l.add(jl2);
jl2.setBorder(BorderFactory.createLineBorder(Color.black));
jl1=new JLabel(" Welcome to Administrator Page ");
l.add(jl1);
jl1.setForeground(Color.black);
jl1.setBounds(400,10,700,50);
jl1.setFont(new Font("Curlz MT", Font.BOLD, 25));
jl4=new JLabel(" Add Quiz ");
l.add(jl4);
jl4.setForeground(Color.black);
jl4.setBounds(20,70,140,50);
jl4.setFont(new Font("Curlz MT", Font.BOLD, 25));
ImageIcon ic3=new ImageIcon("i.png");
Image im3=ic3.getImage().getScaledInstance(100,100,Image.SCALE_SMOOTH);
ic3=new ImageIcon(im3);
JLabel l3=new JLabel(ic3);
l3.setBounds(20,150,100,100);
l.add(l3);
l.setBorder(BorderFactory.createLineBorder(Color.black));
l3.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
jl4.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
jl4.addMouseListener(new MouseAdapter()
{
public void mouseClicked (MouseEvent e)
{
new addquiz();
jf.dispose();
}
});
l3.addMouseListener(new MouseAdapter()
{
public void mouseClicked (MouseEvent e)
{
new addquiz();
jf.dispose();
}
});
jl5=new JLabel(" Add Question ");
l.add(jl5);
jl5.setForeground(Color.black);
jl5.setBounds(200,250,170,50);
jl5.setFont(new Font("Curlz MT", Font.BOLD, 25));
ImageIcon ic4=new ImageIcon("i.png");
Image im4=ic4.getImage().getScaledInstance(100,100,Image.SCALE_SMOOTH);
ic4=new ImageIcon(im4);
JLabel l4=new JLabel(ic4);
l4.setBounds(230,330,100,100);
l.add(l4);
l.setBorder(BorderFactory.createLineBorder(Color.black));
l4.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
jl5.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
jl5.addMouseListener(new MouseAdapter()
{
public void mouseClicked (MouseEvent e)
{
new addques();
jf.dispose();
}
});
l4.addMouseListener(new MouseAdapter()
{
public void mouseClicked (MouseEvent e)
{
new addques();
jf.dispose();
}
});
jl6=new JLabel(" View All Visitors ");
l.add(jl6);
jl6.setForeground(Color.black);
jl6.setBounds(430,70,250,50);
jl6.setFont(new Font("Curlz MT", Font.BOLD, 25));
jl5.setBackground(Color.black);
ImageIcon ic5=new ImageIcon("i.png");
Image im5=ic5.getImage().getScaledInstance(100,100,Image.SCALE_SMOOTH);
ic5=new ImageIcon(im5);
JLabel l5=new JLabel(ic5);
l5.setBounds(460,150,100,100);
l.add(l5);
l.setBorder(BorderFactory.createLineBorder(Color.black));
jl7=new JLabel(" View Top 10 Winners ");
l.add(jl7);
jl7.setForeground(Color.black);
jl7.setBounds(950,70,250,50);
jl7.setFont(new Font("Curlz MT", Font.BOLD, 25));
jl7.setBackground(Color.black);
ImageIcon ic7=new ImageIcon("i.png");
Image im7=ic7.getImage().getScaledInstance(100,100,Image.SCALE_SMOOTH);
ic7=new ImageIcon(im7);
JLabel l7=new JLabel(ic7);
l7.setBounds(980,150,100,100);
l.add(l7);
l.setBorder(BorderFactory.createLineBorder(Color.black));
l7.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
jl7.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
jl7.addMouseListener(new MouseAdapter()
{
public void mouseClicked (MouseEvent e)
{
new showwin();
jf.dispose();
}
});
l7.addMouseListener(new MouseAdapter()
{
public void mouseClicked (MouseEvent e)
{
new showwin();
jf.dispose();
}
});
jl8=new JLabel(" Change Password ");
l.add(jl8);
jl8.setForeground(Color.black);
jl8.setBounds(680,250,200,50);
jl8.setFont(new Font("Curlz MT", Font.BOLD, 25));
jl8.setBackground(Color.black);
ImageIcon ic6=new ImageIcon("i.png");
Image im6=ic6.getImage().getScaledInstance(100,100,Image.SCALE_SMOOTH);
ic6=new ImageIcon(im6);
JLabel l6=new JLabel(ic6);
l6.setBounds(730,330,100,100);
l.add(l6);
l.setBorder(BorderFactory.createLineBorder(Color.black));
ImageIcon ic1=new ImageIcon("c.png");
Image im1=ic1.getImage().getScaledInstance(30,30,Image.SCALE_SMOOTH);
ic1=new ImageIcon(im1);
JLabel l1=new JLabel(ic1);
l1.setBounds(1160,10,30,30);
l.add(l1);
l1.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
l1.addMouseListener(new MouseAdapter()
{
public void mouseClicked (MouseEvent e)
{
jf.dispose();
}
});
ImageIcon ic2=new ImageIcon("p.png");
Image im2=ic2.getImage().getScaledInstance(40,40,Image.SCALE_SMOOTH);
ic2=new ImageIcon(im2);
JLabel l2=new JLabel(ic2); //backarrow
l2.setBounds(10,10,40,40);
l.add(l2);
l2.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
l2.addMouseListener(new MouseAdapter()
{
public void mouseClicked(MouseEvent r)
{
new login();
jf.dispose();
}
});
jf.setVisible(true);
}
public static void main(String [] ar)
{
new admin();
}
} |
package com.dahua.design.behavioral.interpreter;
import java.util.HashSet;
import java.util.Set;
public class Area {
Set<String> city = new HashSet<String>(){{add("武汉市");add("上海市");}};
Set<String> type = new HashSet<String>(){{add("医生");add("老人");add("儿童");}};
private IDCardExpression idCardExpression;
public Area() {
TerminalExpression cityInterpreter = new TerminalExpression(city, ":");
TerminalExpression typeInterpreter = new TerminalExpression(type, "-");
idCardExpression = new OrExpression(cityInterpreter, typeInterpreter);
}
void getTicket(String expression){
boolean interpreter = idCardExpression.interpreter(expression);
if (interpreter){
System.out.println("恭喜你,可以免票");
}else {
System.out.println("对不起,请购票");
}
}
}
|
package powerup.engine;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
public class KeyHandler extends KeyAdapter {
private GraphicsController controller = null;
public KeyHandler(GraphicsController controller) {
super();
this.controller = controller;
}
public void keyPressed(KeyEvent e) {
controller.getGameClient().keyEvent(e);
}
}
|
package br.usp.memoriavirtual.servlet.rest;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.ejb.EJB;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import br.usp.memoriavirtual.modelo.entidades.Acesso;
import br.usp.memoriavirtual.modelo.entidades.Autor;
import br.usp.memoriavirtual.modelo.entidades.Instituicao;
import br.usp.memoriavirtual.modelo.entidades.Usuario;
import br.usp.memoriavirtual.modelo.entidades.bempatrimonial.BemPatrimonial;
import br.usp.memoriavirtual.modelo.fachadas.ModeloException;
import br.usp.memoriavirtual.modelo.fachadas.remoto.EditarAutorRemote;
import br.usp.memoriavirtual.modelo.fachadas.remoto.EditarInstituicaoRemote;
import br.usp.memoriavirtual.modelo.fachadas.remoto.MemoriaVirtualRemote;
import br.usp.memoriavirtual.modelo.fachadas.remoto.RealizarBuscaSimplesRemote;
@Path("/")
@Produces({ MediaType.APPLICATION_JSON })
@javax.enterprise.context.RequestScoped
public class Listar implements Serializable{
private static final long serialVersionUID = 6983171202115368169L;
@EJB
EditarInstituicaoRemote editarInstituicaoEJB;
@EJB
EditarAutorRemote editarAutorEJB;
@EJB
RealizarBuscaSimplesRemote realizarBuscaSimplesEJB;
@EJB
MemoriaVirtualRemote memoriaVirtualEJB;
public Listar() {
super();
}
@GET
@Path("/listarinstituicoes")
public List<Instituicao> listarInstituicoes(@QueryParam("busca") String busca,@Context HttpServletRequest request){
try {
Usuario usuario = (Usuario) request.getSession().getAttribute("usuario");
List<Instituicao> instituicoes = null;
if (usuario.isAdministrador()) {
instituicoes = editarInstituicaoEJB.listarInstituicoes(busca);
}
else {
instituicoes = new ArrayList<Instituicao>();
List<Instituicao> parcial = null;
for(Acesso a : usuario.getAcessos()){
parcial = editarInstituicaoEJB.listarInstituicoes(busca, a.getGrupo(), usuario);
for(Instituicao i: parcial){
if(!instituicoes.contains(i)){
instituicoes.add(i);
}
}
}
}
return instituicoes;
} catch (ModeloException m) {
m.printStackTrace();
}
catch (Exception e) {
e.printStackTrace();
}
return null;
}
@GET
@Path("/listarbempatrimonial/{inst}")
public List<BemPatrimonial> listarBensInstituicao(@PathParam("inst") String inst, @QueryParam("busca") String busca,
@Context HttpServletRequest request) {
//Usuario usuario = (Usuario) request.getSession().getAttribute("usuario");
Integer instituicaoId = Integer.parseInt(inst);
try {
List<BemPatrimonial> bensPatrimoniais = realizarBuscaSimplesEJB.buscar(busca);
List<BemPatrimonial> resultado = new ArrayList<BemPatrimonial>();
for (BemPatrimonial b : bensPatrimoniais) {
if (b.getInstituicao().getId() == instituicaoId) {
resultado.add(b);
}
}
return resultado;
} catch (ModeloException m) {
m.printStackTrace();
}
return null;
}
@GET
@Path("/listarautores")
public List<Autor> listarAutores(@QueryParam("busca") String busca,@Context HttpServletRequest request){
try {
List<Autor> autores = null;
autores = editarAutorEJB.listarAutores(busca);
return autores;
} catch (ModeloException m) {
m.printStackTrace();
}
return null;
}
boolean verificaAcesso(BemPatrimonial b, List<Acesso> acessos){
boolean temAcesso = false;
for(Acesso a : acessos){
if(a.getInstituicao().getId()==b.getInstituicao().getId()){
temAcesso = true;
}
}
return temAcesso;
}
@GET
@Path("/listarbempatrimonial")
public List<BemPatrimonial> listarBens(@QueryParam("busca") String busca,@Context HttpServletRequest request){
Usuario usuario = (Usuario) request.getSession().getAttribute("usuario");
try {
List<BemPatrimonial> bensPatrimoniais = realizarBuscaSimplesEJB.buscar(busca);
List<BemPatrimonial> excluir = new ArrayList<BemPatrimonial>();
if(!usuario.isAdministrador()){
for(BemPatrimonial b : bensPatrimoniais){
if(!verificaAcesso(b, usuario.getAcessos())){
excluir.add(b);
}
}
bensPatrimoniais.removeAll(excluir);
}
return bensPatrimoniais;
} catch (ModeloException m) {
m.printStackTrace();
}
return null;
}
@GET
@Path("/listarbempatrimonialrevisao")
public List<BemPatrimonial> listarBensRevisao(@QueryParam("busca") String busca,@Context HttpServletRequest request){
Usuario usuario = (Usuario) request.getSession().getAttribute("usuario");
try {
List<BemPatrimonial> bensPatrimoniais = realizarBuscaSimplesEJB.buscar(busca);
List<BemPatrimonial> excluir = new ArrayList<BemPatrimonial>();
if(!usuario.isAdministrador()){
for(BemPatrimonial b : bensPatrimoniais){
if(!verificaAcesso(b, usuario.getAcessos())){
excluir.add(b);
}
}
}
for(BemPatrimonial b : bensPatrimoniais){
if(b.getInstituicao().getRevisao() == false)
excluir.add(b);
}
bensPatrimoniais.removeAll(excluir);
return bensPatrimoniais;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
@GET
@Path("/listarusuarios")
public List<Usuario> listarUsuarios(@QueryParam("busca") String busca,@Context HttpServletRequest request){
try {
Usuario usuario = (Usuario) request.getSession().getAttribute("usuario");
List<Usuario> usuarios = memoriaVirtualEJB.listarUsuarios(busca,usuario);
return usuarios;
} catch (ModeloException m) {
m.printStackTrace();
}
return null;
}
}
|
package controller.util.collectors.impl;
import controller.constants.FrontConstants;
import controller.exception.WrongInputDataException;
import controller.util.collectors.DataCollector;
import domain.Schedule;
import org.apache.log4j.Logger;
import resource_manager.ResourceManager;
import javax.servlet.http.HttpServletRequest;
public class ScheduleDataCollector extends DataCollector<Schedule> {
private static ResourceManager resourceManager = ResourceManager.INSTANCE;
private static final Logger logger = Logger.getLogger(ScheduleDataCollector.class);
@Override
public Schedule retrieveData(HttpServletRequest request) throws WrongInputDataException {
logger.info("Retrieving schedule data from request");
int counter = 2;
String departure = request.getParameter(FrontConstants.DEPARTURE_TIME);
String arrival = request.getParameter(FrontConstants.ARRIVAL_TIME);
Schedule schedule = new Schedule();
if (departure != null && departure.matches(resourceManager.getRegex("reg.time"))){
schedule.setDeparture(departure);
counter--;
}
if (arrival != null && arrival.matches(resourceManager.getRegex("reg.time"))){
schedule.setArrival(arrival);
counter--;
}
if (counter != 0){
logger.warn("Not all input forms filled correctly");
request.setAttribute(FrontConstants.SCHEDULE, schedule);
throw new WrongInputDataException("Not all input form filled correctly");
}
return schedule;
}
}
|
package prefeitura.siab.apresentacao;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import org.springframework.web.context.WebApplicationContext;
import prefeitura.siab.controller.BusinessException;
import prefeitura.siab.controller.VinculoController;
import prefeitura.siab.tabela.VinculoEmpregaticio;
@Component
@Scope(WebApplicationContext.SCOPE_REQUEST)
public class NewVinculo {
//ATRIBUTOS
private @Autowired VinculoController controller;
private VinculoEmpregaticio vinculo;
//PROPRIEDADES
public VinculoEmpregaticio getVinculo() {
return vinculo;
}
public void setVinculo(VinculoEmpregaticio vinculo) {
this.vinculo = vinculo;
}
//CONSTRUTOR
public NewVinculo() {
this.vinculo = new VinculoEmpregaticio();
}
//MÉTODOS
public String saveVinculo(){
FacesMessage message = new FacesMessage();
try{
controller.salvarVinculo(vinculo);
message.setSummary("Vinculo salvo com Sucesso!");
message.setSeverity(FacesMessage.SEVERITY_INFO);
}catch(BusinessException e){
message.setSummary(e.getMessage());
message.setSeverity(FacesMessage.SEVERITY_ERROR);
}
FacesContext context = FacesContext.getCurrentInstance();
context.addMessage(null, message);
return null;
}
}
|
package rjm.romek.awscourse.bcrypt;
import java.util.List;
import java.util.stream.Collectors;
import org.junit.Test;
import com.google.common.collect.ImmutableList;
public class UserInsertSqlGenerator {
private List<UserInsertSql> userInsertSqls = ImmutableList.of(
UserInsertSql.builder().withUserName("tester").withPassword("tester").build()
);
@Test
public void generate() {
userInsertSqls.stream()
.map(s -> s.convertToSqlInsert())
.collect(Collectors.toList())
.forEach(System.out::println);
}
}
|
/**
*
*/
package com.polyvelo.servlets;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import com.polyvelo.beans.Product;
import com.polyvelo.beans.User;
import com.polyvelo.forms.addProductForm;
/**
* Servlet gérant l'affichage du formulaire de création d'un produit ainsi que l'ajout de ces produits.
* @author Erwan Matrat & Charles Daumont
* @version 1.0
*/
public class ShopManager extends HttpServlet {
private static final long serialVersionUID = 1L;
public static final String VUE_SHOP = "/WEB-INF/restricted/merchant/add_product.jsp";
public static final String ATT_PRODUCT = "product";
public static final String ATT_USER = "user";
public static final String ATT_FORM = "form";
public static final String ATT_SESSION_USER ="userSession";
/**
* Simple affichage du formulaire.
*/
public void doGet( HttpServletRequest request, HttpServletResponse response ) throws ServletException, IOException
{
/* Affichage de la page d'ajout de produit */
this.getServletContext().getRequestDispatcher( VUE_SHOP ).forward( request, response );
}
/**
* Récupération des données du formulaire, validation des données et enregistrement du produit en BDD.
*/
public void doPost( HttpServletRequest request, HttpServletResponse response ) throws ServletException, IOException
{
/* Pr�paration de l'objet formulaire */
addProductForm form = new addProductForm();
/* Traitement de la requ�te et r�cup�ration du bean en r�sultant */
// R�cup�ration de l'id de l'utilisateur qui ajoute le produit
HttpSession session = request.getSession();
User user = (User) session.getAttribute( ATT_SESSION_USER );
Product product = form.ajouterProduit(request);
if(form.getErreurs().isEmpty()){
product.addProductBDD(user.getId());
}
request.setAttribute( ATT_FORM, form );
request.setAttribute( ATT_PRODUCT, product );
this.getServletContext().getRequestDispatcher(VUE_SHOP).forward( request, response );
}
} |
package com.qualitas.modelo;
import asjava.uniclientlibs.UniDynArray;
import asjava.uniobjects.UniCommand;
import asjava.uniobjects.UniCommandException;
import asjava.uniobjects.UniFile;
import asjava.uniobjects.UniFileException;
import asjava.uniobjects.UniSelectList;
import asjava.uniobjects.UniSelectListException;
import asjava.uniobjects.UniSession;
import asjava.uniobjects.UniSessionException;
import com.qualitas.modelo.entities.TipoEndoso;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
public class ConectaUniverse {
private String server = "110.10.0.176"; // ip server
private String userName = "gaquino"; // usuario
private String password = "angel13"; // contraseña
private String accountPath = "/sise"; // cuenta
public String DBtype = "UNIVERSE"; // tipo de cuenta
public UniSession session; // UniVerse session
public ConectaUniverse() {
session = new UniSession();
procesar();
}
public void procesar() {
try {
session.setHostName(server);
session.setUserName(userName);
session.setPassword(password);
session.setAccountPath(accountPath);
session.setDataSourceType(DBtype);
System.out.println("Termino asignar valores");
session.connect();
System.out.println("Conexion establecida");
} catch (UniSessionException e) {
System.out.println("Error en la conexion ");
System.out.println(e.getMessage());
} catch (Exception e) {
System.out.println("Error en la conexion " + e.getMessage());
}
}
public List<TipoEndoso> leer() {
String cmdString;
UniCommand command = null;
System.out.println("\nEjecuta Comando inicio >>>\n");
List <TipoEndoso> lista = new ArrayList<>();
try {
cmdString = "SSELECT TENDOSO";
command = session.command();
command.setCommand(cmdString);
command.exec();
UniSelectList uvslLista = session.selectList(0);
UniFile uvfBDSise = session.openFile("TENDOSO");
while(!uvslLista.isLastRecordRead()) {
String idBDSise = uvslLista.next().toString();
if (!idBDSise.isEmpty()) {
System.out.println("Encontro registro " + idBDSise);
uvfBDSise.setRecordID(idBDSise);
UniDynArray uvdRegBDSise = new UniDynArray(uvfBDSise.read().toString());
String descripcion = uvdRegBDSise.extract(1).toString();
String tipo = uvdRegBDSise.extract(2).toString();
TipoEndoso tipoEndoso = new TipoEndoso(idBDSise, descripcion, tipo);
lista.add(tipoEndoso);
}
}
System.out.println(command.response());
} catch (UniSessionException e) {
System.out.println(" ERROR:UniSessonException:" + e.getMessage() + "\n");
} catch (UniCommandException e) {
System.out.println(" ERROR:UniCommandException:" + e.getMessage() + "\n");
} catch (UniSelectListException e) {
System.out.println(" ERROR:UniSelectListException:" + e.getMessage() + "\n");
} catch (UniFileException e) {
System.out.println(" ERROR:UniFileException:" + e.getMessage() + "\n");
}
System.out.println("Ejecuta Comando fin <<<\n");
return lista;
}
}
|
package com.emoney.web.model;
import com.emoney.core.model.EntityBase;
import lombok.Getter;
import lombok.Setter;
import javax.persistence.*;
@Getter
@Setter
@Entity
@Table(name = "user_rating")
public class UserRatingEntity extends EntityBase {
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "transaction_id")
private JobTransactionEntity transaction;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "poster_id")
private UserEntity poster;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "worker_id")
private UserEntity worker;
@Column(name = "poster_review")
private Integer posterReview;
@Column(name = "worker_review")
private Integer workerReview;
}
|
package com.goldgov.dygl.module.partymember.dao;
import java.util.List;
import java.util.Map;
import org.apache.ibatis.annotations.Param;
import com.goldgov.dygl.dynamicfield.DynamicField;
import com.goldgov.dygl.module.partymember.service.PartyMemberQuery;
import com.goldgov.gtiles.core.dao.mybatis.annotation.MybatisRepository;
import com.goldgov.gtiles.module.user.service.User;
@MybatisRepository("partyMemberDao_AB")
public interface IPartyMemberDao_AB {
void addInfo(@Param("fields") DynamicField field,@Param("partyMemberID") String partyMemberID);
void updateInfo(@Param("entityID") String entityID,@Param("fields") DynamicField field);
void deleteInfo(@Param("ids") String[] entityIDs);
Map<String, Object> findInfoById(@Param("id") String partyMemberID,@Param("fields") DynamicField field);
List<Map<String, Object>> findInfoListByPage(@Param("query") PartyMemberQuery abQuery,@Param("fields") DynamicField field);
void updateABInfoFromUser(@Param("userId")String userId, @Param("user")User user);
void addABInfoFromUser(@Param("userId")String userId, @Param("user")User user);
String getAAID(@Param("abId")String entityID);
}
|
package com.example.idbsystem.dao;
import com.example.idbsystem.bean.ImgInfos;
import org.apache.ibatis.annotations.*;
import java.util.List;
@Mapper
public interface Imginorsdao {
@Insert("insert manage(pid,examtime,diagnosis,age,sex,edu,mmse,moca,fmri,smri,abetapet,fdgpet)values(#{pid},#{examtime},#{diagnosis},#{age},#{sex},#{edu},#{mmse},#{moca},#{fmri},#{smri},#{abetapet},#{fdgpet})")
boolean insertImginros(ImgInfos imgInfos);
@Insert("insert fmri(pid,examtime,img)values(#{pid},#{examtime},#{img})")
boolean insertfmri(Integer pid, String examtime, byte[] img);
@Insert("insert smri(pid,examtime,img)values(#{pid},#{examtime},#{img})")
boolean insertsmri(Integer pid, String examtime, byte[] img);
@Insert("insert abetapet(pid,examtime,img)values(#{pid},#{examtime},#{img})")
boolean insertabetapet(Integer pid, String examtime, byte[] img);
@Insert("insert fdgpet(pid,examtime,img)values(#{pid},#{examtime},#{img})")
boolean insertfdgpet(Integer pid, String examtime, byte[] img);
/**
* 动态查询
* 每个操作的注解还提供一个provider注解,可以通过java方法提供动态sql语句
* method参数指定的方法,必须是public String的,可以为static。
*/
// @Select("select * from manage where diagnosis=#{diagnosis} and fmri=#{fmri} and smri=#{smri} and abetapet=#{abetapet} and fdgpet=#{fdgpet}")
@SelectProvider(type = com.example.idbsystem.dao.SqlProvider.class,method = "selectImginrosSql")
List<ImgInfos> selectImginros(String diagnosis, String fmri, String smri, String abetapet, String fdgpet);
@Select("select * from manage where pid=#{pid} and examtime=#{examtime}")
List<ImgInfos> selectImginrosbyidandexamtime(String pid, String examtime);
/**
* #{}和 ${}注入参数,需要注意单引号的问题
* @Param 设置key, 可以通过key取值
*/
// @Select("select img from ${param1} where pid='${param2}' and examtime='${param3}'")
// String selectimg(String table, String pid, String examtime);
@Select("select img from ${table} where pid=#{pid} and examtime=#{examtime}")
String selectimg(@Param("table") String table, @Param("pid") String pid, @Param("examtime") String examtime);
}
|
package com.ajay.TIAA;
public class PrintFibo {
public static void main(String[] args) {
int num=5;
System.out.print(0+":"+1+":");
fibt(num);
}
private static void fibt(int num) {
int a=0;
int b=1;
int i=2;
while(i<num) {
int c = a+b;
System.out.print(c +":");
a=b;
b=c;
i++;
}
}
}
|
package sample;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.ResourceBundle;
import GameService.GameService;
import Player.Player;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Group;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import GameService.Game;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.Pane;
import javafx.stage.Stage;
public class Controller {
@FXML
private ResourceBundle resources;
@FXML
private URL location;
@FXML
private Button startGameButton;
@FXML
private Button connectButton;
private static Parent root;
@FXML
void initialize() {
startGameButton.setOnAction(actionEvent -> {
startGameButton.getScene().getWindow().hide();
Thread server = new Thread(new GameService());
Game game = new Game();
try {
game.start(new Stage());
} catch (Exception e) {
e.printStackTrace();
}
Thread player = null;
try {
player = new Thread(new Player(Player.nickName));
} catch (IOException e) {
e.printStackTrace();
}
player.start();
});
connectButton.setOnAction(actionEvent -> {
Game game = new Game();
try {
game.start(new Stage());
} catch (Exception e) {
e.printStackTrace();
}
//stage.showAndWait();
Thread player = null;
try {
player = new Thread(new Player("Client1"));
} catch (IOException e) {
e.printStackTrace();
}
player.start();
});
}
}
|
package ec.com.yacare.y4all.lib.util;
import android.content.Context;
import android.database.ContentObserver;
import android.graphics.Color;
import android.os.Handler;
import android.os.SystemClock;
import android.provider.Settings;
import android.text.format.DateFormat;
import android.util.AttributeSet;
import android.widget.TextView;
import java.util.Calendar;
import ec.com.yacare.y4all.activities.R;
import ec.com.yacare.y4all.activities.principal.Y4HomeActivity;
/**
* Created by yacare on 28/01/2017.
*/
public class DigitalClock extends TextView {
Calendar mCalendar;
private final static String m12 = "h:mm:ss aa";
private final static String m24 = "dd/MM/yyyy k:mm:ss";
private FormatChangeObserver mFormatChangeObserver;
private Runnable mTicker;
private Handler mHandler;
private boolean mTickerStopped = false;
String mFormat;
public DigitalClock(Context context) {
super(context);
initClock(context);
}
public DigitalClock(Context context, AttributeSet attrs) {
super(context, attrs);
initClock(context);
}
private void initClock(Context context) {
// Resources r = mContext.getResources();
if (mCalendar == null) {
mCalendar = Calendar.getInstance();
}
mFormatChangeObserver = new FormatChangeObserver();
getContext().getContentResolver().registerContentObserver(
Settings.System.CONTENT_URI, true, mFormatChangeObserver);
setFormat();
}
@Override
protected void onAttachedToWindow() {
mTickerStopped = false;
super.onAttachedToWindow();
mHandler = new Handler();
/**
* requests a tick on the next hard-second boundary
*/
mTicker = new Runnable() {
public void run() {
if (mTickerStopped) return;
if(Y4HomeActivity.circleProgressSegundo != null){
int porcentajeSegundos = mCalendar.get(Calendar.SECOND) * 100 / 60;
Y4HomeActivity.circleProgressSegundo.changePercentage(porcentajeSegundos, mCalendar.get(Calendar.HOUR_OF_DAY));
mCalendar.setTimeInMillis(System.currentTimeMillis());
setText(DateFormat.format(mFormat, mCalendar));
int porcentajeMinuto = mCalendar.get(Calendar.MINUTE) * 100 / 60;
Y4HomeActivity.circleProgressMinuto.changePercentage(porcentajeMinuto);
int porcentajeHora = mCalendar.get(Calendar.HOUR) * 100 / 12;
Y4HomeActivity.circleProgressHora.changePercentage(porcentajeHora, porcentajeSegundos);
if(mCalendar.get(Calendar.HOUR_OF_DAY) > 12 && mCalendar.get(Calendar.HOUR_OF_DAY) < 19){
Y4HomeActivity.layoutReloj.setBackgroundResource(R.drawable.fondo_reloj_tarde);
setTextColor(Color.BLACK);
Y4HomeActivity.textYacare.setTextColor(Color.BLACK);
}else if(mCalendar.get(Calendar.HOUR_OF_DAY) >= 19){
Y4HomeActivity.layoutReloj.setBackgroundResource(R.drawable.fondo_reloj_noche);
setTextColor(Color.WHITE);
Y4HomeActivity.textYacare.setTextColor(Color.WHITE);
}else{
Y4HomeActivity.layoutReloj.setBackgroundResource(R.drawable.fondo_reloj_dia);
setTextColor(Color.BLACK);
Y4HomeActivity.textYacare.setTextColor(Color.BLACK);
}
}
invalidate();
long now = SystemClock.uptimeMillis();
long next = now + (1000 - now % 1000);
mHandler.postAtTime(mTicker, next);
}
};
mTicker.run();
}
@Override
protected void onDetachedFromWindow() {
super.onDetachedFromWindow();
mTickerStopped = true;
}
/**
* Pulls 12/24 mode from system settings
*/
private boolean get24HourMode() {
return android.text.format.DateFormat.is24HourFormat(getContext());
}
private void setFormat() {
// if (get24HourMode()) {
mFormat = m24;
// } else {
// mFormat = m12;
// }
}
private class FormatChangeObserver extends ContentObserver {
public FormatChangeObserver() {
super(new Handler());
}
@Override
public void onChange(boolean selfChange) {
setFormat();
}
}
}
|
package servlet.web;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class MyWebServlet extends HttpServlet{
public void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException{
PrintWriter out = res.getWriter();
out.println("<h2>Hello MyWebServlet</h2>");
out.close();
}
} |
package com.example.gymsy;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import com.example.gymsy.connection.PostData;
import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;
public class NuevoUsuario extends Activity {
String [] etapas = {"Volumen", "Definicion"};
String [] frecuencias = {"Ninguna/1 vez/semana", "3/4 veces/semana", "5/mas veces/semanas"};
String [] lesion = {"Si", "No"};
private TextView username;
private EditText nombreUsuario;
private TextView password;
private EditText contrasena;
private TextView height;
private EditText altura;
private TextView weight;
private EditText peso;
private TextView stage;
private Spinner etapa;
private TextView currentFrequency;
private Spinner frecuenciaActual;
private TextView targetFrequency;
private Spinner frecuenciaObjetivo;
private TextView injury;
private Spinner lesionSiNo;
private TextView injuredArea;
private EditText zonaLesion;
private String _nombreUsuario;
private String _altura;
private String _peso;
private String _etapa;
private String _frecActual;
private String _frecObjetivo;
private String _lesionSiNo;
private String _zonaLesion;
private String _contrasenia;
public NuevoUsuario(){
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.nuevo_usuario);
username = findViewById(R.id._username);
nombreUsuario = findViewById(R.id._nombreUsuario);
password = findViewById(R.id._password);
contrasena = findViewById(R.id._contrasenia);
height = findViewById(R.id._heigh);
altura = findViewById(R.id._altura);
weight = findViewById(R.id._weight);
peso = findViewById(R.id._pesoString);
stage = findViewById(R.id._stageText);
etapa = findViewById(R.id._etapa);
etapa.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item,
etapas));
currentFrequency = findViewById(R.id._currentFrec);
frecuenciaActual = findViewById(R.id._frecuenciaAct);
frecuenciaActual.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item,
frecuencias));
targetFrequency = findViewById(R.id._targetFrec);
frecuenciaObjetivo = findViewById(R.id._frecObj);
frecuenciaObjetivo.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item,
frecuencias));
injury = findViewById(R.id._injury);
lesionSiNo = findViewById(R.id._lesionSiNo);
lesionSiNo.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item,
lesion));
injuredArea = findViewById(R.id._injuredArea);
zonaLesion = findViewById(R.id._zonaLesion);
}
/* Obtiene los datos que se han introducido en el cuestionario y en el caso de que no haya un
* usuario con mismo nombre de usuario, lo registra en la base de datos de la API, y te devuelve
* a la pantalla de MainActivity
*/
public void registrarUsuario(View view) throws NoSuchAlgorithmException, UnsupportedEncodingException {
_contrasenia = contrasena.getText().toString();
_nombreUsuario = nombreUsuario.getText().toString();
_altura = altura.getText().toString();
_peso = peso.getText().toString();
_etapa = etapa.getSelectedItem().toString();
_frecActual = frecuenciaActual.getSelectedItem().toString();
_frecObjetivo = frecuenciaObjetivo.getSelectedItem().toString();
_lesionSiNo = lesionSiNo.getSelectedItem().toString();
_zonaLesion = "";
if (_lesionSiNo.equalsIgnoreCase("Si")){
_zonaLesion = zonaLesion.getText().toString();
_lesionSiNo = "1";
}
else{
_lesionSiNo = "0";
}
int nivel;
if(_nombreUsuario.isEmpty() || _altura.isEmpty() || _peso.isEmpty() ||
_etapa.isEmpty() || _frecActual.isEmpty() || _frecObjetivo.isEmpty() || _lesionSiNo.isEmpty()){
Toast toast = Toast.makeText(getApplicationContext(), "Rellene los campos que faltan",
Toast.LENGTH_LONG);
toast.show();
}
else{
String jsonRet = postData();
if(jsonRet.contains("Username Exists")){
Toast toast = Toast.makeText(getApplicationContext(),"Usuario ya existente", Toast.LENGTH_SHORT);
toast.show();
}
else if(jsonRet.contains("Registered")){
Toast toast = Toast.makeText(getApplicationContext(),"Registrado!", Toast.LENGTH_SHORT);
toast.show();
}
else{
if(_frecActual.contains("1")){
nivel = 1;
}
else if(_frecActual.contains("3")){
nivel = 2;
}
else{
nivel = 3;
}
}
Intent mainActivity = new Intent(getApplicationContext(),MainActivity.class);
startActivity(mainActivity);
}
}
/* Registra al usuario en la base de datos de la API */
public String postData() {
try {
String data = "username="+_nombreUsuario+"&password="+_contrasenia+"&altura="+_altura+"&peso="+_peso+"&etapa="+_etapa+"&lesion="+_lesionSiNo+"&zonaLesion="+_zonaLesion;
String url = "http://35.180.41.33/auth/register/";
PostData foo = new PostData(data, url);
String jsonResult = foo.postData();
Log.e("test", jsonResult );
return jsonResult;
}
catch(Exception e){
e.printStackTrace();
String fail = "{\"msg\":\"Username Exists\"}";
return fail;
}
}
}
|
package com.rsm.yuri.projecttaxilivredriver.FirebaseService;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
//import androidx.core.content.LocalBroadcastManager;
import android.util.Log;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;
import com.google.firebase.messaging.FirebaseMessagingService;
import com.google.firebase.messaging.RemoteMessage;
import com.rsm.yuri.projecttaxilivredriver.FirebaseService.utils.NotificationUtils;
import com.rsm.yuri.projecttaxilivredriver.main.ui.MainActivity;
import org.json.JSONException;
import org.json.JSONObject;
/**
* Created by yuri_ on 25/04/2018.
*/
public class MyFirebaseMessagingService extends FirebaseMessagingService {
private static final String TAG = MyFirebaseMessagingService.class.getSimpleName();
private NotificationUtils notificationUtils;
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
Log.d("d", "onMessageReceived()");
//Log.d("d", "From: " + remoteMessage.getFrom());
if (remoteMessage == null)
return;
// Check if message contains a notification payload.
if (remoteMessage.getNotification() != null) {
Log.d("d", "Notification Body: " + remoteMessage.getNotification().getBody());
handleNotification(remoteMessage.getNotification().getBody());
}
// Check if message contains a data payload.
if (remoteMessage.getData().size() > 0) {
Log.d("d", "Data Payload: " + remoteMessage.getData().toString());
try {
JSONObject json = new JSONObject(remoteMessage.getData().toString());
handleDataMessage(json);
} catch (Exception e) {
Log.d("d", "Exception: " + e.getMessage());
}
}
}
private void handleNotification(String message) {
if (!NotificationUtils.isAppIsInBackground(getApplicationContext())) {
// app is in foreground, broadcast the push message
Intent pushNotification = new Intent("pushNotification");
pushNotification.putExtra("message", message);
LocalBroadcastManager.getInstance(this).sendBroadcast(pushNotification);
// play notification sound
NotificationUtils notificationUtils = new NotificationUtils(getApplicationContext());
notificationUtils.playNotificationSound();
}else{
// If the app is in background, firebase itself handles the notification
}
}
private void handleDataMessage(JSONObject json) {
Log.d("d", "push json: " + json.toString());
try {
//JSONObject data = json.getJSONObject("data");
String requesterEmail = json.getString("requesterEmail");
String requesterName = json.getString("requesterName");
String placeOriginAddress = json.getString("placeOriginAddress");
String placeDestinoAddress = json.getString("placeDestinoAddress");
double latOrigem = json.getDouble("latOrigem");
double longOrigem = json.getDouble("longOrigem");
double latDestino = json.getDouble("latDestino");
double longDestino = json.getDouble("longDestino");
String travelDate = json.getString("travelDate");
double travelPrice = json.getDouble("travelPrice");
//JSONObject payload = json.getJSONObject("payload");
Log.d("d", "MyFirebaseMessagingService.handleDataMessage() requesterEmail: " + requesterEmail);
Log.d("d", "MyFirebaseMessagingService.handleDataMessage() requesterName " + requesterName);
Log.d("d", "MyFirebaseMessagingService.handleDataMessage() placeOriginAddress: " + placeOriginAddress);
Log.d("d", "MyFirebaseMessagingService.handleDataMessage() placeDestinoAddress " + placeDestinoAddress);
Log.d("d", "MyFirebaseMessagingService.handleDataMessage() latOrigem: " + latOrigem);
Log.d("d", "MyFirebaseMessagingService.handleDataMessage() longOrigem: " + longOrigem);
Log.d("d", "MyFirebaseMessagingService.handleDataMessage() latDestino: " + latDestino);
Log.d("d", "MyFirebaseMessagingService.handleDataMessage() longDestino: " + longDestino);
Log.d("d", "MyFirebaseMessagingService.handleDataMessage() travelDate: " + travelDate);
Log.d("d", "MyFirebaseMessagingService.handleDataMessage() travelPrice: " + travelPrice);
/*Intent i = new Intent();
i.setClass(this, MainActivity.class);*/
Bundle args = new Bundle();
args.putString("requesterEmail", requesterEmail);
args.putString("requesterName", requesterName);
args.putString("placeOriginAddress", placeOriginAddress);
args.putString("placeDestinoAddress", placeDestinoAddress);
args.putDouble("latOrigem", latOrigem);
args.putDouble("longOrigem", longOrigem);
args.putDouble("latDestino", latDestino);
args.putDouble("longDestino", longDestino);
args.putString("travelDate", travelDate);
args.putDouble("travelPrice", travelPrice);
/*i.putExtras(args);
i.putExtra(MainActivity.DATA_REQUEST_TRAVEL_MSG_KEY, "true");
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_FROM_BACKGROUND);
startActivity(i);*/
Intent intent = new Intent(MainActivity.RECEIVER_INTENT);
intent.putExtras(args);
intent.putExtra(MainActivity.DATA_REQUEST_TRAVEL_MSG_KEY, MainActivity.DATA_REQUEST_TRAVEL_MSG);
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
/*startActivity(new Intent(this, MainActivity.class));*/
/*if (!NotificationUtils.isAppIsInBackground(getApplicationContext())) {
// app is in foreground, broadcast the push message
Intent pushNotification = new Intent("pushNotification");
pushNotification.putExtra("requesterName", requesterName);
LocalBroadcastManager.getInstance(this).sendBroadcast(pushNotification);
// play notification sound
NotificationUtils notificationUtils = new NotificationUtils(getApplicationContext());
notificationUtils.playNotificationSound();
} else {
// app is in background, show the notification in notification tray
Intent resultIntent = new Intent(getApplicationContext(), MainActivity.class);
resultIntent.putExtra("requesterName", requesterName);
// check for image attachment
//if (TextUtils.isEmpty(imageUrl)) {
//showNotificationMessage(getApplicationContext(), title, message, timestamp, resultIntent);
//} else {
// image is present, show notification with image
// showNotificationMessageWithBigImage(getApplicationContext(), title, message, timestamp, resultIntent, imageUrl);
//}
}*/
} catch (JSONException e) {
Log.d("d", "Json Exception: " + e.getMessage());
} catch (Exception e) {
Log.d("d", "Exception: " + e.getMessage());
}
}
/**
* Showing notification with text only
*/
private void showNotificationMessage(Context context, String title, String message, String timeStamp, Intent intent) {
notificationUtils = new NotificationUtils(context);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
notificationUtils.showNotificationMessage(title, message, timeStamp, intent);
}
/**
* Showing notification with text and image
*/
private void showNotificationMessageWithBigImage(Context context, String title, String message, String timeStamp, Intent intent, String imageUrl) {
notificationUtils = new NotificationUtils(context);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
notificationUtils.showNotificationMessage(title, message, timeStamp, intent, imageUrl);
}
}
|
package com.mengdo.pub.service.impl;
import com.google.common.collect.Maps;
import com.mengdo.pub.cons.Constanst;
import com.mengdo.pub.dao.PubTokenDao;
import com.mengdo.pub.dao.entity.PubTokenEntity;
import com.mengdo.pub.enums.EnumTokenType;
import com.mengdo.pub.service.WXSignService;
import com.mengdo.pub.utils.Configs;
import com.mengdo.pub.utils.GsonUtils;
import com.mengdo.pub.utils.WXSignUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.Map;
/**
* @author piaoxj
* @email piaoxj89@gmail.com
* @mobile 15901283289
*/
//@Service("wxSignService")
public class WXSignServiceImpl implements WXSignService {
private static Logger logger = LoggerFactory.getLogger(WXSignServiceImpl.class);
@Resource
private PubTokenDao pubTokenDao;
@Override
public String jsapiSign(String pubCode,String url) {
Map<String,String> map = Configs.getConfigsByFile(pubCode);
String appId = map.get(Constanst.APPID);
String apiList = map.get(Constanst.APILIST);
PubTokenEntity resultEntity = pubTokenDao.getOne(pubCode, EnumTokenType.JSAPI_TICKET);
String token = resultEntity.getToken();
String nonceStr = WXSignUtils.createNonceStr();
Map<String,Object> resultMap = Maps.newTreeMap();
resultMap.put("jsapi_ticket",token);
resultMap.put("noncestr",nonceStr);
resultMap.put("timestamp",WXSignUtils.createTimestamp());
resultMap.put("url",url);
String signature = WXSignUtils.getSign(resultMap,null,null,"sha1");
resultMap.put("signature",signature);
resultMap.put("appId",appId);
String[] jsApiList = apiList.split(",");
resultMap.put("jsApiList",jsApiList);
resultMap.put("debug",false);
resultMap.remove("jsapi_ticket");
resultMap.remove("url");
resultMap.remove("noncestr");
resultMap.put("nonceStr",nonceStr);
String json = GsonUtils.toJson(resultMap);
logger.info("[PUB返回前端通用参数为] [{}]",json);
return json;
}
@Override
public String authRequest(String pubCode) {
if("dlcqgame".equals(pubCode)){
return "SUCCESS";
}
return "FAIL";
}
}
|
package com.maia.bank.services;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.when;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mockito;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import com.maia.bank.domain.Cliente;
import com.maia.bank.repository.ClienteRepository;
import com.maia.bank.services.impl.ClienteServicesImpl;
@ExtendWith(SpringExtension.class)
@ActiveProfiles("tests")
public class ClienteServicesTests {
ClienteServices clienteServices;
@MockBean
ClienteRepository repository;
Cliente entity;
@BeforeEach
public void setUp() {
this.clienteServices = new ClienteServicesImpl(repository);
}
public static Cliente createCliente() {
return Cliente.builder()
.id(1l)
.nome("DK Maia")
.cpf("83658134836")
.email("maia@maia.ok")
.nomeDaMae("Nome da Mãe")
.ddd("41")
.celular("974123698")
.build();
}
@Test
@DisplayName("Deve Salvar um novo Cliente na base de Dados")
public void saveCliente() {
//cenario
Cliente entity = createCliente();
when(repository.save(entity)).thenReturn(
createCliente() );
//execução
Cliente savedCliente = clienteServices.save(entity);
//verificação
assertThat(savedCliente.getId()).isNotNull();
assertThat(savedCliente.getNome()).isEqualTo("DK Maia");
assertThat(savedCliente.getNomeDaMae()).isEqualTo("Nome da Mãe");
assertThat(savedCliente.getCpf()).isEqualTo("83658134836");
Mockito.verify(repository, Mockito.times(1)).save(entity); // verifica se passou neste metodo ao menos UMA VEZ(1X).
}
}
|
package org.usfirst.frc.team467.robot;
import java.io.IOException;
import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.core.LoggerContext;
import org.apache.logging.log4j.core.config.Configuration;
import org.apache.logging.log4j.core.config.LoggerConfig;
import org.usfirst.frc.team467.robot.Autonomous.Action;
import org.usfirst.frc.team467.robot.Autonomous.ActionGroup;
import org.usfirst.frc.team467.robot.vision.VisionIntegration;
import org.usfirst.frc.team467.robot.Autonomous.MatchConfiguration;
import org.usfirst.frc.team467.robot.simulator.DriveSimulator;
import org.usfirst.frc.team467.robot.simulator.draw.RobotShape;
import org.usfirst.frc.team467.robot.GrabberSolenoid;
public class Logging {
public static void init() {
final LoggerContext ctx = (LoggerContext) LogManager.getContext(false);
final Configuration config = ctx.getConfiguration();
// Modify all the loggers
config.addLogger(Robot.class.getName(), new LoggerConfig(Robot.class.getName(), Level.INFO, true));
// LOOGER.info("WRITE SOMETHING IN HERE WITH: {}" WriteVaribleHere(), andHereIfThereIsAnotherOne());
// Enable extra logging for classes you want to debug
config.addLogger(Climber.class.getName(), new LoggerConfig(Climber.class.getName(), Level.INFO, true));
// config.addLogger(Action.class.getName(), new LoggerConfig(Action.class.getName(), Level.INFO, true));
config.addLogger(Drive.class.getName(), new LoggerConfig(Drive.class.getName(), Level.INFO, true));
// config.addLogger(ActionGroup.class.getName(), new LoggerConfig(ActionGroup.class.getName(), Level.WARN, true));
// config.addLogger(DriveSimulator.class.getName(), new LoggerConfig(DriveSimulator.class.getName(), Level.WARN, true));
config.addLogger(Elevator.class.getName(), new LoggerConfig(Elevator.class.getName(), Level.INFO, true));
config.addLogger(Grabber.class.getName(), new LoggerConfig(Grabber.class.getName(), Level.INFO, true));
config.addLogger(MatchConfiguration.class.getName(), new LoggerConfig(MatchConfiguration.class.getName(), Level.INFO, true));
// config.addLogger(OpticalSensor.class.getName(), new LoggerConfig(OpticalSensor.class.getName(), Level.WARN, true));
// config.addLogger(Ramp.class.getName(), new LoggerConfig(Ramp.class.getName(), Level.INFO, true));
// config.addLogger(Ramps.class.getName(), new LoggerConfig(Ramps.class.getName(), Level.INFO, true));
// config.addLogger(org.usfirst.frc.team467.robot.simulator.Robot.class.getName(),
// new LoggerConfig(org.usfirst.frc.team467.robot.simulator.Robot.class.getName(), Level.INFO, true));
// config.addLogger(RobotShape.class.getName(), new LoggerConfig(RobotShape.class.getName(), Level.WARN, true));
// config.addLogger(Rumbler.class.getName(), new LoggerConfig(Rumbler.class.getName(), Level.WARN, true));
// config.addLogger(TalonSpeedControllerGroup.class.getName(), new LoggerConfig(TalonSpeedControllerGroup.class.getName(), Level.INFO, true));
// config.addLogger(VisionIntegration.class.getName(), new LoggerConfig(VisionIntegration.class.getName(), Level.WARN, true));
// config.addLogger(XBoxJoystick467.class.getName(), new LoggerConfig(XBoxJoystick467.class.getName(), Level.WARN, true));
// config.addLogger(TiltMonitor.class.getName(), new LoggerConfig(TiltMonitor.class.getName(), Level.INFO, true));
config.addLogger(GrabberSolenoid.class.getName(), new LoggerConfig(GrabberSolenoid.class.getName(), Level.INFO, true));
ctx.updateLoggers();
}
private static void setupDefaultLogging() {
// Create a logging appender that writes our pattern to the console.
// Our pattern looks like the following:
// 42ms INFO MyClass - This is my info message
String pattern = "%rms %p %c - %m%n";
// PatternLayout layout = new PatternLayout(pattern);
// Logger.getRootLogger().addAppender(new ConsoleAppender(layout));
// try {
// RollingFileAppender rollingFileAppender = new RollingFileAppender(layout, "/home/admin/log/Robot467.log");
// rollingFileAppender.setMaxBackupIndex(20);
// rollingFileAppender.setMaximumFileSize(1_000_000);
// rollingFileAppender.rollOver();
// Logger.getRootLogger().addAppender(rollingFileAppender);
// } catch (IOException e) {
// System.out.println("Failed to create log file appender: " + e.getMessage());
// }
}
} |
package pl.wenusix.familiada.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.server.ResponseStatusException;
import pl.wenusix.familiada.domain.*;
import pl.wenusix.familiada.repository.QuestionRepository;
import pl.wenusix.familiada.repository.RankRepository;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
@Service
public class GameService {
private final List<Game> games = new ArrayList<>();
private final QuestionRepository questionRepository;
private final RankRepository rankRepository;
@Autowired
public GameService(QuestionRepository questionRepository, RankRepository rankRepository) {
this.questionRepository = questionRepository;
this.rankRepository = rankRepository;
}
public String generateNewGame(String login) {
Game game= new Game(login, questionRepository);
games.add(game);
return game.getId();
}
@Scheduled(fixedRate = 60_000)
public void autoRemove() {
LocalDateTime now = LocalDateTime.now();
List<Game> actual = this.games.stream().filter(v -> now.plusHours(2).isAfter(v.getRecentlyActivity())).collect(Collectors.toList());
this.games.clear();
this.games.addAll(actual);
}
public GameSnapshot getGameDetails(String gameId){
return games.stream()
.filter(v -> v.getId().equals(gameId))
.map(Game::getSnapshot)
.findAny()
.orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND));
}
public Attempt tryGuess(String gameId, String enteredWord){
Game game = games.stream()
.filter(v -> v.getId().equals(gameId)).
findAny().orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND));
Attempt attempt = game.getActualQuestion().tryGuess(enteredWord);
if(attempt.getResult() != Result.FAILURE) {
game.addPoints(attempt.getAnswer().getPoints());
}
if(attempt.getResult() == Result.WIN){
if(game.getLevel() >= 7) {
Rank rank = rankRepository.save(new Rank(game));
attempt.finish(rank);
this.games.remove(game);
return attempt;
}
game.levelUp();
}
return attempt;
}
public GameSnapshot hintLetter(String gameId, int answerNumber){
Long rankId = null;
Game game = games.stream()
.filter(v -> v.getId().equals(gameId)).
findAny().orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND));
int num = 1;
for(Answer answer : game.getActualQuestion().getAnswersToGuess()){
if(num == answerNumber){
if(answer.isGuessed()) throw new ResponseStatusException(HttpStatus.BAD_REQUEST);
answer.hintLetter();
if(answer.isGuessed()) game.addPoints(answer.getPoints());
if(game.getActualQuestion().getAnswersToGuess().stream().allMatch(Answer::isGuessed)){
if(game.getLevel() >= 7) {
Rank rank = rankRepository.save(new Rank(game));
rankId = rank.getId();
this.games.remove(game);
break;
}
game.levelUp();
}
break;
}
num++;
}
GameSnapshot snapshot = game.getSnapshot();
snapshot.setRankId(rankId);
return snapshot;
}
}
|
package org.quarkchain.web3j.sample;
import java.math.BigInteger;
import java.util.Optional;
import org.quarkchain.web3j.crypto.ECKeyPair;
import org.quarkchain.web3j.crypto.Hash;
import org.quarkchain.web3j.protocol.Web3j;
import org.quarkchain.web3j.protocol.core.response.GetTransactionReceipt;
import org.quarkchain.web3j.utils.Numeric;
public class TransactionHelper {
private static final int SLEEP_DURATION = 10000;
private static final int ATTEMPTS = 20;
private Web3j web3j;
public TransactionHelper(Web3j web3j) {
super();
this.web3j = web3j;
}
public GetTransactionReceipt.TransactionReceipt waitForTransactionReceipt(String transactionHash) throws Exception {
Optional<GetTransactionReceipt.TransactionReceipt> transactionReceiptOptional = getTransactionReceipt(
transactionHash, SLEEP_DURATION, ATTEMPTS);
if (!transactionReceiptOptional.isPresent()) {
throw new Exception("Transaction reciept not generated after " + ATTEMPTS + " attempts");
}
return transactionReceiptOptional.get();
}
private Optional<GetTransactionReceipt.TransactionReceipt> getTransactionReceipt(String transactionHash,
int sleepDuration, int attempts) throws Exception {
Optional<GetTransactionReceipt.TransactionReceipt> receiptOptional = sendTransactionReceiptRequest(
transactionHash);
for (int i = 0; i < attempts; i++) {
if (!receiptOptional.isPresent() || receiptOptional.get().getTimestamp().equals("0x0")) {
Thread.sleep(sleepDuration);
receiptOptional = sendTransactionReceiptRequest(transactionHash);
} else {
break;
}
}
return receiptOptional;
}
private Optional<GetTransactionReceipt.TransactionReceipt> sendTransactionReceiptRequest(String transactionHash)
throws Exception {
GetTransactionReceipt transactionReceipt = web3j.getTransactionReceipt(transactionHash).sendAsync().get();
return transactionReceipt.getTransactionReceipt();
}
public static void getPubKey(String privKey) {
BigInteger privateKeyBI = Numeric.toBigInt(privKey);
ECKeyPair kp = ECKeyPair.create(privateKeyBI);
BigInteger pkBI = kp.getPublicKey();
System.out.println("pubkey=" + Numeric.toHexStringWithPrefix(pkBI));
}
public static String buildMethodId(String methodSignature) {
byte[] input = methodSignature.getBytes();
byte[] hash = Hash.sha3(input);
return Numeric.toHexString(hash).substring(0, 10);
}
public static String encodeEvent(String methodSignature) {
byte[] input = methodSignature.getBytes();
byte[] hash = Hash.sha3(input);
return Numeric.toHexString(hash);
}
}
|
package com.rx.mvvm.viewmodel;
import android.app.Application;
import android.util.Log;
import com.rx.mvvm.repository.IUserRepository;
import com.rx.mvvm.repository.RepositoryFactory;
import com.rx.mvvm.repository.entity.User;
import com.rx.rxmvvmlib.viewmodel.base.RxBaseViewModel;
import androidx.annotation.NonNull;
/**
* Created by wuwei
* 2021/5/19
* 佛祖保佑 永无BUG
*/
public class MainViewModel extends RxBaseViewModel {
private final IUserRepository userRepository;
public MainViewModel(@NonNull Application application) {
super(application);
userRepository = RepositoryFactory.getUserRepository();
}
@Override
public void onCreate() {
super.onCreate();
/* userRepository.login().subscribe(new TObserver<BaseEntity>() {
@Override
public void onRequestStart() {
}
@Override
public void onRequestEnd() {
}
@Override
public void onSuccees(BaseEntity baseEntity) {
}
@Override
public void onFailure(String code, String message) {
}
});*/
userRepository.saveUserCache(123, "哈哈哈哈哈哈");
Log.i("TAG", "saveUserCsasache-111: " + userRepository.getUid());
Log.i("TAG", "saveUserCsasache-222: " + userRepository.getToken());
Log.i("TAG", "saveUserCsasache-333---------------------------: " );
userRepository.saveUser(new User((long) 1,"aaa","张三",20));
Log.i("TAG", "saveUserCsasache-444: " + userRepository.getUser(1).toString());
}
}
|
package at.ebinterface.validation.validator;
import at.ebinterface.validation.parser.EbiVersion;
import at.ebinterface.validation.rtr.generated.VerifyDocumentResponse;
import at.ebinterface.validation.validator.jaxb.Result;
/**
* DTO for the XML Schema validation result
*
* @author pl
*/
public final class ValidationResult {
private String schemaValidationErrorMessage;
private EbiVersion determinedEbInterfaceVersion;
/**
* Schematronvalidation result
*/
private Result result;
/**
* Holds a potential signature validation exception, which is returned by the validation service
* *
*/
private String signatureValidationExceptionMessage;
/**
* Certificate specific results
*/
private VerifyDocumentResponse verifyDocumentResponse;
public ValidationResult (){}
public String getSchemaValidationErrorMessage() {
return schemaValidationErrorMessage;
}
public void setSchemaValidationErrorMessage(final String schemaValidationErrorMessage) {
this.schemaValidationErrorMessage = schemaValidationErrorMessage;
}
public EbiVersion getDeterminedEbInterfaceVersion() {
return determinedEbInterfaceVersion;
}
public void setDeterminedEbInterfaceVersion(
final EbiVersion determinedEbInterfaceVersion) {
this.determinedEbInterfaceVersion = determinedEbInterfaceVersion;
}
public Result getSchematronResult() {
return result;
}
public void setSchematronResult(final Result result) {
this.result = result;
}
public VerifyDocumentResponse getVerifyDocumentResponse() {
return verifyDocumentResponse;
}
public void setVerifyDocumentResponse(final VerifyDocumentResponse verifyDocumentResponse) {
this.verifyDocumentResponse = verifyDocumentResponse;
}
public String getSignatureValidationExceptionMessage() {
return signatureValidationExceptionMessage;
}
public void setSignatureValidationExceptionMessage(final String signatureValidationExceptionMessage) {
this.signatureValidationExceptionMessage = signatureValidationExceptionMessage;
}
}
|
package com.mineskies.bungeecord.event;
import com.mineskies.bungeecord.Constants;
import com.mineskies.bungeecord.MSBungee;
import com.mineskies.bungeecord.util.MessageUtil;
import net.md_5.bungee.api.Favicon;
import net.md_5.bungee.api.ServerPing;
import net.md_5.bungee.api.chat.TextComponent;
import net.md_5.bungee.api.event.ProxyPingEvent;
import net.md_5.bungee.api.plugin.Listener;
import net.md_5.bungee.event.EventHandler;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
public class PingListener implements Listener {
private static BufferedImage favicon = null;
@EventHandler
public void onProxyPing(ProxyPingEvent event) {
if (favicon == null) {
favicon = this.getFavicon();
}
ServerPing serverPing = event.getResponse();
String message = MessageUtil.getCenteredMessage(Constants.MOTD_TOP_LINE, MessageUtil.CENTER_PX_BUNGEE)
+ "\n" + MessageUtil.getCenteredMessage(Constants.MOTD_BOTTOM_LINE, MessageUtil.CENTER_PX_BUNGEE);
serverPing.setDescriptionComponent(new TextComponent(message));
serverPing.setFavicon(Favicon.create(favicon));
event.setResponse(serverPing);
}
private BufferedImage getFavicon(){
BufferedImage img = null;
try {
img = ImageIO.read(new File(MSBungee.getInstance().getDataFolder(), "favicon.png"));
} catch(IOException e){
e.printStackTrace();
}
return img;
}
}
|
import java.util.Scanner;
public class Question4 {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
System.out.println("enetr number of elements ");
int n=sc.nextInt();
int ar[]=new int[n];
for(int i=0;i<ar.length;i++)
{
ar[i]=sc.nextInt();
}
int sum=0;
int avg=0;
for(int i=0;i<ar.length;i++)
{
sum=sum+ar[i];
avg=avg+sum/ar.length;
}
System.out.println("the avg of array elements is:");
System.out.println(avg);
// TODO Auto-generated method stub
}
}
|
package com.learning.usercenter.service;
import com.learning.usercenter.entity.po.RoleResource;
import java.util.List;
import java.util.Set;
/**
* @author Zzz
* @date 2021年8月11日10:14:54
*/
public interface IRoleResourceService {
/**
* 批量给角色添加资源
*
* @param roleId 角色id
* @param resourceIds 资源id列表
* @return 是否操作成功
*/
boolean saveBatch(Long roleId, Set<Long> resourceIds);
/**
* 删除角色拥有的资源
*
* @param roleId 角色id
* @return 是否操作成功
*/
boolean removeByRoleId(Long roleId);
/**
* 查询角色拥有资源id
*
* @param roleId 角色id
* @return 角色拥有的资源id集合
*/
Set<Long> queryByRoleId(Long roleId);
/**
* 根据角色id列表查询资源关系
*
* @param roleIds 角色id集合
* @return 角色资源关系集合
*/
List<RoleResource> queryByRoleIds(Set<Long> roleIds);
}
|
/**
*
*/
package work.waynelee.captcha;
import java.util.Objects;
import org.springframework.web.bind.ServletRequestUtils;
import org.springframework.web.context.request.ServletWebRequest;
import com.wf.captcha.Captcha;
import com.wf.captcha.GifCaptcha;
import com.wf.captcha.SpecCaptcha;
import work.waynelee.captcha.properties.CaptchaProperties;
import work.waynelee.captcha.properties.CaptchaType;
/**
*
* @author 李文庆
* 2019年5月20日 下午3:11:56
*/
public class CaptchaGenerateFactory {
public static Captcha getCaptcha(CaptchaProperties properties,ServletWebRequest request){
boolean isGif = ServletRequestUtils.getBooleanParameter(request.getRequest(),"gif",false);
Integer width = ServletRequestUtils.getIntParameter(request.getRequest(), "width",properties.getWidth());
Integer height = ServletRequestUtils.getIntParameter(request.getRequest(), "height",properties.getHeight());
Integer length = ServletRequestUtils.getIntParameter(request.getRequest(), "length",properties.getLength());
if (isGif) {
return new GifCaptcha(width,height,length);
}else{
if (Objects.equals(properties.getCaptchaType(), CaptchaType.PNG)) {
return new SpecCaptcha(width,height,length);
}
if (Objects.equals(properties.getCaptchaType(),CaptchaType.GIF)) {
return new GifCaptcha(width,height,length);
}
}
return null;
}
}
|
package com.one.sugarcane.sellerinfo.service;
import java.util.List;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.one.sugarcane.sellerinfo.dao.SellerInfoDaoImpl;
import com.one.sugarcane.entity.Course;
import com.one.sugarcane.entity.PublicCourseType;
import com.one.sugarcane.entity.SellerCourseType;
import com.one.sugarcane.entity.SellerInfo;
import com.one.sugarcane.entity.SellerLogin;
@Service
@Transactional(readOnly=false)
public class SellerInfoServiceImpl {
@Resource
private SellerInfoDaoImpl sellerInfoDaoImpl;
/**
* 培训机构注册
* @author 张梦洲,狗晟儿,傻崔
* @date 2018/4/30
*/
public void saveSellerInfo(SellerInfo sellerInfo) {
sellerInfoDaoImpl.saveSellerInfo(sellerInfo);
}
public SellerInfo getpass(String name, String email) {
return sellerInfoDaoImpl.fineByName(name,email);
}
public void updateSellerInfo(SellerInfo sellerinfo) {
sellerInfoDaoImpl.updateSellerInfo(sellerinfo);
}
public void resetPassword(String email, String randomPasswordString) {
SellerInfo s = new SellerInfo();
s = sellerInfoDaoImpl.findByEmail(email);
SellerLogin sl = s.getSellerLogin();
sl.setPassword(randomPasswordString);
sellerInfoDaoImpl.updateSellerInfo(s);
}
/**
* temp 获取所有培训机构
* @author 王孜润
* @date 2018/5/21
*/
public List<SellerInfo> showOrg() {
return this.sellerInfoDaoImpl.getOrg();
}
/**
* 首页获取所有培训机构
* @author 王孜润
* @date 2018/6/11
*/
public List<SellerInfo> findOrg() {
return this.sellerInfoDaoImpl.selectOrg();
}
/**
* 通过id查找seller
* @name 王孜润
*/
public SellerInfo selectById(int id) {
return sellerInfoDaoImpl.findById(id);
}
public List<SellerCourseType> findSellerById(int id) {
return sellerInfoDaoImpl.selectSellerCourseTypeById(id);
}
/**
* 通过SellerId查找course
* @name 王孜润
*/
public List<Course> findBySellerId(int sellerId1,int page){
List<Course> list = sellerInfoDaoImpl.findBySellerId(sellerId1,page);
return list;
}
/**
* 查询所有课程publicCourseType
* @author 王孜润
* @date 2018/5/22
* **/
public List<PublicCourseType> findTypeAll(){
List<PublicCourseType> list = sellerInfoDaoImpl.selectAll();
return list;
}
/**
* 删除
* @author 王孜润
* @date 2018/5/22
* **/
public boolean deleteCourseType(int id) {
return sellerInfoDaoImpl.delete(id);
}
/**
* 得到页码数
* @return
*/
public int getPageCount(int sellerId) {
if((this.sellerInfoDaoImpl.findRowsCountBySellerID(sellerId))%4==0) {
return (int)(this.sellerInfoDaoImpl.findRowsCountBySellerID(sellerId)/4);
}else {
return (int)(this.sellerInfoDaoImpl.findRowsCountBySellerID(sellerId)/4+1);
}
// return (int) Math.ceil((this.sellerInfoDaoImpl.findCount(sellerId)/6));
}
/**
* 培训机构详情分类列表查询
* @author 王孜润
* @date 2018/5/30
* @param model
* @return
*/
public List<Course> listByType(int sellerCourseTypeID,int page){
return sellerInfoDaoImpl.selectType(sellerCourseTypeID,page);
}
/**
* 课程分类
* @author 王孜润
* @date 2018/5/31
*/
public List<Course> findTypeId(int sellerCourseTypeID,int sellerId){
return sellerInfoDaoImpl.findTypeId(sellerCourseTypeID,sellerId);
}
/**
* 分类查询页码数
*/
public int getTypeCoursePageCount(int sellerCourseTypeID) {
return (int) Math.ceil((this.sellerInfoDaoImpl.findTypeCourseCount(sellerCourseTypeID))/3);
}
}
|
package com.facebook.react.animated;
import com.facebook.react.bridge.JavaOnlyMap;
import com.facebook.react.bridge.ReadableMap;
class TrackingAnimatedNode extends AnimatedNode {
private final JavaOnlyMap mAnimationConfig;
private final int mAnimationId;
private final NativeAnimatedNodesManager mNativeAnimatedNodesManager;
private final int mToValueNode;
private final int mValueNode;
TrackingAnimatedNode(ReadableMap paramReadableMap, NativeAnimatedNodesManager paramNativeAnimatedNodesManager) {
this.mNativeAnimatedNodesManager = paramNativeAnimatedNodesManager;
this.mAnimationId = paramReadableMap.getInt("animationId");
this.mToValueNode = paramReadableMap.getInt("toValue");
this.mValueNode = paramReadableMap.getInt("value");
this.mAnimationConfig = JavaOnlyMap.deepClone(paramReadableMap.getMap("animationConfig"));
}
public void update() {
AnimatedNode animatedNode = this.mNativeAnimatedNodesManager.getNodeById(this.mToValueNode);
this.mAnimationConfig.putDouble("toValue", ((ValueAnimatedNode)animatedNode).getValue());
this.mNativeAnimatedNodesManager.startAnimatingNode(this.mAnimationId, this.mValueNode, (ReadableMap)this.mAnimationConfig, null);
}
}
/* Location: C:\Users\august\Desktop\tik\df_rn_kit\classes.jar.jar!\com\facebook\react\animated\TrackingAnimatedNode.class
* Java compiler version: 6 (50.0)
* JD-Core Version: 1.1.3
*/ |
package com.tencent.matrix.trace.d;
import android.app.Activity;
import android.os.Process;
import android.support.v4.app.Fragment;
import com.tencent.matrix.c.c;
import com.tencent.matrix.trace.b.b;
import org.json.JSONObject;
public abstract class a extends c implements b, com.tencent.matrix.trace.core.a.a {
final com.tencent.matrix.trace.a btG;
String btH;
boolean isBackground;
protected abstract String getTag();
a(com.tencent.matrix.trace.a aVar) {
super(aVar);
this.btG = aVar;
}
public void onChange(Activity activity, Fragment fragment) {
String str;
if (activity == null) {
str = "null";
} else {
str = activity.getClass().getName() + (fragment == null ? "" : "&" + fragment.getClass().getName());
}
this.btH = str;
}
public void onFront(Activity activity) {
this.isBackground = false;
}
public void onBackground(Activity activity) {
this.isBackground = true;
}
public void onActivityCreated(Activity activity) {
}
public void onActivityPause(Activity activity) {
}
public void onActivityStarted(Activity activity) {
}
public void onCreate() {
com.tencent.matrix.d.b.i("Matrix.BaseTracer", "[onCreate] name:%s process:%s", getClass().getSimpleName(), Integer.valueOf(Process.myPid()));
com.tencent.matrix.trace.core.a.tE().a((com.tencent.matrix.trace.core.a.a) this);
com.tencent.matrix.trace.core.b tF = com.tencent.matrix.trace.core.b.tF();
if (tF.bty != null && !tF.bty.contains(this)) {
tF.bty.add(this);
}
}
public void onDestroy() {
com.tencent.matrix.d.b.i("Matrix.BaseTracer", "[onDestroy] name:%s process:%s", getClass().getSimpleName(), Integer.valueOf(Process.myPid()));
com.tencent.matrix.trace.core.a.tE().b((com.tencent.matrix.trace.core.a.a) this);
com.tencent.matrix.trace.core.b tF = com.tencent.matrix.trace.core.b.tF();
if (tF.bty != null) {
tF.bty.remove(this);
}
}
protected final void b(JSONObject jSONObject) {
com.tencent.matrix.c.b bVar = new com.tencent.matrix.c.b();
bVar.tag = getTag();
bVar.brm = jSONObject;
this.btG.a(bVar);
}
}
|
package com.innoviti.cibil.segment;
import com.innoviti.cibil.constant.SegmentType;
import com.innoviti.cibil.util.CibilUtil;
/**
* Account number segment also know as PI. It is a Required segment if the
* Enquiry Purpose (Positions 94-95 of the TUEF Enquiry Header Segment) is
* “Locate Plus”, “Account Review” or “Retro Enquiry,” for all other enquiries
* it is a When Available segment. It occurs no more than 4 times per Enquiry
* Record (I01 to I04).
*
* @author tariq.anwar
*
*/
public class AccountNumberSegment{
//3 bytes - required
private String segmentTag;
//10 bytes- required
private String accountNumber;
private int size = 36;
public AccountNumberSegment(String segmentTag, String accountNumber){
this.segmentTag = segmentTag;
this.accountNumber = accountNumber;
}
public String getSegmentTag() {
return segmentTag;
}
public void setSegmentTag(String segmentTag) {
this.segmentTag = segmentTag;
}
public String getAccountNumber() {
return accountNumber;
}
public void setAccountNumber(String accountNumber) {
this.accountNumber = accountNumber;
}
public int getSize() {
return size;
}
public byte [] toByteArray(){
byte [] totalBytes = null;
byte [] headerBytes = null;
byte [] segementBytes = getSegmentTag().getBytes();
//2 bytes for field tag, two bytes length, values bytes
headerBytes = CibilUtil.addByteArray(SegmentType.ACCOUNT_NUMBER_SEGMENT.getValue().getBytes(), CibilUtil.createHeaderLength(segementBytes.length));
segementBytes = CibilUtil.addByteArray(headerBytes, segementBytes);
byte [] accountNoBytes = accountNumber.getBytes();
headerBytes = CibilUtil.addByteArray("01".getBytes(), CibilUtil.createHeaderLength(accountNoBytes.length));
accountNoBytes = CibilUtil.addByteArray(headerBytes, accountNoBytes);
totalBytes = CibilUtil.addByteArray(segementBytes, accountNoBytes);
return totalBytes;
}
}
|
package kr.or.kosta.ams.entity;
import java.util.Formatter;
import kr.or.kosta.ams.entity.Account;
/**
* 여러개의 계좌 관리를 위한 클래스
* @author 이대용
*
*/
public class AccountManager {
private Account[] accounts;
private int count;
private int index;
public AccountManager() {
this(100);
}
public AccountManager(int size) {
accounts = new Account[size];
}
// Setter/Getter Method
public Account[] getAccounts() {
return accounts;
}
public void setAccounts(Account[] accounts) {
this.accounts = accounts;
}
public int getCount() {
return count;
}
public void setCount(int count) {
this.count = count;
}
/**
* 신규계좌 개설
* @param accountNum 계좌번호
* @param accountOwner 예금주
* @param passwd 비밀번호
* @param restMoney 잔액
*/
public void open(String accountNum, String accountOwner, int passwd, long restMoney) {
Account account = new Account(accountNum, accountOwner, passwd, restMoney);
open(account);
}
public void open(Account account) {
accounts[count] = account;
count++;
}
/**
* 전체계좌 출력
*/
public void printAll() {
Formatter formatter = new Formatter();
formatter.format("%1$13s", "계좌번호");
System.out.println("===============================================================");
System.out.println(String.format("%1$9s", "계좌번호")+ String.format("%1$17s", "예금주") + String.format("%1$13s", "비밀번호")
+ String.format("%1$13s", "현재잔액") + String.format("%1$13s", "대출금액"));
System.out.println("===============================================================");
for (int i = 0; i < count; i++) {
accounts[i].print();
}
}
/**
* @param obj 출력하고자 하는 객체 (배열 혹은 단일객체)
*/
public void print(Object obj) {
if (obj == null)
{
System.out.println("조회된 계좌가 존재하지 않습니다.");
} else {
System.out.println("조회된 계좌 정보는 아래와 같습니다.");
System.out.println("계좌번호\t예금주\t비밀번호\t현재잔액");
System.out.println("=====================================");
if (obj instanceof Account[]) {
Account[] acc = (Account[])obj;
for (int i = 0; i < acc.length; i++) {
if (acc[i] == null) {
break;
}
acc[i].print();
}
}
if (obj instanceof Account) {
Account acc = (Account) obj;
acc.print();
}
}
}
/**
* @param accountNum 조회하고자 하는 계좌번호
* @return 조회된 계좌정보
*/
public Account get(String accountNum) {
for (int i = 0; i < count; i++) {
if (accounts[i].getAccountNum().equals(accountNum)) {
return accounts[i];
}
}
return null;
}
/**
* @param accountOwner 검색하고자 하는 예금주명
* @return 검색된 계좌들
*/
public Account[] search(String accountOwner) {
// count를 2씩 나누면서 null이 아닌 값을 찾아 실제 몇개의 계좌가 있는지 조회한다.
// count / 2 의 값이 null이면 해당 값의 왼쪽으로 다시 2로 나누고, null아니면 해당 값의 우측으로 2를 나눈다.
int start = 0;
int end = accounts.length;
int mid = (end - start) / 2;
int index = countArrayCount(start,end,mid);
if (index == 0) {
return null;
}
Account[] rtAccounts = new Account[index];
int cnt = 0;
for (int i = 0; i < count; i++) {
if (accounts[i].getAccountOwner().equals(accountOwner)) {
rtAccounts[cnt] = accounts[i];
cnt++;
}
}
return rtAccounts;
}
/**
* 배열의 빈 공간을 제외한 실제 값 갯수 찾기
* @param start
* @param end
* @param mid
* @return
*/
private int countArrayCount(int start, int end, int mid) {
int s=0;
int e=0;
int m=0;
if (start != end && mid != 1) {
if (accounts[mid] == null) {
s = start;
e = mid-1;
m = (e-s)/2;
} else {
s = mid+1;
e = end;
m = (e-s)/2;
}
countArrayCount(s, e, m);
} else {
index = mid;
}
return index;
}
/**
* @param accountNum 삭제하고자 하는 계좌번호
* @return 삭제여부
*/
public boolean remove(String accountNum) {
for (int i = 0; i < count; i++) {
if (accounts[i].getAccountNum().equals(accountNum)) {
// 배열 크기 하나 줄이면서 이동
accounts[i] = null;
if (i != count-1) {
for (int j=i; j < count; j++) {
accounts[j] = accounts[j+1];
if (j == count-1) {
break;
}
}
}
count = count-1;
return true;
}
}
return false;
}
}
|
package org.gtiles.components.gtcms.service;
import java.util.List;
import com.goldgov.dygl.module.partymember.exception.NoAuthorizedFieldException;
import org.gtiles.components.gtcms.domain.GtcmsBlobGroup;
import org.gtiles.components.gtcms.service.GtcmsBlobGroupQuery;
/**
*
* Title: IGtcmsBlobGroupService<br>
* Description: <br>
* Copyright @ 2011~2016 Goldgov .All rights reserved.<br>
*
* @author GuoXP
* @createDate 2016年6月23日
* @version $Revision: $
*/
public interface IGtcmsBlobGroupService {
public void addInfo(GtcmsBlobGroup gtcmsblobgroup) throws NoAuthorizedFieldException;
public void updateInfo(GtcmsBlobGroup gtcmsblobgroup) throws NoAuthorizedFieldException;
public void deleteInfo(String[] entityIDs) throws NoAuthorizedFieldException;
public GtcmsBlobGroup findInfoById(String entityID)throws NoAuthorizedFieldException;
public List<GtcmsBlobGroup> findInfoList(GtcmsBlobGroupQuery query)
throws NoAuthorizedFieldException;
}
|
package tk.ludva.restfulchecker;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/**
* Class responsible for creating full URLs from base URLs + paths.
* @author Lu2
*
*/
public class UrlWorker
{
/**
* Creates full URL from base URL + path.
* @param currentUrlString base URL as String.
* @param link path as String.
* @return Full URL as String.
* @throws MalformedURLException if base URL is not valid URL.
*/
public static String constructUrl(String currentUrlString, String link) throws MalformedURLException
{
URL currentUrl = new URL(currentUrlString);
return constructUrl(currentUrl, link);
}
/**
* Creates full URL from base URL + path.
* @param currentUrl base URL as URL
* @param link path as String.
* @return Full URL as String.
*/
public static String constructUrl(URL currentUrl, String link)
{
link = chop(link);
if (link.startsWith("http"))
{
return link;
}
else if (link.startsWith("/"))
{
if (currentUrl.getHost().endsWith("/"))
{
link = link.substring(1);
}
return (currentUrl.getProtocol() + "://" + currentUrl.getHost() + link);
}
else if (link.startsWith("./"))
{
link = link.substring(2);
}
String buildedUrl = currentUrl.getProtocol() + "://" + currentUrl.getHost() + currentUrl.getPath();
// buildedUrl = buildedUrl.substring(0, buildedUrl.lastIndexOf('/') + 1);
if (buildedUrl.endsWith("/"))
{
}
else
{
buildedUrl = buildedUrl + "/";
}
buildedUrl = buildedUrl + link;
return buildedUrl;
}
/**
* Creates list of full URLs from base URL + list of paths.
* @param currentUrlString base URL as String.
* @param odkazy List of paths in String.
* @return List of full URLs.
*/
public static List<String> getUrls(String currentUrlString, List<String> odkazy)
{
URL currentUrl;
List<String> urls = new ArrayList<String>();
try
{
currentUrl = new URL(currentUrlString);
}
catch (MalformedURLException e)
{
e.printStackTrace();
return urls;
}
for (String link : odkazy)
{
urls.add(constructUrl(currentUrl, link));
}
return urls;
}
/**
* Cut starting and trailing \ (if any) from link.
* @param link in String.
* @return chopped link in String.
*/
private static String chop(String link)
{
if (link.startsWith("\"") && link.endsWith("\""))
{
return link.substring(1, link.length() - 1);
}
return link;
}
}
|
package gov.nasa.nasapicturesofgivendays.services;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.util.Optional;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;
import gov.nasa.nasapicturesofgivendays.configurations.AppConfiguration;
@RunWith(MockitoJUnitRunner.class)
public class PictureServiceImplTest {
@Mock
private RestTemplate restTemplate;
@Mock
private AppConfiguration appConfig;
@Mock
private ResponseEntity<Object> reponseEntity;
PictureService pictureService;
@Before
public void setUp() {
pictureService = new PictureServiceImpl(appConfig, restTemplate);
when(appConfig.getServerUrl()).thenReturn("testUrl");
when(reponseEntity.getBody()).thenReturn(null);
}
@Test
public void whenGetPictureThenRestTemplateWasCompletedSuccessfully() {
when(restTemplate.getForEntity(anyString(), any())).thenReturn(reponseEntity);
pictureService.getPicture(Optional.of(true), Optional.of("2020-2-6"));
// then
verify(appConfig, times(1)).getServerUrl();
verify(restTemplate, times(1)).getForEntity(anyString(), any());
verify(reponseEntity, times(1)).getBody();
}
@Test(expected = NullPointerException.class)
public void whenGetPictureAndRestTemplateThrowException() {
// when
when(restTemplate.getForEntity(anyString(), any())).thenThrow(NullPointerException.class);
pictureService.getPicture(Optional.of(false), Optional.of("2020-2-6"));
}
}
|
package com.kh.runLearn.mypage.controller;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
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 org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.bind.support.SessionStatus;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import com.kh.runLearn.board.model.service.BoardService;
import com.kh.runLearn.board.model.vo.Board;
import com.kh.runLearn.common.Exception;
import com.kh.runLearn.common.PageInfo;
import com.kh.runLearn.common.Pagination;
import com.kh.runLearn.member.model.vo.Member;
import com.kh.runLearn.member.model.vo.Member_Image;
import com.kh.runLearn.mypage.model.service.MypageService;
import com.kh.runLearn.product.model.vo.Product_Option;
@SessionAttributes("loginUser")
@Controller
public class MypageController {
@Autowired
private MypageService myService;
@Autowired
private BoardService bService;
@Autowired
private BCryptPasswordEncoder bcryptPasswordEncoder;
@RequestMapping(value = "memberUpdate.do") // id하고 name값은 변경 불가하니 첨부터 값불러오게끔
public ModelAndView mUpdateView(ModelAndView mv, HttpSession session) {
Member loginUser = (Member) session.getAttribute("loginUser");
String userId = loginUser.getM_id();
Member_Image profile = myService.selectProfile(userId);
mv.addObject("profile", profile);
mv.setViewName("mypage/memberUpdate");
return mv;
// return "mypage/memberUpdate";
}
@RequestMapping(value = "mUpdate.do", method = RequestMethod.POST)
public String updateMember(@ModelAttribute Member m, @ModelAttribute Member_Image mi,
@RequestParam(value = "uploadFile", required = false) MultipartFile uploadFile, HttpSession session,
HttpServletRequest request, Model model) {
Member loginUser = (Member) session.getAttribute("loginUser");
String userId = loginUser.getM_id();
Member_Image profile = myService.selectProfile(userId);
if (m.getM_pw().equals("")) {
m.setM_pw(loginUser.getM_pw());
} else {
String encpwd = bcryptPasswordEncoder.encode(m.getM_pw());
m.setM_pw(encpwd);
}
int result = myService.updateMember(m);
if (uploadFile != null && !uploadFile.isEmpty()) {
String renameFileName = saveFile(uploadFile, request);
if (renameFileName != null) {
mi.setM_origin_name(uploadFile.getOriginalFilename());
mi.setM_changed_name(renameFileName);
}
myService.updateMember_Image(mi);
}
if (result > 0) {
loginUser.setM_pw(m.getM_pw());
loginUser.setM_email(m.getM_email());
loginUser.setM_phone(m.getM_phone());
loginUser.setPostnum(m.getPostnum());
loginUser.setG_address(m.getG_address());
loginUser.setR_address(m.getR_address());
loginUser.setD_address(m.getD_address());
session.setAttribute("loginUser", loginUser);
}
model.addAttribute("profile", profile);
model.addAttribute("cate", "수강목록");
return "redirect:mypage.do?";
}
public String saveFile(MultipartFile file, HttpServletRequest request) { // 이미지 파일 저장
String root = request.getSession().getServletContext().getRealPath("resources");
String savePath = root + "\\images\\member";
File folder = new File(savePath);
if (!folder.exists()) {
folder.mkdirs();
}
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
String originalFileName = file.getOriginalFilename();
String renameFileName = sdf.format(new java.sql.Date(System.currentTimeMillis())) + "."
+ originalFileName.substring(originalFileName.lastIndexOf(".") + 1);
String renamePath = folder + "\\" + renameFileName;
try {
file.transferTo(new File(renamePath));
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return renameFileName;
}
@RequestMapping("mypage.do")
public ModelAndView myPage(@RequestParam(value = "page", required = false) Integer page, HttpSession session,
ModelAndView mv, @RequestParam("cate") String cate) {
Member loginUser = (Member) session.getAttribute("loginUser");
String userId = loginUser.getM_id();
int currentPage = 1;
int boardLimit = 5;
int lCount = myService.selectLectureCount(userId);
int nPayLcount = myService.selectNopayLectureCount(userId);
int nPayPcount = myService.selectPlistCount(userId);
int count = 1;
Member_Image profile = myService.selectProfile(userId);
if (page != null) {
currentPage = page;
}
// 튜터신청여부
Board tutorYN = bService.selectBoardTutor(userId);
if (cate.equals("수강목록")) {
int listCount = myService.selectLectureCount(userId); // 수강목록 수
PageInfo pi = Pagination.getPageInfo(currentPage, listCount, boardLimit);
ArrayList<Map<String, String>> lList = myService.selectLectureView(userId, pi); // 수강목록
mv.addObject("lList", lList);
mv.addObject("listCount", listCount);
mv.addObject("pi", pi);
mv.addObject("tutorYN", tutorYN);
mv.addObject("count", count);
}
if (cate.equals("강의찜목록")) {
int listCount = myService.selectNopayLectureCount(userId);
PageInfo pi = Pagination.getPageInfo(currentPage, listCount, boardLimit);
ArrayList<Map<String, Object>> noPaylList = myService.selectNoPayLectureView(userId, pi); // 강의 찜목록
for (int i = 0; i < noPaylList.size(); i++) {
int system = Integer.parseInt(String.valueOf(noPaylList.get(i).get("L_SYSTEM")));
if (system == 0) {
noPaylList.get(i).put("L_SYSTEM", "영상");
} else if (system == 1) {
noPaylList.get(i).put("L_SYSTEM", "현장");
}
}
mv.addObject("noPaylList", noPaylList);
mv.addObject("listCount", listCount);
mv.addObject("pi", pi);
}
if (cate.equals("상품찜목록") || cate.equals("productCate")) {
int listCount = myService.selectPlistCount(userId); // 상품 찜 목록수
PageInfo pi = Pagination.getPageInfo(currentPage, listCount, boardLimit);
ArrayList<Map<String, Object>> pList = myService.selectProductView(userId, pi); // 상품 찜목록
for (int i = 0; i < pList.size(); i++) {
String p_option = "";
p_option = pList.get(i).get("P_OPTION").toString();
if (!p_option.equals("")) {
ArrayList<Product_Option> po = myService.selectProductOption(p_option);
pList.get(i).put("po", po);
} else {
break;
}
}
mv.addObject("pList", pList);
mv.addObject("listCount", listCount);
mv.addObject("pi", pi);
}
if (cate.equals("결제상품") || cate.equals("productPay")) {
int listCount = myService.productPayCount(userId); // 결제상품수
PageInfo pi = Pagination.getPageInfo(currentPage, listCount, boardLimit);
ArrayList<Map<String, Object>> pList = myService.productPayList(userId, pi); // 상품 결제목록
for (int i = 0; i < pList.size(); i++) {
String p_option = "";
p_option = pList.get(i).get("P_OPTION").toString();
if (!p_option.equals("")) {
ArrayList<Product_Option> po = myService.selectProductOption(p_option);
pList.get(i).put("po", po);
} else {
break;
}
}
mv.addObject("productPay", "productPay");
mv.addObject("pList", pList);
mv.addObject("listCount", listCount);
mv.addObject("pi", pi);
}
if (cate.equals("튜터")) {
int listCount = myService.tuterLectureCount(userId);
PageInfo pi = Pagination.getPageInfo(currentPage, listCount, boardLimit);
ArrayList<Map<String, Object>> tLectureList = myService.selectTuterLecturePageView(userId, pi);
for (int i = 0; i < tLectureList.size(); i++) {
if (tLectureList.get(i).get("L_CONFIRM").equals("N")) {
tLectureList.get(i).put("L_CONFIRM", "미승낙");
} else {
tLectureList.get(i).put("L_CONFIRM", "승낙");
}
}
for (int i = 0; i < tLectureList.size(); i++) {
int system = Integer.parseInt(String.valueOf(tLectureList.get(i).get("L_SYSTEM")));
if (system == 0) {
tLectureList.get(i).put("L_SYSTEM", "영상");
} else if (system == 1) {
tLectureList.get(i).put("L_SYSTEM", "현장");
}
}
mv.addObject("pi", pi);
mv.addObject("tLectureList", tLectureList);
}
mv.addObject("profile", profile);
mv.addObject("lCount", lCount);
mv.addObject("nPayLcount", nPayLcount);
mv.addObject("nPayPcount", nPayPcount);
mv.addObject("cate", cate);
mv.addObject("tutorYN", tutorYN);
mv.setViewName("mypage/mypage");
return mv;
}
@RequestMapping("enterTutor.do") // 튜터 신청페이지로 이동
public String enterTutorForm() {
return "mypage/enterTutorForm";
}
@RequestMapping(value = "tutorInsert.do", method = RequestMethod.POST) // 튜터 신청
public ModelAndView tutorInsert(@ModelAttribute Board b, ModelAndView mv, HttpSession session) throws Exception {
Member loginUser = (Member) session.getAttribute("loginUser");
b.setM_id(loginUser.getM_id());
int result = myService.insertEnterTutor(b);
if (result > 0) {
mv.addObject("cate", "수강목록").setViewName("redirect:mypage.do");
} else {
throw new Exception("튜터 신청에 실패하였습니다.");
}
return mv;
}
@RequestMapping("cash.do")
public String cash() {
return "cash";
}
@RequestMapping("myEnterTutor.do")
public ModelAndView myEnterTutor(HttpSession session, ModelAndView mv) {
Member loginUser = (Member) session.getAttribute("loginUser");
Board b = bService.selectBoardTutor(loginUser.getM_id());
mv.addObject("b", b).setViewName("mypage/myEnterTutor");
return mv;
}
@RequestMapping("tutorUpdateView.do")
public ModelAndView tutorUpdateView(@RequestParam("b_num") int b_num, ModelAndView mv) {
Board b = bService.selectBoard(b_num);
mv.addObject("b", b).setViewName("mypage/enterTutorUpdate");
return mv;
}
@RequestMapping(value = "tutorUpdate.do", method = RequestMethod.POST)
public ModelAndView updateEnterTutor(@ModelAttribute Board b, ModelAndView mv) {
int result = bService.updateBoard(b);
if (result > 0) {
mv.addObject("cate", "수강목록").setViewName("redirect:mypage.do");
return mv;
} else {
throw new Exception("튜터신청 수정에 실패하였습니다.");
}
}
@RequestMapping("deleteEnterTutor.do")
public ModelAndView deleteEnterTutor(ModelAndView mv, @RequestParam("b_num") int b_num) throws Exception {
int result = bService.deleteBoard(b_num);
if (result > 0) {
mv.addObject("cate", "수강목록").setViewName("redirect:mypage.do");
} else {
throw new Exception("튜터신청 삭제에 실패하였습니다.");
}
return mv;
}
@RequestMapping("deleteMember.do")
public String deleteMember(SessionStatus status, HttpSession session) {
Member loginUser = (Member) session.getAttribute("loginUser");
String userId = loginUser.getM_id();
int deleteMember = myService.deleteMember(userId);
if(deleteMember > 0) {
status.setComplete();
return "redirect:home.do";
}else{
throw new Exception("삭제실패하였습니다.");
}
}
} |
package chatterby.messages;
import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
import java.sql.Date;
import chatterby.network.Payload;
import chatterby.network.UnrecognizedPayloadException;
/**
* A user message.
*
* @author scoleman
* @version 1.0.0
* @since 1.0.0
*/
public class Message implements Payload
{
/**
* The minimum length of a message payload.
*/
private static final int MIN_LENGTH = 4 + 8 + 4 + 4;
private final String username;
private final Date sendDate;
private final String tag;
private final String message;
/**
* Construct the message.
*
* @param username an arbitrary username
* @param message the message body
* @param sendDate the date at which the message was sent
* @param tag an arbitrary topic tag; may be null
*/
public Message(String username, Date sendDate, String tag, String message)
{
this.username = username.trim();
this.sendDate = sendDate;
this.tag = (tag == null) ? null : tag.trim();
this.message = message.trim();
}
/**
* Construct the message.
*
* @param username an arbitrary username
* @param message the message body
* @param tag an arbitrary topic tag; may be null
*/
public Message(String username, String tag, String message)
{
this.username = username.trim();
this.sendDate = new Date(System.currentTimeMillis());
this.tag = (tag == null) ? null : tag.trim();
this.message = message.trim();
}
public String getUsername()
{
return this.username;
}
public Date getSendDate()
{
return this.sendDate;
}
public String getTag()
{
return this.tag;
}
public String getMessage()
{
return this.message;
}
/**
* Parse a message into a byte payload.
*
* @return the payload
*/
public byte[] payload()
{
byte[] usernameBytes = null;
byte[] tagBytes = null;
byte[] messageBytes = null;
try
{
usernameBytes = this.username.getBytes("UTF8");
messageBytes = this.message.getBytes("UTF8");
if (this.tag == null)
tagBytes = new byte[0];
else
tagBytes = this.tag.getBytes("UTF8");
}
catch (UnsupportedEncodingException e)
{
/* If we can't encode to UTF-8, we're pretty well boned. */
}
byte[] payload = new byte[
4 + usernameBytes.length /* length + size of username */
+ 8 /* send date */
+ 4 + tagBytes.length /* length + size of tag */
+ 4 + messageBytes.length /* length + size of message */
];
ByteBuffer.wrap(payload)
.putInt(usernameBytes.length).put(usernameBytes)
.putLong(this.sendDate.getTime())
.putInt(tagBytes.length).put(tagBytes)
.putInt(messageBytes.length).put(messageBytes);
return payload;
}
/**
* Parse a byte payload into a message.
*
* @param payload the payload
* @return the message
* @throws UnrecognizedPayloadException
*/
public static Message parseMessage(byte[] payload) throws UnrecognizedPayloadException
{
if (payload.length < Message.MIN_LENGTH)
throw new UnrecognizedPayloadException("Payload identifies as a message, but is too short");
ByteBuffer buffer = ByteBuffer.wrap(payload);
byte[] usernameBytes = new byte[buffer.getInt()];
buffer.get(usernameBytes, 0, usernameBytes.length);
long sendTimestamp = buffer.getLong();
byte[] tagBytes = new byte[buffer.getInt()];
buffer.get(tagBytes, 0, tagBytes.length);
byte[] messageBytes = new byte[buffer.getInt()];
buffer.get(messageBytes, 0, messageBytes.length);
try
{
return new Message(new String(usernameBytes, "UTF8"),
new Date(sendTimestamp),
(tagBytes.length > 0) ? null : new String(tagBytes, "UTF8"),
new String(messageBytes, "UTF8"));
}
catch (UnsupportedEncodingException e)
{
throw new UnrecognizedPayloadException(e);
}
}
} |
package com.tefper.daas.parque.repository;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import com.tefper.daas.parque.entity.Component;
@Repository
public interface ComponentRepository extends JpaRepository<Component, String> {
public List<Component> findByMaincomponentkey(String mainComponentKey);
public List<Component> findByParentassignproductid(String íd);
}
|
/**
*
*/
package sdh.java.session6;
/**
* @author sudhi
*
*/
public interface Assignment3InterfaceShape {
void draw();
void getArea();
}
|
package com.tencent.mm.plugin.appbrand.jsapi.audio;
import android.text.TextUtils;
import com.tencent.mm.g.a.jt;
import com.tencent.mm.plugin.appbrand.jsapi.audio.JsApiSetBackgroundAudioState.SetBackgroundAudioListenerTask;
import com.tencent.mm.plugin.appbrand.media.music.a.a;
import com.tencent.mm.protocal.c.avq;
import com.tencent.mm.sdk.b.b;
import com.tencent.mm.sdk.b.c;
import com.tencent.mm.sdk.platformtools.x;
import com.tencent.tmassistantsdk.openSDK.OpenSDKTool4Assistant;
import java.util.HashMap;
import java.util.Map;
import org.json.JSONObject;
class JsApiSetBackgroundAudioState$SetBackgroundAudioListenerTask$2 extends c<jt> {
final /* synthetic */ SetBackgroundAudioListenerTask fIV;
JsApiSetBackgroundAudioState$SetBackgroundAudioListenerTask$2(SetBackgroundAudioListenerTask setBackgroundAudioListenerTask) {
this.fIV = setBackgroundAudioListenerTask;
this.sFo = jt.class.getName().hashCode();
}
public final /* synthetic */ boolean a(b bVar) {
jt jtVar = (jt) bVar;
x.i("MicroMsg.Music.SetBackgroundAudioListenerTask", "musicPlayerListener callback action : %d", new Object[]{Integer.valueOf(jtVar.bTE.action)});
Map hashMap = new HashMap();
String str = jtVar.bTE.state;
if (jtVar.bTE.action == 10) {
if (jtVar.bTE.appId.equals(this.fIV.appId)) {
x.i("MicroMsg.Music.SetBackgroundAudioListenerTask", "appId is same, don't send ON_PREEMPTED event");
return false;
}
x.i("MicroMsg.Music.SetBackgroundAudioListenerTask", "send ON_PREEMPTED event, sender appId:%s, receive appId:%s", new Object[]{jtVar.bTE.appId, this.fIV.appId});
hashMap.put(OpenSDKTool4Assistant.EXTRA_STATE, str);
this.fIV.fIt = new JSONObject(hashMap).toString();
this.fIV.action = jtVar.bTE.action;
SetBackgroundAudioListenerTask.b(this.fIV);
return true;
}
avq avq = jtVar.bTE.bTy;
if (avq == null) {
x.e("MicroMsg.Music.SetBackgroundAudioListenerTask", "wrapper is null");
return false;
} else if (jtVar.bTE.bTG) {
int i;
if (jtVar.bTE.action == 2 && jtVar.bTE.bTH) {
i = 1;
} else {
boolean i2 = false;
}
if (i2 != 0) {
x.e("MicroMsg.Music.SetBackgroundAudioListenerTask", "isSwitchMusicIng, don't callback!");
return false;
}
if (this.fIV.appId.equals(a.ala().ghU)) {
hashMap.put("src", avq.rYp);
hashMap.put(OpenSDKTool4Assistant.EXTRA_STATE, str);
hashMap.put("errCode", Integer.valueOf(jtVar.bTE.errCode));
Object obj = "";
if (!TextUtils.isEmpty(jtVar.bTE.Yy)) {
obj = jtVar.bTE.Yy;
}
hashMap.put("errMsg", obj);
this.fIV.fIt = new JSONObject(hashMap).toString();
this.fIV.action = jtVar.bTE.action;
SetBackgroundAudioListenerTask.c(this.fIV);
return true;
}
x.i("MicroMsg.Music.SetBackgroundAudioListenerTask", "appId is not equals preAppId, don't send any event, appId:%s, preAppId:%s", new Object[]{this.fIV.appId, a.ala().ghU});
return false;
} else {
x.e("MicroMsg.Music.SetBackgroundAudioListenerTask", "is not from QQMusicPlayer, don't callback!");
return false;
}
}
}
|
/*
* Copyright 2016 Johns Hopkins University
*
* 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 org.dataconservancy.cos.osf.client.retrofit;
import java.util.List;
import java.util.Map;
import com.squareup.okhttp.ResponseBody;
import org.dataconservancy.cos.osf.client.model.Comment;
import org.dataconservancy.cos.osf.client.model.Contributor;
import org.dataconservancy.cos.osf.client.model.FileVersion;
import org.dataconservancy.cos.osf.client.model.Identifier;
import org.dataconservancy.cos.osf.client.model.Log;
import org.dataconservancy.cos.osf.client.model.File;
import org.dataconservancy.cos.osf.client.model.Institution;
import org.dataconservancy.cos.osf.client.model.License;
import org.dataconservancy.cos.osf.client.model.MetaSchema;
import org.dataconservancy.cos.osf.client.model.Node;
import org.dataconservancy.cos.osf.client.model.LightNode;
import org.dataconservancy.cos.osf.client.model.Registration;
import org.dataconservancy.cos.osf.client.model.LightRegistration;
import org.dataconservancy.cos.osf.client.model.User;
import org.dataconservancy.cos.osf.client.model.LightUser;
import org.dataconservancy.cos.osf.client.model.Wiki;
import retrofit.Call;
import retrofit.http.GET;
import retrofit.http.Path;
import retrofit.http.QueryMap;
import retrofit.http.Streaming;
import retrofit.http.Url;
/**
* Abstracts the execution of HTTP queries against the OSF version 2 JSON API and unmarshals the JSON response to
* Java domain objects, which represent instances of the types presented by the OSF JSON API.
* <p>
* For each domain object, there are typically two methods: 1) given a URL to a object, unmarshal it; 2) given a URL to
* a collection of objects of the same type, unmarshal the collection into a List<T>. Because {@link Node},
* {@link Registration}, and {@link User} are of broad interest likely to accommodate a number of use cases,
* they have additional consideration.
* </p>
* <p>
* Firstly, these classes have lightweight representations in {@link LightNode}, {@link LightRegistration}, and
* {@link LightUser}. Their lightweight nature is achieved by omitting most properties of the object except for
* identifiers and dates, and omitting relationships to other objects that would require link traversal (resulting in
* additional HTTP and object creation overhead). Secondly, the {@code OsfService} provides additional methods that
* support retrieval according to criteria expressed as query parameters, allowing for, e.g. server-side filtering of
* results. This allows clients who may need to process a large number of objects to retrieve them quickly and
* efficiently. After identifying the lightweight objects of interest, their "heavy" counterparts can be retrieved.
* </p>
* <p>
* Collections returned by {@code OsfService} are transparently paginated by the underlying {@code List} implementation.
* Clients are encouraged to keep the creation of streams (e.g. via {@link List#stream()}) to a minimum, and to
* code defensively, recognizing that there is HTTP request overhead when traversing the elements of a stream. It is
* difficult to provide specific recommendations, as what is considered efficient will depend on the use case. However,
* here are some options to consider when working with streams:
* </p>
* <ul>
* <li>Most <a href="https://docs.oracle.com/javase/8/docs/api/java/util/stream/package-summary.html#StreamOps">
* terminal operations</a> are eager, meaning that the entire
* stream will be processed to exhaustion. Consider use of {@link java.util.stream.Stream#iterator()} when
* processing the entire stream is not necessary.</li>
* <li>If multiple traversals of the same collection are required, consider streaming the result into a new data
* structure (e.g. a new {@code Collection} or {@code Map}) before executing additional operations.</li>
* <li>Alternately, retrieve the stream once, and perform all the operations in a single traversal of the
* stream.</li>
* <li>Understand that {@code RuntimeException} may be thrown while processing a stream if network interruptions or
* latency prevent the retrieval of a results page.</li>
* </ul>
* <p>
* Methods which accept a {@link Url} as a method parameter may be optionally encoded. Retrofit will automatically
* encode as appropriate. For example, the following two URLs will result in the same results despite the difference
* in encoding:
* </p>
* <pre>
* List<Comment> comments;
*
* comments = osfService.comments("https://api.osf.io/v2/nodes/y9jdt/comments/?filter[target]=2eg28wm3x3c9")
* .execute().body();
*
* assertEquals(1, comments.size());
* assertEquals("chdpxqekghpk", comments.get(0).getId());
*
* comments = osfService.comments("https://api.osf.io/v2/nodes/y9jdt/comments/?filter%5Btarget%5D=2eg28wm3x3c9")
* .execute().body();
*
* assertEquals(1, comments.size());
* assertEquals("chdpxqekghpk", comments.get(0).getId());
* </pre>
* <p>
* However, methods which accept a {@link retrofit.http.Query} or {@link QueryMap} require their parameters to <em>not
* </em> be encoded. Retrofit will encode the parameters as a rule (unless {@code encoded = true} is present). For
* example, the following two method calls are not equivalent: the call which is <em>not encoded</em> returns the
* correct value:
* </p>
* <pre>
* List<LightNode> publicNodes;
*
* publicNodes = osfService.nodeIds(params("filter[public]", "true")).execute().body();
*
* final int count = publicNodes.size(); // 18499; correct count, the filter is applied and only public nodes returned
* assertTrue(publicNodes.size() > 1);
*
* publicNodes = osfService.nodeIds(params("filter%5Bpublic%5d", "true")).execute().body();
*
* assertNotEquals(count, publicNodes.size()); // 18508; the filter is ignored, public and private nodes are returned
* </pre>
*
* @author Elliot Metsger (emetsger@jhu.edu)
* @author Karen Hanson (karen.hanson@jhu.edu)
*/
public interface OsfService {
/**
*
* @param url
* @return
*/
@GET
Call<Comment> comment(@Url String url);
/**
*
* @param url
* @return
*/
@GET
Call<List<Comment>> comments(@Url String url);
/**
*
* @param url
* @return
*/
@GET
Call<Contributor> contributor(@Url String url);
/**
*
* @param url
* @return
*/
@GET
Call<List<Contributor>> contributors(@Url String url);
/**
*
* @param url
* @return
*/
@GET
Call<File> file(@Url String url);
/**
*
* @param url
* @return
*/
@GET
Call<List<File>> files(@Url String url);
/**
*
* @param url
* @return
*/
@GET
Call<FileVersion> fileversion(@Url String url);
/**
*
* @param url
* @return
*/
@GET
Call<FileVersion> fileversions(@Url String url);
/**
*
* @param url
* @return
*/
@GET
Call<Identifier> identifier(@Url String url);
/**
*
* @param url
* @return
*/
@GET
Call<List<Identifier>> identifiers(@Url String url);
/**
*
* @param url
* @return
*/
@GET
Call<Institution> institution(@Url String url);
/**
*
* @param url
* @return
*/
@GET
Call<List<Institution>> institutions(@Url String url);
/**
*
* @param url
* @return
*/
@GET
Call<License> license(@Url String url);
/**
*
* @param url
* @return
*/
@GET
Call<List<License>> licenses(@Url String url);
/**
*
* @param url
* @return
*/
@GET
Call<Log> log(@Url String url);
/**
*
* @param url
* @return
*/
@GET
Call<List<Log>> logs(@Url String url);
/**
*
* @param url
* @return
*/
@GET
Call<MetaSchema> metaschema(@Url String url);
/**
*
* @param url
* @return
*/
@GET
Call<List<MetaSchema>> metaschemas(@Url String url);
/**
*
* @param url
* @return
*/
@GET
Call<Node> node(@Url String url);
/**
*
* @param url
* @return
*/
@GET
Call<List<Node>> nodes(@Url String url);
/**
*
* @param nodeId
* @return
*/
@GET("nodes/{id}/")
Call<Node> nodeById(@Path("id") String nodeId);
/**
*
* @return
*/
@GET("nodes/")
Call<List<LightNode>> nodeIds();
/**
*
* @param params
* @return
*/
@GET("nodes/")
Call<List<LightNode>> nodeIds(@QueryMap Map<String, String> params);
/**
*
* @param url
* @return
*/
@GET
Call<LightNode> lightnode(@Url String url);
/**
*
* @param url
* @return
*/
@GET
Call<List<LightNode>> lightnodes(@Url String url);
/**
*
* @param url
* @return
*/
@GET
Call<Registration> registration(@Url String url);
/**
*
* @param url
* @return
*/
@GET
Call<List<Registration>> registrations(@Url String url);
/**
*
* @param id
* @return
*/
@GET("registrations/{id}/")
Call<Registration> registrationById(@Path("id") String id);
/**
*
* @return
*/
@GET("registrations/")
Call<List<LightRegistration>> registrationIds();
/**
*
* @param params
* @return
*/
@GET("registrations/")
Call<List<LightRegistration>> registrationIds(@QueryMap Map<String, String> params);
/**
*
* @param url
* @return
*/
@GET
Call<LightRegistration> lightregistration(@Url String url);
/**
*
* @param url
* @return
*/
@GET
Call<List<LightRegistration>> lightregistrations(@Url String url);
/**
*
* @param url
* @return
*/
@Streaming
@GET
Call<ResponseBody> stream(@Url String url);
/**
*
* @param url
* @return
*/
@GET
Call<User> user(@Url String url);
/**
*
* @param url
* @return
*/
@GET
Call<List<User>> users(@Url String url);
/**
*
* @param id
* @return
*/
@GET("users/{id}/")
Call<User> userById(@Path("id") String id);
/**
*
* @return
*/
@GET("users/")
Call<List<LightUser>> userIds();
/**
*
* @param params
* @return
*/
@GET("users/")
Call<List<LightUser>> userIds(@QueryMap Map<String, String> params);
/**
*
* @param url
* @return
*/
@GET
Call<LightUser> lightuser(@Url String url);
/**
*
* @param url
* @return
*/
@GET
Call<List<LightUser>> lightusers(@Url String url);
/**
*
* @param url
* @return
*/
@GET
Call<Wiki> wiki(@Url String url);
/**
*
* @param url
* @return
*/
@GET
Call<List<Wiki>> wikis(@Url String url);
}
|
package com.example.bowen.sunitalker.frags.search;
import com.example.bowen.sunitalker.R;
import com.example.bowen.sunitalker.activities.SearchActivity;
import com.example.common.comm.app.Fragment;
/**
* 搜索群的界面实现
*/
public class SearchGroupFragment extends Fragment
implements SearchActivity.SearchFragment {
public SearchGroupFragment() {
// Required empty public constructor
}
@Override
protected int getContentLayoutId() {
return R.layout.fragment_search_user;
}
@Override
public void search(String content) {
}
}
|
/* *****************************************************************************
* Name: Alan Turing
* Coursera User ID: 123456
* Last modified: 1/1/2019
**************************************************************************** */
public class MaximumSquareSubmatrix {
public static int size(int[][] a) {
int[][] b = new int[a.length][a.length];
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < a.length; j++) {
if (i == 0 || j == 0) {
b[i][j] = a[i][j];
}
else if (a[i][j] == 1) {
b[i][j] = Math.min(b[i - 1][j], Math.min(b[i - 1][j - 1], b[i][j - 1])) + 1;
}
else {
b[i][j] = 0;
}
}
}
int max = b[0][0];
for (int i = 0; i < b.length; i++) {
for (int j = 0; j < b.length; j++) {
if (b[i][j] > max) {
max = b[i][j];
}
}
}
return max;
}
public static void main(String[] args) {
int n = StdIn.readInt();
int[][] a = new int[n][n];
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < a.length; j++) {
a[i][j] = StdIn.readInt();
}
}
int num = size(a);
System.out.println(num);
}
}
|
package ElementsOfProgrammingInterview.Chapter16Recursion.Exercise1HanoiTower;
import java.util.*;
public class Solution2 {
// Main idea
// Using the 3 rings transfer to successfully transfer 4 rings
private static final int NUM_PEGS = 3;
public static void computeTowerHanoi(int numRings) {
// initialize
List<Deque<Integer>> pegs = new ArrayList<>();
for (int i = 0; i < NUM_PEGS; i++) {
pegs.add(new LinkedList<>());
}
int[] a = new int[10];
Integer[] A = new Integer[10];
var b = A.length;
for (int i = numRings; i >= 1; i--) {
pegs.get(0).addFirst(i);
}
// main function
computeTowerHanoiSteps(numRings, pegs, 0, 1, 2);
}
private static void computeTowerHanoiSteps(int numRingsToMove, List<Deque<Integer>> pegs, int fromPeg, int toPeg, int usePeg) {
if (numRingsToMove > 0) {
computeTowerHanoiSteps(numRingsToMove - 1, pegs, fromPeg, usePeg, toPeg);
var dishToMove = pegs.get(fromPeg).removeFirst();
pegs.get(toPeg).addFirst(dishToMove);
System.out.println("Move from peg " + fromPeg + " to peg " + toPeg);
computeTowerHanoiSteps(numRingsToMove - 1, pegs, usePeg, toPeg, fromPeg);
}
}
public static void main(String[] args) {
computeTowerHanoi(100);
}
}
|
package mygroup;
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Scanner;
import java.util.Set;
/**
* @author liming.gong
*/
public class SocketClient {
ByteBuffer writeBuffer = ByteBuffer.allocate(1024);
ByteBuffer readBuffer = ByteBuffer.allocate(1024);
public void start() throws IOException {
SocketChannel socketChannel = SocketChannel.open();
socketChannel.configureBlocking(false);
socketChannel.connect(new InetSocketAddress("localhost", 8001));
Selector selector = Selector.open();
socketChannel.register(selector, SelectionKey.OP_CONNECT);
try(Scanner scanner = new Scanner(System.in)) {
while (true) {
selector.select();
Set<SelectionKey> keys = selector.selectedKeys();
System.out.println("keys=" + keys.size());
Iterator<SelectionKey> keyIterator = keys.iterator();
while (keyIterator.hasNext()) {
SelectionKey key = keyIterator.next();
keyIterator.remove();
if (key.isConnectable()) {
socketChannel.finishConnect();
socketChannel.register(selector, SelectionKey.OP_WRITE);
System.out.println("server connected...");
break;
} else if (key.isWritable()) {
System.out.print("写数据:");
String message = scanner.nextLine();
writeBuffer.clear();
writeBuffer.put(message.getBytes());
writeBuffer.flip();
socketChannel.write(writeBuffer);
socketChannel.register(selector, SelectionKey.OP_READ);
} else if (key.isReadable()) {
System.out.print("获取数据");
SocketChannel client = (SocketChannel) key.channel();
readBuffer.clear();
int num = client.read(readBuffer);
System.out.println(new String(readBuffer.array(), 0, num));
socketChannel.register(selector, SelectionKey.OP_WRITE);
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) throws IOException {
System.out.println(args.length);
if (args.length == 1) {
new SocketClient().start();
} else {
try (Socket socket = new Socket("127.0.0.1", 8001);) {
OutputStream os = socket.getOutputStream();
String s = "hello world";
os.write(s.getBytes());
os.close();
} catch (Exception e) { /* do nth */}
}
}
} |
package com.smxknife.cache.custom.store.impl;
import com.smxknife.cache.custom.store.DataStore;
import com.smxknife.cache.custom.store.StoreAccessException;
import com.smxknife.cache.custom.store.ValueHolder;
import java.util.concurrent.ConcurrentHashMap;
/**
* @author smxknife
* 2020/6/8
*/
public class WeakValueDataStore<K, V> implements DataStore<K, V> {
private ConcurrentHashMap<K, ValueHolder<V>> map = new ConcurrentHashMap<>();
@Override
public ValueHolder<V> get(K key) throws StoreAccessException {
return map.get(key);
}
@Override
public void put(K key, V value) throws StoreAccessException {
WeakValueHolder<V> valueHolder = new WeakValueHolder<>(value);
map.put(key, valueHolder);
}
@Override
public ValueHolder<V> remove(K key) throws StoreAccessException {
return map.remove(key);
}
@Override
public void clear() throws StoreAccessException {
map.clear();
}
}
|
package com.hubspot.dropwizard.issue9;
import com.hubspot.dropwizard.guicier.GuiceBundle;
import io.dropwizard.Application;
import io.dropwizard.setup.Bootstrap;
import io.dropwizard.setup.Environment;
public class App extends Application<AppConfiguration> {
public static void main(String... args) throws Exception {
new App().run(args);
}
@Override
public void initialize(Bootstrap<AppConfiguration> bootstrap) {
bootstrap.addBundle(GuiceBundle.defaultBuilder(AppConfiguration.class)
.modules(new ContainerModule())
.build());
}
@Override
public void run(AppConfiguration configuration, Environment environment) throws Exception {
}
}
|
package mygroup;
import java.util.*;
final class FooObject{
private int x;
public FooObject(int _x) {
x = _x;
}
public void set(int _x) {
x = _x;
}
public String toString() {
return "x = " + x;
}
}
public class ShalowCopy {
@SuppressWarnings("unchecked")
private static void testClone() {
HashMap<Integer, FooObject> mif = new HashMap<>();
mif.put(2, new FooObject(13));
mif.put(3, new FooObject(23));
mif.put(1, new FooObject(33));
HashMap<Integer, FooObject> mifClone = (HashMap<Integer, FooObject>)mif.clone();
mif.get(3).set(99);
System.out.println(mifClone.get(3));
HashMap<Integer, String> map = new HashMap<Integer, String>();
map.put(2, "microsoft");
map.put(3, "yahoo");
map.put(1, "amazon");
Map<Integer, String> mClone =
(HashMap<Integer, String>)map.clone();
System.out.println(System.identityHashCode(map.get(3)));
System.out.println(System.identityHashCode(mClone.get(3)));
String previous = map.replace(3, "google");
System.out.println(previous); // yahoo
System.out.println(map.get(3)); // google
System.out.println(mClone.get(3)); // yahoo, because previous change was "replace".
System.out.println(System.identityHashCode(map.get(3))); // new object
System.out.println(System.identityHashCode(mClone.get(3))); // old object
}
public static void main(String[] args) {
HashMap<Integer, FooObject> mif = new HashMap<>();
mif.put(2, new FooObject(13));
mif.put(3, new FooObject(23));
mif.put(1, new FooObject(33));
HashMap<Integer, FooObject> mCopy = new HashMap<>(mif);
mCopy.get(3).set(44);
System.out.println(mif.get(3));
System.out.println("---------------");
testClone();
}
}
|
package app.data;
import java.util.List;
import org.springframework.data.repository.CrudRepository;
import app.model.Flight;
public interface IFlightRepository extends CrudRepository<Flight, Long>{
public List<Flight> findByCompanyId(Long id);
}
|
package banking.exceptions;
public class DepositWithdrawTransferException extends Exception {
public DepositWithdrawTransferException() {
}
public DepositWithdrawTransferException(String message) {
super(message);
}
public DepositWithdrawTransferException(Throwable cause) {
super(cause);
}
public DepositWithdrawTransferException(String message, Throwable cause) {
super(message, cause);
}
public DepositWithdrawTransferException(String message, Throwable cause, boolean enableSuppression,
boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
}
}
|
package com.nightonke.githubwidget;
/**
* Created by Weiping on 2016/4/25.
*/
public class Day {
public int year = -1;
public int month = -1;
public int day = -1;
// Level is used to record the color of the block
public int level = -1;
// Data is used to calculated the height of the pillar
public int data = -1;
public Day(int year, int month, int day, int level, int data) {
this.year = year;
this.month = month;
this.day = day;
this.level = level;
this.data = data;
}
}
|
package Exercicio3;
public class Main {
public static void main(String[] args) {
Supermarket market1 = new Supermarket(1.5, "Continente", 12345);
System.out.println(market1);
market1.setPotatoesPrice(1.25);
System.out.println("New potatoe price : " + market1.getPotatoesPrice());
System.out.println("-------------------");
System.out.println(market1.toString());
System.out.println("Total potatoes price: " + market1.getMarketTotal(3));
}
}
|
package com.rbkmoney.adapter.atol.service.atol.constant;
import lombok.AllArgsConstructor;
import lombok.Getter;
/**
* Операции с фискальным аппаратом
*/
@Getter
@AllArgsConstructor
public enum Operations {
// чек «Приход»
SELL("sell"),
// чек «Возврат прихода»
SELL_REFUND("sell_refund"),
// чек «Коррекция прихода»
SELL_CORRECTION("sell_correction"),
// чек «Расход»
BUY("buy"),
// чек «Возврат расхода»
BUY_REFUND("buy_refund"),
// чек «Коррекция расхода»
BUY_CORRECTION("buy_correction");
private String operation;
}
|
package com.aciton;
import com.entity.BooksEntity;
import com.service.BookService;
import org.apache.struts2.ServletActionContext;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.Vector;
/**
* Created by 滩涂上的芦苇 on 2016/6/7.
*/
public class UpdateBookAction {
public static final long serialVersionUID = 1L;
public static final String ADMIN = "admin";
public static final String INDEX = "index";
public HttpServletRequest request;
private BookService bookService;
public BookService getBookService() {
return bookService;
}
public void setBookService(BookService bookService) {
this.bookService = bookService;
}
private String isbn;
private String title;
private String category;
private BigDecimal price;
private String profile;
public String getIsbn() {
return isbn;
}
public void setIsbn(String isbn) {
this.isbn = isbn;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public BigDecimal getPrice() {
return price;
}
public void setPrice(BigDecimal price) {
this.price = price;
}
public String getProfile() {
return profile;
}
public void setProfile(String profile) {
this.profile = profile;
}
public String execute() {
request = ServletActionContext.getRequest();
if ((int)request.getSession().getAttribute("isAdmin")!=1) {
request.setAttribute("status", "Fatal: you are not administrator!");
ServletActionContext.setRequest(request);
return INDEX;
}
try {
BooksEntity book = bookService.queryByIsbn(isbn);
// book not exist, insert operation
if (book == null && price.compareTo(BigDecimal.ZERO)==1) {
book = new BooksEntity();
book.setIsbn(isbn);
book.setTitle(title);
book.setCategory(category);
book.setPrice(price);
bookService.addBook(book);
request.setAttribute("status", "添加图书成功");
}
else { // book exist, update operation
boolean changed = false;
if (title != null && title != "") {
book.setTitle(title);
changed = true;
}
if (category != null && category != "") {
book.setCategory(category);
changed = true;
}
if (price.compareTo(BigDecimal.ZERO)==1) {
book.setPrice(price);
changed = true;
}
if (!changed){
request.setAttribute("status", "图书添加失败,请仔细检查");
ServletActionContext.setRequest(request);
return ADMIN;
}
bookService.updateBook(book);
}
Vector<BooksEntity> books = new Vector<BooksEntity>();
books = bookService.queryAll();
request.setAttribute("booklist", books);
request.setAttribute("isbn",isbn);
request.setAttribute("profile",profile);
} catch (Exception e) {
e.printStackTrace();
}
ServletActionContext.setRequest(request);
return ADMIN;
}
}
|
package Day14;
import java.util.Calendar;
import java.util.Scanner;
public class Day14_2 {
public static void main(String[] args) {
// Scanner scanner = new Scanner(System.in);
System.out.println("검색 연도 : "); int year = scanner.nextInt();
System.out.println("검색 월 : "); int smonth = scanner.nextInt();
달력검색(syear,smonth); //메소드 호출
//현재 날짜의 달력
Calendar calendar = Calendar.getInstance(); // 1.현재 달력 가져오기
int today = calendar.get(calendar.DAY_OF_MONTH); // 2. 현재 날짜의 일수
int year = calendar.get(calendar.YEAR); // 3. 현재 날짜의 연도
int month = calendar.get(calendar.MONTH)+1; // 4. 현재 날짜의 월 +1 [1월:0~]
calendar.set(year, month-1,1); // 5. 현재 날짜의 1일
int sDay = calendar.get(Calendar.DAY_OF_WEEK); // 6. 시작 요일
int eDay = calendar.getActualMaximum(Calendar.DAY_OF_MONTH); // 7. 현재 날자
// 달력 출력
System.out.println("========== " + year +"년" + month + "월===================");
System.out.println("일\t월\t화\t수\t목\t금\t토");
System.out.println("=============================");
int ssDay = sDay; //요일 구분 [토요일마다 줄바꿈]
// 현 월의 1일의 위치 앞까지 공백 채우기
for(int i=1;i<eDay;i++) {
if (i == today) System.err.print(i+"\t");
else System.out.print(i+"\t");
//줄바꿈
if(ssDay%7 == 0) System.out.println(); //줄바꿈
ssDay++; //요일증가
// 요일출력
for(int i = 1; i<=eDay;i++);
if(i == today) System.out.print("["+i+"]"+"\t");
System.out.print(i+"\t");
//줄바꿈
System.out.println(); //줄바꿈
}
}
}
|
package dino;
import dino.task.Task;
import dino.task.ToDo;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class MarkDoneTest {
@Test
public void markAsDone_success() {
Task task = new ToDo("test todo");
task.setDone();
assertEquals("T | 1 | test todo", task.toString());
}
}
|
import com.sun.source.tree.Tree;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.TreeMap;
public class SemAnalizer {
// static TreeMap<Integer, ArrayList<String>> maxWords = new TreeMap<>();
// static TreeMap<Integer, ArrayList<String>> maxWordsWithLetterCnt = new TreeMap<>();
// static TreeMap<Integer, ArrayList<String>> maxWords2Words = new TreeMap<>();
// static TreeMap<Integer, ArrayList<String>> maxWordsFilter = new TreeMap<>();
public static void main(String[] args) throws FileNotFoundException {
// System.out.println(findMaxWords(Reader.readHunFirstNames("borbala.txt")));
// System.out.println(findMaxWordsWithLetterCnt(Reader.read("borbala.txt"),1));
// System.out.println(findMaxWords(Reader.read("borbala.txt")));
// System.out.println(filteredMoreThan15Words(Reader.read("borbala.txt")));
}
// nem a forrászövegünkre jellemző szavak szűrése
public static TreeMap<Integer, ArrayList<String>> filteredMoreThan15Words(HashMap<String, Integer> words) {
TreeMap<Integer, ArrayList<String>> maxWordsFilter = new TreeMap<>();
for (int i = 4; i < 20; i++) {
for (Integer integer : findMaxWordsWithLetterCnt(words, i).keySet()) {
if (integer > 30) {
for (int j = 0; j < findMaxWordsWithLetterCnt(words, i).get(integer).size(); j++) {
String word = findMaxWordsWithLetterCnt(words, i).get(integer).get(j);
if (word.equals("hogy") || word.equals("volt") || word.equals("csak") || word.equals("aztán") || word.equals("mint") || word.equals("hanem") || word.equals("mert") || word.equals("hogy")
|| word.equals("azután") || word.equals("mintha") || word.equals("vagy") || word.equals("valami") || word.equals("pedig") || word.equals("annak") || word.equals("minden") || word.equals("most") || word.equals("mely")
) {
} else {
maxWordsFilter.putIfAbsent(integer, new ArrayList<>());
maxWordsFilter.get(integer).add(word);
}
}
}
}
}
return maxWordsFilter;
}
// Gyűjtsd ki egy szöveg 10 leggyakoribb nevét!
// még nincs kész
//2. Gyűjtsd ki egy szöveg 10 leggyakoribb 2-3-4 szófordulatát!
// findMaxWordsOf2Words(Reader.read2Words("borbala.txt"));
// Gyűjts ki a leggyakoribb "letterCnt" betűs szót.
public static TreeMap<Integer, ArrayList<String>> findMaxWordsWithLetterCnt(HashMap<String, Integer> words, int letterCnt) {
TreeMap<Integer, ArrayList<String>> maxWordsWithLetterCnt = new TreeMap<>();
int maxCnt = Integer.MAX_VALUE;
for (int i = 0; i < 10; ) {
Integer actuelMaxCnt = findMaxWordsUnderMaxCntWithLetterCnt(words, maxCnt, letterCnt);
maxWordsWithLetterCnt.putIfAbsent(actuelMaxCnt, new ArrayList<>());
for (String s : words.keySet()) {
if (words.get(s).equals(actuelMaxCnt) && s.toCharArray().length == (letterCnt)) {
maxWordsWithLetterCnt.get(actuelMaxCnt).add(s);
i++;
}
}
if (actuelMaxCnt < 0) {
break;
}
maxCnt = actuelMaxCnt;
}
maxWordsWithLetterCnt.remove(Integer.MIN_VALUE);
return maxWordsWithLetterCnt;
}
public static Integer findMaxWordsUnderMaxCntWithLetterCnt(HashMap<String, Integer> words, int underMaxCnt, int letterCnt) {
int max = Integer.MIN_VALUE;
for (String s : words.keySet()) {
if ((!s.equals("")) && words.get(s) > max && words.get(s) < underMaxCnt && s.toCharArray().length == (letterCnt)) {
max = words.get(s);
}
}
return max;
}
public static TreeMap<Integer, ArrayList<String>> findMaxWordsOf2Words(HashMap<String, Integer> words) {
TreeMap<Integer, ArrayList<String>> maxWords = new TreeMap<>();
TreeMap<Integer, ArrayList<String>> maxWords2Words = new TreeMap<>();
int maxCnt = Integer.MAX_VALUE;
for (int i = 0; i < 10; ) {
Integer actuelMaxCnt = findMaxWordsUnderMaxCnt(words, maxCnt);
maxWords2Words.putIfAbsent(actuelMaxCnt, new ArrayList<>());
for (String s : words.keySet()) {
if (words.get(s).equals(actuelMaxCnt)) {
maxWords2Words.get(actuelMaxCnt).add(s);
i++;
}
}
maxCnt = actuelMaxCnt;
}
return maxWords;
}
// 1. Gyűjtsd ki egy szöveg 10 leggyakoribb szavát!
public static TreeMap<Integer, ArrayList<String>> findMaxWords(HashMap<String, Integer> words) {
TreeMap<Integer, ArrayList<String>> maxWords = new TreeMap<>();
int maxCnt = Integer.MAX_VALUE;
for (int i = 0; i < 10; ) {
Integer actuelMaxCnt = findMaxWordsUnderMaxCnt(words, maxCnt);
maxWords.putIfAbsent(actuelMaxCnt, new ArrayList<>());
for (String s : words.keySet()) {
if (words.get(s).equals(actuelMaxCnt)) {
maxWords.get(actuelMaxCnt).add(s);
i++;
}
}
maxCnt = actuelMaxCnt;
}
return maxWords;
}
public static Integer findMaxWordsUnderMaxCnt(HashMap<String, Integer> words, int underMaxCnt) {
int max = Integer.MIN_VALUE;
for (String s : words.keySet()) {
if ((!s.equals("")) && words.get(s) > max && words.get(s) < underMaxCnt) {
max = words.get(s);
}
}
return max;
}
}
|
/*
* 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 vasylts.blackjack.user;
/**
*
* @author VasylcTS
*/
public interface IUserManager {
public Long createUser(String login, String password);
public boolean deleteUser(Long id);
public boolean deleteUser(String login, String password);
public IUser getUser(Long id);
public IUser getUser(String login, String password);
}
|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.clerezza.sparql.query.impl;
import org.apache.clerezza.IRI;
import org.apache.clerezza.sparql.query.*;
import java.util.*;
/**
* This class implements {@link GroupGraphPattern}.
*
* @author hasan
*/
public class SimpleGroupGraphPattern implements GroupGraphPattern {
private List<Expression> constraints = new ArrayList<Expression>();
private List<GraphPattern> graphPatterns = new ArrayList<GraphPattern>();
private SelectQuery subSelect = null;
private boolean lastBasicGraphPatternIsComplete = true;
@Override
public boolean isSubSelect() {
return subSelect != null;
}
@Override
public SelectQuery getSubSelect() {
return subSelect;
}
@Override
public Set<GraphPattern> getGraphPatterns() {
return subSelect == null ? new LinkedHashSet(graphPatterns) : null;
}
@Override
public List<Expression> getFilter() {
return subSelect == null ? constraints : null;
}
public void setSubSelect(SelectQuery subSelect) {
this.subSelect = subSelect;
}
/**
* Adds a {@link GraphPattern} to the group.
*
* @param graphPattern
* the GraphPattern to be added.
*/
public void addGraphPattern(GraphPattern graphPattern) {
subSelect = null;
graphPatterns.add(graphPattern);
lastBasicGraphPatternIsComplete =
!(graphPattern instanceof BasicGraphPattern || graphPattern instanceof PathSupportedBasicGraphPattern);
}
/**
* Adds a constraint to the {@link GroupGraphPattern}.
*
* @param constraint
* an {@link Expression} as the constraint to be added.
*/
public void addConstraint(Expression constraint) {
subSelect = null;
constraints.add(constraint);
}
public void endLastBasicGraphPattern() {
lastBasicGraphPatternIsComplete = true;
}
/**
* If the last {@link GraphPattern} added to the group is not a
* {@link SimplePathSupportedBasicGraphPattern}, then creates one containing the
* specified {@link PropertyPathPattern}s and adds it to the group.
* Otherwise, adds the specified {@link PropertyPathPattern}s to the last
* added {@link SimplePathSupportedBasicGraphPattern} in the group.
*
* @param propertyPathPatterns
* a set of {@link PropertyPathPattern}s to be added into a
* {@link SimplePathSupportedBasicGraphPattern} of the group.
*/
public void addPropertyPathPatterns(Set<PropertyPathPattern> propertyPathPatterns) {
subSelect = null;
if (lastBasicGraphPatternIsComplete) {
graphPatterns.add(new SimplePathSupportedBasicGraphPattern(propertyPathPatterns));
lastBasicGraphPatternIsComplete = false;
} else {
GraphPattern prevGraphPattern;
int size = graphPatterns.size();
prevGraphPattern = graphPatterns.get(size-1);
if (prevGraphPattern instanceof SimplePathSupportedBasicGraphPattern) {
((SimplePathSupportedBasicGraphPattern) prevGraphPattern).addPropertyPathPatterns(propertyPathPatterns);
}
}
}
/**
* If the last {@link GraphPattern} added to the group is not a
* {@link SimpleBasicGraphPattern}, then creates one containing the
* specified {@link TriplePattern}s and adds it to the group.
* Otherwise, adds the specified {@link TriplePattern}s to the last
* added {@link SimpleBasicGraphPattern} in the group.
*
* @param triplePatterns
* a set of {@link TriplePattern}s to be added into a
* {@link SimpleBasicGraphPattern} of the group.
*/
public void addTriplePatterns(Set<TriplePattern> triplePatterns) {
subSelect = null;
GraphPattern prevGraphPattern;
int size = graphPatterns.size();
if (!lastBasicGraphPatternIsComplete && (size > 0)) {
prevGraphPattern = graphPatterns.get(size-1);
if (prevGraphPattern instanceof SimpleBasicGraphPattern) {
((SimpleBasicGraphPattern) prevGraphPattern)
.addTriplePatterns(triplePatterns);
return;
}
}
graphPatterns.add(new SimpleBasicGraphPattern(triplePatterns));
lastBasicGraphPatternIsComplete = false;
}
/**
* Adds an {@link OptionalGraphPattern} to the group consisting of
* a main ImmutableGraph pattern and the specified {@link GroupGraphPattern} as
* the optional pattern.
* The main ImmutableGraph pattern is taken from the last added {@link GraphPattern}
* in the group, if it exists. Otherwise, the main ImmutableGraph pattern is null.
*
* @param optional
* a {@link GroupGraphPattern} as the optional pattern of
* an {@link OptionalGraphPattern}.
*/
public void addOptionalGraphPattern(GroupGraphPattern optional) {
subSelect = null;
GraphPattern prevGraphPattern = null;
int size = graphPatterns.size();
if (size > 0) {
prevGraphPattern = graphPatterns.remove(size-1);
}
graphPatterns.add(new SimpleOptionalGraphPattern(prevGraphPattern, optional));
lastBasicGraphPatternIsComplete = true;
}
public void addMinusGraphPattern(GroupGraphPattern subtrahend) {
subSelect = null;
GraphPattern prevGraphPattern = null;
int size = graphPatterns.size();
if (size > 0) {
prevGraphPattern = graphPatterns.remove(size-1);
}
graphPatterns.add(new SimpleMinusGraphPattern(prevGraphPattern, subtrahend));
lastBasicGraphPatternIsComplete = true;
}
@Override
public Set<IRI> getReferredGraphs() {
Set<IRI> referredGraphs = new HashSet<IRI>();
if (subSelect != null) {
GroupGraphPattern queryPattern = subSelect.getQueryPattern();
referredGraphs.addAll(queryPattern.getReferredGraphs());
} else {
for (GraphPattern graphPattern : graphPatterns) {
referredGraphs.addAll(getReferredGraphs(graphPattern));
}
}
return referredGraphs;
}
private Set<IRI> getReferredGraphs(GraphPattern graphPattern) {
Set<IRI> referredGraphs = new HashSet<IRI>();
if (graphPattern instanceof GraphGraphPattern) {
GraphGraphPattern graphGraphPattern = (GraphGraphPattern) graphPattern;
UriRefOrVariable ImmutableGraph = graphGraphPattern.getGraph();
if (!ImmutableGraph.isVariable()) {
referredGraphs.add(ImmutableGraph.getResource());
}
referredGraphs.addAll(graphGraphPattern.getGroupGraphPattern().getReferredGraphs());
} else if (graphPattern instanceof AlternativeGraphPattern) {
List<GroupGraphPattern> alternativeGraphPatterns =
((AlternativeGraphPattern) graphPattern).getAlternativeGraphPatterns();
for (GroupGraphPattern groupGraphPattern : alternativeGraphPatterns) {
referredGraphs.addAll(groupGraphPattern.getReferredGraphs());
}
} else if (graphPattern instanceof OptionalGraphPattern) {
GraphPattern mainGraphPattern = ((OptionalGraphPattern) graphPattern).getMainGraphPattern();
referredGraphs.addAll(getReferredGraphs(mainGraphPattern));
GroupGraphPattern optionalGraphPattern = ((OptionalGraphPattern) graphPattern).getOptionalGraphPattern();
referredGraphs.addAll(optionalGraphPattern.getReferredGraphs());
} else if (graphPattern instanceof MinusGraphPattern) {
GraphPattern minuendGraphPattern = ((MinusGraphPattern) graphPattern).getMinuendGraphPattern();
referredGraphs.addAll(getReferredGraphs(minuendGraphPattern));
GroupGraphPattern subtrahendGraphPattern = ((MinusGraphPattern) graphPattern).getSubtrahendGraphPattern();
referredGraphs.addAll(subtrahendGraphPattern.getReferredGraphs());
} else if (graphPattern instanceof GroupGraphPattern) {
GroupGraphPattern groupGraphPattern = (GroupGraphPattern) graphPattern;
referredGraphs.addAll(groupGraphPattern.getReferredGraphs());
}
return referredGraphs;
}
}
|
package melerospaw.deudapp.utils;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
/**
* Created by Juan José Melero on 26/05/2015.
*/
public class InternalMemoryUtils {
/**Devuelve un <i>Bitmap</i> a partir de una imagen almacenada en <i>data/data/nuestraApp/files</i>.
* @param context
* @param rutaImagen Donde se encuentra la imagen a partir de <i>data/data/nuestraApp/files</i>.
* @return Devuelve el <i>Bitmap</i> de la imagen indicada o <i>null</i> si no existe la imagen.*/
public static Bitmap obtenerImagenBitmap(Context context, String rutaImagen){
try{
FileInputStream fileInputStream = new FileInputStream(context.getFilesDir() + "/" + rutaImagen);
return BitmapFactory.decodeStream(fileInputStream);
}catch(IOException e){
System.out.println("No se ha podido obtener la imagen en " + rutaImagen);
return null;
}
}
/**Guarda una imagen en la memoria interna del dispositivo, en <i>data/data/app/files</i>,
* comprobando antes que no exista ya una igual.
* @param context
* @param bitmap Objeto <i>Bitmap</i> de la imagen. Sus medidas deben ser de 142px x 142px
* @param nombreImagen Nombre que que tenga la imagen en <i>data/data/nuestraApp/files</i>.
* No debe contener espacios.
* @return Devuelve un booleano que indica si la imagen se ha guardado correctamente o no.*/
public static boolean guardarImagen(Context context, Bitmap bitmap, String nombreImagen){
if (!isArchivoRepetido(context, nombreImagen) && bitmap != null) {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();
try {
FileOutputStream fileOutputStream = context.openFileOutput(nombreImagen, Context.MODE_PRIVATE);
fileOutputStream.write(byteArray);
fileOutputStream.close();
} catch (IOException e) {
System.out.println("No se ha podido guardar la imagen " + nombreImagen);
return false;
}
return true;
}
System.out.println("No se ha podido guardar la imagen " + nombreImagen + ". " +
"Puede deberse a que la imagen sea nula o a que ya hay guardada una" +
" con el mismo nombre.");
return false;
}
/**Devuelve un booleano indicando si el archivo ya existe en el directorio <i>data/data/app/files</i>
* @param context
* @param nombreArchivo El nombre del archivo en la carpeta <i>/data/data/nuestraApp/files</i>, empezando sin barra. Por ejemplo:
* <i>imagen.jpg</i>.
* @return boolean indicando si existe o no el archivo.*/
private static boolean isArchivoRepetido(Context context, String nombreArchivo) {
File file = new File(context.getFilesDir().getPath() + "/" + nombreArchivo);
return file.exists()? true : false;
}
/**Obtiene una imagen en forma de archivo <i>Bitmap</i> desde la carpeta assets
* @param context
* @param nommbreImagen Nombre de la imagen en la carpeta assets, empezando sin barra. Por ejemplo,
* <i>imagen.jpg</i>.
* @return La imagen convertida en <i>Bitmap</i>*/
public static Bitmap obtenerImagenDesdeAssets(Context context, String nommbreImagen){
try {
return BitmapFactory.decodeStream(context.getAssets().open(nommbreImagen));
}catch(IOException e){
System.out.println("No se ha podido encontrar la imagen en assets");
e.printStackTrace();
return null;
}
}
/**Elimina un archivo de <i>data/data/nuestraApp/files</i>
* @param context
* @param nombre Nombre del archivo que queremos borrar
* @return Devuelve un booleano indicando si se ha borrado el archivo o no. Si no se ha borrado
* es porque la ruta está mal indicada*/
public static boolean eliminarArchivoInterno(Context context, String nombre){
return new File(context.getFilesDir().getPath() + "/" + nombre).delete();
}
/**Convierte la imagen a un tamaño de 5cm (142px x 142px).
* @param bitmap <i>Bitmap</i> con la imagen que queremos redimensionar.
* @returns Devuelve un bitmap escalado a 142px x 142px*/
public static Bitmap prepararBitmap(Bitmap bitmap){
Bitmap bitmapRecortado = null;
// Primero la recorta el lado mas largo para que tenga un ratio de aspecto 1:1
if (bitmap.getWidth() != bitmap.getHeight()){
int anchura = bitmap.getWidth();
int altura = bitmap.getHeight();
if (anchura < altura){
int alturaSobrante = altura - anchura;
int y = alturaSobrante / 2;
bitmapRecortado = Bitmap.createBitmap(bitmap, 0, y, anchura, anchura);
} else if (altura < anchura){
int anchuraSobrante = anchura - altura;
int x = anchuraSobrante / 2;
bitmapRecortado = Bitmap.createBitmap(bitmap, x, 0, altura, altura);
}
} else
bitmapRecortado = bitmap;
//Escala la imagen a 142px
Bitmap bitmapescalado = Bitmap.createScaledBitmap(bitmapRecortado, 142, 142, false);
return bitmapescalado;
}
}
|
package com.rawa.ac.uk;
public interface workflowBlock {
public void execute(BlockEnvironment env, BlockInputs inputs, BlockOutputs outputs) throws Exception;
}
|
package com.thyssenkrupp.tks.fls.qf.server.qcs.receive.xml.builder;
import com.thyssenkrupp.tks.fls.qf.server.qcs.receive.xml.GeometrieType;
import com.thyssenkrupp.tks.fls.qf.server.qcs.receive.xml.KokilleTypEnum;
import com.thyssenkrupp.tks.fls.qf.server.qcs.receive.xml.STRANGPlanungType;
import com.thyssenkrupp.tks.fls.qf.server.qcs.receive.xml.SchrottAnteilType;
import java.io.StringWriter;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.JAXBException;
import javax.xml.namespace.QName;
public class STRANGPlanungTypeBuilder
{
public static String marshal(STRANGPlanungType sTRANGPlanungType)
throws JAXBException
{
JAXBElement<STRANGPlanungType> jaxbElement = new JAXBElement<>(new QName("TESTING"), STRANGPlanungType.class , sTRANGPlanungType);
StringWriter stringWriter = new StringWriter();
return stringWriter.toString();
}
private KokilleTypEnum kokilleTyp;
private GeometrieType planBrammenGeometrie;
private Long planBrammenGewicht;
private Long strang;
private Double breitenverstellung;
private SchrottAnteilType schrottZurFolgeBramme;
private Long lCR;
private String charge;
private String brammenart;
private Boolean kokillenwechsel;
public STRANGPlanungTypeBuilder setKokilleTyp(KokilleTypEnum value)
{
this.kokilleTyp = value;
return this;
}
public STRANGPlanungTypeBuilder setPlanBrammenGeometrie(GeometrieType value)
{
this.planBrammenGeometrie = value;
return this;
}
public STRANGPlanungTypeBuilder setPlanBrammenGewicht(Long value)
{
this.planBrammenGewicht = value;
return this;
}
public STRANGPlanungTypeBuilder setStrang(Long value)
{
this.strang = value;
return this;
}
public STRANGPlanungTypeBuilder setBreitenverstellung(Double value)
{
this.breitenverstellung = value;
return this;
}
public STRANGPlanungTypeBuilder setSchrottZurFolgeBramme(SchrottAnteilType value)
{
this.schrottZurFolgeBramme = value;
return this;
}
public STRANGPlanungTypeBuilder setLCR(Long value)
{
this.lCR = value;
return this;
}
public STRANGPlanungTypeBuilder setCharge(String value)
{
this.charge = value;
return this;
}
public STRANGPlanungTypeBuilder setBrammenart(String value)
{
this.brammenart = value;
return this;
}
public STRANGPlanungTypeBuilder setKokillenwechsel(Boolean value)
{
this.kokillenwechsel = value;
return this;
}
public STRANGPlanungType build()
{
STRANGPlanungType result = new STRANGPlanungType();
result.setKokilleTyp(kokilleTyp);
result.setPlanBrammenGeometrie(planBrammenGeometrie);
result.setPlanBrammenGewicht(planBrammenGewicht);
result.setStrang(strang);
result.setBreitenverstellung(breitenverstellung);
result.setSchrottZurFolgeBramme(schrottZurFolgeBramme);
result.setLCR(lCR);
result.setCharge(charge);
result.setBrammenart(brammenart);
result.setKokillenwechsel(kokillenwechsel);
return result;
}
} |
package pageObjects;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.FindBys;
import org.openqa.selenium.support.PageFactory;
import java.util.List;
import java.util.Random;
import java.util.concurrent.TimeUnit;
public class LoginPage
{
WebDriver driver;
@FindBy(linkText = "Sign in")
private WebElement signin;
@FindBy(id = "email")
private WebElement email;
@FindBy(id = "passwd")
private WebElement password;
@FindBy(id = "SubmitLogin")
private WebElement submit;
public LoginPage(WebDriver driver)
{
this.driver = driver;
PageFactory.initElements(driver, this);
}
public void setEmail(String email)
{
WebElement emailInput = this.email;
emailInput.clear();
emailInput.sendKeys(email);
}
public void setPassword(String password)
{
WebElement passwdInput = this.password;
passwdInput.clear();
passwdInput.sendKeys(password);
}
public void clickSubmit()
{
submit.click();
}
public void doLogin(String username, String password)
{
signin.click();
driver.manage().timeouts().implicitlyWait(3, TimeUnit.SECONDS);
this.setEmail(username);
this.setPassword(password);
clickSubmit();
}
}
|
package com.passing.hibernate.beans;
import java.util.Set;
/**
* TbEnWord generated manually
*/
public class TbEnWordAttr extends AbstractTbEnWordAttr implements java.io.Serializable {
// Constructors
/** default constructor */
public TbEnWordAttr() {
}
/** full constructor */
public TbEnWordAttr(int dict_id, int word_id, String part_of_speech, int meaning_num, String extd_attr, String mean, Set<TbEnWordExmp> tb_en_word_exmp) {
super(dict_id, word_id, part_of_speech, meaning_num, extd_attr, mean, tb_en_word_exmp);
}
}
|
package com.company.exceptions;
public class snakeNotFoundException extends Exception {
public snakeNotFoundException(String msg){
super(msg);
}
}
|
package iarfmoose;
import java.util.HashSet;
import java.util.Optional;
import java.util.Set;
import com.github.ocraft.s2client.protocol.data.UnitType;
import com.github.ocraft.s2client.protocol.game.Race;
public class ThreatState implements State{
private String name;
private Integer baseCount;
private Integer gasCount;
private Integer workerCount;
private Float armySupply;
private Integer productionFacilityCount;
private Set<Race> enemyRaces;
private Set<UnitType> keyUnits;
private TimeWindow timeWindow;
private ThreatResponse response;
public ThreatState(String name, TimeWindow timeWindow, ThreatResponse response) {
this.name = name;
this.baseCount = null;
this.gasCount = null;
this.workerCount = null;
this.armySupply = null;
this.productionFacilityCount = null;
this.enemyRaces = new HashSet<Race>();
this.keyUnits = new HashSet<UnitType>();
this.timeWindow = timeWindow;
this.response = response;
}
//GET VALUES:
public String getName() {
return this.name;
}
@Override
public Optional<Integer> getBaseCount() {
return Optional.ofNullable(baseCount);
}
@Override
public Optional<Integer> getGasCount() {
return Optional.ofNullable(gasCount);
}
@Override
public Optional<Integer> getWorkerCount() {
return Optional.ofNullable(workerCount);
}
@Override
public Optional<Float> getArmySupply() {
return Optional.ofNullable(armySupply);
}
public Optional<Integer> getProductionFacilityCount() {
return Optional.ofNullable(productionFacilityCount);
}
public Set<Race> getRaces() {
return enemyRaces;
}
public Set<UnitType> getKeyUnits() {
return keyUnits;
}
public TimeWindow getTimeWindow() {
return timeWindow;
}
public ThreatResponse getResponse() {
return response;
}
//SET VALUES:
public void addRace(Race enemyRace) {
this.enemyRaces.add(enemyRace);
}
public void addKeyUnit(UnitType unitType) {
this.keyUnits.add(unitType);
}
public void setProductionFacilityCount(int count) {
this.productionFacilityCount = count;
}
public void setBaseCount(int count) {
this.baseCount = count;
}
public void setGasCount(int count) {
this.gasCount = count;
}
public void respond() {
response.respond();
}
}
|
package studio.baka.originiumcraft.inventory.processing;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import net.minecraft.client.Minecraft;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.items.ItemStackHandler;
import scala.actors.threadpool.Arrays;
import studio.baka.originiumcraft.OriginiumCraft;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.List;
public class OCProcessManager {
private static final List<OCProcess> processOneMaterial = new ArrayList<>();
private static final List<OCProcess> processTwoMaterial = new ArrayList<>();
private static final List<OCProcess> processThreeMaterial = new ArrayList<>();
public static void register(String modId) {
ResourceLocation processFileLocation = new ResourceLocation(modId + ":processes/processes.json");
try {
Gson gson = new Gson();
InputStream in = Minecraft.getMinecraft().getResourceManager().getResource(processFileLocation).getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
List<OCProcess> processes = Arrays.asList(gson.fromJson(reader, OCProcess[].class));
registerAll(processes);
} catch (IOException e) {
OriginiumCraft.logger.error("Failed to load process recipes for \"" + modId + "\"");
OriginiumCraft.logger.error(e);
}
}
public static void register(OCProcess process) {
if(process==null||process.Materials==null)
return;
switch (process.Materials.size()) {
case 1:
processOneMaterial.add(process);
break;
case 2:
processTwoMaterial.add(process);
break;
case 3:
processThreeMaterial.add(process);
break;
default:
OriginiumCraft.logger.error("Unexpected OCProcess with " + process.Materials.size() + " type of material cannot be loaded.");
break;
}
}
public static void registerAll(List<OCProcess> processes) {
for (OCProcess process :
processes) {
register(process);
}
}
public static OCProcess tryMatch(ItemStackHandler itemStackHandler) {
int materialCount = 0;
List<String> currentRegistryNames = new ArrayList<>();
for (int i = 0; i < 3; i++) {
if (!itemStackHandler.getStackInSlot(i).isEmpty()) {
materialCount++;
currentRegistryNames.add(itemStackHandler.getStackInSlot(i).getItem().getRegistryName().toString());
}
}
switch (materialCount) {
case 1:
return tryMatch(currentRegistryNames, processOneMaterial);
case 2:
return tryMatch(currentRegistryNames, processTwoMaterial);
case 3:
return tryMatch(currentRegistryNames, processThreeMaterial);
default:
return null;
}
}
public static boolean canExactMatch(ItemStackHandler itemStackHandler, OCProcess process) {
int materialCount = 0;
Hashtable<String, Integer> current = new Hashtable<>();
for (int i = 0; i < 3; i++) {
if (!itemStackHandler.getStackInSlot(i).isEmpty()) {
materialCount++;
current.put(itemStackHandler.getStackInSlot(i).getItem().getRegistryName().toString(),
new Integer(itemStackHandler.getStackInSlot(i).getCount()));
}
}
for (OCProcess.ProcessMaterial material : process.Materials
) {
if (!current.containsKey(material.RegistryName) || current.get(material.RegistryName) < material.Quantity)
return false;
}
return true;
}
private static OCProcess tryMatch(List<String> currentMaterialRegistryNames, List<OCProcess> processList) {
for (OCProcess process :
processList) {
if (match(currentMaterialRegistryNames, process))
return process;
}
return null;
}
private static boolean match(List<String> currentMaterialRegistryNames, OCProcess process) {
List<String> requiredMaterialNameList = new ArrayList<>();
for (OCProcess.ProcessMaterial material :
process.Materials) {
requiredMaterialNameList.add(material.RegistryName);
}
return currentMaterialRegistryNames.containsAll(requiredMaterialNameList);
}
}
|
/*
* LumaQQ - Java QQ Client
*
* Copyright (C) 2004 luma <stubma@163.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package edu.tsinghua.lumaqq.ui.dialogs;
import static edu.tsinghua.lumaqq.resource.Messages.*;
import java.util.List;
import edu.tsinghua.lumaqq.models.Group;
import edu.tsinghua.lumaqq.widgets.qstyle.Slat;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.ControlEvent;
import org.eclipse.swt.events.ControlListener;
import org.eclipse.swt.events.MouseAdapter;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Dialog;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.widgets.TableItem;
/**
* <pre>
* 组选择窗口,用在添加一个好友时,选择把这个好友放到哪个组
* </pre>
*
* @author luma
*/
public class SelectGroupDialog extends Dialog {
// 显示组名的列表
private Table table;
// model
private List<Group> model;
// selection
private int selection;
/**
* @param parent
*/
public SelectGroupDialog(Shell parent) {
super(parent);
selection = -1;
}
/**
* 设置model,缺省选择第一项,即“我的好友”
* @param model
*/
public void setModel(List<Group> model) {
this.model = model;
}
/**
* 打开对话框
* @return 选择的组索引
*/
public Group open() {
// 创建shell
Shell parent = getParent();
Shell shell = new Shell(parent, SWT.DIALOG_TRIM | SWT.APPLICATION_MODAL);
shell.setText(select_group_title);
shell.setSize(120, 200);
// 初始化界面布局
initLayout(shell);
// 初始化组名表内容
initTable();
// 打开对话框
shell.layout();
shell.open();
Display display = parent.getDisplay();
// set dialog to center of screen
Rectangle dialogRect = shell.getBounds();
Rectangle displayRect = display.getBounds();
shell.setLocation((displayRect.width-dialogRect.width)/2, (displayRect.height-dialogRect.height)/2);
while (!shell.isDisposed()) {
if (!display.readAndDispatch()) display.sleep();
}
// 如果用户直接关闭,返回我的好友组,如果没有找到我的好友组,返回第一个找到的好友组
if(selection == -1) {
for(Group g : model) {
if(g.isDefaultFriend())
return g;
}
for(Group g : model) {
if(g.isFriendly())
return g;
}
return null;
} else
return model.get(selection);
}
/**
* 在表中添加组名
*/
private void initTable() {
if(model == null)
return;
int i = 0;
for(Group g : model) {
TableItem ti = new TableItem(table, SWT.NONE);
ti.setText(g.name);
ti.setData(new Integer(i++));
}
}
/**
* 初始化界面布局
* @param shell
*/
private void initLayout(final Shell shell) {
// 设置对话框layout
GridLayout layout = new GridLayout();
layout.marginHeight = layout.marginWidth = layout.horizontalSpacing = layout.verticalSpacing = 0;
shell.setLayout(layout);
// 提示标签
Label lblHint = new Label(shell, SWT.CENTER);
lblHint.setText(select_group_label_hint);
lblHint.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
// 组名table
table = new Table(shell, SWT.SINGLE | SWT.FULL_SELECTION | SWT.BORDER);
table.setLayoutData(new GridData(GridData.FILL_BOTH));
table.addControlListener(new ControlListener() {
public void controlResized(ControlEvent e) {
table.getColumn(0).setWidth(table.getClientArea().width);
}
public void controlMoved(ControlEvent e) {
// 没什么要做的
}
});
table.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
selection = table.getSelectionIndex();
if(selection != -1)
selection = (Integer)table.getItem(selection).getData();
}
});
// 表头
new TableColumn(table, SWT.CENTER);
table.setHeaderVisible(false);
// 确定按钮
Slat btnOK = new Slat(shell, SWT.NONE);
btnOK.setText(button_ok);
btnOK.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
btnOK.addMouseListener(new MouseAdapter() {
@Override
public void mouseUp(MouseEvent e) {
if(selection == -1)
MessageDialog.openWarning(shell, message_box_common_warning_title, message_box_please_select_group);
else
shell.close();
}
});
}
}
|
package com.inalab.util;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.inalab.dao.LoginDao;
public class ApplicationLoader {
public static void load() {
ApplicationContext appContext = new ClassPathXmlApplicationContext("applicationContext.xml");
LoginDao loginDao = (LoginDao) appContext.getBean("loginDao");
}
public static void main(String[] args) {
ApplicationLoader.load();
}
}
|
package me.cursedblackcat.dajibot2.diamondseal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Random;
/**
* Represents a diamond seal machine/banner.
* @author Darren Yip
*
*/
public class DiamondSeal {
private String name;
private String commandName;
private ArrayList<DiamondSealEntity> entities;
private int[] rates; //Represents the percent draw rates of the entities of the corresponding index, multiplied by 10. For example, if rates[0] is 10, entities.get(0) has a pull chance of 1 percent. Should add up to 1000.
private int[] rateRanges; //Used in random number selection. Each index is the sum of itself and all the previous indices. For example, if rates is {10, 45, 45, 145} then rateRanges is {10, 55, 100, 245}
public DiamondSeal(String n, String c, ArrayList<DiamondSealEntity> ent, int[] r) {
/*Check if rates add up to 100%*/
int sum = 0;
for(int i : r) {
sum += i;
}
if (sum != 1000) {
throw new IllegalArgumentException("Diamond seal rate does not add up to 100%. Adds up to " + (sum / 10) + "%");
}
/*Assign the variables*/
name = n;
commandName = c;
entities = ent;
rates = r;
/*Calculate the rate ranges to be used for gacha pulls*/
rateRanges = new int[rates.length];
rateRanges[0] = rates[0];
for (int i = 1; i < rates.length; i++) {
rateRanges[i] = rateRanges[i - 1] + rates[i];
}
if (rateRanges[rateRanges.length - 1] != 1000) {
throw new IllegalArgumentException("Upper bound of rate range is not 1000 (100.0%). rateRanges was " + Arrays.toString(rateRanges));
}
}
public String getCommandName() {
return commandName;
}
public DiamondSealCard drawFromMachine() {
Random r = new Random();
int randNum = r.nextInt(1000); //random int from 0 to 999, inclusive
for (int i = 0; i < rateRanges.length; i++) {
if (randNum < rateRanges[i]) {
DiamondSealEntity result = entities.get(i);
if (result instanceof DiamondSealCard) {
return (DiamondSealCard) result;
} else {
return ((DiamondSealSeries) result).getRandomCard();
}
}
}
return new DiamondSealCard("An error has occurred.");
}
public ArrayList<DiamondSealEntity> getEntities(){
return entities;
}
public String[] getEntityNames() {
String[] names = new String[entities.size()];
for (int i = 0; i < entities.size(); i++) {
names[i] = entities.get(i).getName();
}
return names;
}
public String getInfo() {
String response = "**" + name + "**\n\n";
for (int i = 0; i < entities.size(); i++) {
response += entities.get(i).getName() + " - " + (double) rates[i] / 10 + "%\n";
}
return response;
}
public int[] getRates() {
return rates;
}
public String getName() {
return name;
}
}
|
package jassonrm.a8queens;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.GridLayout;
import android.widget.GridView;
import android.widget.ImageView;
public class Board extends AppCompatActivity {
public int board = 0;
private Button startBtn;
private GridView boardGrid;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_board);
boardGrid = findViewById(R.id.board);
boardGrid.setAdapter(new ImageAdapter(this));
startBtn = findViewById(R.id.startBtn);
startBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
board++;
if (board > 92) {
board = 1;
}
Queens.enumerate(8, board);
ImageAdapter adapter = (ImageAdapter) boardGrid.getAdapter();
adapter.notifyDataSetChanged();
}
});
}
}
|
package mx.indra.hpqctestlink.service;
import java.io.File;
import mx.indra.hpqctestlink.beans.MTCP;
public interface HPQCXLSProcessService {
public MTCP processXLS(File excelFile) throws Exception;
}
|
package net.minecraft.network.play.server;
import java.io.IOException;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.network.INetHandler;
import net.minecraft.network.Packet;
import net.minecraft.network.PacketBuffer;
import net.minecraft.network.play.INetHandlerPlayClient;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
public class SPacketUseBed implements Packet<INetHandlerPlayClient> {
private int playerID;
private BlockPos bedPos;
public SPacketUseBed() {}
public SPacketUseBed(EntityPlayer player, BlockPos posIn) {
this.playerID = player.getEntityId();
this.bedPos = posIn;
}
public void readPacketData(PacketBuffer buf) throws IOException {
this.playerID = buf.readVarIntFromBuffer();
this.bedPos = buf.readBlockPos();
}
public void writePacketData(PacketBuffer buf) throws IOException {
buf.writeVarIntToBuffer(this.playerID);
buf.writeBlockPos(this.bedPos);
}
public void processPacket(INetHandlerPlayClient handler) {
handler.handleUseBed(this);
}
public EntityPlayer getPlayer(World worldIn) {
return (EntityPlayer)worldIn.getEntityByID(this.playerID);
}
public BlockPos getBedPosition() {
return this.bedPos;
}
}
/* Location: C:\Users\BSV\AppData\Local\Temp\Rar$DRa6216.20396\Preview\Preview.jar!\net\minecraft\network\play\server\SPacketUseBed.class
* Java compiler version: 8 (52.0)
* JD-Core Version: 1.1.3
*/ |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.