text
stringlengths 10
2.72M
|
|---|
package com.gxtc.huchuan.ui.live.member;
import com.gxtc.commlibrary.data.BaseRepository;
import com.gxtc.huchuan.bean.ChatJoinBean;
import com.gxtc.huchuan.bean.LiveRoomBean;
import com.gxtc.huchuan.bean.SignUpMemberBean;
import com.gxtc.huchuan.http.ApiCallBack;
import com.gxtc.huchuan.http.ApiObserver;
import com.gxtc.huchuan.http.ApiResponseBean;
import com.gxtc.huchuan.http.service.LiveApi;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;
/**
* Created by Gubr on 2017/4/3.
*/
public class MemberManagerSource extends BaseRepository implements MemberManagerContract.Source {
@Override
public void getDatas(HashMap<String,String> map,ApiCallBack<ArrayList<ChatJoinBean.MemberBean>> callBack) {
// ArrayList<SignUpMemberBean> beans = new ArrayList<SignUpMemberBean>() {{
// for (int i = 0; i < 20; i++) {
// SignUpMemberBean signUpMemberBean = new SignUpMemberBean();
// signUpMemberBean.setName("名字i" + i);
// signUpMemberBean.setUserCode("sldkfj");
// signUpMemberBean.setHeadPic("https://gss0.baidu.com/9vo3dSag_xI4khGko9WTAnF6hhy/zhidao/pic/item/8ad4b31c8701a18bbef9f231982f07082838feba.jpg");
// signUpMemberBean.setIsBlack("1");
// signUpMemberBean.setIsBlock("1");
// add(signUpMemberBean);
// }
// }};
// callBack.onSuccess(beans);
addSub(LiveApi.getInstance().getlistJoinMember(map).subscribeOn(Schedulers.io()).observeOn
(AndroidSchedulers.mainThread()).subscribe(new
ApiObserver<ApiResponseBean<ArrayList<ChatJoinBean.MemberBean>>>(callBack)));
}
}
|
/*
* @(#)ScormPreviewBean.java
*
* Copyright(c) 2006, Jin-pil Chung
* All rights reserved.
*/
package com.ziaan.scorm2004;
import java.sql.PreparedStatement;
import java.util.ArrayList;
import java.util.List;
import java.util.Vector;
import com.ziaan.library.ConfigSet;
import com.ziaan.library.DataBox;
import com.ziaan.library.DBConnectionManager;
import com.ziaan.library.ErrorManager;
import com.ziaan.library.ListSet;
import com.ziaan.library.RequestBox;
import com.ziaan.library.SQLString;
import com.ziaan.scorm2004.runtime.client.SequencingEngineBean;
/**
* 마스터폼 - 맛보기 학습창 Bean Class
*
* @version 1.0 2006. 4. 19.
* @author Jin-pil Chung
*
*/
public class ScormPreviewBean
{
/**
* 맛보기 설정 화면
*
* @param box
* @return ArrayList
* @throws Exception
*/
public List selectPreviewOrgList(RequestBox box) throws Exception
{
DBConnectionManager connMgr = null;
ListSet ls = null;
ListSet ls1 = null;
List resultList = null;
String sql = "";
try
{
connMgr = new DBConnectionManager();
resultList = new ArrayList();
String v_subj = box.getString("p_subj");
String v_courseCode = "";
String v_orgID = "";
sql =
"\n SELECT subj, course_code, org_id, ord " +
"\n FROM tz_subj_contents " +
"\n WHERE subj = ':p_subj' " +
"\n ORDER BY ord ";
sql = sql.replaceAll( ":p_subj", v_subj );
ls = connMgr.executeQuery( sql );
while ( ls.next() )
{
List list = new ArrayList();
v_courseCode = ls.getString("course_code");
v_orgID = ls.getString("org_id");
sql =
"\n SELECT " +
"\n LEVEL, ORG_TREE_ORD, ORG_ID, ORG_TITLE, COURSE_CODE, " +
"\n ITEM_ID, ITEM_PID, ITEM_ID_REF, ITEM_PARAMETERS, ITEM_TITLE, " +
"\n ITEM_META, OBJ_ID, TREE_ORD, PREVIOUS, NEXT, EXIT, ABANDON, " +
"\n RES_ID, RES_HREF, RES_SCORM_TYPE, RES_META, UPLOAD_PATH " +
"\n FROM " +
"\n ( " +
"\n SELECT " +
"\n A.TREE_ORD as ORG_TREE_ORD, A.ORG_ID, A.ORG_TITLE, A.COURSE_CODE, " +
"\n B.ITEM_ID, B.ITEM_PID, B.ITEM_ID_REF, B.ITEM_PARAMETERS, B.ITEM_TITLE, " +
"\n B.META_LOCATION ITEM_META, B.OBJ_ID, B.TREE_ORD, B.PREVIOUS, B.NEXT, B.EXIT, B.ABANDON, " +
"\n C.RES_ID, C.RES_HREF, C.RES_SCORM_TYPE, C.META_LOCATION RES_META, D.UPLOAD_PATH " +
"\n FROM " +
"\n TYS_ORGANIZATION A, TYS_ITEM B, TYS_RESOURCE C, TYS_COURSE D " +
"\n WHERE " +
"\n A.COURSE_CODE = ':course_code' " +
"\n AND A.COURSE_CODE = B.COURSE_CODE " +
"\n AND B.COURSE_CODE = D.COURSE_CODE " +
"\n AND A.ORG_ID = B.ORG_ID " +
"\n AND B.COURSE_CODE = C.COURSE_CODE(+) " +
"\n AND B.ORG_ID = C.ORG_ID(+) " +
"\n AND B.ITEM_ID = C.ITEM_ID(+) " +
"\n AND B.ITEM_ID_REF = C.RES_ID(+) " +
"\n ) T " +
"\n START WITH " +
"\n ITEM_PID = ':org_id' " +
"\n CONNECT BY " +
"\n PRIOR ITEM_ID = ITEM_PID " +
"\n ORDER SIBLINGS BY TREE_ORD ";
sql = sql.replaceAll( ":course_code", v_courseCode );
sql = sql.replaceAll( ":org_id", v_orgID );
ls1 = connMgr.executeQuery( sql );
while ( ls1.next() )
{
list.add( ls1.getDataBox() );
}
resultList.add( list );
}
}
catch (Exception ex)
{
ErrorManager.getErrorStackTrace( ex, box, sql );
throw new Exception("sql = " + sql + "\r\n" + ex.getMessage());
}
finally
{
if(ls != null) { try { ls.close(); }catch (Exception e) {} }
if(ls1 != null) { try { ls1.close(); }catch (Exception e) {} }
if(connMgr != null) { try { connMgr.freeConnection(); }catch (Exception e10) {} }
}
return resultList;
}
/**
* 맛보기설정 수정
*
* @param box
* @return
* @throws Exception
*/
public int updatePreview( RequestBox box ) throws Exception
{
DBConnectionManager connMgr = null;
PreparedStatement pstmt = null;
String sql = "";
int isOk = 0;
try
{
connMgr = new DBConnectionManager();
connMgr.setAutoCommit(false);
String v_subj = box.getString("p_subj");
Vector v_objID = box.getVector( "p_obj_id" );
String v_userid = box.getSession("userid");
// delete
sql =
"\n delete from tz_previewobj " +
"\n where subj = " + SQLString.Format(v_subj);
isOk = connMgr.executeUpdate( sql );
// insert
sql =
"\n insert into tz_previewobj " +
"\n ( subj, oid, ordering, luserid, ldate ) " +
"\n values ( ?, ?, ?, ?, TO_CHAR( sysdate, 'YYYYMMDDHH24MISS' ) ) ";
pstmt = connMgr.prepareStatement(sql);
for ( int i=0; i<v_objID.size(); i++ )
{
pstmt.setString( 1, v_subj );
pstmt.setString( 2, (String) v_objID.get(i) );
pstmt.setInt( 3, i+1 );
pstmt.setString( 4, v_userid );
isOk = pstmt.executeUpdate();
if ( isOk < 0 )
{
connMgr.rollback();
return -1;
}
}
connMgr.commit();
}
catch ( Exception ex )
{
connMgr.rollback();
ErrorManager.getErrorStackTrace(ex, box, sql);
throw new Exception("sql = " + sql + "\r\n" + ex.getMessage() );
}
finally
{
if ( pstmt != null ) { try { pstmt.close(); } catch ( Exception e ) { } }
if ( connMgr != null ) { try { connMgr.setAutoCommit(true); } catch (Exception e2) {} }
if ( connMgr != null ) { try { connMgr.freeConnection(); } catch (Exception e10) {} }
}
return isOk;
}
/**
* 맛보기로 설정된 Item을 반환한다.
*
* @param box
* @return
* @throws Exception
*/
public List selectPreviewSelectedItem( RequestBox box ) throws Exception
{
DBConnectionManager connMgr = null;
ListSet ls = null;
ArrayList list = null;
String sql = "";
try
{
connMgr = new DBConnectionManager();
list = new ArrayList();
String v_subj = box.getString("p_subj");
sql =
"\n SELECT OID " +
"\n FROM tz_previewobj " +
"\n WHERE subj = ':subj' ";
sql = sql.replaceAll( ":subj", v_subj );
ls = connMgr.executeQuery( sql );
while ( ls.next() )
{
list.add( ls.getString("oid") );
}
}
catch (Exception ex)
{
ErrorManager.getErrorStackTrace( ex, box, sql );
throw new Exception("sql = " + sql + "\r\n" + ex.getMessage());
}
finally
{
if(ls != null) { try { ls.close(); }catch (Exception e) {} }
if(connMgr != null) { try { connMgr.freeConnection(); }catch (Exception e10) {} }
}
return list;
}
/**
* 맛보기 페이지 Url을 반환한다.
*
* @param box
* @return
*/
public String getPreviewUrl( RequestBox box ) throws Exception
{
DBConnectionManager connMgr = null;
ListSet ls = null;
String sql = "";
String previewUrl = "";
String webPath = "";
try
{
connMgr = new DBConnectionManager();
String v_subj = box.getString("p_subj");
String v_ordering = box.getStringDefault("p_ordering", "1" );
webPath = box.getString("p_webpath");
sql =
"\n SELECT " +
"\n a.course_code, a.item_id, a.item_parameters, b.res_href, " +
"\n c.ordering, c.oid, e.upload_path " +
"\n FROM " +
"\n tys_item a, tys_resource b, tz_previewobj c, " +
"\n (SELECT subj, course_code, org_id FROM tz_subj_contents WHERE subj = ':subj') d, " +
"\n tys_course e " +
"\n WHERE 1 = 1 " +
"\n AND a.course_code = b.course_code " +
"\n AND b.course_code = d.course_code " +
"\n AND d.course_code = e.course_code " +
"\n AND c.subj = d.subj " +
"\n AND a.org_id = b.org_id " +
"\n AND b.org_id = d.org_id " +
"\n AND a.item_id = b.item_id " +
"\n AND a.obj_id = c.oid " +
"\n AND c.ordering = ':ordering' ";
sql = sql.replaceAll( ":subj", v_subj );
sql = sql.replaceAll( ":ordering", v_ordering );
ls = connMgr.executeQuery( sql );
String courseCode = "";
if ( ls.next() )
{
courseCode = ls.getString("course_code");
previewUrl = ls.getString("res_href") + ls.getString("item_parameters");
}
if ( webPath.equals("") )
{
ConfigSet conf = new ConfigSet();
SequencingEngineBean seb = new SequencingEngineBean();
String uploadCode = seb.selectUploadPath( courseCode );
String webPathKey = "SCORM2004.WEBPATH." + uploadCode;
if ( !uploadCode.equals("") )
{
webPath = conf.getProperty( webPathKey );
box.put( "p_webpath", webPath );
}
else
{
webPath = "";
}
}
}
catch (Exception ex)
{
ErrorManager.getErrorStackTrace( ex, box, sql );
throw new Exception("sql = " + sql + "\r\n" + ex.getMessage());
}
finally
{
if(ls != null) { try { ls.close(); }catch (Exception e) {} }
if(connMgr != null) { try { connMgr.freeConnection(); }catch (Exception e10) {} }
}
return webPath + previewUrl;
}
public String[] getMinMaxOrdering( RequestBox box ) throws Exception
{
DBConnectionManager connMgr = null;
ListSet ls = null;
String sql = "";
String minOrdering = "";
String maxOrdering = "";
try
{
connMgr = new DBConnectionManager();
String v_subj = box.getString("p_subj");
sql =
"\n SELECT MIN(ordering) as minOrdering, MAX (ordering) as maxOrdering " +
"\n FROM tz_previewobj " +
"\n WHERE subj = " + SQLString.Format( v_subj );
ls = connMgr.executeQuery( sql );
if ( ls.next() )
{
minOrdering = ls.getString("minOrdering");
maxOrdering = ls.getString("maxOrdering");
}
}
catch (Exception ex)
{
ErrorManager.getErrorStackTrace( ex, box, sql );
throw new Exception("sql = " + sql + "\r\n" + ex.getMessage());
}
finally
{
if(ls != null) { try { ls.close(); }catch (Exception e) {} }
if(connMgr != null) { try { connMgr.freeConnection(); }catch (Exception e10) {} }
}
return new String[]{ minOrdering, maxOrdering };
}
}
|
package com.demo.jsf;
import com.sun.faces.config.ConfigureListener;
import com.sun.faces.config.FacesInitializer;
import com.sun.faces.config.InitFacesContext;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.ServletContextInitializer;
import org.springframework.boot.web.servlet.ServletListenerRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.web.context.ServletContextAware;
import javax.faces.bean.ManagedBean;
import javax.faces.webapp.FacesServlet;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import java.util.HashSet;
import java.util.Set;
@SpringBootApplication
public class JSFDemoApplication {
public static void main(String[] args) {
SpringApplication.run(JSFDemoApplication.class, args);
}
@Bean
public ServletRegistrationBean facesServletRegistration() {
ServletRegistrationBean registration = new ServletRegistrationBean(
new FacesServlet(), "*.xhtml");
registration.setLoadOnStartup(1);
return registration;
}
@Bean
public ServletListenerRegistrationBean<ConfigureListener> jsfConfigureListener() {
return new ServletListenerRegistrationBean<ConfigureListener>(
new ConfigureListener());
}
}
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package hdfcraft;
import java.io.IOException;
import java.io.ObjectInputStream;
import hdfcraft.minecraft.Material;
/**
*
* @author pepijn
*/
public class GroundCoverLayer extends CustomLayer {
public GroundCoverLayer(String name, MixedMaterial material, int colour) {
super(name, "a 1 block layer of " + name + " on top of the terrain", DataSize.BIT, 30, colour);
mixedMaterial = material;
exporter = new GroundCoverLayerExporter(this);
}
@Override
public void setName(String name) {
super.setName(name);
setDescription("a " + thickness + " block layer of " + name + " on top of the terrain");
}
public MixedMaterial getMaterial() {
return mixedMaterial;
}
public void setMaterial(MixedMaterial material) {
mixedMaterial = material;
}
public int getThickness() {
return thickness;
}
public void setThickness(int thickness) {
this.thickness = thickness;
setDescription("a " + thickness + " block layer of " + getName() + " on top of the terrain");
}
public int getEdgeWidth() {
return edgeWidth;
}
public void setEdgeWidth(final int edgeWidth) {
this.edgeWidth = edgeWidth;
}
public EdgeShape getEdgeShape() {
return edgeShape;
}
public void setEdgeShape(EdgeShape edgeShape) {
if (edgeShape == null) {
throw new NullPointerException();
}
this.edgeShape = edgeShape;
}
public NoiseSettings getNoiseSettings() {
return noiseSettings;
}
public void setNoiseSettings(NoiseSettings noiseSettings) {
this.noiseSettings = noiseSettings;
}
public boolean isSmooth() {
return smooth;
}
public void setSmooth(boolean smooth) {
this.smooth = smooth;
}
// @Override
public LayerExporter<GroundCoverLayer> getExporter() {
return exporter;
}
// Comparable
@Override
public int compareTo(Layer layer) {
if (priority < layer.priority) {
return -1;
} else if (priority > layer.priority) {
return 1;
} else if ((layer instanceof GroundCoverLayer) && (Math.abs(((GroundCoverLayer) layer).thickness) != Math.abs(thickness))) {
return Math.abs(((GroundCoverLayer) layer).thickness) - Math.abs(thickness);
} else {
return getId().compareTo(layer.getId());
}
}
private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
in.defaultReadObject();
exporter = new GroundCoverLayerExporter(this);
// Legacy support
if (colour != 0) {
setColour(colour);
colour = 0;
}
if (thickness == 0) {
thickness = 1;
}
if (mixedMaterial == null) {
mixedMaterial = MixedMaterial.create(material);
material = null;
}
if (edgeShape == null) {
edgeWidth = 1;
if (thickness == 1) {
edgeShape = EdgeShape.SHEER;
} else {
edgeShape = EdgeShape.ROUNDED;
}
}
}
@Deprecated
private Material material;
@Deprecated
private int colour;
private int thickness = 1;
private int edgeWidth = 1;
private MixedMaterial mixedMaterial;
private EdgeShape edgeShape = EdgeShape.SHEER;
private NoiseSettings noiseSettings;
private boolean smooth;
private transient GroundCoverLayerExporter exporter;
private static final long serialVersionUID = 1L;
public enum EdgeShape {SHEER, LINEAR, SMOOTH, ROUNDED}
}
|
package com.android.recommender.movie;
import java.util.ArrayList;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.android.recommender.HTTPTransfer;
import com.android.recommender.model.Movie;
import com.example.recommender.R;
import android.app.Activity;
import android.app.Fragment;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.AdapterView.OnItemClickListener;
public class ListMovieFragment extends Fragment {
private List<Movie> movieList = new ArrayList<Movie>();
private ProgressBar progressBar1;
private View empty;
private ListView listView1;
private Context context;
onTitleSearchListener cbTitleSearch;
private String queryUrl, userName;
public ListMovieFragment(String userName, String queryUrl){
this.userName = userName;
this.queryUrl = queryUrl;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
context = container.getContext();
View rootView = inflater.inflate(R.layout.fragment_list_movie, container, false);
listView1 = (ListView) rootView.findViewById(R.id.listView1);
progressBar1 = (ProgressBar) rootView.findViewById(R.id.progressBar1);
empty = rootView.findViewById(R.id.empty);
listView1.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Movie movie = movieList.get(position);
cbTitleSearch.onTitleSearch(movie.getTitle());
Log.i("selectedMovie", position + " " + movie.getTitle());
}
});
HTTPListMovie rest = new HTTPListMovie();
rest.execute(queryUrl);
return rootView;
}
public interface onTitleSearchListener {
public void onTitleSearch(String movieTitle);
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
cbTitleSearch = (onTitleSearchListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement onTitleSearchListener");
}
}
class HTTPListMovie extends HTTPTransfer{
@Override
protected void onPostExecute(String result) {
try {
JSONArray jArray = new JSONArray(result);
int nMovies = jArray.length();
for (int i = 0; i < nMovies; i++) {
JSONObject json_data = jArray.getJSONObject(i);
Movie movie = new Movie();
movie.setId(json_data.getInt("id"));
movie.setTitle(json_data.getString("title"));
movie.setPubYear(json_data.getInt("pubYear"));
movie.setGenre(json_data.getString("genre"));
movie.setRating(json_data.getString("rating"));
movieList.add(movie);
}
if(nMovies == 0){
empty.setVisibility(View.VISIBLE);
}
MovieArrayAdapter adapter = new MovieArrayAdapter(context, movieList, R.layout.list_item_movie);
listView1.setAdapter(adapter);
} catch (JSONException e) {
Log.e("Error", e.toString());
}
progressBar1.setVisibility(View.INVISIBLE);
}
}
}
|
package com.fanfte.rpc.spring;
import lombok.Data;
/**
* Created by tianen on 2018/11/8
*
* @author fanfte
* @date 2018/11/8
**/
@Data
public class User {
String id;
private String name;
private String email;
private int age;
}
|
package com.joalib.donate.action;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.joalib.DAO.DonateDAO;
import com.joalib.DTO.ActionForward;
import com.joalib.DTO.Donate_ApplicationDTO;
public class DonateApplicationAddAction implements Action {
@Override
public ActionForward execute(HttpServletRequest request, HttpServletResponse response) throws Exception {
ActionForward forward=null;
ServletContext context = request.getServletContext();
int donate_no = Integer.parseInt(request.getParameter("donate_no"));
String donate_application_member = request.getParameter("donateApplicationMember");
String donate_writer = request.getParameter("donateWriter");
Donate_ApplicationDTO dto = new Donate_ApplicationDTO();
dto.setDonate_no(donate_no);
dto.setDonate_application_member(donate_application_member);
dto.setDonate_writer(donate_writer);
DonateDAO dao = DonateDAO.getinstance();
int i = dao.DonateApplicationAdd(dto);
if(i > 0) {
forward = new ActionForward();
forward.setRedirect(true);
forward.setPath("Donate_read.jsp?donate_no="+donate_no);
}
return forward;
}
}
|
package com.orsegrups.splingvendas.model;
import com.j256.ormlite.field.DatabaseField;
import com.j256.ormlite.table.DatabaseTable;
import java.io.Serializable;
/**
* Created by filipeamaralneis on 17/12/16.
*/
@DatabaseTable(tableName = "pedido_produto" )
public class PedidoProduto implements Serializable {
@DatabaseField(generatedId=true)
private Integer idPedido;
@DatabaseField(foreign = true)
private Pedido pedido;
@DatabaseField(foreign = true)
private Produto produto;
@DatabaseField
private Integer quantidade;
public PedidoProduto() {
}
public Integer getIdPedido() {
return idPedido;
}
public void setIdPedido(Integer idPedido) {
this.idPedido = idPedido;
}
public Pedido getPedido() {
return pedido;
}
public void setPedido(Pedido pedido) {
this.pedido = pedido;
}
public Produto getProduto() {
return produto;
}
public void setProduto(Produto produto) {
this.produto = produto;
}
public Integer getQuantidade() {
return quantidade;
}
public void setQuantidade(Integer quantidade) {
this.quantidade = quantidade;
}
}
|
package life.zhangwq.community.community.dto;
import lombok.Data;
/**
* Created by zhangwq on 2019/10/12.
*/
@Data
public class GithubUser {
private String name;
private Long id;
private String bio; // descriptin
private String avatarUrl;
}
|
package mine;
public class test {
public static void main(String[] args) {
Mine mine = new Mine();
mine.createFan();
mine.createFan();
mine.createFan();
mine.createFan();
mine.createFan();
mine.startFan(0);
mine.stopFan(0);
mine.startFan(0);
mine.stopFan(0);
mine.startFan(3);
mine.startFan(2);
mine.stopFan(3);
mine.stopFan(2);
mine.startFan(0);
mine.stopFan(0);
}
}
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package Trivia;
import java.awt.BorderLayout;
import java.awt.Button;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
/**
*
* @author adeea0332
*/
class PanMainGame extends JPanel implements ActionListener {
JButton btnBack, btnNext, btn;
JRadioButton[] radioButton = new JRadioButton[4];
public static PanMainGame panMainGame = new PanMainGame();
public static PanMain panMain = new PanMain();
int i = 0;
public PanMainGame() {
btnBack = new JButton("Back");
btnNext = new JButton("Next");;
btn = new JButton("btn");
btnBack.addActionListener(this);
btnNext.addActionListener(this);
add(btnBack);
add(btnNext);
radioButton[0] = new JRadioButton("Question A");
radioButton[1] = new JRadioButton("Question B");
radioButton[2] = new JRadioButton("Question C");
radioButton[3] = new JRadioButton("Question D");
ButtonGroup bG = new ButtonGroup();
for (int i = 0; i < radioButton.length; i++) {
bG.add(radioButton[i]);
this.add(radioButton[i]);
}
}
public void actionPerformed(ActionEvent event) {
if (event.getSource() == btnNext) {
add(btn);
}
}
}
|
package com.zundrel.ollivanders.common.feature;
import net.minecraft.block.sapling.LargeTreeSaplingGenerator;
import net.minecraft.world.gen.feature.AbstractTreeFeature;
import net.minecraft.world.gen.feature.DefaultFeatureConfig;
import java.util.Random;
public class RedwoodSaplingGenerator extends LargeTreeSaplingGenerator {
@Override
protected AbstractTreeFeature<DefaultFeatureConfig> createTreeFeature(Random random) {
return new RedwoodTreeFeature(DefaultFeatureConfig::deserialize, true);
}
@Override
protected AbstractTreeFeature<DefaultFeatureConfig> createLargeTreeFeature(Random random) {
return new MegaRedwoodTreeFeature(DefaultFeatureConfig::deserialize, false, random.nextBoolean());
}
}
|
package com.test;
import com.test.base.ListNode;
/**
* Given a sorted linked list, delete all nodes that have duplicate numbers,
* leaving only distinct numbers from the original list.
* 给一个排序好的链表,删除所有重复的节点
*
* Example 1:
* Input: 1->2->3->3->4->4->5
* Output: 1->2->5
*
* Example 2:
* Input: 1->1->1->2->3
* Output: 2->3
*
* @author YLine
*
* 2019年8月20日 上午9:45:50
*/
public class SolutionA
{
public ListNode deleteDuplicates(ListNode head)
{
ListNode result = new ListNode(-1);
result.next = head;
// 删除逻辑
ListNode temp = result;
boolean isDelete = false;
while (null != temp && null != temp.next && null != temp.next.next)
{
if (temp.next.val == temp.next.next.val)
{
isDelete = true;
temp.next = temp.next.next;
}
else
{
if (isDelete)
{
isDelete = false;
temp.next = temp.next.next;
}
else
{
temp = temp.next;
}
}
}
if (isDelete)
{
isDelete = false;
temp.next = temp.next.next;
}
return result.next;
}
}
|
package containers;
import java.awt.Rectangle;
import java.util.ArrayList;
import java.util.HashMap;
import com.rapplebob.ArmsAndArmorChampions.AAA_C;
public class Container {
public Rectangle conSurf = new Rectangle(0, 0, 0, 0);
public String TITLE = "";
public String ID = "";
public int conSize = 20;
public boolean ACTIVE = false;
public ContainerState STATE = ContainerState.STATIC;
public ContainerType TYPE = ContainerType.DEFAULT;
public HashMap<String, Content> CONTENT = new HashMap<String, Content>();
public Activator EXIT = new Activator();
private Rectangle BOX = new Rectangle(0, 0, 0, 0);
public Alignment ALIGNMENT = Alignment.CENTER;
public Fill FILL = Fill.NONE;
public boolean DECORATED = true;
public float TRANSPARENCY = 1.0f;
public boolean BACKGROUND = true;
public boolean MOVING = false;
public void update(){
conSurf = new Rectangle(0, BOX.height - conSize, BOX.width, conSize);
EXIT.set(ActivatorType.BUTTON, "EXITACTFROMCONTAINER", "X", "", "switchCon_" + ID, new Rectangle(conSurf.width - conSize, conSurf.y, conSize, conSize));
for(int i = 0; i < CONTENT.size(); i++){
CONTENT.get(i).update();
}
}
public Container(String title, String id, boolean active, int x, int y, int width, int height, int controllerSize, ContainerState state, ContainerType type, Alignment alig, Fill fill, boolean decorated, float trans, boolean background){
ID = id;
TITLE = title;
ACTIVE = active;
STATE = state;
TYPE = type;
conSize = controllerSize;
if(width + Fill.getWidth(AAA_C.w, fill) < 50){
width = 50;
}
BOX = new Rectangle(x, y, width + Fill.getWidth(AAA_C.w, fill), height + Fill.getHeight(AAA_C.h, fill));
ALIGNMENT = alig;
FILL = fill;
DECORATED = decorated;
TRANSPARENCY = trans;
BACKGROUND = background;
update();
}
public void add(Content C){
C.Y += getBox().height;
if(DECORATED){
C.Y -= conSize;
}
CONTENT.put(C.ID, C);
}
public void switchState(){
if(ACTIVE){
ACTIVE = false;
}else{
ACTIVE = true;
}
}
public boolean justMoved = false;
public boolean move(int diffX, int diffY){
boolean movetofront = false;
if(ACTIVE && MOVING && STATE != ContainerState.STATIC){
movetofront = true;
justMoved = true;
BOX.x += diffX;
BOX.y += diffY;
update();
}
return movetofront;
}
public void stop(){
MOVING = false;
justMoved = false;
}
public boolean collides(Rectangle r){
if(ACTIVE){
if(r.intersects(getBox())){
return true;
}else{
return false;
}
}else{
return false;
}
}
public Rectangle getBox(){
return new Rectangle(BOX.x + Alignment.getX(AAA_C.w, ALIGNMENT), BOX.y + Alignment.getY(AAA_C.h, ALIGNMENT), BOX.width, BOX.height);
}
public Rectangle getConBox(){
Rectangle getbox = getBox();
return new Rectangle(getbox.x, getbox.y + getbox.height - conSize, getbox.width, conSize);
}
public void mouseMoved(Rectangle mouse){
for(int i = 0; i < CONTENT.size(); i++){
CONTENT.get(i).mouseMoved(mouse, getBox().x, getBox().y);
}
}
public boolean getActById(String id, Activator A){
boolean temp = false;
for(int i = 0; i < CONTENT.size(); i++){
Menu m = (Menu) CONTENT.get(i);
if(m.TYPE == ContentType.MENU){
if(m.getActById(id, A)){
temp = true;
break;
}
}
}
return temp;
}
}
|
package com.javalintest.backend.controllers;
import com.javalintest.backend.config.Constants;
import com.javalintest.backend.managers.UsersManager;
import com.javalintest.backend.model.request.UserRequestModel;
import com.javalintest.backend.model.response.Result;
import com.javalintest.backend.model.response.UserExistsResult;
import io.javalin.http.Context;
import io.javalin.plugin.openapi.annotations.HttpMethod;
import io.javalin.plugin.openapi.annotations.OpenApi;
import io.javalin.plugin.openapi.annotations.OpenApiContent;
import io.javalin.plugin.openapi.annotations.OpenApiRequestBody;
import io.javalin.plugin.openapi.annotations.OpenApiResponse;
import javax.inject.Inject;
import javax.inject.Singleton;
@Singleton
public class UserStatusController extends UserController {
private final UsersManager manager;
@Inject
public UserStatusController(final UsersManager manager) {
this.manager = manager;
}
@OpenApi(
summary = "Check if user exists",
operationId = "doesUserExist",
path = "/" + ROOT_PATH + Constants.USER_EXISTS_PATH,
method = HttpMethod.GET,
tags = {"User"},
requestBody = @OpenApiRequestBody(content = {@OpenApiContent(from = UserRequestModel.class)}),
responses = {
@OpenApiResponse(
status = "200",
content = {@OpenApiContent(from = UserExistsResult.class)}),
@OpenApiResponse(
status = "400",
content = {@OpenApiContent(from = Result.class)})
})
public void doesUserExist(final Context ctx) {
final UserRequestModel userModel = validateBody(ctx, UserRequestModel.class);
if (userModel == null) {
return;
}
final Result result = manager.userExists(userModel);
ctx.status(result.getStatusCode());
ctx.json(result);
}
}
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package poker;
/**
*
* @author skorp
*/
public class Move {
public enum Type {
SB, BB, FOLD, CHECK, CALL, RAISE
}
public Type type;
public int value;
public Move(Type type, int value) {
this.type = type;
if (type != Type.FOLD && type != Type.CHECK) {
this.value = value;
}
}
@Override
public String toString() {
if (type != Type.FOLD && type != Type.CHECK) {
return type + "(" + value + ")";
}
return type.toString();
}
}
|
package com.manuvastra;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.MotionEvent;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
public class ReviewCart extends AppCompatActivity {
private static final String TAG = ReviewCart.class.getSimpleName();
private ReviewAdapter adapter;
List<CartItem> cartItems = new ArrayList<CartItem>();
private TextView totalPrice;
TextView address1;
TextView address;
TextView payment1;
TextView payment;
LinearLayout linearLayout;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_review_cart);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
address1 = (TextView) findViewById(R.id.address1);
address = (TextView) findViewById(R.id.address);
payment1 = (TextView) findViewById(R.id.payment1);
payment = (TextView) findViewById(R.id.payment);
linearLayout = (LinearLayout) findViewById(R.id.checkout1);
toolbar.setNavigationOnClickListener(
new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(),BrowseActivity.class);
startActivity(intent);
}
}
);
ListView itemListView = (ListView) findViewById(R.id.item_list);
cartItems = Cart.getCart().getCartItemsList();
adapter = new ReviewAdapter(
this,
R.layout.content_dipslay_cart, // custom layout for the list
cartItems
);
itemListView.setAdapter(adapter);
adapter.notifyDataSetChanged();
totalPrice = (TextView) findViewById(R.id.total_price);
address1.setVisibility(View.VISIBLE);
address.setVisibility(View.VISIBLE);
payment1.setVisibility(View.VISIBLE);
payment.setVisibility(View.VISIBLE);
linearLayout.setVisibility(View.VISIBLE);
setPrice();
itemListView.setOnTouchListener(new ListView.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
int action = event.getAction();
switch (action) {
case MotionEvent.ACTION_DOWN:
// Disallow ScrollView to intercept touch events.
v.getParent().requestDisallowInterceptTouchEvent(true);
break;
case MotionEvent.ACTION_UP:
// Allow ScrollView to intercept touch events.
v.getParent().requestDisallowInterceptTouchEvent(false);
break;
}
// Handle ListView touch events.
v.onTouchEvent(event);
return true;
}
});
}
public void checkoutButtonClick(View view) {
placeOrder();
}
public void placeOrder() {
//tracker
//TrackerEvents.trackAll(tracker);
//tracker.pauseEventTracking();
Intent intent = new Intent(this, FinishActivity.class);
startActivity(intent);
// Context context = getApplicationContext();
// Tracker tracker = DemoUtils.getAndroidTrackerClassic(context, getCallback());
// //tracker.resumeEventTracking();
//
//
// Emitter e = tracker.getEmitter();
// String uri = "10.209.47.193:58080";
// HttpMethod method = HttpMethod.POST;
// RequestSecurity security = RequestSecurity.HTTP;
//
// if (!e.getEmitterStatus()) {
// e.setEmitterUri(uri);
// e.setRequestSecurity(security);
// e.setHttpMethod(method);
// }
// TextView totalPriceView = (TextView) findViewById(R.id.total_price_review);
// Double totalPrice = Double.parseDouble(totalPriceView.getText().toString());
List<CartItem> items = Cart.getCart().getCartItemsList();
CartItem item;
for(int i=0;i<items.size();i++){
item = items.get(i);
}
}
public void setPrice(){
runOnUiThread(new Runnable() {
@Override
public void run() {
totalPrice.setText(Cart.getCart().getPrice()+"");
}
});
}
}
|
package com.pooyaco.gazelle.web.bundle;
/**
* Created by h.rostami on 2015/03/18.
*/
public class GazelleBundle_en extends GazelleResourceBundle<GazelleResources> {
public GazelleBundle_en() {
super();
}
}
|
package ninja.pelirrojo.takibat.irc;
import java.util.Formattable;
import java.util.Formatter;
public class Server extends User implements Formattable{
private final String name;
public Server(String a){
super(a,a,a);
name = a;
}
public String toString(){
return name;
}
public void formatTo(Formatter f, int l, int w, int p) {
}
}
|
/**
* Tag class
* @author Amy Guinto
* @author Aziz Rahman
*/
package model;
import java.io.Serializable;
public class Tag implements Serializable {
private String type;
private String value;
/**
* Tag constructor initializes tag type-value pair
* @param type
* @param value
*/
public Tag(String type, String value) {
this.type = type;
this.value = value;
}
/**
* getType() is a getter for the tag type
* @return String
*/
public String getType() {
return type;
}
/**
* getValue() is a getter for the tag value
* @return String
*/
public String getValue() {
return value;
}
/**
* setType() is a setter for the tag type
* @param type
*/
public void setType(String type){
this.type = type;
}
/**
* setVal() is a setter for the tag value
* @param val
*/
public void setVal(String val){
this.value = val;
}
/**
* equalsType(String) checks if types of tags are equals
* @param type
* @return boolean
*/
public boolean equalsType(String type) {
return type.equalsIgnoreCase(type);
}
/**
* equalsVal(String) checks if values of tags are equal
* @param val
* @return boolean
*/
public boolean equalsVal(String val){
return value.equalsIgnoreCase(val);
}
}
|
package com.spring.professional.exam.tutorial.module03.question04.jdbc.callback.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.spring.professional.exam.tutorial.module03.question04.jdbc.callback.dao.EmployeeDao;
@Service
public class EmployeeReportService {
@Autowired
EmployeeDao employeeDao ;
public void printReport() {
System.out.println("Report Printing Starting ");
System.out.println("findAverageSalaryModernImplementation = "+ employeeDao.findAverageSalaryModernImplementation());
System.out.println("findAverageSalaryRowByRow = "+employeeDao.findAverageSalaryRowByRow());
System.out.println("findAverageSalarySqlLevel = "+ employeeDao.findAverageSalarySqlLevel());
System.out.println("findEmployeeIdFromEmail = "+ employeeDao.findEmployeeIdFromEmail("John.Doe@corp.com"));
System.out.println("findAverageSalaryCalculatedOnEntireResultSet = "+ employeeDao.findAverageSalaryCalculatedOnEntireResultSet());
System.out.println("Employees List = ");
employeeDao.findEmployees().forEach(System.out::println);
System.out.println("Ending Report Printing");
}
}
|
package com.oa.menu.controller;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import com.oa.menu.form.MenuItem;
import com.oa.menu.service.MenuItemService;
import com.oa.page.PageUtils;
import com.oa.page.form.Page;
@Controller
@RequestMapping(value="/setting/menuItemManager")
public class MenuItemController {
@Autowired
private MenuItemService menuItemService;
@RequestMapping(value="/addMenuItem")
public String addMenuItem(@ModelAttribute("menuItem") MenuItem menuItem) {
menuItemService.addMenuItem(menuItem);
return "redirect:/setting/menuItemManager/listMenuItems";
}
@RequestMapping(value="/listMenuItems")
public String selectAllMenuItem(Map<String,Object> map,HttpServletRequest request) {
String pageNo = request.getParameter("pageNo");
pageNo=pageNo==null?"1":pageNo;
String pageSize = request.getParameter("pageSize");
pageSize=pageSize==null?"10":pageSize;
map.put("menuItem", new MenuItem());
Page<MenuItem> page = PageUtils.createPage(Integer.parseInt(pageSize), menuItemService.selectAllMenuItem().size(),Integer.parseInt(pageNo));
List<MenuItem> menuItemList = menuItemService.selectMenuItemsByPage(page);
map.put("menuItemList", menuItemList);
map.put("page", page);
return "/setting/menuItemManager/menuItemList";
}
@RequestMapping(value="/editMenuItemByName/{menuName}")
public ModelAndView selectMenuItemByName(@PathVariable("menuName")String menuName) {
MenuItem item = menuItemService.selectMenuItemByName(menuName);
Map<String,Object> map = new HashMap<String,Object>();
map.put("menuItem", item);
return new ModelAndView("/setting/menuItemManager/editMenuItem",map);
}
@RequestMapping(value="/editMenuItemById/{id}")
public ModelAndView selectMenuItemById(@PathVariable("id")int menuId) {
MenuItem menu= menuItemService.selectMenuItemById(menuId);
Map<String,Object> model = new HashMap<String,Object>();
model.put("menuItem", menu);
return new ModelAndView("/setting/menuItemManager/editMenuItem",model);
}
@RequestMapping(value="/updateMenuItem", method=RequestMethod.POST)
public String updateMenuItem(@ModelAttribute("menuItem")MenuItem menuItem) {
menuItemService.updateMenuItem(menuItem);
return "redirect:/setting/menuItemManager/listMenuItems";
}
@RequestMapping(value="/deleteMenuItem/{id}")
public String deleteMenuItem(@PathVariable("id") Integer menuId) {
menuItemService.deleteMenuItem(menuId);
return "redirect:/setting/menuItemManager/listMenuItems";
}
}
|
package org.kevoree.registry.exception;
/**
* Created by leiko on 09/01/15.
*/
public class InvalidNamespaceException extends Exception {
public InvalidNamespaceException(String message) {
super(message);
}
}
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package org.jearl.ejb.translatable;
/**
*
* @author bamasyali
*/
public interface TranslatableInterface {
String getValue(String field);
void setValue(String field, String value);
}
|
/*
* Copyright 2002-2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.web.socket.server.standard;
import java.io.IOException;
import java.lang.reflect.Constructor;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.glassfish.tyrus.core.TyrusUpgradeResponse;
import org.glassfish.tyrus.core.Utils;
import org.glassfish.tyrus.servlet.TyrusHttpUpgradeHandler;
import org.glassfish.tyrus.spi.WebSocketEngine.UpgradeInfo;
import org.glassfish.tyrus.spi.Writer;
import org.springframework.util.ReflectionUtils;
import org.springframework.web.socket.server.HandshakeFailureException;
/**
* A WebSocket {@code RequestUpgradeStrategy} for Oracle's GlassFish 4.1 and higher.
*
* @author Rossen Stoyanchev
* @author Juergen Hoeller
* @author Michael Irwin
* @since 4.0
*/
public class GlassFishRequestUpgradeStrategy extends AbstractTyrusRequestUpgradeStrategy {
private static final Constructor<?> constructor;
static {
try {
ClassLoader classLoader = GlassFishRequestUpgradeStrategy.class.getClassLoader();
Class<?> type = classLoader.loadClass("org.glassfish.tyrus.servlet.TyrusServletWriter");
constructor = type.getDeclaredConstructor(TyrusHttpUpgradeHandler.class);
ReflectionUtils.makeAccessible(constructor);
}
catch (Exception ex) {
throw new IllegalStateException("No compatible Tyrus version found", ex);
}
}
@Override
protected void handleSuccess(HttpServletRequest request, HttpServletResponse response,
UpgradeInfo upgradeInfo, TyrusUpgradeResponse upgradeResponse) throws IOException, ServletException {
TyrusHttpUpgradeHandler handler = request.upgrade(TyrusHttpUpgradeHandler.class);
Writer servletWriter = newServletWriter(handler);
handler.preInit(upgradeInfo, servletWriter, request.getUserPrincipal() != null);
response.setStatus(upgradeResponse.getStatus());
upgradeResponse.getHeaders().forEach((key, value) -> response.addHeader(key, Utils.getHeaderFromList(value)));
response.flushBuffer();
}
private Writer newServletWriter(TyrusHttpUpgradeHandler handler) {
try {
return (Writer) constructor.newInstance(handler);
}
catch (Exception ex) {
throw new HandshakeFailureException("Failed to instantiate TyrusServletWriter", ex);
}
}
}
|
package patterns.behavioral.state;
public class GumballMachine
{
/**
* 机器持有各个状态
*/
private State hasQuarterState;
private State noQuarterState;
private State soldOutState;
private State soldState;
/**
* 当前状态
*/
private State currentState;
/**
* 当前机器剩余的数量
*/
private int count = 0;
/**
* 初始化机器的状态
*
* @param numberGumball
*/
public GumballMachine(int numberGumball)
{
this.hasQuarterState = new HasQuarterState(this);
this.noQuarterState = new NoQuarterState(this);
this.soldOutState = new SoldOutState(this);
this.soldState = new SoldState(this);
count = numberGumball;
if(numberGumball > 0)
{
currentState = noQuarterState;
}
else
{
currentState = soldOutState;
}
}
public void insertQuarter()
{
this.currentState.insertQuarter();
}
public void ejectQuarter()
{
this.currentState.ejectQuarter();
}
public void turnCrank()
{
this.currentState.turnCrank();
this.currentState.disPens();
}
public void setCurrentState(State currentState)
{
this.currentState = currentState;
}
public void releaseBall()
{
System.out.println("有一个球滚出来...");
if(count != 0)
{
count -= 1;
}
}
public State getHasQuarterState()
{
return hasQuarterState;
}
public State getNoQuarterState()
{
return noQuarterState;
}
public State getSoldOutState()
{
return soldOutState;
}
public State getSoldState()
{
return soldState;
}
public State getCurrentState()
{
return currentState;
}
public int getCount()
{
return count;
}
}
|
package com.edasaki.rpg.items;
import org.bukkit.Material;
import org.bukkit.inventory.ItemStack;
public abstract class RPGItem {
public String identifier;
public String name = null;
public Material material = null;
public String description = null;
public boolean soulbound;
public abstract ItemStack generate();
}
|
package com.cninnovatel.ev.wxapi;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import com.cninnovatel.ev.App;
import com.cninnovatel.ev.HexMeet;
import com.cninnovatel.ev.R;
import com.cninnovatel.ev.conf.ConferenceJoiner;
import com.cninnovatel.ev.conf.WeChat;
import com.cninnovatel.ev.utils.Utils;
import com.tencent.mm.sdk.modelbase.BaseReq;
import com.tencent.mm.sdk.modelbase.BaseResp;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.IWXAPIEventHandler;
import com.tencent.mm.sdk.openapi.WXAPIFactory;
public class WXEntryActivity extends Activity implements IWXAPIEventHandler
{
private final long five_minutes = 5 * 60 * 1000l;
private IWXAPI api;
public static final String APP_ID = "xxxxxxxxxxx"; //only for example
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
api = WXAPIFactory.createWXAPI(this, APP_ID, false);
api.handleIntent(getIntent(), this);
}
@Override
public void onResp(BaseResp resp)
{
String result;
switch (resp.errCode)
{
case BaseResp.ErrCode.ERR_OK:
result = getString(R.string.share_success);
break;
case BaseResp.ErrCode.ERR_USER_CANCEL:
result = getString(R.string.share_canceled);
break;
case BaseResp.ErrCode.ERR_AUTH_DENIED:
result = getString(R.string.auth_error);
break;
default:
result = getString(R.string.unknown_reason_error);
break;
}
Utils.showToast(this, result);
if (getString(R.string.share_success).equals(result))
{
try
{
if (WeChat.sharingMeeting != null)
{
long now = System.currentTimeMillis();
long starts = WeChat.sharingMeeting.getStartTime();
if (starts - now > five_minutes)
{
HexMeet.actionStart(this);
return;
}
else if (WeChat.isFromSchedulingOK)
{
Context context = HexMeet.getInstance() != null ? HexMeet.getInstance() : App.getContext();
Intent intent = new Intent(context, ConferenceJoiner.class);
intent.putExtra("meeting", WeChat.sharingMeeting);
context.startActivity(intent);
}
}
}
finally
{
WeChat.sharingMeeting = null;
}
}
finish();
}
@Override
public void onReq(BaseReq req)
{
}
}
|
package de.example.simpleREST.model;
import java.time.LocalDateTime;
import java.util.List;
import java.util.UUID;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import org.springframework.format.annotation.DateTimeFormat;
public interface ProdOrderRepository extends CrudRepository<ProdOrder, UUID> {
@Query("select e from #{#entityName} e where created between ?1 and ?2")
List<ProdOrder> findInRange(
@DateTimeFormat(pattern="yyyy-MM-dd'T'HH:mm:ss") LocalDateTime start,
@DateTimeFormat(pattern="yyyy-MM-dd'T'HH:mm:ss") LocalDateTime end);
}
|
package Tools;
import com.fazecast.jSerialComm.SerialPort;
import java.util.Timer;
public class Emulator {
/**
* Generate data over a parbola.
* @return
*/
public static int[] xGens = new int[13];
public static void main(String args[]){
SerialPort[] ports = SerialPort.getCommPorts();
SerialPort port1 = null;
SerialPort port2 = null;
for (SerialPort port: ports) {
if(port.getSystemPortName().equals("COM1")) port1 = port;
if(port.getSystemPortName().equals("COM6")) port2 = port;
}
port1.openPort();
// port2.openPort();
Timer timer = new Timer();
timer.schedule(new DataSender(port1), 0, 5000);
}
}
|
package com.lfalch.korome;
import java.io.IOException;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import com.lfalch.korome.packets.InvalidPacketException;
import com.lfalch.korome.packets.Packet;
import com.lfalch.korome.packets.PacketMethod;
public class Server extends Thread{
private volatile boolean running;
public Server() throws SocketException {
super();
serverSocket = new DatagramSocket(45565);
}
public static void main(String[] args) {
try {
Server server = new Server();
server.start();
}
catch (SocketException e) {
e.printStackTrace();
}
}
DatagramSocket serverSocket;
@Override
public void run() {
running = true;
while(running){
try {
Packet pa = Packet.receive(serverSocket);
InetAddress address = pa.getAddress();
int port = pa.getPort();
System.out.println(address.getHostAddress() + ":" + port + " " + pa.getContent());
pa = new Packet(PacketMethod.MSG, PacketMethod.MSG.generateAttribute("Body", "I got your " + pa.getMethod() + "-message"));
pa.send(serverSocket, address, port);
}
catch (IOException e) {
e.printStackTrace();
}catch (InvalidPacketException e) {
e.printStackTrace();
}
}
serverSocket.close();
System.out.println("Stopped running");
}
}
|
package pl.manufacturer.object.util;
import java.util.Random;
public class BasicTypeValueGeneratorUtil {
private static Random random = new Random();
private BasicTypeValueGeneratorUtil() {
// this should be empty
}
public static String generateString(int length) {
int leftLimit = 97; // letter 'a'
int rightLimit = 122; // letter 'z'
Random random = new Random();
StringBuilder buffer = new StringBuilder(length);
for (int i = 0; i < length; i++) {
int randomLimitedInt = leftLimit + (int)
(random.nextFloat() * (rightLimit - leftLimit + 1));
buffer.append((char) randomLimitedInt);
}
return buffer.toString();
}
public static Boolean generateBoolean() {
return random.nextBoolean();
}
public static Integer generateInteger() {
return random.nextInt();
}
public static Long generateLong() {
return random.nextLong();
}
public static Double generateDouble() {
return random.nextDouble();
}
public static Float generateFloat() {
return random.nextFloat();
}
public static Character generateCharacter() {
return (char) (random.nextInt('z' - 'a') + 'a');
}
public static Byte generateByte() {
byte[] oneByte = new byte[1];
random.nextBytes(oneByte);
return oneByte[0];
}
public static Short generateShort() {
return (short) random.nextInt(Short.MAX_VALUE + 1);
}
}
|
package homework3;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
public class Student extends Person {
public int sid = -1;
private int noOfGrades = 0;
private double[] grades = new double[100];
public static int noOfStudents = 0;
public Student(String s, int id) {
super(s);
this.sid = id;
noOfStudents = noOfStudents + 1;
}
public Student(String s, int id, int weight, int height) {
super(s, weight, height);
this.sid = id;
noOfStudents = noOfStudents + 1;
}
private double getValue(String g) {
double val = 0;
switch(g) {
case "A+": val = 4.00; break;
case "A": val = 3.66; break;
case "A-": val = 3.33; break;
case "B+": val = 3.00; break;
case "B": val = 2.66; break;
case "B-": val = 2.33; break;
case "C+": val = 2.00; break;
case "C": val = 1.66; break;
case "C-": val = 1.33; break;
case "D+": val = 1.00; break;
case "D": val = 0.66; break;
case "D-": val = 0.33; break;
default: val = -1.00; break;
}
return val;
}
public void setGrade(String g) {
double v = getValue(g);
if (v < 0)
System.out.println("Warning: grade not set.");
else
setGrade(v);
}
private void setGrade(double d) {
if (noOfGrades < this.grades.length) {
noOfGrades = noOfGrades + 1;
this.grades[noOfGrades - 1] = d;
}
else
System.out.println("Warning: the grade not set");
}
public double getGPA() {
double sum = 0;
for (int i = 0; i < noOfGrades; i++)
sum = sum + grades[i];
if (noOfGrades == 0)
return 0.0;
else
return sum/noOfGrades;
}
public double calcAvgGPA(Student[] arr) {
return Student.getAveGPA(arr);
}
public static double calcAvgGPA(Person[] arr) {
double[] AllGPAs = new double[arr.length];
for (int i=0; i < arr.length; i++) {
AllGPAs[i] = ((Student) arr[i]).getGPA();
}
return Util.mean(AllGPAs);
}
public static Person[] readFile(String filename) {
String content = null;
File file = new File(filename);
try {
FileReader reader = new FileReader(file);
char[] chars = new char[(int) file.length()];
reader.read(chars);
content = new String(chars);
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
String[] splits = content.split("\n");
Person[] p = new Person[splits.length];
for (int i=0; i < splits.length; i++) {
String[] splitline = splits[i].split(" ");
Student s1 = new Student(splitline[0]+" "+splitline[1], Integer.parseInt(splitline[2]),
Integer.parseInt(splitline[6]), Integer.parseInt(splitline[7]));
s1.setGrade(splitline[3]);
s1.setGrade(splitline[4]);
s1.setGrade(splitline[5]);
p[i] = s1;
}
return p;
}
public static double getAveGPA(Student[] arr) {
double[] AllGPAs = new double[arr.length];
for (int i=0; i < arr.length; i++) {
AllGPAs[i] = arr[i].getGPA();
}
return Util.mean(AllGPAs);
}
}
|
/**
* 此处是证书
*/
package com.pansoft.xbrl.cloud;
|
package gov.nih.mipav.view.renderer.J3D.surfaceview.rfaview;
import com.sun.j3d.utils.geometry.*;
import com.sun.j3d.utils.picking.*;
import java.awt.*;
import javax.media.j3d.*;
import javax.vecmath.*;
/**
* <p>Title: DefaultPorbe</p>
*
* <p>Description: The default probe is the cyan probe. This class builds the default probe. It also defines the
* geometry shape of the default probe.</p>
*
* @author Ruida Cheng
*/
public class DefaultProbe {
//~ Instance fields ------------------------------------------------------------------------------------------------
/** Ambient, emissive, sepcualar, diffuse color is used for the attenuation lighting. */
protected Color3f ambientColor = new Color3f(1.0f, 0.0f, 0.0f);
/** Define the cyan color. */
protected Color3f cyan = new Color3f(Color.cyan);
/** DOCUMENT ME! */
protected Color3f diffuseColor = new Color3f(1.0f, 0.0f, 0.0f);
/** DOCUMENT ME! */
protected Color3f emissiveColor = new Color3f(0.0f, 0.0f, 0.0f);
/** Define the green color. */
protected Color3f green = new Color3f(Color.green);
/** Agent to set the probe pickable. */
protected PickCanvas pickCanvas;
/** DOCUMENT ME! */
protected Color3f sepcualarColor = new Color3f(1.0f, 1.0f, 1.0f);
/** Cone shape part of the probe. */
private Cone coneDefault;
/** Indicator probe cone shape. */
private Cone coneIndicator;
/** Transform group of the indicator cone shape. */
private TransformGroup coneIndicatorTG;
/** Transform group of the cone shape. */
private TransformGroup coneTG;
/** Cylinder shape part of the probe. */
private Cylinder cylinderDefault;
/**
* Indicator is used by the default probe to switch color between cyan and green. Indicator is the green color
* probe. I prefer switching the branch group rather than changing the java3d geometry appearance because the
* appearance changes waste time and memory. /** Indicator probe cylinder shape.
*/
private Cylinder cylinderIndicator;
/** Transform group of the indicator cylinder shape. */
private TransformGroup cylinderIndicatorTG;
/** Transform group of the cylinder shape. */
private TransformGroup cylinderTG;
/** The root of the default probe. */
private TransformGroup defaultProbe;
/** The root branch group of the cyan default robe. */
private BranchGroup defaultProbeBG;
/** The root branch group of the green indicator probe. */
private BranchGroup indicatorProbeBG;
/** Switch group used to switch between cyan and green probes. */
private Switch switchGroup = new Switch();
/** Y original coordinate value. */
private float yOrigin;
//~ Constructors ---------------------------------------------------------------------------------------------------
/**
* Constructor, initialize the probe shapes.
*/
public DefaultProbe() {
init();
}
//~ Methods --------------------------------------------------------------------------------------------------------
/**
* Enable the probe to rotate around the entry point.
*
* @param flag boolean <code>true</code> means around the entry point, <code>false</code> around the origin.
*/
public void enableEntryPointRotation(boolean flag) {
Transform3D cylinderTrans = new Transform3D();
Transform3D coneTrans = new Transform3D();
Matrix3d matrixAdjustCylinder = new Matrix3d();
Transform3D cylinderIndicatorTrans = new Transform3D();
Transform3D coneIndicatorTrans = new Transform3D();
if (flag) {
yOrigin = 1.0f;
} else {
yOrigin = 0.0f;
}
cylinderTrans.setTranslation(new Vector3f(0.0f, 1.75f - yOrigin, 0.0f));
cylinderTG.setTransform(cylinderTrans);
matrixAdjustCylinder.rotZ(Math.PI);
coneTrans.setTranslation(new Vector3f(0.0f, 1.25f - yOrigin, 0.0f));
coneTrans.setRotation(matrixAdjustCylinder);
coneTG.setTransform(coneTrans);
cylinderIndicatorTrans.setTranslation(new Vector3f(0.0f, 1.75f - yOrigin, 0.0f));
cylinderIndicatorTG.setTransform(cylinderIndicatorTrans);
coneIndicatorTrans.setTranslation(new Vector3f(0.0f, 1.25f - yOrigin, 0.0f));
coneIndicatorTrans.setRotation(matrixAdjustCylinder);
coneIndicatorTG.setTransform(coneIndicatorTrans);
}
/**
* Check whether the probe being picked or not.
*
* @param pickedShape picked geometry shape.
*
* @return boolean <code>true</code> probe picked, <code>false</code> probe not picked.
*/
protected boolean findProbe(Shape3D pickedShape) {
if (cylinderDefault.getShape(0) == pickedShape) {
return true;
} else if (coneDefault.getShape(0) == pickedShape) {
return true;
} else {
return false;
}
}
/**
* Get the root of the default probe.
*
* @return TransformGroup The root transform group of the probe.
*/
protected TransformGroup getProbe() {
return defaultProbe;
}
/**
* Initialize the probe geometry shapes.
*/
protected void init() {
// Create appearance for display of light.
Appearance appearance = new Appearance();
/** Set the attenuation lighting effect. */
Material probeMaterials = new Material(emissiveColor, emissiveColor, cyan, sepcualarColor, 50.0f);
probeMaterials.setCapability(Material.ALLOW_COMPONENT_READ);
probeMaterials.setCapability(Material.ALLOW_COMPONENT_WRITE);
appearance.setMaterial(probeMaterials);
// Create a group that will be the root of the arrow
defaultProbe = new TransformGroup();
defaultProbe.setCapability(TransformGroup.ALLOW_CHILDREN_READ);
defaultProbe.setCapability(TransformGroup.ALLOW_TRANSFORM_READ);
defaultProbeBG = new BranchGroup();
defaultProbeBG.setCapability(Group.ALLOW_CHILDREN_EXTEND);
defaultProbeBG.setCapability(Group.ALLOW_CHILDREN_READ);
defaultProbeBG.setCapability(Group.ALLOW_CHILDREN_WRITE);
defaultProbeBG.setCapability(Node.ALLOW_PICKABLE_READ);
defaultProbeBG.setCapability(Node.ALLOW_PICKABLE_WRITE);
indicatorProbeBG = new BranchGroup();
indicatorProbeBG.setCapability(Group.ALLOW_CHILDREN_EXTEND);
indicatorProbeBG.setCapability(Group.ALLOW_CHILDREN_READ);
indicatorProbeBG.setCapability(Group.ALLOW_CHILDREN_WRITE);
indicatorProbeBG.setCapability(Node.ALLOW_PICKABLE_READ);
indicatorProbeBG.setCapability(Node.ALLOW_PICKABLE_WRITE);
defaultProbe.addChild(switchGroup);
switchGroup.addChild(defaultProbeBG);
switchGroup.addChild(indicatorProbeBG);
switchGroup.setWhichChild(Switch.CHILD_NONE);
switchGroup.setCapability(Switch.ALLOW_SWITCH_WRITE);
switchGroup.setCapability(Switch.ALLOW_CHILDREN_WRITE);
switchGroup.setCapability(Switch.ALLOW_CHILDREN_READ);
switchGroup.setWhichChild(0);
// create cylinder
cylinderDefault = new Cylinder(0.01f, 0.5f, Primitive.GENERATE_NORMALS, appearance);
cylinderDefault.getShape(0).setCapability(Shape3D.ALLOW_APPEARANCE_READ);
cylinderDefault.getShape(0).setCapability(Shape3D.ALLOW_APPEARANCE_WRITE);
cylinderDefault.getShape(0).setCapability(Shape3D.ALLOW_GEOMETRY_WRITE);
cylinderDefault.getShape(0).setCapability(Shape3D.ALLOW_GEOMETRY_READ);
cylinderDefault.getShape(0).setCapability(Geometry.ALLOW_INTERSECT);
cylinderDefault.getShape(0).setAppearanceOverrideEnable(false);
Transform3D cylinderTrans = new Transform3D();
cylinderTrans.setTranslation(new Vector3f(0.0f, 1.75f, 0.0f));
cylinderTG = new TransformGroup(cylinderTrans);
cylinderTG.setCapability(TransformGroup.ALLOW_CHILDREN_READ);
cylinderTG.setCapability(TransformGroup.ALLOW_TRANSFORM_READ);
cylinderTG.setCapability(TransformGroup.ALLOW_TRANSFORM_WRITE);
cylinderTG.addChild(cylinderDefault);
defaultProbeBG.addChild(cylinderTG);
// Create a cone
coneDefault = new Cone(0.01f, 0.5f, Primitive.GENERATE_NORMALS, appearance);
coneDefault.getShape(0).setCapability(Shape3D.ALLOW_APPEARANCE_READ);
coneDefault.getShape(0).setCapability(Shape3D.ALLOW_APPEARANCE_WRITE);
coneDefault.getShape(0).setCapability(Shape3D.ALLOW_GEOMETRY_WRITE);
coneDefault.getShape(0).setCapability(Shape3D.ALLOW_GEOMETRY_READ);
coneDefault.getShape(0).setCapability(Geometry.ALLOW_INTERSECT);
coneDefault.getShape(0).setAppearanceOverrideEnable(false);
// Create the transform and transform group that will position the cone on the arrow
Transform3D coneTrans = new Transform3D();
Matrix3d matrixAdjustCylinder = new Matrix3d();
// coneTrans.setRotationScale( matrixAdjustCylinder );
matrixAdjustCylinder.rotZ(Math.PI);
coneTrans.setTranslation(new Vector3f(0.0f, 1.25f, 0.0f));
coneTrans.setRotation(matrixAdjustCylinder);
coneTG = new TransformGroup(coneTrans);
coneTG.setCapability(TransformGroup.ALLOW_TRANSFORM_READ);
coneTG.setCapability(TransformGroup.ALLOW_TRANSFORM_WRITE);
coneTG.setCapability(TransformGroup.ALLOW_CHILDREN_READ);
// Add the cone to the cone transform group
coneTG.addChild(coneDefault);
defaultProbeBG.addChild(coneTG);
// set pickable
try {
PickCanvas.setCapabilities(cylinderDefault.getShape(0), PickTool.INTERSECT_FULL);
PickCanvas.setCapabilities(coneDefault.getShape(0), PickTool.INTERSECT_FULL);
} catch (RestrictedAccessException error) { }
// following builds the green indicator probe geometry. */
Material mat;
Appearance app = new Appearance();
mat = new Material(emissiveColor, emissiveColor, green, sepcualarColor, 50.0f);
mat.setCapability(Material.ALLOW_COMPONENT_READ);
mat.setCapability(Material.ALLOW_COMPONENT_WRITE);
app.setMaterial(mat);
// create cylinder
cylinderIndicator = new Cylinder(0.01f, 0.5f, Primitive.GENERATE_NORMALS, app);
cylinderIndicator.getShape(0).setCapability(Shape3D.ALLOW_APPEARANCE_READ);
cylinderIndicator.getShape(0).setCapability(Shape3D.ALLOW_APPEARANCE_WRITE);
cylinderIndicator.getShape(0).setCapability(Shape3D.ALLOW_GEOMETRY_WRITE);
cylinderIndicator.getShape(0).setCapability(Shape3D.ALLOW_GEOMETRY_READ);
cylinderIndicator.getShape(0).setCapability(Geometry.ALLOW_INTERSECT);
cylinderIndicator.getShape(0).setAppearanceOverrideEnable(false);
Transform3D cylinderIndicatorTrans = new Transform3D();
cylinderIndicatorTrans.setTranslation(new Vector3f(0.0f, 1.75f, 0.0f));
cylinderIndicatorTG = new TransformGroup(cylinderIndicatorTrans);
cylinderIndicatorTG.setCapability(TransformGroup.ALLOW_CHILDREN_READ);
cylinderIndicatorTG.setCapability(TransformGroup.ALLOW_TRANSFORM_READ);
cylinderIndicatorTG.setCapability(TransformGroup.ALLOW_TRANSFORM_WRITE);
cylinderIndicatorTG.addChild(cylinderIndicator);
indicatorProbeBG.addChild(cylinderIndicatorTG);
// Create a cone
coneIndicator = new Cone(0.01f, 0.5f, Primitive.GENERATE_NORMALS, app);
coneIndicator.getShape(0).setCapability(Shape3D.ALLOW_APPEARANCE_READ);
coneIndicator.getShape(0).setCapability(Shape3D.ALLOW_APPEARANCE_WRITE);
coneIndicator.getShape(0).setCapability(Shape3D.ALLOW_GEOMETRY_WRITE);
coneIndicator.getShape(0).setCapability(Shape3D.ALLOW_GEOMETRY_READ);
coneIndicator.getShape(0).setCapability(Geometry.ALLOW_INTERSECT);
coneIndicator.getShape(0).setAppearanceOverrideEnable(false);
// Create the transform and transform group that will position the cone on the arrow
Transform3D coneIndicatorTrans = new Transform3D();
coneIndicatorTrans.setTranslation(new Vector3f(0.0f, 1.25f, 0.0f));
coneIndicatorTrans.setRotation(matrixAdjustCylinder);
coneIndicatorTG = new TransformGroup(coneIndicatorTrans);
coneIndicatorTG.setCapability(TransformGroup.ALLOW_TRANSFORM_READ);
coneIndicatorTG.setCapability(TransformGroup.ALLOW_TRANSFORM_WRITE);
coneIndicatorTG.setCapability(TransformGroup.ALLOW_CHILDREN_READ);
// Add the cone to the cone transform group
coneIndicatorTG.addChild(coneIndicator);
indicatorProbeBG.addChild(coneIndicatorTG);
}
/**
* Set the probe translation in the local coordinate system.
*
* @param value y coordinate value of the local coordinate system.
*/
protected void setProbeCoordinate(float value) {
// default probe
Transform3D transCylinder = new Transform3D();
Vector3f vCylinder = new Vector3f();
cylinderTG.getTransform(transCylinder);
transCylinder.get(vCylinder);
vCylinder.y = (1.75f - yOrigin - value);
transCylinder.setTranslation(vCylinder);
cylinderTG.setTransform(transCylinder);
Transform3D transCone = new Transform3D();
Vector3f vCone = new Vector3f();
coneTG.getTransform(transCone);
transCone.get(vCone);
vCone.y = (1.25f - yOrigin - value);
transCone.setTranslation(vCone);
coneTG.setTransform(transCone);
// indicator probe
cylinderIndicatorTG.setTransform(transCylinder);
coneIndicatorTG.setTransform(transCone);
}
/**
* Switch the default probe between color cyan and color green.
*
* @param flag boolean <code>true</code> green color, <code>false</code> cyan color.
*/
protected void setProbeGreenColor(boolean flag) {
if (flag) {
switchGroup.setWhichChild(1);
} else {
switchGroup.setWhichChild(0);
}
}
}
|
/*
* Copyright 2020 Red Hat, Inc. and/or its affiliates.
*
* 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.optaplanner.core.impl.score.stream.drools.bi;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.function.LongSupplier;
import java.util.stream.Stream;
import org.drools.model.Argument;
import org.drools.model.DSL;
import org.drools.model.PatternDSL;
import org.drools.model.Variable;
import org.drools.model.view.ExprViewItem;
import org.drools.model.view.ViewItemBuilder;
import org.optaplanner.core.impl.score.stream.drools.common.DroolsPatternBuilder;
import org.optaplanner.core.impl.score.stream.drools.common.DroolsRuleStructure;
import org.optaplanner.core.impl.score.stream.drools.uni.DroolsUniRuleStructure;
public final class DroolsBiRuleStructure<A, B, PatternVar> extends DroolsRuleStructure<PatternVar> {
private final Variable<A> a;
private final Variable<B> b;
private final DroolsPatternBuilder<PatternVar> primaryPattern;
private final List<ViewItemBuilder<?>> shelved;
private final List<ViewItemBuilder<?>> prerequisites;
private final List<ViewItemBuilder<?>> dependents;
public <APatternVar> DroolsBiRuleStructure(DroolsUniRuleStructure<A, APatternVar> aRuleStructure,
DroolsUniRuleStructure<B, PatternVar> bRuleStructure, LongSupplier variableIdSupplier) {
super(variableIdSupplier);
this.a = aRuleStructure.getA();
this.b = bRuleStructure.getA();
this.primaryPattern = bRuleStructure.getPrimaryPatternBuilder();
List<ViewItemBuilder<?>> newShelved = new ArrayList<>(aRuleStructure.getShelvedRuleItems());
newShelved.addAll(bRuleStructure.getShelvedRuleItems());
this.shelved = Collections.unmodifiableList(newShelved);
List<ViewItemBuilder<?>> newPrerequisites = new ArrayList<>(aRuleStructure.getPrerequisites());
newPrerequisites.add(aRuleStructure.getPrimaryPatternBuilder().build());
newPrerequisites.addAll(aRuleStructure.getDependents());
newPrerequisites.addAll(bRuleStructure.getPrerequisites());
this.prerequisites = Collections.unmodifiableList(newPrerequisites);
this.dependents = Collections.unmodifiableList(bRuleStructure.getDependents());
}
public DroolsBiRuleStructure(Variable<A> aVariable, Variable<B> bVariable,
DroolsPatternBuilder<PatternVar> primaryPattern, List<ViewItemBuilder<?>> shelved,
List<ViewItemBuilder<?>> prerequisites, List<ViewItemBuilder<?>> dependents,
LongSupplier variableIdSupplier) {
super(variableIdSupplier);
this.a = aVariable;
this.b = bVariable;
this.primaryPattern = primaryPattern;
this.shelved = Collections.unmodifiableList(shelved);
this.prerequisites = Collections.unmodifiableList(prerequisites);
this.dependents = Collections.unmodifiableList(dependents);
}
public <C> DroolsBiRuleStructure<A, B, PatternVar> existsOrNot(PatternDSL.PatternDef<C> existencePattern,
boolean shouldExist) {
ExprViewItem item = DSL.exists(existencePattern);
if (!shouldExist) {
item = DSL.not(item);
}
return new DroolsBiRuleStructure<>(a, b, primaryPattern, shelved, prerequisites, mergeDependents(item),
getVariableIdSupplier());
}
public Variable<A> getA() {
return a;
}
public Variable<B> getB() {
return b;
}
@Override
public List<ViewItemBuilder<?>> getShelvedRuleItems() {
return shelved;
}
@Override
public List<ViewItemBuilder<?>> getPrerequisites() {
return prerequisites;
}
@Override
public DroolsPatternBuilder<PatternVar> getPrimaryPatternBuilder() {
return primaryPattern;
}
@Override
public List<ViewItemBuilder<?>> getDependents() {
return dependents;
}
@Override
protected Class[] getVariableTypes() {
return Stream.of(a, b).map(Argument::getType).toArray(Class[]::new);
}
}
|
package cn.sort.heapSort;
/**
* @Author: xiaoni
* @Date: 2020/3/14 20:15
*
* 堆排序(大顶堆、小顶堆)----C语言 - 蓝海人 - 博客园 https://www.cnblogs.com/lanhaicode/p/10546257.html
*
* 堆和普通树的区别
* 内存占用:
* 普通树占用的内存空间比它们存储的数据要多。你必须为节点对象以及左/右子节点指针分配额外的内存。堆仅仅使用数组,且不使用指针
* (可以使用普通树来模拟堆,但空间浪费比较大,不太建议这么做)
*
* 平衡:
* 二叉搜索树必须是“平衡”的情况下,其大部分操作的复杂度才能达到O(nlog2n)。你可以按任意顺序位置插入/删除数据,或者使用 AVL 树或者红黑树,但是在堆中实际上不需要整棵树都是有序的。我们只需要满足对属性即可,所以在堆中平衡不是问题。因为堆中数据的组织方式可以保证O(nlog2n) 的性能
*
* 搜索:
* 在二叉树中搜索会很快,但是在堆中搜索会很慢。在堆中搜索不是第一优先级,因为使用堆的目的是将最大(或者最小)的节点放在最前面,从而快速的进行相关插入、删除操作
*/
public class HeapSort {
/* Function: 构建大顶堆 */
public static void buildMaxHeap(int[] heap, int len) {
int i;
int temp;
/**
* 升序----使用大顶堆
* 大顶堆:arr[i] >= arr[2i+1] && arr[i] >= arr[2i+2]
* 降序----使用小顶堆
* 小顶堆:arr[i] <= arr[2i+1] && arr[i] <= arr[2i+2]
*/
for (i = len / 2 - 1; i >= 0; i--) {
if ((2 * i + 1) < len && heap[i] < heap[2 * i + 1]) /* 根节点大于左子树 */ {
temp = heap[i];
heap[i] = heap[2 * i + 1];
heap[2 * i + 1] = temp;
/*
* 检查交换后的左子树是否满足大顶堆性质 如果不满足 则重新调整子树结构
* 把if里面的条件分来开看2*(2*i+1)+1 < len的作用是判断该左子树有没有左子树(可能有点绕),
* heap[2*i+1] < heap[2*(2*i+1)+1]就是判断左子树的左子树的值是否大于左子树,
* 如果是,那么就意味着交换值过后左子树大顶堆的性质被破环了,需要重构该左子树
*/
if ((2 * (2 * i + 1) + 1 < len && heap[2 * i + 1] < heap[2 * (2 * i + 1) + 1]) || (2 * (2 * i + 1) + 2 < len && heap[2 * i + 1] < heap[2 * (2 * i + 1) + 2])) {
buildMaxHeap(heap, len);
}
}
if ((2 * i + 2) < len && heap[i] < heap[2 * i + 2]) /* 根节点大于右子树 */ {
temp = heap[i];
heap[i] = heap[2 * i + 2];
heap[2 * i + 2] = temp;
/* 检查交换后的右子树是否满足大顶堆性质 如果不满足 则重新调整子树结构 */
if ((2 * (2 * i + 2) + 1 < len && heap[2 * i + 2] < heap[2 * (2 * i + 2) + 1]) || (2 * (2 * i + 2) + 2 < len && heap[2 * i + 2] < heap[2 * (2 * i + 2) + 2])) {
buildMaxHeap(heap, len);
}
}
}
}
/* Function: 交换交换根节点和数组末尾元素的值*/
public static void swap(int[] heap, int len) {
int temp;
temp = heap[0];
heap[0] = heap[len - 1];
heap[len - 1] = temp;
}
public static void main(String[] args) {
int[] a = {7, 3, 8, 5, 1, 2};
int len = 6; /* 数组长度 */
int i;
for (i = len; i > 0; i--) {
buildMaxHeap(a, i);
swap(a, i);
}
for (i = 0; i < len; i++) {
System.out.println("%d " + a[i]);
}
}
}
|
/*
* Copyright 2019 WeBank
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.webank.wedatasphere.qualitis.rule.constant;
import java.util.Arrays;
import java.util.List;
/**
* Enum in checkTemplate of AlarmConfig
* @author howeye
*/
public enum CheckTemplateEnum {
/**
* Monthly, weekly, day and fixed name
*/
MONTH_FLUCTUATION(1,"月波动", "Month Fluctuation", Arrays.asList(Number.class)),
WEEK_FLUCTUATION(2,"周波动", "Week Fluctuation", Arrays.asList(Number.class)),
DAY_FLUCTUATION(3,"日波动", "Daily Fluctuation", Arrays.asList(Number.class)),
FIXED_VALUE(4,"固定值", "Fix Value", Arrays.asList(Number.class)),
;
private Integer code;
private String zhMessage;
private String enMessage;
private List<Class> classes;
CheckTemplateEnum(Integer code, String zhMessage, String enMessage, List<Class> classes) {
this.code = code;
this.zhMessage = zhMessage;
this.enMessage = enMessage;
this.classes = classes;
}
public Integer getCode() {
return code;
}
public String getZhMessage() {
return zhMessage;
}
public String getEnMessage() {
return enMessage;
}
public List<Class> getClasses() {
return classes;
}
public static String getCheckTemplateName(Integer code) {
for (CheckTemplateEnum c : CheckTemplateEnum.values()) {
if (c.getCode().equals(code)) {
return c.getZhMessage();
}
}
return null;
}
public static Integer getCheckTemplateCode(String checkTemplateName) {
for (CheckTemplateEnum c : CheckTemplateEnum.values()) {
if (c.getZhMessage().equals(checkTemplateName)) {
return c.getCode();
}
}
return null;
}
public static String getCheckTemplateName(Integer code, String local) {
for (CheckTemplateEnum c : CheckTemplateEnum.values()) {
if (c.getCode().equals(code)) {
if (local.equals("en_US")) {
return c.getEnMessage();
} else {
return c.getZhMessage();
}
}
}
return null;
}
public static Integer getCheckTemplateCode(String checkTemplateName, String local) {
for (CheckTemplateEnum c : CheckTemplateEnum.values()) {
if (local.equals("en_US")) {
if (c.getEnMessage().equals(checkTemplateName)) {
return c.getCode();
}
} else {
if (c.getZhMessage().equals(checkTemplateName)) {
return c.getCode();
}
}
}
return null;
}
}
|
package boying.Interface;
/*
* 请求接口封装,根据传入city id组装不同的请求地址,进行请求,并返回结果数据
*/
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class getCityWeather {
private String url = "";
public String getUrl() {
return this.url;
}
public String getHttpResponse(String cityCode) throws IOException{
String line = "";
String httpResult = "";
url = "http://www.weather.com.cn/data/cityinfo/" + cityCode + ".html";
try {
//HttpURLConnection connection = URLConnetcion.getConnection(url);
URL urlConnection = new URL(url);
//打开连接
HttpURLConnection connection = (HttpURLConnection)urlConnection.openConnection();
//DataOutputStream out = null;
//设置连接参数
connection.setRequestMethod("GET");
connection.setDoInput(true);
connection.setUseCaches(false);
connection.setInstanceFollowRedirects(true);
//设置请求参数
connection.setRequestProperty("Content-Type", "text/html");
connection.setRequestProperty("Charset", "utf-8");
connection.setRequestProperty("Accep-Charset", "utf-8");
//建立实际的链接
connection.connect();//当调用connection.getInputStream()时会自动调用该函数,此处无须调用
//读取网页内容
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
while((line = reader.readLine()) != null) {
httpResult = httpResult + line.toString();
}
reader.close();
// System.out.println(connection.toString());
// String s = connection.getRequestMethod();
// System.out.println(connection.getRequestMethod());
// System.out.println("ResponseCode is " + connection.getResponseCode());
// System.out.println("ResponseMessage is " + connection.getResponseMessage());
// //System.out.println("ResponseType is " + connection.getRequestProperty("Content-Type"));
//断开链接
connection.disconnect();
}catch (Exception e) {
e.printStackTrace();
}
//System.out.println(httpResult);
return httpResult;//返回接口的json串
}
}
|
package jire.packet;
import jire.network.Client;
public class PacketBuildEvent extends PacketServiceEvent {
public PacketBuildEvent(Client client, PacketService service,
Packet packet, PacketRepresentation packetRepresentation) {
super(client, service, packet, packetRepresentation);
}
}
|
import java.util.Scanner;
public class BitwiseOperator {
public static short countBits(int num) {
short count = 0;
if(num == 0) {
return 0;
}
while(num != 0){
count += num & 1;
num >>>= 1;
}
return count;
}
// Time Complexity is O(x) where x is word sizeaa
public static short computeParityBruteForce(long x){
short result = 0;
if(x == 0) {
return 0;
}
// while(x != 0) {
// result ^= (x&1);
// x >>>= 1;
// }
while(x != 0) {
if((x & 1) != 0 ) {
result ^= 1;
}
x >>>= 1;
}
return result;
}
//Time Complexity O(k) where k is the number of bit set to 1
public static short computeParityOptimized(long x) {
short result = 0;
while(x != 0) {
result ^= 1;
x &= (x-1);
}
return result;
}
//Time Complexity is O(1) i.e independent of word size
public static long swapBits(long num, int i, int j) {
if (((num >>> i) & 1) != ((num >>> j) & 1)) {
long bitMask = (1L << i) | (1L << j );
num ^= bitMask;
}
return num;
}
public static long multiply(long num1, long num2) {
long sum = 0;
while(num1 != 0) {
if((num1 & 1) != 0) {
sum = add(sum, num2);
}
num1 >>>= 1;
num2 <<= 1;
}
return sum;
}
public static int divide(int x, int y) {
int result = 0;
int power = 32;
long yPower = (long)y << power;
while(x >= y) {
while (yPower > x) {
yPower >>>= 1;
--power;
}
result = (result + 1) << power;
x -= yPower;
}
return result;
}
private static long add(long a, long b) {
while(b != 0) {
long carry = (a&b);
a = a^b;
b = carry << 1;
}
return a;
}
public static long reverse(int x) {
long result = 0;
while(x > 0) {
result = result * 10 + (x % 10);
x /= 10;
}
return result;
}
public static boolean isPallindrome(int x) {
if(x <= 0) {
return x == 0;
}
int numDigit = (int)(Math.floor(Math.log10(x))) + 1;
int msdMask = (int)Math.pow(10, numDigit - 1);
for(int i = 0; i < (numDigit / 2); ++i) {
if(x / msdMask != x % 10) {
return false;
}
x /= msdMask; //Remove least significant digit
x %= 10; //Remove most significant digit
msdMask /= 100;
}
return true;
}
//Computer power
public static double power(double x, int y) {
double result = 1.0;
// long power = y;
if(y < 0) {
//power = -power;
y = (-1) * y;
x = 1.0 / x;
}
/*
while(power != 0) {
if((power & 1) != 0) {
result *= x;
}
x *= x;
power >>>= 1;
}
*/
while(y != 0) {
if( (y & 1) != 0) {
result *= x;
}
x *= x;
y >>>= 1;
}
return result;
}
public static void main(String args[]) {
Scanner sc = new Scanner (System.in);
//Calculate number of 1's bits in a non negative integer
System.out.println("Enter the non negetive integer");
int num = sc.nextInt();
int count = countBits(num);
System.out.println("No of 1 bits:" + count );
//Compute parity bit using bruteforce and optimized
System.out.println("Enter long to compute parity bits");
long longNum = sc.nextLong();
long parityCountBrute = computeParityBruteForce(longNum);
long parityCountOptimized = computeParityBruteForce(longNum);
System.out.println("Number of 1's using bruteforce methos :" + parityCountBrute);
System.out.println("Number of 1's using optimized methos :" + parityCountOptimized);
//Swap bits in long
System.out.println("Enter the long to swap bits");
long swapBitNum = sc.nextLong();
long afterSwapNum = swapBits(swapBitNum, 1 , 2);
System.out.println(afterSwapNum);
//Multiplication of two number
System.out.println("Enter two number to multiple");
long num1 = sc.nextLong();
long num2 = sc.nextLong();
long num3 = multiply(num1, num2);
System.out.println("Multiplication is:" + num3);
//Divide two integer numbers
System.out.println("Enter two number to divide");
int divNum1 = sc.nextInt();
int divNum2 = sc.nextInt();
int resultDiv = divide(divNum1, divNum2);
System.out.println("Quotient is:" + resultDiv);
//Reverse an integer
System.out.println("Enter the integer number to reverse");
int reverseInt = sc.nextInt();
System.out.println("the reversed digit is " + reverse(reverseInt));
//Check if a number is pallindrome or not
System.out.println("Enter the integer number to check if it is a pallindrome or not");
int palInt = sc.nextInt();
System.out.println(isPallindrome(palInt));
//Compute power of x and y
// System.out.println("Enter double value and integer to calculate power");
// double x = sc.nextDouble();
// int y = sc.nextInt();
// double result = power(x,y);
// System.out.println("Power is: " + result);
}
}
|
package model.bst;
import java.lang.Math;
import java.lang.IllegalArgumentException;
/**
* The TreeSet class creates a Set of any type
* and arranges them in sorted order
*/
public class TreeSet<E extends Comparable<E>> implements Set<E> {
protected TreeNode<E> root;
protected int size;
/**
* Creates an instance of the TreeSet<>
*/
public TreeSet() {
this.size = 0;
}
/**
* @param element : element to be added
* @return boolean : elemented successfully added -> true
* else -> false
* @modifies this
* @effect adds element if element does not already exist
*/
public boolean add(E element) {
// if tree is empty, initialize root
if(this.root == null) {
this.root = new TreeNode<E>(element);
return true;
}
TreeNode<E> curr = this.root;
// have to keep track of parent node
while((curr.data.compareTo(element) > 0 && curr.right != null) ||
(curr.data.compareTo(element) < 0 && curr.left != null)) {
if(curr.data.compareTo(element) > 0)
curr = curr.right;
else if(curr.data.compareTo(element) < 0)
curr = curr.left;
else {
// if it is the same as another element (compareTo function returns 0)
// then do not add duplicate
return false;
}
}
// add child to parent node depending on comparison
if(curr.data.compareTo(element) > 0) {
curr.right = new TreeNode<E>(element);
}
else if(curr.data.compareTo(element) < 0) {
curr.left = new TreeNode<E>(element);
}
size++;
return true;
}
/**
* @param element : element to be removed
* @return boolean : elemented successfully removed -> true
* else -> false
* @modifies this
* @effect removes element if element exists
*/
public boolean remove(E element) {
// if element not contained in tree, return false
if(!contains(element))
return false;
// handle case of deletion of root
if(this.root.data.equals(element)) {
if(this.root.isLeaf()) {
this.root = null;
}
else if(!this.root.hasBothChildren()) {
if(this.root.left != null)
this.root = this.root.left;
else
this.root = this.root.right;
}
else {
removeBothChildNode(this.root);
}
return true;
}
// handle the case of deletion of any other node
TreeNode<E> parent = getParentOf(element);
TreeNode<E> elementNode = null;
if(parent.left.data.equals(element))
elementNode = parent.left;
else
elementNode = parent.right;
if(elementNode.isLeaf()) {
removeLeaf(elementNode, parent);
}
else if(elementNode.hasBothChildren()) {
removeBothChildNode(elementNode);
}
else {
removeSingleChild(elementNode, parent);
}
return true;
}
// requires that element E is not data of root
private TreeNode<E> getParentOf(E element) {
TreeNode<E> parent = this.root;
TreeNode<E> curr = this.root;
while(curr.data.equals(element)) {
parent = curr;
if(curr.data.compareTo(element) > 0)
curr = curr.left;
else
curr = curr.right;
}
return parent;
}
// private method responsible for deleting a node which is identified to be a leaf
// (have no child)
// @param element : element to be removed
// @param parent: the parent of the element to be removed
private void removeLeaf(TreeNode<E> element, TreeNode<E> parent) {
if(parent.left.equals(element)) {
parent.left = null;
}
else {
parent.right = null;
}
}
// private method responsible for deleting a node which is identified to have a
// single child
// @param element : element to be removed
// @param parent: the parent of the element to be removed
private void removeSingleChild(TreeNode<E> elementNode, TreeNode<E> parent) {
if(parent.left.equals(elementNode)) {
if(parent.left.left != null)
parent.left = parent.left.left;
else
parent.left = parent.left.right;
}
else {
if(parent.right.left != null)
parent.right = parent.right.left;
else
parent.right = parent.right.right;
}
}
// private method responsible for deleting a node which is identified
// to have both children
// @param element : element to be removed
private void removeBothChildNode(TreeNode<E> elementNode) {
TreeNode<E> rightChild = elementNode.right;
TreeNode<E> leftmostChild = rightChild;
TreeNode<E> parent = elementNode;
while(leftmostChild.left != null) {
parent = leftmostChild;
leftmostChild = rightChild.left;
}
elementNode.data = leftmostChild.data;
removeSingleChild(leftmostChild, parent);
}
// returns the height of the tree
public int getHeight() {
return getHeight(this.root);
}
// @param node : root of the tree
// returns the height of the tree with node as root
protected int getHeight(TreeNode<E> node) {
if(node == null) {
return 0;
}
else {
return 1 + Math.max(getHeight(node.left), getHeight(node.right));
}
}
/**
* @return size of the current state of the set
*/
public int size() {
return size;
}
/**
* @param element : element to be checked for containment
* @return boolean : contains -> true
* else -> false
*/
public boolean contains(E element) {
TreeNode<E> curr = this.root;
while(curr != null) {
if(curr.data.compareTo(element) > 0)
curr = curr.right;
else if(curr.data.compareTo(element) < 0)
curr = curr.left;
else
return true;
}
return false;
}
/**
* This class represents a Node of the Tree in a TreeSet
* @specfield data
* @specfield children (left and right instances of Nodes)
*/
protected class TreeNode<E> {
E data;
TreeNode<E> left;
TreeNode<E> right;
/**
* Constructs and instance of TreeNode
* @param data : the data in the node
* @param left : the left child reference
* @param right : the right child reference
*/
TreeNode(E data, TreeNode<E> left, TreeNode<E> right) {
this.data = data;
this.left = left;
this.right = right;
}
/**
* Constructs an instance of TreeNode
* @param data : the data in the node
* sets left and right children to null
*/
TreeNode(E data) {
this(data, null, null);
}
/**
* Constructs an instance of TreeNode
* sets left and right children to null
* sets data to null
*/
TreeNode() {
this(null, null, null);
}
/**
* returns if this is a leafNode
* returns true if both children are null
* returns false otherwise
*/
boolean isLeaf() {
return this.left == null && this.right == null;
}
/**
* @param other : Another object to be compared to
* returns true if this and other object are the same
* Are same if they have same data
*/
public boolean equals(Object other) {
if(!(other instanceof TreeNode)) {
return false;
}
TreeNode<E> o = (TreeNode<E>) other;
return o.data.equals(this.data);
}
/**
* returns true if neither of its children are null
*/
boolean hasBothChildren() {
return this.left != null && this.right != null;
}
}
}
|
package com.GestiondesClub.entities;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
@Entity
@Table(name="TypeEvenement")
@NamedQuery(name="TypeEvenement.findAll", query="SELECT te FROM TypeEvenement te")
public class TypeEvenement {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id", updatable = false, nullable = false)
private Long id;
@Column(name="typeEvenement", unique = true)
private String typeEvenement;
@Column(name="localiter")
private int localiter;
public TypeEvenement() {
super();
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getTypeEvenement() {
return typeEvenement;
}
public void setTypeEvenement(String typeEvenement) {
this.typeEvenement = typeEvenement;
}
public int getLocaliter() {
return localiter;
}
public void setLocaliter(int localiter) {
this.localiter = localiter;
}
}
|
package com.filestore.callable;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.util.concurrent.Callable;
import org.codehaus.jettison.json.JSONObject;
public class ReadCallable implements Callable<JSONObject>
{
private String key = null;
private String storeLoc = null;
public ReadCallable(String key, String string) {
this.key = key;
this.storeLoc = storeLoc;
}
@Override
public JSONObject call() throws Exception {
boolean isDone = true;
JSONObject json = new JSONObject();
try {
String className = "com.filestore.manager.DataStoreManager";
Class<?> classType = Class.forName(className);
Class<?>[] parameterTypesForConstructor = {};
Constructor<?> constructorInstance = classType.getConstructor(parameterTypesForConstructor);
Object[] initArguments = {};
Object instance = constructorInstance.newInstance(initArguments);
Class<?>[] parameterTypes = { String.class, String.class };
Object[] args = { this.key, this.storeLoc };
Method methodToInvoke;
methodToInvoke = classType.getMethod("readFromStore", parameterTypes);
json = (JSONObject) methodToInvoke.invoke(instance, args);
} catch (Exception e) {
isDone = false;
e.printStackTrace();
}
return json;
}
}
|
package de.Schambes.Hangman;
import java.util.ArrayList;
import java.util.regex.Pattern;
public class Word {
private final String word;
private final char[] letters;
private char[] lettersHidden;
private String wordHidden;
private final int length;
private ArrayList<Character> revealed;
public Word() {
this(Utils.getWord());
}
public Word(String str) {
revealed = new ArrayList<Character>();
this.length = str.length();
this.word = str.replaceAll("\\s", "_");
this.letters = str.toCharArray();
this.lettersHidden = word.replaceAll("[\\wßäöü&&[^0-9_]]", "-").toCharArray();
this.wordHidden = new String(this.lettersHidden);
}
/**@return matches number of revealed characters, if -2, the character is invalid (all non-word characters), if -1, the character was looked up yet
*
* */
public int lookUp(char c) {
c = Character.toLowerCase(c);
if(Character.toString(c).matches("[^\\p{Alpha}&&[^äüöß]]")) {
return -2;
}
String rev = new String();
for(char r : this.revealed){
rev = rev + r;
}
if(Pattern.compile(Character.toString(c)).matcher(rev).find()) {
return -1;
}
this.revealed.add(c);
int count = 0;
for(int i = 0; i < this.length; i++) {
if(Character.toLowerCase(this.letters[i]) == c) {
this.lettersHidden[i] = this.letters[i];
count++;
}
}
this.wordHidden = new String(lettersHidden);
return count;
}
public boolean won() {
return this.wordHidden.equals(word);
}
/**@return if output -1, the player hasn't won, else it represents the count of revealed letters*/
public int lookUp(String str) {
if(str.replace("_", " ").equalsIgnoreCase(this.word.replace("_", " "))) {
int count = 0;
for(int i = 0; i < this.length; i++) {
if(this.lettersHidden[i] == '-' && this.lettersHidden[i] != this.letters[i]) {
count++;
}
}
this.lettersHidden = this.letters;
this.wordHidden = this.word;
return count;
}
return -1;
}
public String toString() {
return this.wordHidden;
}
public int getLength() {
return this.length;
}
}
|
package com.prep.etc;
public class Enumeration {
enum Student{
A(5),B(10),C(25),D(50),E(100),F(200);
private int value;
private Student(int value){
this.value=value;
}
};
public static void main(String[] args){
System.out.println(Student.A.value);
}
}
|
package ru.job4j.merge;
/**
* Class Merge реализует слияние отсортированных массивов.
* Использован алгоритм сортировки слиянием.
* @author Goureev Ilya (mailto:ill-jah@yandex.ru)
* @version 1
* @since 2017-04-13
*/
public class Merge {
/**
* Сливает 2 массива в 1 c сортировкой значения по возрастанию.
* @param first первый сливаемый массив типа int.
* @param second второй сливаемый массив типа int.
* @return array объединённый и отсортированный массив типа int.
*/
public int[] merge(int[] first, int[] second) {
int[] merged = new int[first.length + second.length];
int tmp;
for (int a = 0, b = 0, c = 0; c < merged.length; c++) {
if (a == first.length) {
tmp = second[b++];
} else if (b == second.length || first[a] < second[b]) {
tmp = first[a++];
} else {
tmp = second[b++];
}
merged[c] = tmp;
}
return merged;
}
}
|
package com.logicbig.example;
public class MainScreenProperties {
private int refreshRate;
private int width;
private int height;
public int getRefreshRate() {
return refreshRate;
}
public void setRefreshRate(int refreshRate) {
this.refreshRate = refreshRate;
}
public int getWidth() {
return width;
}
public void setWidth(int width) {
this.width = width;
}
public int getHeight() {
return height;
}
public void setHeight(int height) {
this.height = height;
}
@Override
public String toString() {
return "MainScreenProperties{" +
"refreshRate=" + refreshRate +
", width=" + width +
", height=" + height +
'}';
}
}
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package org.inbio.ara.persistence.format;
import java.util.Calendar;
import javax.persistence.EmbeddedId;
import javax.persistence.Entity;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import org.inbio.ara.persistence.LogGenericEntity;
/**
*
* @author pcorrales
*/
@Entity
@Table(name = "report_layout_element_format")
public class ReportLayoutElementFormat extends LogGenericEntity {
@EmbeddedId
protected ReportLayoutElementFormatPK reportLayoutElementFormatPK;
@JoinColumn(name = "report_layout_element_id", referencedColumnName = "report_layout_element_id", insertable = false, updatable = false)
@ManyToOne(optional = false)
private ReportLayoutElement reportLayoutElement;
public ReportLayoutElementFormat() {
}
public ReportLayoutElementFormat(ReportLayoutElementFormatPK reportLayoutElementFormatPK) {
this.reportLayoutElementFormatPK = reportLayoutElementFormatPK;
}
public ReportLayoutElementFormat(ReportLayoutElementFormatPK reportLayoutElementFormatPK, Calendar creationDate, String createdBy, Calendar lastModificationDate, String lastModificationBy) {
this.reportLayoutElementFormatPK = reportLayoutElementFormatPK;
this.setCreatedBy(createdBy);
this.setCreationDate(creationDate);
this.setLastModificationBy(lastModificationBy);
this.setLastModificationDate(lastModificationDate);
}
public ReportLayoutElementFormat(Long elementFormatId, Long reportLayoutElementId) {
this.reportLayoutElementFormatPK = new ReportLayoutElementFormatPK(elementFormatId, reportLayoutElementId);
}
public ReportLayoutElementFormatPK getReportLayoutElementFormatPK() {
return reportLayoutElementFormatPK;
}
public void setReportLayoutElementFormatPK(ReportLayoutElementFormatPK reportLayoutElementFormatPK) {
this.reportLayoutElementFormatPK = reportLayoutElementFormatPK;
}
public ReportLayoutElement getReportLayoutElement() {
return reportLayoutElement;
}
public void setReportLayoutElement(ReportLayoutElement reportLayoutElement) {
this.reportLayoutElement = reportLayoutElement;
}
@Override
public int hashCode() {
int hash = 0;
hash += (reportLayoutElementFormatPK != null ? reportLayoutElementFormatPK.hashCode() : 0);
return hash;
}
@Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof ReportLayoutElementFormat)) {
return false;
}
ReportLayoutElementFormat other = (ReportLayoutElementFormat) object;
if ((this.reportLayoutElementFormatPK == null && other.reportLayoutElementFormatPK != null) || (this.reportLayoutElementFormatPK != null && !this.reportLayoutElementFormatPK.equals(other.reportLayoutElementFormatPK))) {
return false;
}
return true;
}
@Override
public String toString() {
return "org.inbio.ara.persistence.format.ReportLayoutElementFormat[reportLayoutElementFormatPK=" + reportLayoutElementFormatPK + "]";
}
}
|
package org.isc.certanalysis.repository;
import org.isc.certanalysis.domain.Crl;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.jpa.repository.EntityGraph;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.stereotype.Repository;
import java.util.List;
import java.util.Optional;
/**
* @author p.dzeviarylin
*/
@Repository
public interface CrlRepository extends JpaRepository<Crl, Long>, JpaSpecificationExecutor<Crl> {
String CRL_BY_ISSUER_AND_SCHEME_ID = "crlByIssuerAndSchemeId";
Crl findByActiveIsTrueAndIssuerPrincipal(String issuerPrincipal);
Crl findByActiveIsFalseAndVersionAndIssuerPrincipal(int version, String issuerPrincipal);
@EntityGraph(attributePaths = "crlRevokeds")
@Cacheable(value = CRL_BY_ISSUER_AND_SCHEME_ID, key = "#issuer + #schemeId")
Optional<Crl> findByActiveIsTrueAndIssuerPrincipalAndFileSchemeId(String issuer, Long schemeId);
public List<Crl> findByActiveIsTrueAndFileId(Long fileId);
}
|
package com.natsu.springbootshirodemo.realm;
import com.natsu.springbootshirodemo.pojo.User;
import com.natsu.springbootshirodemo.service.PermissionService;
import com.natsu.springbootshirodemo.service.RoleService;
import com.natsu.springbootshirodemo.service.UserService;
import java.util.Set;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
public class DatabaseRealm extends AuthorizingRealm {
@Autowired
UserService userService;
@Autowired
RoleService roleService;
@Autowired
PermissionService permissionService;
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
// 进入到这,说明账号已经通过验证
String userName = (String) principalCollection.getPrimaryPrincipal();
// 通过servie获取角色和权限
Set<String> permissions = permissionService.listPermissions(userName);
Set<String> roles = roleService.listRoleNames(userName);
// 授权对象
SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
// 加入通过service获取到的角色和权限
simpleAuthorizationInfo.setRoles(roles);
simpleAuthorizationInfo.setStringPermissions(permissions);
return simpleAuthorizationInfo;
}
/**
* SecurityManager 委托给其进行身份验证
*/
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken)
throws AuthenticationException {
// 获取账号密码
UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken) authenticationToken;
String userName = authenticationToken.getPrincipal().toString();
// 获取数据库中的密码
User user = userService.getByName(userName);
String passwordInDB = user.getPassword();
String salt = user.getSalt();
// 认证信息里存放账号密码, getName() 是当前Realm的集成方法, 通常返回当前类名: databaseRealm
// 放入盐,通过配置的HashedCredentialsMatcher自助校验
SimpleAuthenticationInfo simpleAuthorizationInfo = new SimpleAuthenticationInfo(userName,
passwordInDB,
ByteSource.Util.bytes(salt), getName());
return simpleAuthorizationInfo;
}
}
|
public class Powerit {
public int calc(int n, int k, int m) {
long[] results = new long[n + 1];
long sum = 1;
for(int i = 2; i < results.length; ++i) {
if(results[i] == 0) {
for(int j = i + i; j < results.length; j += i) {
results[j] = i;
}
results[i] = getAns(i, k, m);
} else {
int prime = (int)results[i];
results[i] = results[prime] * results[i/prime];
results[i] %= m;
}
sum += results[i];
sum %= m;
}
return (int)sum;
}
public long getAns(int n, int k, int m) {
long result = 1;
long base = n;
for(int i = 0; i < k; ++i) {
result *= base;
result %= m;
base *= base;
base %= m;
}
return result;
}
}
|
package com.git.cloud.resmgt.compute.model.po;
import com.git.cloud.common.model.base.BaseBO;
public class RmHostResPoolPo extends BaseBO implements java.io.Serializable{
/**
*
*/
private static final long serialVersionUID = 3657155742087231181L;
// Fields
private String id;
private String platformType;
private String serviceType;
private String secureAreaType;
private String secureLayer;
private String availableZoneId;
private String hostTypeId;
// Constructors
/** default constructor */
public RmHostResPoolPo() {
}
/** minimal constructor */
public RmHostResPoolPo(String id) {
this.id = id;
}
/** full constructor */
public RmHostResPoolPo(String id, String platformType, String serviceType,
String secureAreaType, String secureLayer) {
this.id = id;
this.platformType = platformType;
this.serviceType = serviceType;
this.secureAreaType = secureAreaType;
this.secureLayer = secureLayer;
}
// Property accessors
public String getId() {
return this.id;
}
public void setId(String id) {
this.id = id;
}
public String getPlatformType() {
return this.platformType;
}
public void setPlatformType(String platformType) {
this.platformType = platformType;
}
public String getServiceType() {
return this.serviceType;
}
public void setServiceType(String serviceType) {
this.serviceType = serviceType;
}
public String getSecureAreaType() {
return this.secureAreaType;
}
public void setSecureAreaType(String secureAreaType) {
this.secureAreaType = secureAreaType;
}
public String getSecureLayer() {
return this.secureLayer;
}
public void setSecureLayer(String secureLayer) {
this.secureLayer = secureLayer;
}
public String getAvailableZoneId() {
return availableZoneId;
}
public void setAvailableZoneId(String availableZoneId) {
this.availableZoneId = availableZoneId;
}
public String getHostTypeId() {
return hostTypeId;
}
public void setHostTypeId(String hostTypeId) {
this.hostTypeId = hostTypeId;
}
@Override
public String getBizId() {
// TODO Auto-generated method stub
return null;
}
}
|
package com.darwinsys.bookmarkscp;
import android.content.ContentProvider;
import android.content.ContentValues;
import android.database.AbstractCursor;
import android.database.Cursor;
import android.net.Uri;
/**
* A completely mock re-implementation of the BrowserBookmarks CP
* that died back in API 23.
* Not useful except to keep ancient demos alive.
*/
public class BookmarksContentProvider extends ContentProvider {
/** Private inner class just to create a list of data */
private static class Bookmark {
int _id;
String title;
String URL;
Bookmark(int _id, String title, String URL) {
this._id = _id;
this.title = title;
this.URL = URL;
}
}
final static Bookmark[] data = {
new Bookmark(1, "DarwinSys-Java", "https://darwinsys.com/java"),
new Bookmark(2, "Facebook", "https://facebook.com"),
new Bookmark(3, "Google Search", "https://google.com/"),
new Bookmark(4, "Google Maps", "https://google.com/maps"),
new Bookmark(5, "Instagram", "https://instagram.com"),
new Bookmark(6, "Tesla", "https://ts.la/ian40191"),
new Bookmark(7, "Twitter", "https://twitter.com"),
new Bookmark(8, "Yahoo", "https://yahoo.com"),
};
private static final String[] COLUMN_NAMES = {
Browser.BookmarkColumns._ID,
Browser.BookmarkColumns.TITLE,
Browser.BookmarkColumns.URL,
};
/** Static Cursor implementation class */
class DataCursor extends AbstractCursor {
int currentRow = -1;
public boolean onMove(int oldPosition, int newPosition) {
currentRow = newPosition;
return true;
}
@Override
public int getCount() {
return data.length;
}
@Override
public String[] getColumnNames() {
return COLUMN_NAMES;
}
@Override
public String getString(int column) {
switch(column) {
case 0:
throw new IllegalArgumentException();
case 1:
return data[currentRow].title;
case 2:
return data[currentRow].URL;
}
throw new IllegalArgumentException();
}
@Override
public short getShort(int column) {
throw new IllegalArgumentException();
}
@Override
public int getInt(int column) {
if (column == 0) {
return data[currentRow]._id;
}
throw new IllegalArgumentException();
}
@Override
public long getLong(int column) {
if (column == 0) {
return data[currentRow]._id;
}
throw new IllegalArgumentException();
}
@Override
public float getFloat(int column) {
return 0;
}
@Override
public double getDouble(int column) {
throw new UnsupportedOperationException();
}
@Override
public boolean isNull(int column) {
return false;
}
}
public BookmarksContentProvider() {
// empty
}
@Override
public boolean onCreate() {
// empty
return true;
}
@Override
public String getType(Uri uri) {
return "vnd.darwinsys.cursor.dir/bookmark";
}
@Override
public Cursor query(Uri uri, String[] projection, String selection,
String[] selectionArgs, String sortOrder) {
return new DataCursor();
}
// Insert, update and delete won't be implemented, as it's read-only data
@Override
public Uri insert(Uri uri, ContentValues values) {
throw new UnsupportedOperationException("Read-only");
}
@Override
public int update(Uri uri, ContentValues values, String selection,
String[] selectionArgs) {
throw new UnsupportedOperationException("Read-only");
}
@Override
public int delete(Uri uri, String selection, String[] selectionArgs) {
// Implement this to handle requests to delete one or more rows.
throw new UnsupportedOperationException("Read-Only");
}
}
|
package com.egreat.devicemanger;
import java.security.Key;
import java.security.SecureRandom;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
/**
* 使用3DES加密与解密,可对byte[],String类型进行加密与解密 密文可使用String,byte[]存储.
*
*/
public class EncryptUtil {
private String Algorithm = ""; //定义 加密算法,可用
private EncryptUtil(String algorithm) {
this.Algorithm = algorithm;
}
public static EncryptUtil getDesInstance() {
return new EncryptUtil("DESede");
}
public static EncryptUtil getAesInstance() {
return new EncryptUtil("AES");
}
// private Key key; //密钥
/**
* 根据参数生成KEY
*
* @param strKey 密钥字符串
*/
private SecretKeySpec generateKey(String password) {
try {
if(Algorithm.equalsIgnoreCase("AES"))
return generateAesKey(password);
else if("DESede".equalsIgnoreCase(Algorithm))
return generateDesKey(password);
else
return null;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
private SecretKeySpec generateAesKey(String password) {
try {
KeyGenerator kgen = KeyGenerator.getInstance(Algorithm);
kgen.init(128, new SecureRandom(password.getBytes()));
SecretKey secretKey = kgen.generateKey();
byte[] enCodeFormat = secretKey.getEncoded();
SecretKeySpec key = new SecretKeySpec(enCodeFormat, Algorithm);
return key;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public SecretKeySpec generateDesKey(String strKey) {
try {
StringBuffer sb = new StringBuffer(strKey);
while(sb.length()<24) { // 补齐24位。右边补齐0{
sb.append("0");
}
SecretKeySpec deskey = new SecretKeySpec(sb.toString().getBytes(), Algorithm);
return deskey;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* 加密String明文输入,String密文输出
*
* @param strMing String明文
* @return String密文 16进制格式
*/
public String encryptToHexString(String strMing, String password) {
byte[] byteMi = null;
byte[] byteMing = null;
String strMi = "";
try {
byteMing = strMing.getBytes();
byteMi = this.getEncCode(byteMing, password);
strMi = byteArr2HexStr(byteMi);
} catch (Exception e) {
e.printStackTrace();
} finally {
byteMing = null;
byteMi = null;
}
return strMi;
}
/**
* 加密以byte[]明文输入,byte[]密文输出
*
* @param byteS byte[]明文
* @return byte[]密文
*/
private byte[] getEncCode(byte[] byteS, String password) {
byte[] byteFina = null;
Cipher cipher;
try {
Key key = generateKey(password);
cipher = Cipher.getInstance(Algorithm);
cipher.init(Cipher.ENCRYPT_MODE, key);
byteFina = cipher.doFinal(byteS);
} catch (Exception e) {
e.printStackTrace();
} finally {
cipher = null;
}
return byteFina;
}
//数组转16进制字符串
public static String byteArr2HexStr(byte[] arrB) throws Exception {
int iLen = arrB.length;
// 每个byte用两个字符才能表示,所以字符串的长度是数组长度的两倍
StringBuffer sb = new StringBuffer(iLen * 2);
for (int i = 0; i < iLen; i++) {
int intTmp = arrB[i];
// 把负数转换为正数
while (intTmp < 0) {
intTmp = intTmp + 256;
}
// 小于0F的数需要在前面补0
if (intTmp < 16) {
sb.append("0");
}
sb.append(Integer.toString(intTmp, 16));
}
// 最大128位
String result = sb.toString();
// if(result.length()>128){
// result = result.substring(0,result.length()-1);
// }
return result;
}
}
|
package com.community.yuequ.modle;
import java.util.List;
/**
* Created by Administrator on 2016/5/11.
*/
public class YQImageDao {
/**
* {
"errorCode" : 200,
"errorMessage" : "查询成功",
"result" : [ {
"id" : 7,
"name" : "段子",
"img_path" : "http://171.8.238.102:8081/yqfile",
"content_desc" : "",
"program_cnt" : 55
}, {
"id" : 30,
"name" : "趣图",
"img_path" : "http://171.8.238.102:8081/yqfile",
"content_desc" : "",
"program_cnt" : 45
}, {
"id" : 35,
"name" : "美女",
"img_path" : "http://171.8.238.102:8081/yqfile",
"content_desc" : "",
"program_cnt" : 50
}, {
"id" : 40,
"name" : "星座",
"img_path" : "http://171.8.238.102:8081/yqfile",
"content_desc" : "",
"program_cnt" : 60
} ]
}
*/
public int errorCode;
public String errorMessage;
public List<RTextImage> result;
}
|
package com.btress;
import java.util.ArrayList;
import java.util.List;
import java.util.Stack;
public class TreeDiameter {
public static void main(String[] args) {
BinaryTree bst = new BinaryTree();
BinaryTree tree1 = bst.createBinaryTree();
//System.out.println(diameter(tree1.root));
TreeDiameter td = new TreeDiameter();
td.inOrder(tree1.root);
System.out.println();
//BinaryTree tree2 = bst.createBinaryTree();
//td.postOrderIterative(tree2.root);
}
/*
* left height, rheigth+1 or ldiamter,rightdiameter Max
*/
public static int diameter(TreeNode root) {
if (root == null) return 0;
int lHeight = height(root.left);
int rHeight = height(root.right);
int leftDiamter = diameter(root.left);
int rightDiamter = diameter(root.right);
int finalDiameter = Math.max(lHeight+rHeight+1, Math.max(leftDiamter, rightDiamter));
return finalDiameter;
}
public static int height(TreeNode root) {
if(root == null) return 0;
int left = height(root.left);
int right = height(root.right);
if(left > right) {
return left+1;
}else {
return right+1;
}
}
public void inOrder(TreeNode root) {
if(root ==null) return ;
inOrder(root.left);
System.out.print(root.data);
inOrder(root.right);
}
public void preOrder(TreeNode root) {
if(root ==null) return;
System.out.print(root.data);
preOrder(root.left);
preOrder(root.right);
}
public void postOrder(TreeNode root) {
if(root ==null) return;
postOrder(root.left);
postOrder(root.right);
System.out.print(root.data);
}
public void inOrderIterative(TreeNode root) {
if(root == null) return;
// we need a stack
Stack<TreeNode> s = new Stack<>();
TreeNode curr = root;
System.out.println();
while(curr !=null || s.size() >0) {
while(curr !=null) {
s.push(curr);
curr = curr.left;
}
curr = s.pop();
System.out.print(curr.data);
curr = curr.right;
}
}
public void postOrderIterative(TreeNode root) {
List<Integer> res = new ArrayList<Integer>();
if(root==null) {
return ;
}
Stack<TreeNode> stack = new Stack<TreeNode>();
stack.push(root);
while(!stack.isEmpty()) {
TreeNode temp = stack.peek();
if(temp.left==null && temp.right==null) {
TreeNode pop = stack.pop();
res.add(pop.data);
}
else {
if(temp.right!=null) {
stack.push(temp.right);
temp.right = null;
}
if(temp.left!=null) {
stack.push(temp.left);
temp.left = null;
}
}
}
System.out.print(res);
}
public TreeNode LCA(TreeNode root, TreeNode node1, TreeNode node2) {
if(root == null)
return null;
if(root ==node1 || root ==node2)
return root;
TreeNode left = LCA(root.left,node1,node2);
TreeNode right = LCA(root.right,node1,node2);
if(left !=null && right !=null)
return root;
else
return (left!=null?left:right);
}
}
|
package jp.ac.kyushu_u.csce.modeltool.explorer.explorer;
import org.eclipse.core.resources.IContainer;
import org.eclipse.core.resources.IFile;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.jface.viewers.ViewerComparator;
import org.eclipse.jface.viewers.ViewerSorter;
/**
* リソースのソート順を規定するクラス
*
* @author KBK yoshimura
*/
public class ResourceSorter extends ViewerSorter {
/** コンパレータ */
protected ViewerComparator comparator;
/**
* コンストラクタ
*/
public ResourceSorter() {
comparator = new ViewerComparator();
}
/**
* リソース1がリソース2より小さい、等しい、大きい場合に、
* それぞれ負、0、正の値を返す
* @param viewer ビューアー
* @param e1 リソース1
* @param e2 リソース2
*/
public int compare(Viewer viewer, Object e1, Object e2) {
// リソース1、2がフォルダの場合
if (e1 instanceof IContainer && e2 instanceof IContainer) {
return comparator.compare(viewer, e1, e2);
}
// リソース1がフォルダ、リソース2がファイルの場合
if (e1 instanceof IContainer && e2 instanceof IFile) {
return -1;
}
// リソース1がファイル、リソース2がフォルダの場合
if (e1 instanceof IFile && e2 instanceof IContainer) {
return 1;
}
// リソース1,2がファイルの場合
if (e1 instanceof IFile && e2 instanceof IFile) {
return comparator.compare(viewer, e1, e2);
}
return comparator.compare(viewer, e1, e2);
}
}
|
package com.tensquare.qa.test;
import com.tensquare.qa.pojo.Problem;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class IPProjectTest {
@RequestMapping("/retuser")
public Problem returnProblem(){
return new Problem("1","标题","content",null,null,"userid","昵称",0l,0l,0l,null,null,null);
}
}
|
/*
* Banco Davivienda 2008
* Proyecto Utilidades
* Versión 1.0
*/
package com.davivienda.utilidades.archivoxls;
import java.util.ArrayList;
import java.util.Collection;
/**
* Registro - 11/08/2008
* Descripción : Registro que comprende una líneaXLS
* Versión : 1.0
*
* @author jjvargas
* Davivienda 2008
*/
public class Registro {
private Collection<Celda> celdas;
public Registro() {
celdas = new ArrayList<Celda>();
}
public void addCelda(Celda celda) {
celdas.add(celda);
}
public Collection<Celda> getCeldas() {
return celdas;
}
public void setCeldas(ArrayList<Celda> celdas) {
this.celdas = celdas;
}
}
|
package in.anandm.oj.repository;
import in.anandm.oj.model.EvaluationResult;
import in.anandm.oj.model.Solution;
import java.util.List;
import org.springframework.transaction.annotation.Transactional;
public interface EvaluationResultRepository {
@Transactional
EvaluationResult saveEvaluationResult(EvaluationResult evaluationResult);
List<EvaluationResult> getAllEvaluationResultsOfSolution(Solution solution);
}
|
/**
*
*/
package com.needii.dashboard.controller;
import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import com.google.zxing.WriterException;
import com.needii.dashboard.service.CustomerService;
import com.needii.dashboard.service.GenerateQRCode;
import com.needii.dashboard.service.cache.ConfigurationCache;
import com.needii.dashboard.utils.ConfigurationKey;
import com.needii.dashboard.utils.Constants;
/**
* @author Vincent
*
*/
@Controller
@RequestMapping("/")
public class SharingController extends BaseController{
@Autowired
GenerateQRCode generateQRCode;
@Autowired
CustomerService customerService;
@Autowired
ConfigurationCache configurationCache;
@RequestMapping(value = "/get-qr-code", method = RequestMethod.GET)
public @ResponseBody void generateQRCode(@RequestParam("referenceCode") String referenceCode, Model model, HttpServletRequest request) throws WriterException, IOException {
if(referenceCode != null && !referenceCode.isEmpty()) {
generateQRCode.generateQRCodePath(referenceCode);
}
}
@RequestMapping(value = "/share/reference-code", method = RequestMethod.GET)
public String shareQRCode(@RequestParam("referenceCode") String referenceCode,
@RequestParam("bonus") String bonus,
@RequestParam( value = "typeServer", defaultValue = "2") Integer typeServer,
Model model) throws WriterException, IOException {
model.addAttribute("referenceCode", referenceCode);
model.addAttribute("bonus", bonus);
model.addAttribute("domain", typeServer == 1 ? Constants.CMC_RESOURCE_DOMAIN : Constants.RESOURCE_DOMAIN);
model.addAttribute(ConfigurationKey.GOOGLE_ANDROID_LINK, configurationCache.get(ConfigurationKey.GOOGLE_ANDROID_LINK));
model.addAttribute(ConfigurationKey.APPLE_IOS_LINK, configurationCache.get(ConfigurationKey.APPLE_IOS_LINK));
return "referenceCodeSharing";
}
}
|
package com.apon.taalmaatjes.frontend.transition;
import com.apon.taalmaatjes.frontend.presentation.Screen;
import javafx.fxml.FXMLLoader;
import java.util.HashMap;
import java.util.Map;
public class FxmlLocation {
private static FxmlLocation ourInstance = new FxmlLocation();
public static FxmlLocation getInstance() {
return ourInstance;
}
private Map<ScreenEnum, String> mapEnumFxml;
private FxmlLocation() {
// Initialize the map that goes from enum to fxml.
mapEnumFxml = new HashMap();
mapEnumFxml.put(ScreenEnum.VOLUNTEERS_OVERVIEW, VOLUNTEERS_OVERVIEW);
mapEnumFxml.put(ScreenEnum.VOLUNTEERS_DETAIL, VOLUNTEERS_DETAIL);
mapEnumFxml.put(ScreenEnum.VOLUNTEERS_ADD, VOLUNTEERS_ADD);
mapEnumFxml.put(ScreenEnum.VOLUNTEERS_ADD_MATCH, VOLUNTEERS_ADD_MATCH);
mapEnumFxml.put(ScreenEnum.VOLUNTEERS_ADD_INSTANCE, VOLUNTEERS_ADD_INSTANCE);
mapEnumFxml.put(ScreenEnum.VOLUNTEERS_EDIT_LOG, VOLUNTEERS_EDIT_LOG);
mapEnumFxml.put(ScreenEnum.STUDENTS_OVERVIEW, STUDENTS_OVERVIEW);
mapEnumFxml.put(ScreenEnum.STUDENTS_ADD, STUDENTS_ADD);
mapEnumFxml.put(ScreenEnum.STUDENTS_DETAIL, STUDENTS_DETAIL);
mapEnumFxml.put(ScreenEnum.TASKS_OVERVIEW, TASKS_OVERVIEW);
mapEnumFxml.put(ScreenEnum.TASKS_ADD, TASKS_ADD);
mapEnumFxml.put(ScreenEnum.TASKS_DETAIL, TASKS_DETAIL);
mapEnumFxml.put(ScreenEnum.REPORT, REPORT);
}
// Used in other places.
public final static String TAALMAATJES = "com/apon/taalmaatjes/Taalmaatjes";
public final static String MAIN = "com/apon/taalmaatjes/frontend/Main";
// Volunteers
private final static String VOLUNTEERS_OVERVIEW = "com/apon/taalmaatjes/frontend/tabs/volunteers/Volunteers";
private final static String VOLUNTEERS_DETAIL = "com/apon/taalmaatjes/frontend/tabs/volunteers/detail/DetailVolunteer";
private final static String VOLUNTEERS_ADD = "com/apon/taalmaatjes/frontend/tabs/volunteers/add/AddVolunteer";
private final static String VOLUNTEERS_ADD_MATCH = "com/apon/taalmaatjes/frontend/tabs/volunteers/detail/match/AddVolunteerMatch";
private final static String VOLUNTEERS_ADD_INSTANCE = "com/apon/taalmaatjes/frontend/tabs/volunteers/detail/instance/AddVolunteerInstance";
private final static String VOLUNTEERS_EDIT_LOG = "com/apon/taalmaatjes/frontend/tabs/volunteers/detail/log/EditLog";
// Students
private final static String STUDENTS_OVERVIEW = "com/apon/taalmaatjes/frontend/tabs/students/Students";
private final static String STUDENTS_ADD = "com/apon/taalmaatjes/frontend/tabs/students/add/AddStudent";
private final static String STUDENTS_DETAIL = "com/apon/taalmaatjes/frontend/tabs/students/detail/DetailStudent";
// Tasks
private final static String TASKS_OVERVIEW = "com/apon/taalmaatjes/frontend/tabs/task/Tasks";
private final static String TASKS_ADD = "com/apon/taalmaatjes/frontend/tabs/task/add/AddTask";
private final static String TASKS_DETAIL = "com/apon/taalmaatjes/frontend/tabs/task/detail/DetailTask";
// Reports
private final static String REPORT = "com/apon/taalmaatjes/frontend/tabs/report/Report";
/**
* Return the loader based on the screenEnum.
* @param screenEnum Screen to load.
* @return The loader.
*/
public FXMLLoader getLoaderForScreen(ScreenEnum screenEnum) {
return new FXMLLoader(getClass().getClassLoader().getResource(mapEnumFxml.get(screenEnum) + ".fxml"));
}
}
|
package controlador;
import javax.swing.JProgressBar;
import modelo.Hotel;
import modelo.Progreso;
import vista.PConfiguracion;
import vista.VIntroduccion;
import vista.VFrame;
import vista.VTabla;
public class Controlador {
private VFrame frame;
private Hotel hotel;
private boolean pause,stop;
private Progreso proc;
public Controlador(){
inicializar();
}
private void inicializar() {
pause=false;
stop=true;
hotel=new Hotel();
frame=new VFrame(this);
hotel.setpp(frame.getpp().getPA());
frame.setVisible(false);
VIntroduccion intro=new VIntroduccion(frame);
try {
Thread.sleep(1000);
intro.dispose();
frame.setVisible(true);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public void play() {
if(!pause&&stop){
stop=false;
pause=false;
PConfiguracion confi=frame.getpp().getP_confi();
confi.deshabilitar();
frame.getpp().getP_botones().botones_play();
hotel.setNroHab1(confi.getNroHab1());
hotel.setNroHab2(confi.getNroHab2());
hotel.setNroHab3(confi.getNroHab3());
hotel.setNroHab4(confi.getNroHab4());
hotel.setPrecioHab1(confi.getPrecio1());
hotel.setPrecioHab2(confi.getPrecio2());
hotel.setPrecioHab3(confi.getPrecio3());
hotel.setPrecioHab4(confi.getPrecio4());
hotel.setDemanda1(confi.getDemanda1());
hotel.setDemanda2(confi.getDemanda2());
hotel.setDemanda3(confi.getDemanda3());
hotel.setDemanda4(confi.getDemanda4());
hotel.setTemporada(confi.getTemporada());
hotel.setTiempoSim(confi.getTiempo());
hotel.setVelocidad(confi.getVel());
hotel.run();
}else
if(pause){
pause=false;
hotel.run();
}
}
public void setPause() {
pause=true;
stop=false;
frame.getpp().getP_confi().habilitar();
frame.getpp().getP_botones().botones_pause();
hotel.setPause();
proc.setPause();
}
public void setStop() {
stop=true;
pause=false;
frame.getpp().getP_confi().habilitar();
frame.getpp().getP_botones().botones_stop();
proc.setStop();
hotel.setStop();
}
public void generarTabla() {
VTabla tabla=new VTabla(hotel);
tabla.llenar();
}
public Hotel getHotel() {
if(hotel==null)
System.out.println("Retorna el hotel del controlador ESTA VACIO");
return hotel;
}
public void progreso(int t,JProgressBar p){
proc=new Progreso(t,p,this);
proc.setVel(hotel.getVelocidad());
proc.start();
}
}
|
package org.robotframework.formslibrary.chooser;
import java.awt.Component;
import org.netbeans.jemmy.ComponentChooser;
import org.robotframework.formslibrary.util.ComponentType;
/**
* Chooser to select Oracle Forms components based on their type (class) and
* index (occurrence). Hidden components are ignored.
*/
public class ByComponentTypeChooser implements ComponentChooser {
private ComponentType[] allowedTypes;
private int index;
/**
* @param index
* Specifies which occurrence of the component in the context to
* select. Use -1 to select all occurrences.
* @param allowedTypes
* Specifies which component types to include.
*/
public ByComponentTypeChooser(int index, ComponentType... allowedTypes) {
this.index = index;
this.allowedTypes = allowedTypes;
}
@Override
public boolean checkComponent(Component component) {
for (ComponentType type : allowedTypes) {
if (type.matches(component) && component.isShowing()) {
if (index <= 0) {
return true;
} else {
index--;
}
}
}
return false;
}
@Override
public String getDescription() {
StringBuilder builder = new StringBuilder();
for (ComponentType t : allowedTypes) {
if (builder.length() > 0) {
builder.append(" / ");
}
builder.append(t);
}
return builder.toString();
}
}
|
import java.util.Scanner;
public class task5 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Введите число в бинарном формате: ");
String binaryStr = in.nextLine();
int binaryNum = Integer.parseInt(binaryStr, 2);
System.out.println(binaryNum);
}
}
|
/**
* This class is generated by jOOQ
*/
package schema.tables.records;
import javax.annotation.Generated;
import org.jooq.Field;
import org.jooq.Record1;
import org.jooq.Record3;
import org.jooq.Row3;
import org.jooq.impl.UpdatableRecordImpl;
import schema.tables.DjangoCommentClientPermissionRoles;
/**
* This class is generated by jOOQ.
*/
@Generated(
value = {
"http://www.jooq.org",
"jOOQ version:3.8.4"
},
comments = "This class is generated by jOOQ"
)
@SuppressWarnings({ "all", "unchecked", "rawtypes" })
public class DjangoCommentClientPermissionRolesRecord extends UpdatableRecordImpl<DjangoCommentClientPermissionRolesRecord> implements Record3<Integer, String, Integer> {
private static final long serialVersionUID = -1157707201;
/**
* Setter for <code>bitnami_edx.django_comment_client_permission_roles.id</code>.
*/
public void setId(Integer value) {
set(0, value);
}
/**
* Getter for <code>bitnami_edx.django_comment_client_permission_roles.id</code>.
*/
public Integer getId() {
return (Integer) get(0);
}
/**
* Setter for <code>bitnami_edx.django_comment_client_permission_roles.permission_id</code>.
*/
public void setPermissionId(String value) {
set(1, value);
}
/**
* Getter for <code>bitnami_edx.django_comment_client_permission_roles.permission_id</code>.
*/
public String getPermissionId() {
return (String) get(1);
}
/**
* Setter for <code>bitnami_edx.django_comment_client_permission_roles.role_id</code>.
*/
public void setRoleId(Integer value) {
set(2, value);
}
/**
* Getter for <code>bitnami_edx.django_comment_client_permission_roles.role_id</code>.
*/
public Integer getRoleId() {
return (Integer) get(2);
}
// -------------------------------------------------------------------------
// Primary key information
// -------------------------------------------------------------------------
/**
* {@inheritDoc}
*/
@Override
public Record1<Integer> key() {
return (Record1) super.key();
}
// -------------------------------------------------------------------------
// Record3 type implementation
// -------------------------------------------------------------------------
/**
* {@inheritDoc}
*/
@Override
public Row3<Integer, String, Integer> fieldsRow() {
return (Row3) super.fieldsRow();
}
/**
* {@inheritDoc}
*/
@Override
public Row3<Integer, String, Integer> valuesRow() {
return (Row3) super.valuesRow();
}
/**
* {@inheritDoc}
*/
@Override
public Field<Integer> field1() {
return DjangoCommentClientPermissionRoles.DJANGO_COMMENT_CLIENT_PERMISSION_ROLES.ID;
}
/**
* {@inheritDoc}
*/
@Override
public Field<String> field2() {
return DjangoCommentClientPermissionRoles.DJANGO_COMMENT_CLIENT_PERMISSION_ROLES.PERMISSION_ID;
}
/**
* {@inheritDoc}
*/
@Override
public Field<Integer> field3() {
return DjangoCommentClientPermissionRoles.DJANGO_COMMENT_CLIENT_PERMISSION_ROLES.ROLE_ID;
}
/**
* {@inheritDoc}
*/
@Override
public Integer value1() {
return getId();
}
/**
* {@inheritDoc}
*/
@Override
public String value2() {
return getPermissionId();
}
/**
* {@inheritDoc}
*/
@Override
public Integer value3() {
return getRoleId();
}
/**
* {@inheritDoc}
*/
@Override
public DjangoCommentClientPermissionRolesRecord value1(Integer value) {
setId(value);
return this;
}
/**
* {@inheritDoc}
*/
@Override
public DjangoCommentClientPermissionRolesRecord value2(String value) {
setPermissionId(value);
return this;
}
/**
* {@inheritDoc}
*/
@Override
public DjangoCommentClientPermissionRolesRecord value3(Integer value) {
setRoleId(value);
return this;
}
/**
* {@inheritDoc}
*/
@Override
public DjangoCommentClientPermissionRolesRecord values(Integer value1, String value2, Integer value3) {
value1(value1);
value2(value2);
value3(value3);
return this;
}
// -------------------------------------------------------------------------
// Constructors
// -------------------------------------------------------------------------
/**
* Create a detached DjangoCommentClientPermissionRolesRecord
*/
public DjangoCommentClientPermissionRolesRecord() {
super(DjangoCommentClientPermissionRoles.DJANGO_COMMENT_CLIENT_PERMISSION_ROLES);
}
/**
* Create a detached, initialised DjangoCommentClientPermissionRolesRecord
*/
public DjangoCommentClientPermissionRolesRecord(Integer id, String permissionId, Integer roleId) {
super(DjangoCommentClientPermissionRoles.DJANGO_COMMENT_CLIENT_PERMISSION_ROLES);
set(0, id);
set(1, permissionId);
set(2, roleId);
}
}
|
package Game;
import Player.Player;
//So here is a basic concept for a game, where you'll be able to level a player
//and use items to perform tasks. The example here shows I added one item to my bag
public class Game {
private Player player;
public Game(String s) {
player = new Player(s, "123");
System.out.println("New Game");
}
public Player getPlayer() {
return player;
}
public void setPlayer(Player player) {
this.player = player;
}
public static void main(String[] args) {
Game g = new Game("Coobs");
System.out.println(g.getPlayer());
}
}
|
package com.gbros.springboot;
import java.util.HashSet;
import java.util.Set;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
@RestController
@EnableAutoConfiguration
@ComponentScan("com.gbros")
//扫描启动springboot要用到的类
//初始化springboot
public class SpringBoot {
public static void main(String[] args) {
SpringApplication app = new SpringApplication(SpringBoot.class);
app.setWebEnvironment(true);
app.setShowBanner(false);
Set<Object> set = new HashSet<Object>();
app.setSources(set);
app.run(args);
}
}
|
package com.inovi.allerta.activity;
import android.os.Bundle;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.AppCompatActivity;
import android.widget.Button;
import com.inovi.allerta.R;
public class APACPublicarActivity extends AppCompatActivity {
private Button enviar;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_publicar_apac);
this.setTitle("APAC");
// enviar = findViewById(R.id.btnEnviar);
//
// enviar.setOnClickListener(new View.OnClickListener() {
// @Override
// public void onClick(View v) {
//
//
// }
// });
}
}
|
package hwarang.artg.funding.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import hwarang.artg.common.model.CriteriaDTO;
import hwarang.artg.funding.model.FundingReplyVO;
import hwarang.artg.mapper.FundingRelpyMapper;
import lombok.Setter;
@Service
public class FundingReplyServiceImpl implements FundingReplyService{
@Setter(onMethod_ = @Autowired)
private FundingRelpyMapper mapper;
@Override
public int register(FundingReplyVO vo) {
// TODO Auto-generated method stub
return mapper.insert(vo);
}
@Override
public FundingReplyVO get(Long rno) {
// TODO Auto-generated method stub
return mapper.read(rno);
}
@Override
public int modify(FundingReplyVO vo) {
// TODO Auto-generated method stub
return mapper.update(vo);
}
@Override
public int remove(Long rno) {
// TODO Auto-generated method stub
return mapper.delete(rno);
}
@Override
public List<FundingReplyVO> getList(CriteriaDTO cri, Long funding_num) {
// TODO Auto-generated method stub
return mapper.getListWithPaging(cri, funding_num);
}
}
|
package Servidor;
import java.net.*;
// Este paquete se encarga del manejo de los
// DataStream y ObjectStream
import java.io.*;
import java.util.logging.Level;
import java.util.logging.Logger;
public class Servidor {
DataInputStream entrada;//Para leer comunicacion
DataOutputStream salida;//Para enviar comunicacion
//public ArrayList<threadServidor> hilosserver;
Socket cliente1;
Socket cliente2;
FrmServidor ventana;
threadServidor user1;
threadServidor user2;
public Servidor(FrmServidor entrada) {
this.ventana = entrada;
}
public void runServer() {
ServerSocket ss;
try {
ss = new ServerSocket(9998);
while (true) {
//Queda a la espera de la coneccion de los clientes
cliente1 = ss.accept();
System.out.println("Primer Cliente Conectado");
ventana.agregarMensaje("Primer Cliente Conectado");
//aqui iniciaria el hilo
user1 = new threadServidor(cliente1, this);
user1.salida.writeInt(1);
//user1.start();
//Queda a la espera de la coneccion de los clientes
cliente2 = ss.accept();
System.out.println("Segundo Cliente Conectado");
ventana.agregarMensaje("Segundo Cliente Conectado");
ventana.agregarMensaje("---------------------------");
user2 = new threadServidor(cliente2, this);
user2.salida.writeInt(1);
user1.salida.writeInt(2);//inicia proceso de carga de otra pantalla
user2.salida.writeInt(2);//inicia proceso de carga de otra pantalla
user1.salida.writeInt(1);// Asigna el turno al jugador
user2.salida.writeInt(2);
user1.asignacionCliente2(cliente2);
user2.asignacionCliente2(cliente1);
user1.start();
user2.start();
}
} catch (IOException ex) {
Logger.getLogger(Servidor.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
|
/*
* 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 bbdd;
import java.util.ArrayList;
/**
*
* @author jesus
*/
interface BBDD {
/**
* Inicia la conexión con el servidor de Base de datos
*/
public void abrirConexion();
/**
* Funcion para saber si existe el usuario en la bbdd
* @param idUsuario usuario que buscams
* @return true si esta, false si no
*/
public boolean estaUsuario(String idUsuario);
/**
* Funcion para saber si esa contrasena pertenece a un usuario
* @param idUsuario usuario de la contrasena
* @param contrasena contraseña
* @return true si es valida, false en caso contrario
*/
public boolean contrasenaCorrecta(String idUsuario, String contrasena);
/**
* Funcion que devuelve un usuario a traves de su id
* @param idUsuario id del usuario
* @return objeto Usuario con ese id
*/
public Usuario getUsuario(String idUsuario);
/**
* Funcion para obtener la lista con todos los usuarios
* @return arraylist con todos los usuarios
*/
public ArrayList<Usuario> getUsuarios();
/**
* Funcion para guardar un usuario
* @param usuario objeto de tipo usuario que queremos guardar
*/
public void guardarUsuario(Usuario usuario);
/**
* funcion para obtener las reservas de un usuario
* @param idUsuario id del usuario cuyas reservas necesitamos
* @return arraylist con todas las reservas
*/
public ArrayList<Reserva> getReservas(String idUsuario);
/**
* funcion para obtener una sesion
* @param idSesion id de la sesion que queremos
* @return Objeto sesion
*/
public Sesion getSesion(String idSesion);
/**
* Funcion para obtener el tipo de entrada
* @param idEntrada String que indica el id de la entrada
* @return "reducida" en caso de ser reducida, "normal" en otro caso
*/
public String getTipoEntrada(String idEntrada);
/**
* Obtiene una entrada a través de su id
* @param idEntrada
* @return objeto de tipo entrada
*/
public Entrada getEntrada(String idEntrada);
/**
* Funcion para modificar un usuario
* @param usuario
*/
public void modificarUsuario(Usuario usuario);
/**
* Funcion para obtener todas las entradas de la base de datos
* @return un arrayList con todas las entradas
*/
public ArrayList<Entrada> getEntradas();
/**
* Funcion para eliminar la entrada con ese ID
* @param idEntrada
*/
public void eliminarEntrada(String idEntrada);
/**
* Funcion para eliminar la reserva con ese ID
* @param idReserva
*/
public void eliminarReserva(String idReserva);
/**
* Funcion apra obtener todas las películas
* @return
*/
public ArrayList<Pelicula> getPeliculas();
/**
* Funcion para obtener una pelicula a través de su ID
* @param idPelicula
* @return objeto Pelicula
*/
public Pelicula getPelicula(String idPelicula);
/**
* FUncion para obtener los actores de una pelicula
* @param idPelicula
* @return lista con todos los actores
*/
public ArrayList<Actor> getActores(String idPelicula);
/**
* Funcion para obtener los comentarios de una pelicula
* @param idPelicula
* @return lista con todos los comentarios
*/
public ArrayList<Comentario> getComentarios(String idPelicula);
/**
* Funcion para guardar un comentario
* @param comentario
*/
public void guardarComentario(Comentario comentario);
/**
* Funcion que elimina la pelicula con ese id
* @param idPelicula
*/
public void eliminarPelicula(String idPelicula);
/**
* Funcion que modifica una pelicula
* @param pelicula
*/
public void modificarPelicula(Pelicula pelicula);
/**
* Funcion para eliminar todas las entradas relacionadas con una pelicula
* @param idPelicula
*/
public void eliminarEntradasPelicula(String idPelicula);
/**
* Elimina las reservas relacionadas con la pelicula pasada como parametro
* @param idPelicula
*/
public void eliminarReservasPelicula(String idPelicula);
/**
* Elimina los comentarios relacionados con la pelicula pasada como parametro
* @param idPelicula
*/
public void eliminarComentariosPelicula(String idPelicula);
/**
* Elimina las sesiones de la pelicula pasada como parametro
* @param idPelicula
*/
public void eliminarSesionPelicula(String idPelicula);
/**
* Borra los actores de la pelicula pasada como parametro
* @param idPelicula
*/
public void borrarActoresPelicula(String idPelicula);
/**
* Guarda la pelicula pasada como parametro
* @param peli
*/
public void guardarPelicula(Pelicula peli);
/**
* Guarda el actor pasado como parametro
* @param actor
* @param pelicula
*/
public void guardarActor(Actor actor, String pelicula);
/**
* Devuelve true si esta la pelicula en la bbdd, false en caso contrario
* @param pelicula
* @return
*/
public boolean estaPelicula(String pelicula);
/**
* Devuelve true si el actor está en la bbdd, false en caso contrario
* @param nombre
* @param apellidos
* @return
*/
public boolean estaActor(String nombre, String apellidos);
/**
* Obtiene todas las sesiones de la pelicula pasada como parametro
* @param idPelicula id de la peliucla
* @return
*/
public ArrayList<Sesion> getSesionesPelicula(String idPelicula);
/**
* Devuelve la sala con ese id
* @param idSala
* @return
*/
public Sala getSala(String idSala);
/**
* Devuelve true si el asiento está ocupado
* @param idSesion sesion en la que nos encontramos
* @param fila
* @param columna
* @return boolean
*/
public boolean estaOcupadoAsiento(String idSesion,int fila, int columna);
/**
* Guarda en la bbdd la entrada pasada como parametro
* @param entrada
*/
public void guardarEntrada(Entrada entrada);
/**
* Guarda la reserva pasada como parametor
* @param reserva
*/
public void guardarReserva(Usuario usuario,Reserva reserva);
/**
* Obtiene una lista con todas las salas
* @return
*/
public ArrayList<Sala> getSalas();
/**
* Elimina la sala con ese id
* @param idSala
*/
public void eliminarSala(String idSala);
/**
* Modifica la sala pasada como parametor
* @param sala
*/
public void modificarSala(Sala sala);
/**
* Añade la sala pasada como parametor
* @param sala
*/
public void anadirSala(Sala sala);
/**
* Devuelve true si ya existe esa sala
* @param sala
* @return
*/
public boolean estaSala(Sala sala);
/**
* Devuelve una lista con todas las sesiones
* @return
*/
public ArrayList<Sesion> getSesiones();
/**
* Elimina la sesion con ese id
* @param idSesion
*/
public void eliminarSesion(String idSesion);
/**
* Mofifica la sesion pasada como parametro
* @param sesion
*/
public void modificarSesion(Sesion sesion);
/**
* Añade la sesion en la bbdd
* @param sesion
*/
public void anadirSesion(Sesion sesion);
/**
* ELimina todas las entradas en una sesion
* @param idSesion
*/
public void eliminarEntradasSesion(String idSesion);
/**
* Elimina las reservas relacionadas con esa sesion
* @param idSesion
*/
public void eliminarReservasSesion(String idSesion);
/**
* Obtiene todas las entradas relacionadas con una pelicula
* @param idPelicula
* @return
*/
public ArrayList<Entrada> getEntradasPelicula(String idPelicula);
/**
* Guarda la relación entre una pelicula y un actor
* @param pelicula
* @param actor
*/
public void relacionActorPelicula(Pelicula pelicula, Actor actor);
/**
* Sirve para saber si es existente una relacion entre una pelicula y un actor
* @param pelicula
* @param actor
* @return
*/
public boolean estaRelacionActor(Pelicula pelicula, Actor actor);
}
|
package main;
public class ex36 {
public static void main(String[] args) {
// TODO Auto-generated method stub
int[] intArray = new int[] {8, 7, 9, 6, 2, 5, 3, 4};
double[] doubleArray = new double[intArray.length];
int[] intArray2 = new int[intArray.length];
double nr = 2.5;
for(int i=0; i<intArray.length; i++) {
doubleArray[i] = intArray[i] + nr;
}
for(int i=0; i<intArray.length; i++) {
System.out.println(intArray[i]);
}
System.out.println();
for(int i=0; i<doubleArray.length; i++) {
System.out.println(doubleArray[i]);
}
for(int i=0; i<intArray.length; i++) {
intArray2[i] = intArray[i] + (int)nr;
}
System.out.println();
for(int i=0; i<intArray2.length; i++) {
System.out.println(intArray2[i]);
}
}
}
|
/*
* (C) Mississippi State University 2009
*
* The WebTOP employs two licenses for its source code, based on the intended use. The core license for WebTOP applications is
* a Creative Commons GNU General Public License as described in http://*creativecommons.org/licenses/GPL/2.0/. WebTOP libraries
* and wapplets are licensed under the Creative Commons GNU Lesser General Public License as described in
* http://creativecommons.org/licenses/*LGPL/2.1/. Additionally, WebTOP uses the same licenses as the licenses used by Xj3D in
* all of its implementations of Xj3D. Those terms are available at http://www.xj3d.org/licenses/license.html.
*/
package org.webtop.module.geometrical;
public class RayList implements Cloneable {
public float x, y, xv, yv, /*x0,y0,xv0,yv0,*/ z;
public int p;
public float color[] = new float[3];
public RayList next;
public RayList() {}
public RayList(float X, float Y, float Z, float XV, float YV, int P, float[] RGB) {
/*x0=*/x = X;
/*y0=*/y = Y;
/*z0=*/z = Z;
/*xv0=*/xv = XV;
/*yv0=*/yv = YV;
p = P;
color = RGB;
}
public RayList hook(float X, float Y, float Z, float XV, float YV, int P, float[] RGB) {
return next = new RayList(X, Y, Z, XV, YV, P, RGB);
}
public RayList hook(RayList r) {
return next = r;
}
//Removes next ray from the list; returns one after it (if any).
//Unhooking when there is nothing to unhook just returns null.
public RayList unhook() {
if (next != null) {
return next = next.next;
}
return null;
}
//Removes this ray from the list. Slower than unhooking the next.
//Thus, best used only on first ray.
//Returns null if this is a tail ray which thus cannot unhook itself.
//Otherwise, returns this ray.
/**
* @deprecated
*/
public RayList unhookSelf() {
if (next != null) {
x = next.x;
y = next.y;
xv = next.xv;
yv = next.xv;
z = next.z;
p = next.p;
unhook();
return this;
} else {
return null;
}
}
public void propagate(float Z) {
x += xv * (Z - z);
y += yv * (Z - z);
z = Z;
}
public void propagateAll(float Z) {
for (RayList walker = this; walker != null; walker = walker.next) {
float dz = Z - walker.z;
walker.x += walker.xv * dz;
walker.y += walker.yv * dz;
walker.z = Z;
}
}
/*public void reset() {
x=x0;y=y0;
xv=xv0;yv=yv0;
z=0;
}*/
//If 'in' is false, keeps rays that MISS a circle of diameter d at position p
//Returns count of rays pruned. Note that the first ray is never pruned.
//There may be some benefit to having specialized versions of this that make
//assumptions like rays already at p or in==true.
public int prune(float p, float d, boolean in) {
d *= d / 4; //r^2
int misses = 0;
for (RayList walker = next, previous = this; walker != null; ) {
final float x = walker.x + walker.xv * (p - walker.z),
y = walker.y + walker.yv * (p - walker.z);
if ((x * x + y * y < d) == in) {
//DebugPrinter.println("Keeping "+walker+" (projected to r="+Math.sqrt(x*x+y*y)+"; {"+x+','+y+','+p+"})");
previous = walker;
walker = walker.next;
} else {
++misses;
walker = previous.unhook();
}
}
return misses;
}
public static RayList virtualClone(RayList src) {
RayList nu = src.copy(), first = nu, walker;
for (walker = src.next; walker != null; walker = walker.next) {
RayList copy = walker.copy();
copy.color = new float[] {1, 1, 0};
nu = nu.hook(copy);
}
return first;
}
public static RayList clone(RayList src) {
RayList nu = src.copy(), first = nu, walker;
for (walker = src.next; walker != null; walker = walker.next) {
nu = nu.hook(walker.copy());
}
return first;
}
private RayList copy() {
try {
return (RayList)super.clone();
} catch (CloneNotSupportedException e) {
return null;
} //Won't happen; we're Cloneable
}
public String toString() {
return getClass().getName() + "[x=" + x + ",y=" + y + ",xv=" + xv + ",yv=" + yv + ",z=" + z +
",p=" + p + (next == null ? " (tail)]" : "]");
}
//This is slow! Don't call except for debugging. Returns number of rays after this one.
public int getLength() {
int i = 0;
for (RayList walker = next; walker != null; walker = walker.next) {
++i;
}
return i;
}
}
|
package io.github.selchapp.api.model;
import javax.persistence.Column;
import javax.persistence.Embeddable;
import com.fasterxml.jackson.annotation.JsonIgnore;
@Embeddable
public class GPRSPosition {
@Column(nullable = true)
private double lat;
@Column(nullable = true)
private double lng;
public double getLat() {
return lat;
}
public void setLat(double lat) {
this.lat = lat;
}
public double getLng() {
return lng;
}
public void setLng(double lng) {
this.lng = lng;
}
@JsonIgnore
public boolean isValid() {
return lat != 0 && lng != 0;
}
}
|
import javax.xml.stream.XMLStreamException;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Date;
import java.util.*;
/**
* Class used in order to represent each time-frame for each trend.
*/
public class TimeFrame {
Trend trend; //the trend its coming from
Date startedTime; //the time it started
Date finishedTime; //the time it finished
HashMap<String,Integer> representativeWordsBasedOnTF = new HashMap<>();
HashMap<String,Double> representativeWordsBasedOnTFIDF = new HashMap<>();
ArrayList<String> sentimentCalibration; //keeps the calibration of sentiments [0] -> most intense [5] -> weakest
ArrayList<Tweet> tweetsOfFrame;
public TimeFrame(Trend trend,Date startedTime, Date finishedTime){
this.trend = trend;
this.startedTime = startedTime;
this.finishedTime = finishedTime;
sentimentCalibration = new ArrayList<>();
tweetsOfFrame = getTweetsOfFrame(trend);
representativeWordsBasedOnTF = new HashMap<>();
representativeWordsBasedOnTFIDF = new HashMap<>();
}
/**
* Method that finds the representative words of the most intense sentiment of this Time frame
* @throws FileNotFoundException
* @throws XMLStreamException
*/
public void calculateRepresentativeWords(SentimentAnalysis analysis) throws FileNotFoundException, XMLStreamException {
String firstSentiment = sentimentCalibration.get(0); //the most intense sentiment is in index 0
int countOfSentimentWords = 0;
//CALCULATING FOR TF
for (Tweet tweet : tweetsOfFrame){ //for each tweet
String text = tweet.text; //get it's text
ArrayList<String> words = new ArrayList<>(Arrays.asList(text.split(" "))); //split it to tokens
for(String word : words){
if (analysis.containsSecondaryForSpecificSentiment(word,firstSentiment) == true) { //if the word is sentimental
countOfSentimentWords++;
if(representativeWordsBasedOnTF.containsKey(word)){ //if the word has been counted before
representativeWordsBasedOnTF.put(word, representativeWordsBasedOnTF.get(word)+1);
}
else {
representativeWordsBasedOnTF.put(word,1); //else initialize it
}
}
}
}
for (Map.Entry entry : representativeWordsBasedOnTF.entrySet()){
Integer temp = new Integer( (int) entry.getValue() );
double doubleNumb = temp.doubleValue();
Double tfidf = doubleNumb / countOfSentimentWords ; //calculates TFIDF
representativeWordsBasedOnTFIDF.put((String) entry.getKey(), tfidf); //takes every frequency of word and divides it with the count of sentimental words
}
}
/**
* Method that calculates the sentiment calibration for this TimeFrame.
* Sentiments are sorted from the most intense to the most weak
*/
public void calculateSentimentCalibration(){
HashMap<String,Double> scoreCalculator = new HashMap<>();
scoreCalculator.put("anger",new Double(0)); //HashMap initialization
scoreCalculator.put("disgust",new Double(0));
scoreCalculator.put("fear",new Double(0));
scoreCalculator.put("joy",new Double(0));
scoreCalculator.put("sadness",new Double(0));
scoreCalculator.put("surprise",new Double(0));
for (Tweet tweet : tweetsOfFrame){ //for every tweet of the Frame
scoreCalculator.put("anger", scoreCalculator.get("anger") + tweet.angerScore); //updates the values
scoreCalculator.put("disgust", scoreCalculator.get("disgust") + tweet.disgustScore);
scoreCalculator.put("fear", scoreCalculator.get("fear") + tweet.fearScore);
scoreCalculator.put("joy", scoreCalculator.get("joy") + tweet.joyScore);
scoreCalculator.put("sadness", scoreCalculator.get("sadness") + tweet.sadnessScore);
scoreCalculator.put("surprise", scoreCalculator.get("surprise") + tweet.surpriseScore);
}
HashMap<String,Float> sortedMap = sortHashMapByValues(scoreCalculator); //sorts the list by value (score)
for(Map.Entry entry : sortedMap.entrySet()){
sentimentCalibration.add((String) entry.getKey()); //adds the sentiment int the sentiment calibration list
}
Collections.reverse(sentimentCalibration); //reverses the list in order to be in descending order
}
public ArrayList<Tweet> getTweetsOfFrame(Trend trend){
return trend.getTweetsInTimeframe(this);
}
public LinkedHashMap sortHashMapByValues(HashMap passedMap) {
List mapKeys = new ArrayList(passedMap.keySet());
List mapValues = new ArrayList(passedMap.values());
Collections.sort(mapValues);
Collections.sort(mapKeys);
LinkedHashMap sortedMap = new LinkedHashMap();
Iterator valueIt = mapValues.iterator();
while (valueIt.hasNext()) {
Object val = valueIt.next();
Iterator keyIt = mapKeys.iterator();
while (keyIt.hasNext()) {
Object key = keyIt.next();
String comp1 = passedMap.get(key).toString();
String comp2 = val.toString();
if (comp1.equals(comp2)){
passedMap.remove(key);
mapKeys.remove(key);
sortedMap.put((String)key, (Double)val);
break;
}
}
}
return sortedMap;
}
}
|
public class LinkedList {
private Object Obj;
private LinkedList nextNode;
public LinkedList(Object Obj,LinkedList nextNode) {
this.Obj = Obj;
this.nextNode = nextNode;
}
public LinkedList(Object Obj) {
this(Obj,null);
}
public void show(){
System.out.println(Obj.getClass());
if (Obj instanceof Vehicle) {
Vehicle tmpVehicle = (Vehicle) Obj;
tmpVehicle.print();
}
if(nextNode!=null)
nextNode.show();
}
public String toString(){
if (Obj instanceof Vehicle) {
String tmpv;
Vehicle tmpVehicle = (Vehicle) Obj;
tmpv = tmpVehicle.toString();
if(nextNode!=null)
tmpv += nextNode.toString();
return tmpv;
}
return null;
}
public Object getObj(){
return Obj;
}
public LinkedList getNextNode(){
return nextNode;
}
public int countList(){
if(nextNode==null){
return 1;
}else{
return 1 + nextNode.countList();
}
}
public static void main(String args[]){
Vehicle car1 = new Vehicle("A");
Vehicle car2 = new Vehicle("B");
Vehicle car3 = new Vehicle("C");
LinkedList node3 = new LinkedList(car2);
LinkedList node2 = new LinkedList(car2,node3);
LinkedList node1 = new LinkedList(car1,node2);
System.out.println(node1.countList());
System.out.println(node2.countList());
System.out.println(node3.countList());
}
}
|
// https://www.youtube.com/watch?v=3JIwIRir2sM
class Solution {
public int makeConnected(int n, int[][] connections) {
boolean visited[] = new boolean[n];
ArrayList<Integer>[] adj = new ArrayList[n];
for (int i = 0; i < adj.length; i++){
adj[i] = new ArrayList<Integer>();
}
for (int connection[] : connections) {
adj[connection[0]].add(connection[1]);
adj[connection[1]].add(connection[0]);
}
int components = 0;
for (int i = 0; i < n; i++) {
if (visited[i] !=true) {
components++;
dfs(i, visited, adj);
}
}
return connections.length >= n - 1 ? components - 1 : -1;
}
public void dfs(int n,boolean visited[],ArrayList<Integer>[] adj) {
if (visited[n] != true) {
visited[n] = true;
for(int a : adj[n]) {
if(visited[a] != true) {
dfs(a, visited, adj);
}
}
}
}
}
|
/*
* Created on Mar 12, 2007
*
*
* Window - Preferences - Java - Code Style - Code Templates
*/
package com.citibank.ods.modules.product.aggrprodprvt.functionality.valueobject;
/**
* @author leonardo.nakada
*
*
* Window - Preferences - Java - Code Style - Code Templates
*/
public class AggrProdPrvtListFncVO extends BaseAggrProdPrvtListFncVO
{
}
|
package com.master.job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
@Component
public class DemoJob implements BaseJob {
private static Logger _log = LoggerFactory.getLogger(DemoJob.class);
@Override
public void execute(JobExecutionContext context) throws JobExecutionException {
_log.info("----------DemoJob--------");
}
}
|
package com.github.edgar615.cache.spring.caffeine;
import com.github.benmanes.caffeine.cache.Caffeine;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.cache.support.SimpleCacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
@EnableConfigurationProperties({CaffeineCacheProperties.class})
public class CaffeineCacheAutoConfiguration {
@Bean("caffeineCacheManager")
@ConditionalOnCaffeine
@ConditionalOnMissingBean(name = "caffeineCacheManager")
@ConditionalOnClass(com.github.benmanes.caffeine.cache.Cache.class)
public CacheManager caffeineCacheManager(CaffeineCacheProperties properties) {
List<Cache> caches = new ArrayList<>();
List<Cache> caffeine = properties.getSpec().entrySet().stream()
.map(
spec -> new WildcardCaffeineCache(spec.getKey(), Caffeine.from(spec.getValue()).build(),
true))
.collect(Collectors.toList());
caches.addAll(caffeine);
SimpleCacheManager caffeineManager = new SimpleCacheManager();
caffeineManager.setCaches(caches);
caffeineManager.initializeCaches();
return caffeineManager;
}
}
|
package com.kg.python;//import org.gradle.tooling.BuildLauncher;
//import org.gradle.tooling.GradleConnector;
//import org.gradle.tooling.ProjectConnection;
import com.echonest.api.v4.TrackAnalysis;
import com.kg.wub.AudioObject;
import com.kg.wub.system.SpotifyUtils;
import org.json.simple.parser.ParseException;
import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executors;
import static com.kg.python.SpotifyDLTest.STEMS.*;
import static com.kg.python.SpotifyDLTest.STEMS.STEM2;
public class SpotifyDLTest {
public static void main(String args[]) {
/* GradleConnector connector = GradleConnector.newConnector();
connector.forProjectDirectory(new File("."));
ProjectConnection connection = connector.connect();
BuildLauncher build = connection.newBuild();
build.forTasks("runSpleeter");
build.addJvmArguments("-Dspleeter1="+"C:/Users/Paul/Documents/horde/eadc0b07-0d3e-4b6e-8d6a-245b9a31b366001.wav");
build.addJvmArguments("-Dspleeter2="+"spleeter");
build.setStandardOutput(System.out);
build.run();
connection.close();
*/
PythonPIP.installPIP();
String spotifyId="";
String fileName="https://open.spotify.com/track/7mFBGqpnvIT9SyF1WCD9sm?si=I0VviOI8T0u23344rom5_Q";
TrackAnalysis ta=null;
if (fileName.contains("spotify:track:") || fileName.contains("https://open.spotify.com/track/")) {
if (fileName.lastIndexOf("/") > -1) spotifyId = fileName.substring(fileName.lastIndexOf("/") + 1);
else if (fileName.lastIndexOf(":") > -1) spotifyId = fileName.substring(fileName.lastIndexOf(":") + 1);
System.out.println("spotifyID=" + spotifyId);
try {
ta = SpotifyUtils.getAnalysis(spotifyId);
} catch (IOException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}
}
List<File> files=SpotifyDLTest.spotifyAndSpleeter(fileName, new File(System.getProperty("user.dir") + File.separator + URLEncoder.encode(spotifyId)+".mp3"), STEM5);
for (File f:files){
AudioObject.factory(f.getAbsolutePath(),ta);
}
}
public static void spotify(String trackurl, File outputFile) {
boolean isWindows = System.getProperty("os.name")
.toLowerCase().startsWith("windows");
ProcessBuilder builder = new ProcessBuilder();
outputFile.delete();
String pro = "python -m spotdl.command_line.__main__ --overwrite force --song " + trackurl + " -f " + outputFile.getAbsolutePath();
if (isWindows) {
builder.command("cmd.exe", "/c", pro);
} else {
builder.command("sh", "-c", pro);
}
builder.directory(new File(System.getProperty("user.dir")));
builder.inheritIO();
Process process = null;
try {
for (String c : builder.command()) {
System.out.print(c + " ");
}
System.out.println();
process = builder.start();
process.waitFor();
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public static enum STEMS {
STEM0, STEM2, STEM4, STEM5;
}
public static List<File> spotifyAndSpleeter(String trackURL, File outputFile, STEMS stem) {
PythonPIP.installPIP();
ArrayList<File> outfiles = new ArrayList<>();
SpotifyDLTest.spotify(trackURL, outputFile);
outfiles = new ArrayList<>();
outfiles.add(outputFile);
String base = System.getProperty("user.dir") + File.separator + "spleeter" + File.separator + outputFile.getName().replaceAll("^.*?(([^/\\\\\\.]+))\\.[^\\.]+$", "$1") + File.separator;
switch (stem) {
case STEM0:
break;
case STEM2:
SpleeterTest.spleet(outputFile, 2);
outfiles.add(new File(base + "vocals.wav"));
outfiles.add(new File(base + "accompaniment.wav"));
break;
case STEM4:
SpleeterTest.spleet(outputFile, 4);
outfiles.add(new File(base + "vocals.wav"));
outfiles.add(new File(base + "bass.wav"));
outfiles.add(new File(base + "other.wav"));
outfiles.add(new File(base + "drums.wav"));
break;
case STEM5:
SpleeterTest.spleet(outputFile, 5);
outfiles.add(new File(base + "vocals.wav"));
outfiles.add(new File(base + "piano.wav"));
outfiles.add(new File(base + "bass.wav"));
outfiles.add(new File(base + "other.wav"));
outfiles.add(new File(base + "drums.wav"));
break;
default:
throw new IllegalStateException("Unexpected value: stem " + stem);
}
for (File f : outfiles) {
System.out.println(f.exists() + "\t" + f.getAbsolutePath());
}
return outfiles;
}
}
|
// jDownloader - Downloadmanager
// Copyright (C) 2015 JD-Team support@jdownloader.org
//
// 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 3 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, see <http://www.gnu.org/licenses/>.
package jd.plugins.hoster;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Locale;
import org.appwork.utils.StringUtils;
import org.jdownloader.plugins.components.antiDDoSForHost;
import org.jdownloader.plugins.controller.host.LazyHostPlugin.FEATURE;
import jd.PluginWrapper;
import jd.config.Property;
import jd.http.Browser;
import jd.http.URLConnectionAdapter;
import jd.nutils.JDHash;
import jd.nutils.encoding.Encoding;
import jd.plugins.Account;
import jd.plugins.AccountInfo;
import jd.plugins.DownloadLink;
import jd.plugins.DownloadLink.AvailableStatus;
import jd.plugins.HostPlugin;
import jd.plugins.LinkStatus;
import jd.plugins.PluginException;
import jd.plugins.components.PluginJSonUtils;
import jd.plugins.download.DownloadLinkDownloadable;
import jd.plugins.download.HashInfo;
import jd.utils.locale.JDL;
@HostPlugin(revision = "$Revision$", interfaceVersion = 3, names = { "alldebrid.com" }, urls = { "https?://(?:[a-z]\\d+\\.alldebrid\\.com|[a-z0-9]+\\.alld\\.io)/dl/[a-z0-9]+/.+" })
public class AllDebridCom extends antiDDoSForHost {
private static HashMap<Account, HashMap<String, Long>> hostUnavailableMap = new HashMap<Account, HashMap<String, Long>>();
public AllDebridCom(PluginWrapper wrapper) {
super(wrapper);
setStartIntervall(2 * 1000l);
this.enablePremium("http://www.alldebrid.com/offer/");
}
@Override
public FEATURE[] getFeatures() {
return new FEATURE[] { FEATURE.MULTIHOST };
}
private static final String NICE_HOST = "alldebrid.com";
private static final String NICE_HOSTproperty = NICE_HOST.replaceAll("(\\.|\\-)", "");
private static final String NOCHUNKS = "NOCHUNKS";
private final String hash1 = "593f356a67e32332c13d6692d1fe10b7";
private int statuscode = 0;
private Account currAcc = null;
private DownloadLink currDownloadLink = null;
@SuppressWarnings("deprecation")
@Override
public AccountInfo fetchAccountInfo(final Account account) throws Exception {
setConstants(account, null);
HashMap<String, String> accDetails = new HashMap<String, String>();
AccountInfo ac = new AccountInfo();
getPage("https://www.alldebrid.com/api.php?action=info_user&login=" + Encoding.urlEncode(account.getUser()) + "&pw=" + Encoding.urlEncode(account.getPass()));
handleErrors();
/* parse api response in easy2handle hashmap */
String info[][] = br.getRegex("<([^<>]*?)>([^<]*?)</.*?>").getMatches();
for (String data[] : info) {
accDetails.put(data[0].toLowerCase(Locale.ENGLISH), data[1].toLowerCase(Locale.ENGLISH));
}
final ArrayList<String> supportedHosts = new ArrayList<String>();
final String type = accDetails.get("type");
if ("premium".equals(type)) {
/* only platinum and premium support */
getPage("https://www.alldebrid.com/api.php?action=get_host");
String hoster[] = br.toString().split(",\\s*");
if (hoster != null) {
/* workaround for buggy getHost call */
supportedHosts.add("tusfiles.net");
for (String host : hoster) {
if (host == null || host.length() == 0) {
continue;
}
host = host.replace("\"", "").trim();
// hosts that returned decrypted finallinks bound to users ip session. Can not use multihosters..
try {
if (host.equals("depositfiles.com") && accDetails.get("limite_dp") != null && Integer.parseInt(accDetails.get("limite_dp")) == 0) {
logger.info("NOT adding the following host to array of supported hosts as its daily limit is reached: " + host);
continue;
}
} catch (final Exception e) {
logger.severe(e.toString());
}
try {
if (host.equals("filefactory.com") && accDetails.get("limite_ff") != null && Integer.parseInt(accDetails.get("limite_ff")) == 0) {
logger.info("NOT adding the following host to array of supported hosts as its daily limit is reached: " + host);
continue;
}
} catch (final Exception e) {
logger.severe(e.toString());
}
try {
if (host.equals("filesmonster.com") && accDetails.get("limite_fm") != null && Integer.parseInt(accDetails.get("limite_fm")) == 0) {
logger.info("NOT adding the following host to array of supported hosts as its daily limit is reached: " + host);
continue;
}
} catch (final Exception e) {
logger.severe(e.toString());
}
supportedHosts.add(host);
}
}
/* Timestamp given in remaining seconds. */
final String secondsLeft = accDetails.get("timestamp");
if (secondsLeft != null) {
account.setValid(true);
final long validuntil = System.currentTimeMillis() + (Long.parseLong(secondsLeft) * 1001);
ac.setValidUntil(validuntil);
} else {
/* no daysleft available?! */
account.setValid(false);
}
} else {
/* all others are invalid */
account.setValid(false);
}
if (account.isValid()) {
ac.setMultiHostSupport(this, supportedHosts);
ac.setStatus("Premium Account");
} else {
ac.setProperty("multiHostSupport", Property.NULL);
throw new PluginException(LinkStatus.ERROR_PREMIUM, "\r\nFree accounts are not supported!", PluginException.VALUE_ID_PREMIUM_DISABLE);
}
return ac;
}
private void handleErrors() throws PluginException {
final String error = PluginJSonUtils.getJsonValue(br, "error");
if (br.toString().matches("(?i)login fail(?:ed)?")) {
// wrong password and they say this for blocked ip subnet.
throw new PluginException(LinkStatus.ERROR_PREMIUM, "\r\nWrong Username:Password, or IP subnet block.", PluginException.VALUE_ID_PREMIUM_DISABLE);
} else if ("too mutch fail, blocked for 6 hour".equals(br.toString())) {
throw new PluginException(LinkStatus.ERROR_PREMIUM, "\r\nToo many incorrect attempts at login!\r\nYou've been blocked for 6 hours", PluginException.VALUE_ID_PREMIUM_DISABLE);
} else if (hash1.equalsIgnoreCase(JDHash.getMD5(br.toString()))) {
throw new PluginException(LinkStatus.ERROR_PREMIUM, "\r\nYou've been blocked from the API!", PluginException.VALUE_ID_PREMIUM_DISABLE);
} else if (br.getHttpConnection().getResponseCode() == 500) {
throw new PluginException(LinkStatus.ERROR_TEMPORARILY_UNAVAILABLE, "500 internal server error", 15 * 60 * 1000l);
} else if (StringUtils.startsWithCaseInsensitive(error, "To many downloads")) {
// some limitation on concurrent download for this host.
}
}
@Override
public String getAGBLink() {
return "http://www.alldebrid.com/tos/";
}
@Override
public int getMaxSimultanFreeDownloadNum() {
return -1;
}
@Override
public int getMaxSimultanPremiumDownloadNum() {
return -1;
}
@SuppressWarnings("deprecation")
@Override
public void handleFree(final DownloadLink link) throws Exception, PluginException {
showMessage(link, "Task 1: Check URL validity!");
requestFileInformation(link);
handleDL(null, link, link.getDownloadURL());
}
@SuppressWarnings("deprecation")
@Override
public void handlePremium(final DownloadLink link, final Account account) throws Exception {
showMessage(link, "Task 1: Check URL validity!");
requestFileInformation(link);
handleDL(account, link, link.getDownloadURL());
}
@SuppressWarnings("deprecation")
private void handleDL(final Account acc, final DownloadLink link, final String genlink) throws Exception {
if (genlink == null) {
throw new PluginException(LinkStatus.ERROR_PLUGIN_DEFECT);
}
showMessage(link, "Task 2: Download begins!");
int maxChunks = 0;
if (link.getBooleanProperty(AllDebridCom.NOCHUNKS, false)) {
maxChunks = 1;
}
if (br != null && PluginJSonUtils.parseBoolean(PluginJSonUtils.getJsonValue(br, "paws"))) {
final String host = Browser.getHost(link.getDownloadURL());
final DownloadLinkDownloadable downloadLinkDownloadable = new DownloadLinkDownloadable(link) {
@Override
public HashInfo getHashInfo() {
return null;
}
@Override
public long getVerifiedFileSize() {
return -1;
}
@Override
public String getHost() {
return host;
}
};
dl = jd.plugins.BrowserAdapter.openDownload(br, downloadLinkDownloadable, br.createGetRequest(genlink), true, maxChunks);
} else {
dl = jd.plugins.BrowserAdapter.openDownload(br, link, genlink, true, maxChunks);
}
if (dl.getConnection().getResponseCode() == 404) {
/* file offline */
dl.getConnection().disconnect();
throw new PluginException(LinkStatus.ERROR_FILE_NOT_FOUND);
}
if (!dl.getConnection().isContentDisposition() && dl.getConnection().getContentType().contains("html")) {
br.followConnection();
if (br.containsHTML("You are not premium so you can't download this file")) {
throw new PluginException(LinkStatus.ERROR_TEMPORARILY_UNAVAILABLE, "Premium required to download this file.");
} else if (br.containsHTML(">An error occured while processing your request<")) {
logger.info("Retrying: Failed to generate alldebrid.com link because API connection failed for host link: " + link.getDownloadURL());
handleErrorRetries("Unknown error", 3, 30 * 60 * 1000l);
}
if (!isDirectLink(link)) {
if (br.containsHTML("range not ok")) {
throw new PluginException(LinkStatus.ERROR_TEMPORARILY_UNAVAILABLE);
}
/* unknown error */
logger.severe("Error: Unknown Error");
// disable hoster for 5min
tempUnavailableHoster(5 * 60 * 1000l);
} else {
throw new PluginException(LinkStatus.ERROR_TEMPORARILY_UNAVAILABLE);
}
}
/* save generated link, only if... it it comes from handleMulti */
if (!isDirectLink(link)) {
link.setProperty("genLinkAllDebrid", genlink);
}
if (!this.dl.startDownload()) {
try {
if (dl.externalDownloadStop()) {
return;
}
} catch (final Throwable e) {
}
final String errormessage = link.getLinkStatus().getErrorMessage();
if (errormessage != null && (errormessage.startsWith(JDL.L("download.error.message.rangeheaders", "Server does not support chunkload")) || errormessage.equals("Unerwarteter Mehrfachverbindungsfehlernull") || "Unexpected rangeheader format:null".equals(errormessage))) {
/* unknown error, we disable multiple chunks */
if (link.getBooleanProperty(AllDebridCom.NOCHUNKS, false) == false) {
link.setProperty(AllDebridCom.NOCHUNKS, Boolean.valueOf(true));
throw new PluginException(LinkStatus.ERROR_RETRY);
}
}
}
}
private void showMessage(DownloadLink link, String message) {
link.getLinkStatus().setStatusText(message);
}
/** TODO: Replace errorhandling stuff with new API statuscode-errorhamdling */
/** no override to keep plugin compatible to old stable */
@SuppressWarnings("deprecation")
public void handleMultiHost(final DownloadLink link, final Account account) throws Exception {
setConstants(account, link);
synchronized (hostUnavailableMap) {
HashMap<String, Long> unavailableMap = hostUnavailableMap.get(account);
if (unavailableMap != null) {
Long lastUnavailable = unavailableMap.get(link.getHost());
if (lastUnavailable != null && System.currentTimeMillis() < lastUnavailable) {
final long wait = lastUnavailable - System.currentTimeMillis();
throw new PluginException(LinkStatus.ERROR_TEMPORARILY_UNAVAILABLE, "Host is temporarily unavailable via " + this.getHost(), wait);
} else if (lastUnavailable != null) {
unavailableMap.remove(link.getHost());
if (unavailableMap.size() == 0) {
hostUnavailableMap.remove(account);
}
}
}
}
showMessage(link, "Phase 1/2: Generating link");
String host_downloadlink = link.getDownloadURL();
/* here we can get a 503 error page, which causes an exception */
getPage("https://www.alldebrid.com/service.php?pseudo=" + Encoding.urlEncode(account.getUser()) + "&password=" + Encoding.urlEncode(account.getPass()) + "&link=" + Encoding.urlEncode(host_downloadlink) + "&json=true");
final String genlink = PluginJSonUtils.getJsonValue(br, "link");
// todo: fix this, as json now old error handling will be wrong -raztok20160906
if (genlink != null) {
if ("banned".equalsIgnoreCase(genlink.trim())) {
// account is banned
throw new PluginException(LinkStatus.ERROR_PREMIUM, "Account is banned", PluginException.VALUE_ID_PREMIUM_DISABLE);
} else if (genlink.endsWith("alldebrid_server_not_allowed.txt")) {
// they show ip banned in this fashion now, confirmed with admin/support. -raztoki20170310
/*
* {"link":"http:\/\/www.alldebrid.com\/alldebrid_server_not_allowed.txt","host":"uploadedto","filename":"Ip not allowed."
* ,"icon":"\/lib\/images\/hosts\/uploadedto.png","streaming":[],"nb":0,"error":"","paws":false}
*/
statuscode = 1;
handleAPIErrors(br);
}
}
if (genlink == null || !genlink.matches("https?://.+")) {
logger.severe("Error: " + genlink);
handleErrors();
if (genlink.contains("_limit")) {
/* limit reached for this host, wait 4h */
tempUnavailableHoster(4 * 60 * 60 * 1000l);
}
updatestatuscode();
handleAPIErrors(br);
// we need a final error handling for situations when
throw new PluginException(LinkStatus.ERROR_PLUGIN_DEFECT);
}
handleDL(account, link, genlink);
}
protected Browser prepBrowser(final Browser prepBr, final String host) {
if (!(browserPrepped.containsKey(prepBr) && browserPrepped.get(prepBr) == Boolean.TRUE)) {
super.prepBrowser(prepBr, host);
// define custom browser headers and language settings.
prepBr.getHeaders().put("User-Agent", "JDownloader");
prepBr.setCustomCharset("utf-8");
prepBr.setFollowRedirects(true);
}
return prepBr;
}
@SuppressWarnings("deprecation")
@Override
public AvailableStatus requestFileInformation(final DownloadLink dl) throws PluginException, IOException {
setConstants(null, dl);
prepBrowser(br, dl.getDownloadURL());
URLConnectionAdapter con = null;
try {
con = br.openGetConnection(dl.getDownloadURL());
if ((con.isContentDisposition() || con.isOK()) && !con.getContentType().contains("html")) {
if (dl.getFinalFileName() == null) {
dl.setFinalFileName(getFileNameFromHeader(con));
}
dl.setVerifiedFileSize(con.getLongContentLength());
dl.setAvailable(true);
return AvailableStatus.TRUE;
} else {
throw new PluginException(LinkStatus.ERROR_FILE_NOT_FOUND);
}
} catch (final Throwable e) {
if (e instanceof PluginException) {
throw (PluginException) e;
}
getLogger().log(e);
dl.setAvailable(false);
throw new PluginException(LinkStatus.ERROR_FILE_NOT_FOUND);
} finally {
try {
/* make sure we close connection */
con.disconnect();
} catch (final Throwable e) {
}
}
}
/**
* 0 = everything ok, 1-99 = "error"-errors, 100-199 = other errors
*/
private void updatestatuscode() {
String error = PluginJSonUtils.getJsonValue(br, "error");
if (error != null) {
if (error.equals("Ip not allowed.")) {
statuscode = 1;
} else if (error.equals("Hoster unsupported or under maintenance.") || StringUtils.containsIgnoreCase(error, "Host is under maintenance")) {
statuscode = 2;
} else {
statuscode = 666;
}
} else {
error = br.getRegex("<span style='color:#a00;'>(.*?)</span>").getMatch(0);
if (error == null) {
/* No way to tell that something unpredictable happened here --> status should be fine. */
statuscode = 0;
} else {
if (StringUtils.containsIgnoreCase(error, "Host is under maintenance")) {
statuscode = 2;
} else if (error.equals("Invalid link")) {
/* complete html example: 1,;,https://tusfiles.net/xxxxxxxxxxxx : <span style='color:#a00;'>Invalid link</span>,;,0 */
statuscode = 101;
} else if (error.equals("Link is dead")) {
statuscode = 102;
} else {
statuscode = 666;
}
}
}
}
private void handleAPIErrors(final Browser br) throws PluginException {
String statusMessage = null;
try {
switch (statuscode) {
case 0:
/* Everything ok */
break;
case 1:
/* No email entered --> Should never happen as we validate user-input before -> permanently disable account */
if ("de".equalsIgnoreCase(System.getProperty("user.language"))) {
statusMessage = "\r\nDedicated Server/VPN/proxy entdeckt - Account gesperrt!";
} else {
statusMessage = "\r\nDedicated Server/VPN/Proxy detected, account disabled!";
}
throw new PluginException(LinkStatus.ERROR_PREMIUM, statusMessage, PluginException.VALUE_ID_PREMIUM_DISABLE);
case 2:
statusMessage = "Host unsupported or in maintenance";
handleErrorRetries("hoster_unsupported_or_in_maintenance", 20, 5 * 60 * 1000);
case 101:
statusMessage = "Invalid link --> Probably unsupported host";
tempUnavailableHoster(10 * 60 * 1000l);
case 102:
statusMessage = "'Link is dead' --> We don't trust this serverside error --> Retry";
throw new PluginException(LinkStatus.ERROR_TEMPORARILY_UNAVAILABLE, "alldebrid API says 'link is dead''", 60 * 1000l);
default:
/* Unknown error */
statusMessage = "Unknown error";
logger.info(NICE_HOST + ": Unknown API error");
handleErrorRetries("unknownAPIerror", 10, 2 * 60 * 1000l);
}
} catch (final PluginException e) {
logger.info(NICE_HOST + ": Exception: statusCode: " + statuscode + " statusMessage: " + statusMessage);
throw e;
}
}
/**
* Is intended to handle out of date errors which might occur seldom by re-tring a couple of times before we temporarily remove the host
* from the host list.
*
* @param error
* : The name of the error
* @param maxRetries
* : Max retries before out of date error is thrown
*/
private void handleErrorRetries(final String error, final int maxRetries, final long disableTime) throws PluginException {
int timesFailed = this.currDownloadLink.getIntegerProperty(NICE_HOSTproperty + "failedtimes_" + error, 0);
if (timesFailed <= maxRetries) {
logger.info(NICE_HOST + ": " + error + " -> Retrying");
timesFailed++;
this.currDownloadLink.setProperty(NICE_HOSTproperty + "failedtimes_" + error, timesFailed);
throw new PluginException(LinkStatus.ERROR_RETRY, error);
} else {
this.currDownloadLink.setProperty(NICE_HOSTproperty + "failedtimes_" + error, Property.NULL);
logger.info(NICE_HOST + ": " + error + " -> Disabling current host");
tempUnavailableHoster(disableTime);
}
}
private void tempUnavailableHoster(final long timeout) throws PluginException {
if (this.currDownloadLink == null) {
throw new PluginException(LinkStatus.ERROR_PLUGIN_DEFECT, "Unable to handle this errorcode!");
}
synchronized (hostUnavailableMap) {
HashMap<String, Long> unavailableMap = hostUnavailableMap.get(this.currAcc);
if (unavailableMap == null) {
unavailableMap = new HashMap<String, Long>();
hostUnavailableMap.put(this.currAcc, unavailableMap);
}
/* wait 30 mins to retry this host */
unavailableMap.put(this.currDownloadLink.getHost(), (System.currentTimeMillis() + timeout));
}
throw new PluginException(LinkStatus.ERROR_RETRY);
}
private void setConstants(final Account acc, final DownloadLink dl) {
this.currAcc = acc;
this.currDownloadLink = dl;
}
@Override
public boolean canHandle(DownloadLink downloadLink, Account account) throws Exception {
if (isDirectLink(downloadLink)) {
// generated links do not require an account to download
return true;
}
return true;
}
private boolean isDirectLink(final DownloadLink downloadLink) {
if (downloadLink.getDownloadURL().matches(this.getLazyP().getPatternSource())) {
return true;
}
return false;
}
@Override
public void reset() {
}
@Override
public void resetDownloadlink(DownloadLink link) {
}
}
|
package com.bucket.common.vo.base;
import java.io.Serializable;
import java.sql.Date;
/**
* 基础vo
* @author user
*
*/
public class BaseVo implements Serializable {
private static final long serialVersionUID = 2395091349473170650L;
private long id;
private String creator;
private Date createTime;
private String updater;
private String updateTime;
private String reMark;
private Long lockVersion;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getCreator() {
return creator;
}
public void setCreator(String creator) {
this.creator = creator;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public String getUpdater() {
return updater;
}
public void setUpdater(String updater) {
this.updater = updater;
}
public String getUpdateTime() {
return updateTime;
}
public void setUpdateTime(String updateTime) {
this.updateTime = updateTime;
}
public String getReMark() {
return reMark;
}
public void setReMark(String reMark) {
this.reMark = reMark;
}
public Long getLockVersion() {
return lockVersion;
}
public void setLockVersion(Long lockVersion) {
this.lockVersion = lockVersion;
}
}
|
package com.stocktrading.stockquote.repository;
import com.stocktrading.stockquote.entity.Client;
import com.stocktrading.stockquote.entity.PersistingBaseEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Repository;
import javax.annotation.PostConstruct;
@Repository
public class ClientRedisRepositoryImpl implements ClientRedisRepository
{
private static final String HASH_NAME = "client";
@Qualifier("redisTemplate")
@Autowired
private RedisTemplate<String, Client> redisTemplate;
private HashOperations<String, String, PersistingBaseEntity> hashOperations;
public ClientRedisRepositoryImpl()
{
super();
}
@PostConstruct
private void init()
{
hashOperations = redisTemplate.opsForHash();
}
@Override
public void saveClient(Client client)
{
hashOperations.put(HASH_NAME, client.getUuid(), client);
}
@Override
public void updateClient(Client client)
{
hashOperations.put(HASH_NAME, client.getUuid(), client);
}
@Override
public void deleteClient(String clientId)
{
hashOperations.delete(HASH_NAME, clientId);
}
@Override
public Client findClient(String clientId)
{
return (Client) hashOperations.get(HASH_NAME, clientId);
}
}
|
package com.hfjy.framework.logging;
import org.slf4j.ILoggerFactory;
import org.slf4j.Logger;
import com.hfjy.framework.init.Initial;
import ch.qos.logback.classic.LoggerContext;
import ch.qos.logback.classic.joran.JoranConfigurator;
import ch.qos.logback.core.joran.spi.JoranException;
public class LoggerFactory {
private static final Logger logger = LoggerFactory.getLogger(LoggerFactory.class);
static {
try {
LoggerContext loggerContext = (LoggerContext) org.slf4j.LoggerFactory.getILoggerFactory();
loggerContext.reset();
JoranConfigurator joranConfigurator = new JoranConfigurator();
joranConfigurator.setContext(loggerContext);
joranConfigurator.doConfigure(Initial.LOG_CONFIG_FILE);
logger.debug("loaded slf4j configure file ok!");
} catch (JoranException e) {
logger.error("can loading slf4j configure file error", e);
}
}
public static Logger getLogger(String name) {
return new LoggerProcessor(org.slf4j.LoggerFactory.getLogger(name));
}
/**
* Return a logger named corresponding to the class passed as parameter,
* using the statically bound {@link ILoggerFactory} instance.
*
* @param clazz
* the returned logger will be named after clazz
* @return logger
*/
public static Logger getLogger(Class<?> clazz) {
return new LoggerProcessor(org.slf4j.LoggerFactory.getLogger(clazz));
}
/**
* Return the {@link ILoggerFactory} instance in use.
* <p/>
* <p/>
* ILoggerFactory instance is bound with this class at compile time.
*
* @return the ILoggerFactory instance in use
*/
public static ILoggerFactory getILoggerFactory() {
return org.slf4j.LoggerFactory.getILoggerFactory();
}
}
|
package com.example.cape_medics;
import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import org.json.JSONObject;
public class Stroke extends Fragment {
private ImageView imageView18;
private CheckBox chkNA;
private CheckBox checkBox4;
private CheckBox checkBox5;
private CheckBox checkBox6;
private TextView textView55;
private EditText editDoorDrug;
private TextView textView56;
private EditText editStrokeUnit;
private TextView textView57;
private EditText editCasualty;
JSONObject stroke;
public Stroke() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_stroke, container, false);
imageView18 = (ImageView)view.findViewById( R.id.imageView18 );
chkNA = (CheckBox)view.findViewById( R.id.chkNA );
checkBox4 = (CheckBox)view.findViewById( R.id.checkBox4 );
checkBox5 = (CheckBox)view.findViewById( R.id.checkBox5 );
checkBox6 = (CheckBox)view.findViewById( R.id.checkBox6 );
textView55 = (TextView)view.findViewById( R.id.textView55 );
editDoorDrug = (EditText)view.findViewById( R.id.editDoorDrug );
textView56 = (TextView)view.findViewById( R.id.textView56 );
editStrokeUnit = (EditText)view.findViewById( R.id.editStrokeUnit );
textView57 = (TextView)view.findViewById( R.id.textView57 );
editCasualty = (EditText)view.findViewById( R.id.editCasualty );
return view;
}
public JSONObject createJson(){
stroke = new JSONObject();
String facial = null;
String arm = null;
String speech = null;
if(checkBox4.isChecked()) facial = checkBox4.getText().toString();
if(checkBox5.isChecked()) arm = checkBox5.getText().toString();
if(checkBox6.isChecked()) speech = checkBox6.getText().toString();
String door = editDoorDrug.getText().toString();
String strokeStr = editStrokeUnit.getText().toString();
String casual = editCasualty.getText().toString();
try{
stroke.put("Facial", facial);
stroke.put("Arm", arm);
stroke.put("Speech", speech);
stroke.put("Door", door);
stroke.put("Stroke", strokeStr);
stroke.put("Casualty", casual);
}catch (Exception e){
Toast.makeText(getContext(),e.getMessage(),Toast.LENGTH_SHORT).show();
}
return stroke;
}
}
|
package com.company.model;
import com.company.storage.FilmStore;
/**
* Created by abalamanova on May, 2019
*/
public class Film {
public int id;
public String name;
public Type type;
public Fee fee;
public Status status;
public Film(String name, Type type){
this.id = FilmStore.nextId++;
this.name = name;
this.type = type;
this.status = Status.NOT_RENTED;
switch (type) {
case NEW_RELEASES:
this.fee = Fee.PREMIUM;
break;
case OLD:
this.fee = Fee.REGULAR;
break;
case REGULAR:
this.fee = Fee.REGULAR;
break;
}
}
public int getId() {
return id;
}
public String getName() {
return name;
}
public Type getType() {
return type;
}
public Fee getFee() {
return fee;
}
public void setType(Type type) {
this.type = type;
}
public void setStatus(Status status){
this.status = status;
}
public Status getStatus() {
return status;
}
}
|
package com.qfc.yft.ui;
import com.qfc.yft.YftData;
import com.qfc.yft.YftValues;
import com.qfc.yft.data.DataManager;
import com.qfc.yft.entity.User;
import com.qfc.yft.entity.listitem.LIIPeople;
import com.qfc.yft.entity.listitem.LIIProduct;
import com.qfc.yft.ui.current.CurrentPersonActivity;
import com.qfc.yft.ui.current.CurrentProductActivity;
import com.qfc.yft.ui.shop.ShopActivity;
import com.qfc.yft.ui.tabs.chat.ChatActivity;
import com.qfc.yft.utils.JackUtils;
import android.content.Context;
import android.content.Intent;
public class YftActivityGate {
/**
*
* @param context
* @param shopId
* @param shopName
* @param memberType
*/
public static void goShop(Context context,int shopId,String shopName, int memberType){
goShop(context, shopId, shopName, memberType, -1);
}
/**
*
* @param context
* @param shopId
* @param shopName
* @param memberType
* @param tabId
*/
public static void goShop(Context context,int shopId,String shopName, int memberType, int tabId){
Intent intent = new Intent();
intent.setClass(context, ShopActivity.class);
/*intent.putExtra(YftValues.EXTRAS_SHOP_ID, user.getShopId());
intent.putExtra(YftValues.EXTRAS_MEMBER_TYPE, user.getMemberType());*/
User user = new User();
user.setShopId(shopId);
user.setMemberType(memberType);
if(shopId!=YftData.data().getMe().getShopId()){
YftData.data().setCurrentUser(user);
}else{
YftData.data().setMeCurrentUser();//0404
}
intent.putExtra(YftValues.EXTRAS_SHOP_NAME, shopName);
intent.putExtra(YftValues.EXTRAS_SHOP_MEMBER_TYPE, memberType);
if(tabId>-1)intent.putExtra(YftValues.EXTRAS_SHOP_TAB,tabId);
context.startActivity(intent);
}
/**
*
* @param context
* @param prod
*/
public static void goProduct(Context context,LIIProduct prod) {
if(null==prod) return;
YftData.data().storeProduct(prod);
Intent intent = new Intent();
intent.setClass(context, CurrentProductActivity.class);
intent.putExtra(YftValues.EXTRAS_PRODUCT_ID, prod.getProductId());
context.startActivity(intent);
}
public static void goPeople(Context context,LIIPeople peop){
if(null==peop) return;
YftData.data().storePerson(peop);
Intent intent = new Intent();
intent.setClass(context, CurrentPersonActivity.class);
intent.putExtra(YftValues.EXTRAS_ACCOUNT_ID, peop.accountId);
context.startActivity(intent);
}
/**
*
* @param context
* @param userName
* @param id
* @param type
* @param face
*/
public static void goChat(Context context,String userName, Long id, int type, String face){//taotao 0220
if(null==id||id==0) {
JackUtils.showToast(context, YftValues.HINT_NOCHAT);
return;
}
Intent intent = new Intent();
intent.setClass(context,
ChatActivity.class);
intent.putExtra("userName", userName);
intent.putExtra("id", id);
intent.putExtra("type", type);
intent.putExtra("faceIndex", face);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); //Calling startActivity() from outside of an Activity
context.startActivity(intent);
DataManager.getInstance(context)//TODO 检查数据持久化是否到位
.deleteContact(id);
DataManager.getInstance(context)
.addContact(id, type);
}
}
|
package com.example.yuanbaodianfrontend.dao;
import com.example.yuanbaodianfrontend.pojo.YbdGoodnews;
import com.example.yuanbaodianfrontend.pojo.YbdPicture;
import com.example.yuanbaodianfrontend.pojo.YbdUser;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository
public interface UserDao {
//注册
boolean zhuce (YbdUser user);
//登陆
YbdUser login(@Param("phone")String phone , @Param("password") String password);
//个人信息
YbdUser Personal(Integer id);
//修改个人信息
boolean update_Personal(@Param("sex") Integer sex, @Param("id") Integer id, @Param("userName") String userName);
//轮播图展示
List<YbdPicture> rotationChart();
//答题排行榜数据
List<YbdUser> queryUserListByQuestion();
//准确率排行榜数据
List<YbdUser> queryUserListByanswerRate();
//根据id删除用户头像
boolean delete_Head(Integer id);
//根据id添加用户头像
boolean insert_Head(@Param("uploadUrl") String uploadUrl,@Param("id") Integer id);
//修改手机号
boolean updatePhone(@Param("newPhone")String newPhone,@Param("id") Integer id);
//修改密码
boolean updatePwd(@Param("phone")String phone,@Param("password") String password);
//手机号校验
Integer checkTel(String tel);
//日志录入
boolean YbdJournal(@Param("remark")String remark,@Param("operation_ip") String operation_ip,@Param("operation_user") String operation_user,@Param("incident") String incident,@Param("frontback") String frontback);
}
|
package com.zc.base.sys.common.util;
import java.util.HashMap;
import java.util.Map;
public class MyMap {
public static Map<?, ?> quickInitMap(Object... args) {
Map<Object, Object> map = new HashMap();
for (int i = 0; i < args.length; i += 2) {
if (i + 1 < args.length) {
map.put(args[i], args[(i + 1)]);
}
}
return map;
}
}
|
package com.cb.cbfunny.bean;
import java.io.Serializable;
import java.util.ArrayList;
/**
* Created by long on 2016/1/19.
*/
public class GzhkMenuList implements Serializable {
private ArrayList<GzhkMenu> gzhkMenuList;
private long lastUpdateTime;
public long getLastUpdateTime() {
return lastUpdateTime;
}
public void updateLastTime() {
this.lastUpdateTime = System.currentTimeMillis();
}
/**
* 是否需要更新数据 更新时间一天
* @return
*/
public boolean needUpdate() {
return System.currentTimeMillis()-lastUpdateTime>86400000;
}
public ArrayList<GzhkMenu> getGzhkMenuList() {
return gzhkMenuList;
}
public void setGzhkMenuList(ArrayList<GzhkMenu> gzhkMenuList) {
this.gzhkMenuList = gzhkMenuList;
}
}
|
package rally;
import java.util.HashMap;
import org.springframework.stereotype.Component;
public class Items {
// ITEMNAME , ITEM
private HashMap<String, Item> items;
public Items(HashMap<String, Item> initItems) {
this.items = initItems;
}
public HashMap<String, Item> getItems() {
return items;
}
public void setItems(HashMap<String, Item> items) {
this.items = items;
}
}
|
package application.apiInt;
import application.domain.FanBlock;
import org.springframework.web.bind.annotation.RequestParam;
import java.util.List;
public interface Fan {
FanBlock addFan(@RequestParam String name, @RequestParam String pasprortNumber);
FanBlock selectFan(@RequestParam Long fanId);
FanBlock updateFan(@RequestParam Long fanId, @RequestParam String name, @RequestParam String pasprortNumber);
List<FanBlock> selectListFan();
String deleteFan(@RequestParam Long fanId);
}
|
package io.ceph.rgw.client;
import io.ceph.rgw.client.action.ActionFuture;
import io.ceph.rgw.client.action.ActionListener;
import io.ceph.rgw.client.model.notification.SubscribeObjectRequest;
import io.ceph.rgw.client.model.notification.SubscribeObjectResponse;
/**
* A client that provides <a href="https://docs.ceph.com/docs/master/radosgw/s3/objectops/">subscribe operations</a>, sends SubscribeRequest and receives SubscribeResponse.
*
* @author zhuangshuo
* Created by zhuangshuo on 2020/6/4.
* @see Clients#getSubscribe()
* @see io.ceph.rgw.client.model.notification.SubscribeRequest
* @see io.ceph.rgw.client.model.notification.SubscribeResponse
*/
public interface SubscribeClient {
/**
* Subscribe object notification asynchronously.
*
* @param request the subscribe object request
* @param listener the callback listener after action is done
* @return an ActionFuture that cancels the subscription when calling {@link ActionFuture#cancel(boolean)}
*/
ActionFuture<Void> subscribeObjectAsync(SubscribeObjectRequest request, ActionListener<SubscribeObjectResponse> listener);
/**
* Fluent api to subscribe object notification.
*
* @return the request builder
*/
default SubscribeObjectRequest.Builder prepareSubscribeObject() {
return new SubscribeObjectRequest.Builder(this);
}
}
|
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;
/**
* Created by gmarson on 08/05/16.
*/
public class Matrix
{
public int matrixRow = 6;
public int matrixCol = 5;
public double matrixExpectedValue; /// eu to treinando pra ver qual numero. esse numero vai no wright response . Esse numero corresponde ao numero que a rede deve acertar na matriz
public double matrixCurrentValue;
public String matrixString;
public int matrixVector[] = new int[matrixRow * matrixCol + 1];
public char matrixChar[][] = new char[matrixRow][matrixCol];
public Matrix(String filename,int value) {
this.matrixExpectedValue = value;
/// leio do arquivo e passo para a matriz
try {
this.matrixString = readMapFromFile(filename);
Scanner s = new Scanner(this.matrixString);
int i = 0, k = 0;
while (s.hasNextLine()) {
String line = s.nextLine();
line = line.replaceAll("\\s+", "");
//System.out.println(line);
for (int j = 0; j < line.length(); j++) {
char tmp = line.charAt(j);
this.matrixChar[i][j] = tmp;
this.matrixVector[k + 1] = Character.getNumericValue(tmp);
k++;
}
i++;
}
Neuron n = new Neuron();
this.matrixVector[0] = (int) n.bias; //bias
n = null;
} catch (IOException e) {
System.out.println(e);
}
}
private String readMapFromFile(String filename) throws IOException
{
String content = null;
File file = new File(filename); //for ex foo.txt
FileReader reader = null;
try
{
reader = new FileReader(file);
char[] chars = new char[(int) file.length()];
reader.read(chars);
content = new String(chars);
reader.close();
}
catch (IOException e)
{
e.printStackTrace();
}
finally
{
if(reader !=null) {reader.close();}
}
return content;
}
public String getMatrixString()
{
return this.matrixString;
}
public void printMatrixChar()
{
for(int i=0;i<this.matrixRow;i++)
{
for(int j=0; j<this.matrixCol; j++)
{
System.out.print(matrixChar[i][j]);
}
System.out.println();
}
}
public void printMatrixVector()
{
for(int i=0;i<this.matrixVector.length;i++)
{
System.out.println(matrixVector[i]);
}
}
public char getValue(int x, int y)
{
//System.out.print(matrixChar[x][y]);
return this.matrixChar[x][y];
}
}
|
package de.hofuniversity.io.xml;
import org.jdom2.Element;
import de.hofuniversity.core.GeologicalCoordinates;
import de.hofuniversity.core.Stadium;
import de.hofuniversity.core.cache.TeamCache;
/**
*
* @author Markus Exner
*
*/
public class XMLStadiumReader {
public XMLStadiumReader() {}
public Stadium readStadium(Element stadiumElement) {
if (stadiumElement == null) {
throw new IllegalArgumentException("Can not read NULL element for stadium.");
}
Stadium stadium = new Stadium();
stadium.setId(Integer.parseInt(stadiumElement.getAttributeValue("id")));
stadium.setName(stadiumElement.getChildText("name"));
Element locationElement = stadiumElement.getChild("location");
stadium.setCity(locationElement.getChildText("city"));
stadium.setAddress(locationElement.getChildText("adress"));
stadium.setViewers(Integer.parseInt(stadiumElement.getChildText("places")));
Element imagesElement = stadiumElement.getChild("images");
stadium.setImageOutside(imagesElement.getChild("outside").getAttributeValue("url"));
stadium.setImageInside(imagesElement.getChild("inside").getAttributeValue("url"));
GeologicalCoordinates geologicalCoordinates = new GeologicalCoordinates();
geologicalCoordinates.setLongitude(Double.parseDouble(stadiumElement.getChildText("longitude")));
geologicalCoordinates.setLatitude(Double.parseDouble(stadiumElement.getChildText("latitude")));
stadium.setGeologicalCoordinates(geologicalCoordinates);
int teamId = Integer.parseInt(stadiumElement.getAttributeValue("team"));
if (TeamCache.getInstance().contains(teamId))
{
TeamCache.getInstance().get(teamId).setStadium(stadium);
}
return stadium;
}
}
|
public class LogicalOperator {
public static void main (String [] args) {
/* remmember the table
AND & is only when both oparands are have the operands are true.
Inclusive OR | is only false if both operands are false
Exclusive OR ^ is only true if the operands are different
*/
int f = 8;
boolean g = (f >= 8) || (++f <= 10);
System.out.println(f);
}
}
|
package revolt.backend.service;
import revolt.backend.dto.CountryDto;
import java.util.List;
public interface CountryService {
List<CountryDto> getCountries();
CountryDto createCountry(CountryDto countryDto);
CountryDto getCountry(Long id);
CountryDto updateCountry(CountryDto countryDto, Long countryId);
void deleteCountry(Long id);
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.