blob_id
stringlengths 40
40
| language
stringclasses 1
value | repo_name
stringlengths 5
132
| path
stringlengths 2
382
| src_encoding
stringclasses 34
values | length_bytes
int64 9
3.8M
| score
float64 1.5
4.94
| int_score
int64 2
5
| detected_licenses
listlengths 0
142
| license_type
stringclasses 2
values | text
stringlengths 9
3.8M
| download_success
bool 1
class |
|---|---|---|---|---|---|---|---|---|---|---|---|
3f14126cf660c137d2a2fb1972ed5cdad6a67b44
|
Java
|
supermanxkq/projects
|
/omall/src/com/paySystem/ic/web/dto/base/GoodsFormatGroupRelaDTO.java
|
UTF-8
| 1,245
| 1.914063
| 2
|
[] |
no_license
|
package com.paySystem.ic.web.dto.base;
import java.io.Serializable;
import com.paySystem.ic.web.dto.BaseDTO;
/**
* @Title: GoodsFormatGroupRela.java
* @Package: com.paySystem.ic.bean.base
* @Description: 规格分组关联DTO
* @Author: yanwuyang
* @Date: 2014-8-19 下午10:32:01
* @Version: V1.0
*/
public class GoodsFormatGroupRelaDTO extends BaseDTO implements Serializable {
/**
*
*/
private static final long serialVersionUID = -9063546235526049705L;
/**编号 */
private Integer fgrId;
/** 规格编号(规格表Id*/
private Integer formatId;
/**规格分组id(规格分组表Id */
private Integer fgroupId;
/**规格分组名称*/
private String fgroupName;
public String getFgroupName() {
return fgroupName;
}
public void setFgroupName(String fgroupName) {
this.fgroupName = fgroupName;
}
public Integer getFgrId() {
return fgrId;
}
public void setFgrId(Integer fgrId) {
this.fgrId = fgrId;
}
public Integer getFormatId() {
return formatId;
}
public void setFormatId(Integer formatId) {
this.formatId = formatId;
}
public Integer getFgroupId() {
return fgroupId;
}
public void setFgroupId(Integer fgroupId) {
this.fgroupId = fgroupId;
}
}
| true
|
bdff062d62f83f731fe03d1c53d382347c435470
|
Java
|
noresttherein/palimpsest
|
/src/main/scala/net/noresttherein/palimpsest/maps/MutableBSTNode.java
|
UTF-8
| 398
| 2.75
| 3
|
[] |
no_license
|
package net.noresttherein.palimpsest.maps;
/** Base class for binary search tree nodes. Implemented in Java to have the left and right nodes exposed as fields
* rather than getters.
*/
class MutableBSTNode<T extends MutableBSTNode<T>> {
T left;
T right;
MutableBSTNode() {}
MutableBSTNode(T left, T right) {
this.left = left;
this.right = right;
}
/*
*/
}
| true
|
b801ea1cfa000a91867a591e86ab17e952a12dcd
|
Java
|
startupcloudplatform/microservice_address
|
/address-frontend/src/main/java/com/crossent/msxpert/address/controller/AddressController.java
|
UTF-8
| 4,073
| 2.21875
| 2
|
[] |
no_license
|
package com.crossent.msxpert.address.controller;
import com.crossent.msxpert.address.dto.AddressDTO;
import com.crossent.msxpert.address.dto.AddressResultResponse;
import com.crossent.msxpert.address.service.AddressService;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RequestMapping(value = "/v1/address")
@RestController
public class AddressController {
@Autowired
private AddressService addressService;
@ApiOperation(value = "키워드 별 주소 목록 조회 Page")
@ApiImplicitParams({
@ApiImplicitParam(name = "page", value = "page number", required = true, dataType = "int", paramType = "query", defaultValue = ""),
@ApiImplicitParam(name = "pageSize", value = "page 크기", required = true, dataType = "int", paramType = "query", defaultValue = ""),
@ApiImplicitParam(name = "keyword", value = "검색 키워드", required = true, dataType = "string", paramType = "query", defaultValue = "")
})
@RequestMapping(value = "/list", method= RequestMethod.GET)
@ResponseStatus(HttpStatus.OK)
public ResponseEntity<AddressResultResponse> listByKeyword(@RequestParam(value = "page", required = false, defaultValue = "1") int page,
@RequestParam(value = "pageSize", required = false, defaultValue = "15") int pageSize,
@RequestParam String keyword){
return addressService.listByKeyword(page,pageSize, keyword);
}
@ApiOperation(value = "행정구역 시/도 조회 ")
@RequestMapping(value = "/sido/list", method = RequestMethod.GET)
@ResponseStatus(HttpStatus.OK)
public Object listAllSido() {
return addressService.listAllSido();
}
@ApiOperation(value = "행정구역 구/ 조회 ")
@ApiImplicitParams({
@ApiImplicitParam(name = "sido", value = "시/도", required = true, dataType = "string", paramType = "query")
})
@RequestMapping(value = "/gugun/list", method = RequestMethod.GET)
@ResponseStatus(HttpStatus.OK)
public List<String> listAllGuGun(@RequestParam(value = "sido") String sido) {
return addressService.listAllGuGunBySido(sido);
}
@ApiOperation(value = "행정구역 동 조회 ")
@ApiImplicitParams({
@ApiImplicitParam(name = "sido", value = "시/도", required = true, dataType = "string", paramType = "query"),
@ApiImplicitParam(name = "gugun", value = "구/군", required = true, dataType = "string", paramType = "query")
})
@RequestMapping(value = "/dong/list", method = RequestMethod.GET)
@ResponseStatus(HttpStatus.OK)
public List<String> listAllDong(@RequestParam(value = "sido") String sido,
@RequestParam(value= "gugun") String gugun) {
return addressService.listAllDongBySidoAndGuGun(sido, gugun);
}
@ApiOperation(value = "행정구역 조회 by 시/도, 구/군, 동 ")
@ApiImplicitParams({
@ApiImplicitParam(name = "sido", value = "시/도", required = true, dataType = "string", paramType = "query"),
@ApiImplicitParam(name = "gugun", value = "구/군", required = true, dataType = "string", paramType = "query"),
@ApiImplicitParam(name = "dong", value = "동", required = true, dataType = "string", paramType = "query")
})
@GetMapping
@ResponseStatus(HttpStatus.OK)
public AddressDTO getAddress(@RequestParam(value = "sido") String sido,
@RequestParam(value= "gugun") String gugun,
@RequestParam(value= "dong") String dong) {
return addressService.getAddress(sido, gugun, dong);
}
}
| true
|
3f19899706d90fdc5722de38107e986757d1e3db
|
Java
|
vishnuaruvikkarakkaran/ofbnewApp3.0
|
/app/src/main/java/com/enfin/ofabee3/ui/module/userprofile/UserSettingsListAdapter.java
|
UTF-8
| 3,586
| 2.125
| 2
|
[] |
no_license
|
package com.enfin.ofabee3.ui.module.userprofile;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.enfin.ofabee3.R;
import com.enfin.ofabee3.utils.OpenSansTextView;
import com.enfin.ofabee3.utils.OpenSansTextViewBold;
import com.enfin.ofabee3.utils.RecyclerViewItemClickListener;
import java.util.ArrayList;
import hk.ids.gws.android.sclick.SClick;
public class UserSettingsListAdapter extends RecyclerView.Adapter<UserSettingsListAdapter.MenuViewHolder> {
private ArrayList<String> settingsItemList;
private Context mContext;
private RecyclerViewItemClickListener itemClickListener;
private int TYPE_TEXT = 1, TYPE_TEXT_ICON = 2, TYPE_BUTTON = 3;
public boolean canStart = true;
public UserSettingsListAdapter(Context context, ArrayList<String> settingsList) {
this.mContext = context;
this.settingsItemList = settingsList;
}
public void setItemClickListener(RecyclerViewItemClickListener listener) {
this.itemClickListener = listener;
}
@NonNull
@Override
public MenuViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view;
if (viewType == TYPE_TEXT) {
LayoutInflater layoutInflater = LayoutInflater.from(mContext);
view = layoutInflater.inflate(R.layout.settings_item, parent, false);
} else if (viewType == TYPE_BUTTON) {
LayoutInflater layoutInflater = LayoutInflater.from(mContext);
view = layoutInflater.inflate(R.layout.settings_sign_out_button, parent, false);
} else if (viewType == TYPE_TEXT_ICON) {
LayoutInflater layoutInflater = LayoutInflater.from(mContext);
view = layoutInflater.inflate(R.layout.settings_item_with_icon, parent, false);
} else {
LayoutInflater layoutInflater = LayoutInflater.from(mContext);
view = layoutInflater.inflate(R.layout.settings_item, parent, false);
}
RecyclerView.LayoutParams lp = new RecyclerView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
view.setLayoutParams(lp);
MenuViewHolder menuViewHolder = new MenuViewHolder(view);
return menuViewHolder;
}
@Override
public void onBindViewHolder(@NonNull MenuViewHolder holder, int position) {
holder.title.setText(settingsItemList.get(position));
holder.title.setOnClickListener(view -> {
//if (canStart) {
canStart = false;
if (!SClick.check(SClick.BUTTON_CLICK, 2000)) return;
itemClickListener.onItemSelected(position, true);
//}
});
}
@Override
public int getItemCount() {
return settingsItemList.size();
}
public void setCanStart(boolean can){
canStart = can;
}
@Override
public int getItemViewType(int position) {
if (position == 2) {
return TYPE_TEXT;
} else if (position == settingsItemList.size() - 1) {
return TYPE_BUTTON;
} else
return TYPE_TEXT;
}
public class MenuViewHolder extends RecyclerView.ViewHolder {
private OpenSansTextView title;
public MenuViewHolder(@NonNull View itemView) {
super(itemView);
title = itemView.findViewById(R.id.settings_item_title_tv);
}
}
}
| true
|
fe9debccb6287eb7fbc035ef288eb583faa00a0f
|
Java
|
Chraebe/StarPatternFragments
|
/SPF.Server/src/main/java/org/rdfhdt/hdt/triples/TempTriples.java
|
UTF-8
| 3,233
| 2.28125
| 2
|
[
"MIT"
] |
permissive
|
/*
* File: $HeadURL: https://hdt-java.googlecode.com/svn/trunk/hdt-java/src/org/rdfhdt/hdt/triples/TempTriples.java $
* Revision: $Rev: 191 $
* Last modified: $Date: 2013-03-03 11:41:43 +0000 (dom, 03 mar 2013) $
* Last modified by: $Author: mario.arias $
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
* Contacting the authors:
* Mario Arias: mario.arias@deri.org
* Javier D. Fernandez: jfergar@infor.uva.es
* Miguel A. Martinez-Prieto: migumar2@infor.uva.es
* Alejandro Andres: fuzzy.alej@gmail.com
*/
package org.rdfhdt.hdt.triples;
import org.rdfhdt.hdt.enums.TripleComponentOrder;
import org.rdfhdt.hdt.listener.ProgressListener;
import java.io.Closeable;
/**
* Interface for TempTriples implementation.
*
* This is a dynamic interface. For static(read-only) behaviour have a look at
* {@link Triples}
*
*/
public interface TempTriples extends TriplesPrivate, Closeable {
/**
* Add one triple
* @param subject
* @param predicate
* @param object
* @return
*/
boolean insert(int subject, int predicate, int object);
/**
* Adds one or more triples
*
* @param triples
* The triples to be inserted
* @return boolean
*/
boolean insert(TripleID... triples);
/**
* Updates the given TripleID with the new values.
*
* The control has to be given over this method to the TempTriples
* implementation instead of changing the triple manually because some
* implementations might not react well to that (TriplesSet for example, changing
* the triple will not trigger reordering)
*
* @param triple
* @param subj
* @param pred
* @param obj
* @return
*/
boolean update(TripleID triple, int subj, int pred, int obj);
/**
* Deletes one or more triples according to a pattern
*
* @param pattern
* The pattern to match against
* @return boolean
*/
boolean remove(TripleID... pattern);
/**
* Sorts the triples based on the order(TripleComponentOrder) of the
* triples.
* If you want to sort in a different order use setOrder first.
*/
void sort(ProgressListener listener);
void removeDuplicates(ProgressListener listener);
/**
* Sets a type of order(TripleComponentOrder)
*
* @param order
* The order to set
*/
void setOrder(TripleComponentOrder order);
/**
* Gets the currently set order(TripleComponentOrder)
*/
TripleComponentOrder getOrder();
/**
* Clear all triples, resulting in an empty triples section.
*/
void clear();
/**
* Load triples from another instance.
*/
void load(Triples triples, ProgressListener listener);
}
| true
|
365c4760f02223aede69252811a1f0611ad5cb8c
|
Java
|
a-panchenko/BugTracker
|
/src/main/java/controller/project/ProjectController.java
|
UTF-8
| 1,641
| 2.296875
| 2
|
[] |
no_license
|
package controller.project;
import dao.Utils;
import model.Issue;
import model.Project;
import service.issue.IssueService;
import service.issue.IssueServiceImpl;
import service.project.ProjectService;
import service.project.ProjectServiceImpl;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
public class ProjectController extends HttpServlet {
private ProjectService projectService = new ProjectServiceImpl();
private IssueService issueService = new IssueServiceImpl();
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
int id = Integer.valueOf(request.getParameter("id"));
Project project = projectService.getProject(id);
String pageValue = request.getParameter("page");
int page = (pageValue == null) ? 1 : Integer.valueOf(pageValue);
request.setAttribute("currentPage", page);
//pagination: 20 rows per page
int pagesCount = (int) Math.ceil(((double) issueService.getIssues(id).size()) / Utils.ROWS_PER_PAGE);
request.setAttribute("pagesCount", pagesCount);
request.setAttribute("project", project);
List<Issue> issues = issueService.getIssues(id, page);
request.setAttribute("issues", issues);
RequestDispatcher dispatcher = request.getRequestDispatcher("project.jsp");
dispatcher.forward(request, response);
}
}
| true
|
50ae83aca1151efd6c322b5a933afdf01f8cda5b
|
Java
|
yzwall/quick-silver
|
/quick-silver-design-pattern/src/main/java/com/yuanjie/quicksilver/pattern/responsibility/ArrayListRespChain.java
|
UTF-8
| 1,089
| 2.859375
| 3
|
[] |
no_license
|
package com.yuanjie.quicksilver.pattern.responsibility;
import com.google.common.collect.Lists;
import com.yuanjie.quicksilver.pattern.responsibility.handler.AbstractHandler;
import java.util.List;
import java.util.Optional;
public class ArrayListRespChain implements IRespChain<Object, String> {
private List<AbstractHandler<Object, String>> chain = Lists.newArrayList();
private ArrayListRespChain() {
}
public static ArrayListRespChain of() {
return new ArrayListRespChain();
}
@Override
public boolean addHandler(AbstractHandler<Object, String> handler) {
return chain.add(handler);
}
/**
* execute one by one until last handler finished.
*
* @param context
* @return
*/
@Override
public Optional<String> handle(Object context) {
for (int i = 0; i < chain.size(); i++) {
Optional<String> result = chain.get(i).handleTemplate(context);
if (i == chain.size() - 1) {
return result;
}
}
return Optional.empty();
}
}
| true
|
5af5f6cf302ba5ef749a328bceb5fed04c6cbc93
|
Java
|
zhongxingyu/Seer
|
/Diff-Raw-Data/32/32_04f6a41f724496a89dbde43a69dcc523921d5e15/LWJGLTextureState/32_04f6a41f724496a89dbde43a69dcc523921d5e15_LWJGLTextureState_s.java
|
UTF-8
| 33,251
| 1.757813
| 2
|
[] |
no_license
|
/*
* Copyright (c) 2003-2006 jMonkeyEngine
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* * Neither the name of 'jMonkeyEngine' nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.jme.scene.state.lwjgl;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.FloatBuffer;
import java.nio.IntBuffer;
import java.util.ArrayList;
import java.util.Stack;
import java.util.logging.Level;
import org.lwjgl.BufferUtils;
import org.lwjgl.opengl.ARBTextureCompression;
import org.lwjgl.opengl.EXTTextureCompressionS3TC;
import org.lwjgl.opengl.EXTTextureFilterAnisotropic;
import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL12;
import org.lwjgl.opengl.GL13;
import org.lwjgl.opengl.GLContext;
import org.lwjgl.opengl.Util;
import org.lwjgl.opengl.glu.GLU;
import org.lwjgl.opengl.glu.MipMap;
import com.jme.image.Image;
import com.jme.image.Texture;
import com.jme.math.FastMath;
import com.jme.math.Quaternion;
import com.jme.math.Vector3f;
import com.jme.scene.Spatial;
import com.jme.scene.state.RenderState;
import com.jme.scene.state.TextureState;
import com.jme.util.LoggingSystem;
/**
* <code>LWJGLTextureState</code> subclasses the TextureState object using the
* LWJGL API to access OpenGL for texture processing.
*
* @author Mark Powell
* @version $Id: LWJGLTextureState.java,v 1.66 2006-03-09 02:56:27 renanse Exp $
*/
public class LWJGLTextureState extends TextureState {
private static final long serialVersionUID = 1L;
private static Texture[] currentTexture;
//OpenGL texture attributes.
private static int[] textureCorrection = { GL11.GL_FASTEST, GL11.GL_NICEST };
private static int[] textureApply = { GL11.GL_REPLACE, GL11.GL_DECAL,
GL11.GL_MODULATE, GL11.GL_BLEND, GL13.GL_COMBINE, GL11.GL_ADD };
private static int[] textureFilter = { GL11.GL_NEAREST, GL11.GL_LINEAR };
private static int[] textureMipmap = { GL11.GL_NEAREST, // MM_NONE (no
// mipmap)
GL11.GL_NEAREST, GL11.GL_LINEAR, GL11.GL_NEAREST_MIPMAP_NEAREST,
GL11.GL_NEAREST_MIPMAP_LINEAR, GL11.GL_LINEAR_MIPMAP_NEAREST,
GL11.GL_LINEAR_MIPMAP_LINEAR };
private static int[] textureCombineFunc = { GL11.GL_REPLACE,
GL11.GL_MODULATE, GL11.GL_ADD, GL13.GL_ADD_SIGNED,
GL13.GL_SUBTRACT, GL13.GL_INTERPOLATE, GL13.GL_DOT3_RGB,
GL13.GL_DOT3_RGBA };
private static int[] textureCombineSrc = { GL11.GL_TEXTURE,
GL13.GL_PRIMARY_COLOR, GL13.GL_CONSTANT, GL13.GL_PREVIOUS };
private static int[] textureCombineOpRgb = { GL11.GL_SRC_COLOR,
GL11.GL_ONE_MINUS_SRC_COLOR, GL11.GL_SRC_ALPHA,
GL11.GL_ONE_MINUS_SRC_ALPHA };
// first two entries are mostly dummy (except for def = 0) since our alpha's
// only use 3 and 4
private static int[] textureCombineOpAlpha = { GL11.GL_SRC_ALPHA,
GL11.GL_ONE_MINUS_SRC_ALPHA, GL11.GL_SRC_ALPHA,
GL11.GL_ONE_MINUS_SRC_ALPHA };
private static int[] imageComponents = { GL11.GL_RGBA4, GL11.GL_RGB8,
GL11.GL_RGB5_A1, GL11.GL_RGBA8, GL11.GL_LUMINANCE8_ALPHA8,
EXTTextureCompressionS3TC.GL_COMPRESSED_RGB_S3TC_DXT1_EXT,
EXTTextureCompressionS3TC.GL_COMPRESSED_RGBA_S3TC_DXT1_EXT,
EXTTextureCompressionS3TC.GL_COMPRESSED_RGBA_S3TC_DXT3_EXT,
EXTTextureCompressionS3TC.GL_COMPRESSED_RGBA_S3TC_DXT5_EXT,
EXTTextureCompressionS3TC.GL_COMPRESSED_RGB_S3TC_DXT1_EXT,
EXTTextureCompressionS3TC.GL_COMPRESSED_RGBA_S3TC_DXT1_EXT,
EXTTextureCompressionS3TC.GL_COMPRESSED_RGBA_S3TC_DXT3_EXT,
EXTTextureCompressionS3TC.GL_COMPRESSED_RGBA_S3TC_DXT5_EXT };
private static int[] imageFormats = { GL11.GL_RGBA, GL11.GL_RGB,
GL11.GL_RGBA, GL11.GL_RGBA, GL11.GL_LUMINANCE_ALPHA,
GL11.GL_RGB, GL11.GL_RGBA, GL11.GL_RGBA, GL11.GL_RGBA };
private static transient IntBuffer id = BufferUtils.createIntBuffer(1);
private static boolean transformed = false;
/**
* temporary rotation axis vector to flatline memory usage.
*/
private static final Vector3f tmp_rotation1 = new Vector3f();
private static boolean inited = false;
/**
* Constructor instantiates a new <code>LWJGLTextureState</code> object.
* The number of textures that can be combined is determined during
* construction. This equates the number of texture units supported by the
* graphics card.
*
*/
public LWJGLTextureState() {
super();
if (!inited) {
//todo: multitexture is in GL13 - according to forum post: topic=2000
supportsMultiTexture = (GLContext.getCapabilities().GL_ARB_multitexture && GLContext.getCapabilities().OpenGL13);
supportsS3TCCompression = GLContext.getCapabilities().GL_EXT_texture_compression_s3tc;
supportsAniso = GLContext.getCapabilities().GL_EXT_texture_filter_anisotropic;
supportsNonPowerTwo = GLContext.getCapabilities().GL_ARB_texture_non_power_of_two;
if (supportsMultiTexture) {
IntBuffer buf = BufferUtils.createIntBuffer(16); //ByteBuffer.allocateDirect(64).order(ByteOrder.nativeOrder()).asIntBuffer();
GL11.glGetInteger(GL13.GL_MAX_TEXTURE_UNITS, buf);
numTexUnits = buf.get(0);
} else {
numTexUnits = 1;
}
currentTexture = new Texture[numTexUnits];
if (supportsAniso) {
// Due to LWJGL buffer check, you can't use smaller sized buffers
// (min_size = 16 for glGetFloat()).
FloatBuffer max_a = BufferUtils.createFloatBuffer(16);
max_a.rewind();
// Grab the maximum anisotropic filter.
GL11.glGetFloat(
EXTTextureFilterAnisotropic.GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT,
max_a);
// set max.
maxAnisotropic = max_a.get(0);
}
inited = true;
}
texture = new ArrayList();
}
/**
* override MipMap to access helper methods
*/
protected static class LWJGLMipMap extends MipMap {
/**
* @see MipMap#glGetIntegerv
*/
protected static int glGetIntegerv(int what) {
return MipMap.glGetIntegerv( what );
}
/**
* @see MipMap#nearestPower
*/
protected static int nearestPower(int value) {
return MipMap.nearestPower( value );
}
/**
* @see MipMap#bytesPerPixel(int, int)
*/
protected static int bytesPerPixel(int format, int type) {
return MipMap.bytesPerPixel( format, type );
}
}
/*
* (non-Javadoc)
*
* @see com.jme.scene.state.TextureState#bind()
*/
public void load(int unit) {
Texture texture = getTexture(unit);
if (texture == null) {
return;
}
// Create A IntBuffer For Image Address In Memory
//Create the texture
id.clear();
GL11.glGenTextures(id);
GL11.glBindTexture(GL11.GL_TEXTURE_2D, id.get(0));
texture.setTextureId(id.get(0));
textureids[unit]=texture.getTextureId();
// pass image data to OpenGL
Image image = texture.getImage();
if (image == null) {
LoggingSystem.getLogger().log(Level.WARNING,
"Image data for texture is null.");
}
// Set up the anisotropic filter.
if (supportsAniso)
GL11.glTexParameterf(
GL11.GL_TEXTURE_2D,
EXTTextureFilterAnisotropic.GL_TEXTURE_MAX_ANISOTROPY_EXT,
texture.getAnisoLevel());
// set alignment to support images with width % 4 != 0, as images are
// not aligned
GL11.glPixelStorei(GL11.GL_UNPACK_ALIGNMENT, 1);
// Get texture image data. Not all textures have image data.
// For example, AM_COMBINE modes can use primary colors,
// texture output, and constants to modify fragments via the
// texture units.
if (image != null) {
if ( !supportsNonPowerTwo &&
( !FastMath.isPowerOfTwo( image.getWidth() ) ||
!FastMath.isPowerOfTwo( image.getHeight() ) ) )
{
LoggingSystem.getLogger().warning(
"Attempted to apply texture with size that is not power " +
"of 2: " + image.getWidth() + " x " + image.getHeight() );
final int maxSize = LWJGLMipMap.glGetIntegerv(
GL11.GL_MAX_TEXTURE_SIZE );
int actualWidth = image.getWidth();
int w = LWJGLMipMap.nearestPower( actualWidth );
if ( w > maxSize ) {
w = maxSize;
}
int actualHeight = image.getHeight();
int h = LWJGLMipMap.nearestPower( actualHeight );
if ( h > maxSize ) {
h = maxSize;
}
LoggingSystem.getLogger().warning(
"Rescaling image to " + w + " x " + h + " !!!" );
// must rescale image to get "top" mipmap texture image
int format = imageFormats[image.getType()];
int type = GL11.GL_UNSIGNED_BYTE;
int bpp = LWJGLMipMap.bytesPerPixel( format, type );
ByteBuffer scaledImage =
BufferUtils.createByteBuffer( ( w + 4 ) * h * bpp );
int error = MipMap.gluScaleImage(
format, actualWidth, actualHeight, type,
image.getData(), w, h, type, scaledImage );
if ( error != 0 ) {
Util.checkGLError();
}
image.setWidth( w );
image.setHeight( h );
image.setData( scaledImage );
}
// For textures which need mipmaps auto-generating and which
// aren't using compressed images, generate the mipmaps.
// A new mipmap builder may be needed to build mipmaps for
// compressed textures.
if (texture.getMipmap() >= Texture.MM_NEAREST_NEAREST &&
!image.hasMipmaps() && !image.isCompressedType()) {
GLU.gluBuild2DMipmaps(GL11.GL_TEXTURE_2D,
imageComponents[image.getType()], image
.getWidth(), image.getHeight(),
imageFormats[image.getType()],
GL11.GL_UNSIGNED_BYTE, image.getData());
} else {
// Get mipmap data sizes and amount of mipmaps to send to
// opengl. Then loop through all mipmaps and send them.
int[] mipSizes = image.getMipMapSizes();
ByteBuffer data = image.getData();
int max = 1;
int pos = 0;
if (mipSizes == null) {
mipSizes = new int[] { data.capacity() };
} else if (texture.getMipmap() != Texture.MM_NONE ) {
max = mipSizes.length;
}
for ( int m = 0; m < max; m++ )
{
int width = Math.max( 1, image.getWidth() >> m );
int height = Math.max( 1, image.getHeight() >> m );
data.position( pos );
if ( image.isCompressedType() )
{
ARBTextureCompression.glCompressedTexImage2DARB(
GL11.GL_TEXTURE_2D, m,
imageComponents[image.getType()], width, height,
0, mipSizes[m], data );
}
else
{
data.limit( data.position() + mipSizes[m] );
GL11.glTexImage2D(
GL11.GL_TEXTURE_2D, m,
imageComponents[image.getType()], width,
height, 0, imageFormats[image.getType()],
GL11.GL_UNSIGNED_BYTE, data);
}
pos += mipSizes[ m ];
}
}
}
switch (texture.getWrap()) {
case Texture.WM_ECLAMP_S_ECLAMP_T:
GL11.glTexParameteri(GL11.GL_TEXTURE_2D,
GL11.GL_TEXTURE_WRAP_S, GL12.GL_CLAMP_TO_EDGE);
GL11.glTexParameteri(GL11.GL_TEXTURE_2D,
GL11.GL_TEXTURE_WRAP_T, GL12.GL_CLAMP_TO_EDGE);
break;
case Texture.WM_BCLAMP_S_BCLAMP_T:
GL11.glTexParameteri(GL11.GL_TEXTURE_2D,
GL11.GL_TEXTURE_WRAP_S,
GL13.GL_CLAMP_TO_BORDER);
GL11.glTexParameteri(GL11.GL_TEXTURE_2D,
GL11.GL_TEXTURE_WRAP_T,
GL13.GL_CLAMP_TO_BORDER);
break;
case Texture.WM_CLAMP_S_CLAMP_T:
GL11.glTexParameteri(GL11.GL_TEXTURE_2D,
GL11.GL_TEXTURE_WRAP_S, GL11.GL_CLAMP);
GL11.glTexParameteri(GL11.GL_TEXTURE_2D,
GL11.GL_TEXTURE_WRAP_T, GL11.GL_CLAMP);
break;
case Texture.WM_CLAMP_S_WRAP_T:
GL11.glTexParameteri(GL11.GL_TEXTURE_2D,
GL11.GL_TEXTURE_WRAP_S, GL11.GL_CLAMP);
GL11.glTexParameteri(GL11.GL_TEXTURE_2D,
GL11.GL_TEXTURE_WRAP_T, GL11.GL_REPEAT);
break;
case Texture.WM_WRAP_S_CLAMP_T:
GL11.glTexParameteri(GL11.GL_TEXTURE_2D,
GL11.GL_TEXTURE_WRAP_S, GL11.GL_REPEAT);
GL11.glTexParameteri(GL11.GL_TEXTURE_2D,
GL11.GL_TEXTURE_WRAP_T, GL11.GL_CLAMP);
break;
case Texture.WM_WRAP_S_WRAP_T:
GL11.glTexParameteri(GL11.GL_TEXTURE_2D,
GL11.GL_TEXTURE_WRAP_S, GL11.GL_REPEAT);
GL11.glTexParameteri(GL11.GL_TEXTURE_2D,
GL11.GL_TEXTURE_WRAP_T, GL11.GL_REPEAT);
break;
}
}
/**
* <code>apply</code> manages the textures being described by the state.
* If the texture has not been loaded yet, it is generated and loaded using
* OpenGL11. This means the initial pass to set will be longer than
* subsequent calls. The multitexture extension is used to define the
* multiple texture states, with the number of units being determined at
* construction time.
*
* @see com.jme.scene.state.RenderState#apply()
*/
public void apply() {
if (isEnabled()) {
int index;
Texture texture;
for (int i = 0; i < numTexUnits; i++) {
texture = getTexture(i);
if (texture != null)
textureids[i] = texture.getTextureId();
if (texture == currentTexture[i])
continue;
currentTexture[i] = texture;
index = GL13.GL_TEXTURE0 + i;
if (supportsMultiTexture) {
GL13.glActiveTexture(index);
}
if (texture == null) {
GL11.glDisable(GL11.GL_TEXTURE_2D);
continue;
} else
GL11.glEnable(GL11.GL_TEXTURE_2D);
boolean doTrans = texture.getTranslation() != null && !Vector3f.ZERO.equals(texture.getTranslation());
boolean doRot = texture.getRotation() != null && !Quaternion.IDENTITY.equals(texture.getRotation());
boolean doScale = texture.getScale() != null && !Vector3f.UNIT_XYZ.equals(texture.getScale());
if (doTrans || doRot || doScale) {
GL11.glMatrixMode(GL11.GL_TEXTURE);
GL11.glLoadIdentity();
if (doTrans) {
GL11.glTranslatef(texture.getTranslation().x,texture.getTranslation().y,texture.getTranslation().z);
}
if (doRot) {
Vector3f vRot = tmp_rotation1;
float rot = texture.getRotation().toAngleAxis(vRot)
* FastMath.RAD_TO_DEG;
GL11.glRotatef(rot, vRot.x, vRot.y, vRot.z);
}
if (doScale)
GL11.glScalef(texture.getScale().x,
texture.getScale().y, texture.getScale().z);
GL11.glMatrixMode(GL11.GL_MODELVIEW);
transformed = true;
} else if (transformed) {
GL11.glMatrixMode(GL11.GL_TEXTURE);
GL11.glLoadIdentity();
GL11.glMatrixMode(GL11.GL_MODELVIEW);
transformed = false;
}
//texture not yet loaded.
if (texture.getTextureId() == 0) {
load();
} else {
// texture already exists in OpenGL, just bind it
GL11.glBindTexture(GL11.GL_TEXTURE_2D, texture
.getTextureId());
}
// If wrap mode was changed or this texture is new...
if (texture.needsWrapRefresh()) {
texture.setNeedsWrapRefresh(false);
// set up wrap mode
switch (texture.getWrap()) {
case Texture.WM_ECLAMP_S_ECLAMP_T:
GL11.glTexParameteri(GL11.GL_TEXTURE_2D,
GL11.GL_TEXTURE_WRAP_S, GL12.GL_CLAMP_TO_EDGE);
GL11.glTexParameteri(GL11.GL_TEXTURE_2D,
GL11.GL_TEXTURE_WRAP_T, GL12.GL_CLAMP_TO_EDGE);
break;
case Texture.WM_BCLAMP_S_BCLAMP_T:
GL11
.glTexParameteri(GL11.GL_TEXTURE_2D,
GL11.GL_TEXTURE_WRAP_S,
GL13.GL_CLAMP_TO_BORDER);
GL11
.glTexParameteri(GL11.GL_TEXTURE_2D,
GL11.GL_TEXTURE_WRAP_T,
GL13.GL_CLAMP_TO_BORDER);
break;
case Texture.WM_CLAMP_S_CLAMP_T:
GL11.glTexParameteri(GL11.GL_TEXTURE_2D,
GL11.GL_TEXTURE_WRAP_S, GL11.GL_CLAMP);
GL11.glTexParameteri(GL11.GL_TEXTURE_2D,
GL11.GL_TEXTURE_WRAP_T, GL11.GL_CLAMP);
break;
case Texture.WM_CLAMP_S_WRAP_T:
GL11.glTexParameteri(GL11.GL_TEXTURE_2D,
GL11.GL_TEXTURE_WRAP_S, GL11.GL_CLAMP);
GL11.glTexParameteri(GL11.GL_TEXTURE_2D,
GL11.GL_TEXTURE_WRAP_T, GL11.GL_REPEAT);
break;
case Texture.WM_WRAP_S_CLAMP_T:
GL11.glTexParameteri(GL11.GL_TEXTURE_2D,
GL11.GL_TEXTURE_WRAP_S, GL11.GL_REPEAT);
GL11.glTexParameteri(GL11.GL_TEXTURE_2D,
GL11.GL_TEXTURE_WRAP_T, GL11.GL_CLAMP);
break;
case Texture.WM_WRAP_S_WRAP_T:
GL11.glTexParameteri(GL11.GL_TEXTURE_2D,
GL11.GL_TEXTURE_WRAP_S, GL11.GL_REPEAT);
GL11.glTexParameteri(GL11.GL_TEXTURE_2D,
GL11.GL_TEXTURE_WRAP_T, GL11.GL_REPEAT);
break;
}
}
// If texture data was changed, (eg. render to texture) the
// filtering needs to be redone.
if (texture.needsFilterRefresh()) {
texture.setNeedsFilterRefresh(false);
// set up filter mode
GL11.glTexParameteri(GL11.GL_TEXTURE_2D,
GL11.GL_TEXTURE_MAG_FILTER, textureFilter[texture
.getFilter()]);
// set up mipmap mode
GL11.glTexParameteri(GL11.GL_TEXTURE_2D,
GL11.GL_TEXTURE_MIN_FILTER, textureMipmap[texture
.getMipmap()]);
}
// set up correction mode
GL11.glHint(GL11.GL_PERSPECTIVE_CORRECTION_HINT,
textureCorrection[texture.getCorrection()]);
// set Texture apply mode.
GL11.glTexEnvi(GL11.GL_TEXTURE_ENV,
GL11.GL_TEXTURE_ENV_MODE, textureApply[texture
.getApply()]);
if (texture.getApply() == Texture.AM_COMBINE
&& supportsMultiTexture) {
if (texture.getCombineFuncAlpha() == Texture.ACF_DOT3_RGB
|| texture.getCombineFuncAlpha() == Texture.ACF_DOT3_RGBA) {
GL11.glDisable(GL11.GL_TEXTURE_2D);
break;
}
if (texture.getCombineFuncRGB() == Texture.ACF_DOT3_RGB
|| texture.getCombineFuncRGB() == Texture.ACF_DOT3_RGBA) {
// check if supported before proceeding
if (!GLContext.getCapabilities().GL_ARB_texture_env_dot3) {
GL11.glDisable(GL11.GL_TEXTURE_2D);
break;
}
}
int cf = texture.getCombineFuncRGB();
GL11.glTexEnvi(GL11.GL_TEXTURE_ENV, GL13.GL_COMBINE_RGB,
textureCombineFunc[cf]);
GL11.glTexEnvi(GL11.GL_TEXTURE_ENV, GL13.GL_SOURCE0_RGB,
textureCombineSrc[texture.getCombineSrc0RGB()]);
GL11.glTexEnvi(GL11.GL_TEXTURE_ENV, GL13.GL_OPERAND0_RGB,
textureCombineOpRgb[texture.getCombineOp0RGB()]);
if (cf != Texture.ACF_REPLACE) {
GL11.glTexEnvi(GL11.GL_TEXTURE_ENV,
GL13.GL_SOURCE1_RGB, textureCombineSrc[texture
.getCombineSrc1RGB()]);
GL11
.glTexEnvi(GL11.GL_TEXTURE_ENV,
GL13.GL_OPERAND1_RGB,
textureCombineOpRgb[texture
.getCombineOp1RGB()]);
if (cf == Texture.ACF_INTERPOLATE) {
GL11.glTexEnvi(GL11.GL_TEXTURE_ENV,
GL13.GL_OPERAND2_RGB,
textureCombineOpRgb[texture
.getCombineOp2RGB()]);
GL11.glTexEnvi(GL11.GL_TEXTURE_ENV,
GL13.GL_SOURCE2_RGB,
textureCombineSrc[texture
.getCombineSrc2RGB()]);
}
}
cf = texture.getCombineFuncAlpha();
GL11.glTexEnvi(GL11.GL_TEXTURE_ENV, GL13.GL_COMBINE_ALPHA,
textureCombineFunc[cf]);
GL11.glTexEnvi(GL11.GL_TEXTURE_ENV, GL13.GL_SOURCE0_ALPHA,
textureCombineSrc[texture.getCombineSrc0Alpha()]);
GL11
.glTexEnvi(GL11.GL_TEXTURE_ENV,
GL13.GL_OPERAND0_ALPHA,
textureCombineOpAlpha[texture
.getCombineOp0Alpha()]);
if (cf != Texture.ACF_REPLACE) {
GL11
.glTexEnvi(GL11.GL_TEXTURE_ENV,
GL13.GL_SOURCE1_ALPHA,
textureCombineSrc[texture
.getCombineSrc1Alpha()]);
GL11.glTexEnvi(GL11.GL_TEXTURE_ENV,
GL13.GL_OPERAND1_ALPHA,
textureCombineOpAlpha[texture
.getCombineOp1Alpha()]);
if (cf == Texture.ACF_INTERPOLATE) {
GL11.glTexEnvi(GL11.GL_TEXTURE_ENV,
GL13.GL_SOURCE2_ALPHA,
textureCombineSrc[texture
.getCombineSrc2Alpha()]);
GL11.glTexEnvi(GL11.GL_TEXTURE_ENV,
GL13.GL_OPERAND2_ALPHA,
textureCombineOpAlpha[texture
.getCombineOp2Alpha()]);
}
}
GL11.glTexEnvf(GL11.GL_TEXTURE_ENV, GL13.GL_RGB_SCALE,
texture.getCombineScaleRGB());
GL11.glTexEnvf(GL11.GL_TEXTURE_ENV, GL11.GL_ALPHA_SCALE,
texture.getCombineScaleAlpha());
}
if (texture.getEnvironmentalMapMode() == Texture.EM_IGNORE) {
// Do not alter the texure generation status. This allows
// complex texturing outside of texture state to exist
// peacefully.
} else if (texture.getEnvironmentalMapMode() == Texture.EM_NONE) {
// turn off anything that other maps might have turned on
GL11.glDisable(GL11.GL_TEXTURE_GEN_Q);
GL11.glDisable(GL11.GL_TEXTURE_GEN_R);
GL11.glDisable(GL11.GL_TEXTURE_GEN_S);
GL11.glDisable(GL11.GL_TEXTURE_GEN_T);
} else if (texture.getEnvironmentalMapMode() == Texture.EM_SPHERE) {
// generate texture coordinates
GL11.glTexGeni(GL11.GL_S, GL11.GL_TEXTURE_GEN_MODE,
GL11.GL_SPHERE_MAP);
GL11.glTexGeni(GL11.GL_T, GL11.GL_TEXTURE_GEN_MODE,
GL11.GL_SPHERE_MAP);
GL11.glEnable(GL11.GL_TEXTURE_GEN_S);
GL11.glEnable(GL11.GL_TEXTURE_GEN_T);
}
GL11.glTexEnv(GL11.GL_TEXTURE_ENV, GL11.GL_TEXTURE_ENV_COLOR,
texture.getBlendColor());
}
} else {
if (supportsMultiTexture) {
for (int i = 0; i < numTexUnits; i++) {
GL13.glActiveTexture(GL13.GL_TEXTURE0 + i);
GL11.glDisable(GL11.GL_TEXTURE_2D);
currentTexture[i] = null;
}
} else {
GL11.glDisable(GL11.GL_TEXTURE_2D);
currentTexture[0] = null;
}
}
}
public RenderState extract(Stack stack, Spatial spat) {
int mode = spat.getTextureCombineMode();
if (mode == REPLACE || (mode != OFF && stack.size() == 1) ) //todo: use dummy state if off?
return (LWJGLTextureState) stack.peek();
// accumulate the textures in the stack into a single LightState object
LWJGLTextureState newTState = new LWJGLTextureState();
boolean foundEnabled = false;
Object states[] = stack.toArray();
switch (mode) {
case COMBINE_CLOSEST:
case COMBINE_RECENT_ENABLED:
for (int iIndex = states.length - 1; iIndex >= 0; iIndex--) {
TextureState pkTState = (TextureState) states[iIndex];
if (!pkTState.isEnabled()) {
if (mode == COMBINE_RECENT_ENABLED)
break;
else
continue;
} else
foundEnabled = true;
for (int i = 0, max = pkTState.getNumberOfSetTextures(); i < max; i++) {
Texture pkText = pkTState.getTexture(i);
if (newTState.getTexture(i) == null) {
newTState.setTexture(pkText, i);
}
}
}
break;
case COMBINE_FIRST:
for (int iIndex = 0, max = states.length; iIndex < max; iIndex++) {
TextureState pkTState = (TextureState) states[iIndex];
if (!pkTState.isEnabled())
continue;
else
foundEnabled = true;
for (int i = 0; i < numTexUnits; i++) {
Texture pkText = pkTState.getTexture(i);
if (newTState.getTexture(i) == null) {
newTState.setTexture(pkText, i);
}
}
}
break;
case OFF:
break;
}
newTState.setEnabled(foundEnabled);
return newTState;
}
/*
* (non-Javadoc)
*
* @see com.jme.scene.state.TextureState#delete(int)
*/
public void delete(int unit) {
if (unit < 0 || unit >= texture.size() || texture.get(unit) == null)
return;
id.clear();
id.put(((Texture)texture.get(unit)).getTextureId());
id.rewind();
((Texture)texture.get(unit)).setTextureId(0);
GL11.glDeleteTextures(id);
resetTextureIDs();
}
/*
* (non-Javadoc)
*
* @see com.jme.scene.state.TextureState#deleteAll()
*/
public void deleteAll() {
for (int i = 0; i < texture.size(); i++) {
if (texture.get(i) == null)
continue;
id.clear();
id.put(((Texture)texture.get(i)).getTextureId());
id.rewind();
GL11.glDeleteTextures(id);
((Texture)texture.get(i)).setTextureId(0);
}
resetTextureIDs();
}
private void readObject(java.io.ObjectInputStream in) throws IOException,
ClassNotFoundException {
in.defaultReadObject();
id = BufferUtils.createIntBuffer(1);
}
}
| true
|
5da9f8e998f2abad3788dd757feae7e2890e54ab
|
Java
|
charanjitghai/competitiveProgramming
|
/LeetCode/Google/FirstUniqueCharacter.java
|
UTF-8
| 923
| 3.15625
| 3
|
[] |
no_license
|
/**
** author: charanjitghai
** question: https://leetcode.com/explore/interview/card/google/59/array-and-strings/459/
*/
class Solution {
public int firstUniqChar(String s) {
boolean[] repeated = new boolean[26];
int[] firstIdx = new int[26];
for(int i = 0; i < s.length(); i++) {
int li = s.charAt(i) - 'a';
if(! repeated[li]) {
if(firstIdx[li] != 0) {
repeated[li] = true;
}
else {
firstIdx[li] = i + 1;
}
}
}
int minIdx = s.length() + 1;
for(int i = 0; i < 26; i++) {
if((! repeated[i]) && firstIdx[i] > 0) {
if(minIdx > firstIdx[i])
minIdx = firstIdx[i];
}
}
if(minIdx == s.length() + 1)
return -1;
return minIdx -1;
}
}
| true
|
4cbbfd620cbec8db3a3b71d31927304a04561f3d
|
Java
|
revolvernn/feihua-framework
|
/feihua-framework-cms-service/feihua-framework-cms-service-impl/src/main/java/com/feihua/framework/cms/impl/ApiCmsQuestionOptionsPoServiceImpl.java
|
UTF-8
| 2,050
| 1.648438
| 2
|
[
"MIT"
] |
permissive
|
package com.feihua.framework.cms.impl;
import com.feihua.framework.cms.api.ApiCmsQuestionOptionsPoService;
import com.feihua.framework.cms.dto.CmsQuestionOptionsDto;
import com.feihua.framework.cms.po.CmsQuestionOptionsPo;
import com.github.pagehelper.Page;
import feihua.jdbc.api.pojo.PageResultDto;
import feihua.jdbc.api.service.impl.ApiBaseServiceImpl;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
/**
* This class was generated by MyBatis Generator.
* @author revolver 2019-01-17 14:03:09
*/
@Service
public class ApiCmsQuestionOptionsPoServiceImpl extends ApiBaseServiceImpl<CmsQuestionOptionsPo, CmsQuestionOptionsDto, String> implements ApiCmsQuestionOptionsPoService {
@Autowired
com.feihua.framework.cms.mapper.CmsQuestionOptionsPoMapper CmsQuestionOptionsPoMapper;
public ApiCmsQuestionOptionsPoServiceImpl() {
super(CmsQuestionOptionsDto.class);
}
@Override
public PageResultDto<CmsQuestionOptionsDto> searchCmsQuestionOptionssDsf(com.feihua.framework.cms.dto.SearchCmsQuestionOptionssConditionDto dto, feihua.jdbc.api.pojo.PageAndOrderbyParamDto pageAndOrderbyParamDto) {
Page p = super.pageAndOrderbyStart(pageAndOrderbyParamDto);
List<com.feihua.framework.cms.dto.CmsQuestionOptionsDto> list = this.wrapDtos(CmsQuestionOptionsPoMapper.searchCmsQuestionOptionss(dto));
return new PageResultDto(list, this.wrapPage(p));
}
@Override
public CmsQuestionOptionsDto wrapDto(CmsQuestionOptionsPo po) {
if (po == null) { return null; }
CmsQuestionOptionsDto dto = new CmsQuestionOptionsDto();
dto.setId(po.getId());
dto.setQuestionId(po.getQuestionId());
dto.setName(po.getName());
dto.setDataUserId(po.getDataUserId());
dto.setDataOfficeId(po.getDataOfficeId());
dto.setDataType(po.getDataType());
dto.setDataAreaId(po.getDataAreaId());
dto.setUpdateAt(po.getUpdateAt());
return dto;
}
}
| true
|
62c4eeeb0ec05877f23519b5072fabbc9552d4b8
|
Java
|
joseantoniorosales/Recuperacion_Segundo_Trimestre_Prog
|
/gestioncomercialmejorada/ClientList.java
|
ISO-8859-10
| 772
| 3.015625
| 3
|
[] |
no_license
|
package gestioncomercialmejorada;
import java.util.HashMap;
import java.util.Set;
public class ClientList {
private HashMap<String, Usuario> clientList = new HashMap<>();
// Metodo que fija nombre como clave del HashMap clientList
public Set<String> nombre() {
return clientList.keySet();
}
// Metodo para aadir clientes a la lista
public void add(Usuario user) {
// Llama al metodo getNombre desde la clase Usuario
String name = user.getNombre();
clientList.put(name, user);
}
// Metodo para recibir el nombre del cliente
public Usuario get(String nombre) {
return clientList.get(nombre);
}
// Metodo para borrar clientes
public void del(String name) {
clientList.remove(name);
}
}
| true
|
9bb9f8c973613734ac38cb8593da0e4130a17e77
|
Java
|
manish84ya/Hibernate
|
/Hibernate Reverse Engineering/Zoho Project Annotations/com/BugTracking/BugStatus.java
|
UTF-8
| 1,416
| 2.3125
| 2
|
[] |
no_license
|
package com.BugTracking;
// Generated 30 May, 2018 6:17:26 PM by Hibernate Tools 3.5.0.Final
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
/**
* BugStatus generated by hbm2java
*/
@Entity
@Table(name = "bug_status", catalog = "bt2")
public class BugStatus implements java.io.Serializable {
private long bugStatusId;
private Bug bug;
private String statusOfBugIs;
public BugStatus() {
}
public BugStatus(long bugStatusId) {
this.bugStatusId = bugStatusId;
}
public BugStatus(long bugStatusId, Bug bug, String statusOfBugIs) {
this.bugStatusId = bugStatusId;
this.bug = bug;
this.statusOfBugIs = statusOfBugIs;
}
@Id
@Column(name = "Bug_Status_ID", unique = true, nullable = false)
public long getBugStatusId() {
return this.bugStatusId;
}
public void setBugStatusId(long bugStatusId) {
this.bugStatusId = bugStatusId;
}
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "Bug_ID")
public Bug getBug() {
return this.bug;
}
public void setBug(Bug bug) {
this.bug = bug;
}
@Column(name = "Status_Of_Bug_is")
public String getStatusOfBugIs() {
return this.statusOfBugIs;
}
public void setStatusOfBugIs(String statusOfBugIs) {
this.statusOfBugIs = statusOfBugIs;
}
}
| true
|
6cb92bc76fdc7f7a5e5ec61bcaba20b29ef48bac
|
Java
|
aberimen/KodlamaIO-Java-React-Kamp-Odevleri
|
/2.GameManagementProject/src/serviceImpl/OrderManager.java
|
ISO-8859-9
| 1,018
| 2.875
| 3
|
[] |
no_license
|
package serviceImpl;
import domain.Campaign;
import domain.Game;
import domain.Gamer;
import service.OrderService;
public class OrderManager implements OrderService{
private Campaign campaign;
public OrderManager() {
}
public OrderManager(Campaign campaign) {
this.campaign = campaign;
}
@Override
public void orderGame(Game game, Gamer gamer) {
if(campaign != null) {
double oyunFiyati = game.getPrice();
double indirimOrani = campaign.getDiscountRate();
double indirimliFiyat = oyunFiyati - (oyunFiyati*indirimOrani)/100;
System.out.println("Kampanya uyguland: " + campaign.getName());
System.out.println("ndirim oran: %" + indirimOrani);
System.out.println("Eski fiyat: " + oyunFiyati + "TL Indirimli fiyat: " + indirimliFiyat +"TL");
}else {
System.out.println("Kampanya mevcut deil, normal fiyat zerinden fiyatlanrld.");
}
System.out.println(game.getName() + " adl oyun satn alnd- Kullanc: " + gamer.getFirstName());
}
}
| true
|
f94ea81291dccf1fcdee5646cbb86e36d1575162
|
Java
|
cmFodWx5YWRhdjEyMTA5/smell-and-machine-learning
|
/ast_results/westnordost_StreetComplete/app/src/main/java/de/westnordost/streetcomplete/view/MaskSpeechbubbleCornersFrameLayout.java
|
UTF-8
| 1,500
| 1.71875
| 2
|
[] |
no_license
|
// isComment
package de.westnordost.streetcomplete.view;
import android.annotation.TargetApi;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Path;
import android.graphics.RectF;
import android.os.Build;
import android.util.AttributeSet;
import android.widget.FrameLayout;
import de.westnordost.streetcomplete.util.DpUtil;
/**
* isComment
*/
public class isClassOrIsInterface extends FrameLayout {
public isConstructor(Context isParameter) {
super(isNameExpr);
}
public isConstructor(Context isParameter, AttributeSet isParameter) {
super(isNameExpr, isNameExpr);
}
public isConstructor(Context isParameter, AttributeSet isParameter, int isParameter) {
super(isNameExpr, isNameExpr, isNameExpr);
}
@TargetApi(isNameExpr.isFieldAccessExpr.isFieldAccessExpr)
public isConstructor(Context isParameter, AttributeSet isParameter, int isParameter, int isParameter) {
super(isNameExpr, isNameExpr, isNameExpr, isNameExpr);
}
@Override
protected void isMethod(Canvas isParameter) {
Path isVariable = new Path();
int isVariable = (int) isNameExpr.isMethod(isDoubleConstant, isMethod());
isNameExpr.isMethod(new RectF(isIntegerConstant, isIntegerConstant, isNameExpr.isMethod(), isNameExpr.isMethod()), isNameExpr, isNameExpr, isNameExpr.isFieldAccessExpr.isFieldAccessExpr);
isNameExpr.isMethod(isNameExpr);
super.isMethod(isNameExpr);
}
}
| true
|
43f603e55698e74d7e5f00d236d011b92a01d5cb
|
Java
|
xxybfq/factory
|
/src/com/lf/pattern/factory/abstractfactory/MammalAnimalFactory.java
|
UTF-8
| 347
| 2.703125
| 3
|
[] |
no_license
|
package com.lf.pattern.factory.abstractfactory;
/**
* @author sun
* @date 2019/3/10
*/
public class MammalAnimalFactory implements IAnimalFactory {
@Override
public IHabit creatHabit() {
return new MammalAnimalHabitImpl();
}
@Override
public ILife createLife() {
return new MammalAnimalLifeImpl();
}
}
| true
|
bb53e0b2863681dd43eeb2a6ce2df908ae3acb21
|
Java
|
workcraft/workcraft
|
/workcraft/WorkcraftCore/src/org/workcraft/formula/visitors/Inverter.java
|
UTF-8
| 1,251
| 2.609375
| 3
|
[
"MIT"
] |
permissive
|
package org.workcraft.formula.visitors;
import org.workcraft.formula.*;
public final class Inverter implements BooleanVisitor<BooleanFormula> {
private static Inverter instance;
private Inverter() {
}
public static Inverter getInstance() {
if (instance == null) {
instance = new Inverter();
}
return instance;
}
@Override
public BooleanFormula visit(Not node) {
return node.getX();
}
@Override
public BooleanFormula visit(And node) {
return new Not(node);
}
@Override
public BooleanFormula visit(Iff node) {
return new Not(node);
}
@Override
public BooleanFormula visit(Xor node) {
return new Not(node);
}
@Override
public BooleanFormula visit(Zero node) {
return One.getInstance();
}
@Override
public BooleanFormula visit(One node) {
return Zero.getInstance();
}
@Override
public BooleanFormula visit(Imply node) {
return new Not(node);
}
@Override
public BooleanFormula visit(BooleanVariable node) {
return new Not(node);
}
@Override
public BooleanFormula visit(Or node) {
return new Not(node);
}
}
| true
|
967b75660609ff4768166c51f50f2f93211dd78c
|
Java
|
PeaceNChicken/eduManger
|
/eduManger/src/main/java/com/cafe24/eduManger/ContractVo/ContractPrice.java
|
UTF-8
| 1,513
| 2.25
| 2
|
[] |
no_license
|
package com.cafe24.eduManger.ContractVo;
public class ContractPrice {
private String contract_price_code;
private String member_id;
private String contract_price_money;
private String contract_price_etc;
private String contract_price_date;
public String getContract_price_code() {
return contract_price_code;
}
public void setContract_price_code(String contract_price_code) {
this.contract_price_code = contract_price_code;
}
public String getMember_id() {
return member_id;
}
public void setMember_id(String member_id) {
this.member_id = member_id;
}
public String getContract_price_money() {
return contract_price_money;
}
public void setContract_price_money(String contract_price_money) {
this.contract_price_money = contract_price_money;
}
public String getContract_price_etc() {
return contract_price_etc;
}
public void setContract_price_etc(String contract_price_etc) {
this.contract_price_etc = contract_price_etc;
}
public String getContract_price_date() {
return contract_price_date;
}
public void setContract_price_date(String contract_price_date) {
this.contract_price_date = contract_price_date;
}
@Override
public String toString() {
return "ContractPrice [contract_price_code=" + contract_price_code + ", member_id=" + member_id
+ ", contract_price_money=" + contract_price_money + ", contract_price_etc=" + contract_price_etc
+ ", contract_price_date=" + contract_price_date + "]";
}
}
| true
|
dae6759a2c07ed51c291e5e46932b9a3bde43168
|
Java
|
ctamang/java8
|
/src/interviewQuestions/Overriding1.java
|
UTF-8
| 9,905
| 4.09375
| 4
|
[] |
no_license
|
package interviewQuestions;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.SQLException;
/*
1... We can not reduce the visibility or scope of the inherited method from parent class.
2... Shape s = null;
s.draw();
public static void draw(){}
above code will not give us any error, because compiler will replace the s with the class name because the method is static.
3... we can not override static method although we can have the same method name as the parent in the child class with static
keyword only then compile will allow ii.
In this case no method overriding will happen because both methods are class level methods.
4... We can not use static keyword with the child class method if the parent class does not have it. If we use it then compiler will
give us an error.
Same goes for vice-versa. if parent class has static keyword then we can not override it. but we can have the same name method
with the static keyword.
5... Can overridden exception throw different checked exception then the one from the parent class?..
In case of checked exceptions the scope and visibility concept is reverted means --
while overriding a method with exception we can compress the scope of the exception but we cannot widen it.
for e.g.
class Shape{
void draw() throws IOException
{
System.out.println("Shape");
}
}
class Circle extends Shape{
public void draw() throws FileNotFoundException
{
System.out.println("Circle");
}
}
in above example IOException is compressed to FileNotFoundException hence the program compiles fine. although the reverse of
this will throw a compile time error.
Important ::: We can change an exception from checked to unchecked but reverse is not possible
6... Can a return type be different in overridden method.
By using covariant return type we can achieve this. best example is wrapper classes. the restriction is only that the subclass
must have the subtype of the return type that is used in the superclass.
Following are the examples of the correct implementation of this :
Parent class - Number
Child class - Integer, Byte , Short ,Long etc
Parent class - Object
Child class - Number, Integer, Byte , Short ,Long etc
Following are some not correct implementation :
Parent class - Integer
Child class - Number, Long
Parent class - String
Child class - Number, Long
7. What are the rules to be followed while overriding a method?
There are 5 main rules you should kept in mind while overriding a method. They are,
a) Name of the method must be same as that of super class method.
b) Return type of overridden method must be compatible with the method being overridden. i.e if
a method has primitive type as it’s return type then it must be overridden with primitive type only and if a method has
derived type as it’s return type then it must be overridden with same type or it’s sub class types.
c) You must not reduce the visibility of a method while overriding.
d) You must not change parameter list of a method while overriding.
e) You can not increase the scope of exceptions while overriding a method with throws clause.
*********************
SOME MORE QUESTIONS
*********************
1) What is method overriding?
Modifying a super class method in the sub class is called method overriding. Using method overriding, we can change super class
method according to the requirements of sub class.
2) What are the rules to be followed while overriding a method?
There are 5 main rules you should keep in mind while overriding a method. They are,
a) Name of the method must be same as that of super class method.
b) Return type of overridden method must be compatible with the method being overridden. i.e if a method has primitive type as
it’s return type then it must be overridden with primitive type only and if a method has derived type as it’s return type
then it must be overridden with same type or it’s sub class types.
c) You must not reduce the visibility of a method while overriding.
d) You must not change parameter list of a method while overriding.
e) You can not increase the scope of exceptions while overriding a method with throws clause.
3) Can we override static methods?
No, you cannot override static method in Java because method overriding is based upon dynamic binding at runtime and static
methods are bonded using static binding at compile time. Though you can declare a method with same name and method signature
in sub class which does look like you can override static method in Java but in reality that is method hiding. Java won't resolve
method call at runtime and depending upon type of Object which is used to call static method, corresponding method will be called.
It means if you use Parent class's type to call static method, original static will be called from patent class, on the other
hand if you use Child class's type to call static method, method from child class will be called. In short you can not override
static method in Java. If you use Java IDE like Eclipse or Netbeans, they will show warning that static method should be called
using class name and not by using object becaues static method can not be overridden in Java.
4) What happens if we change the arguments of overriding method?
If we change the arguments of overriding method, then that method will be treated as overloaded not overridden.
5) Can we override protected method of super class as public method in the sub class?
Yes. You can increase the visibility of overriding methods but can’t reduce it.
6) Can we change the return type of overriding method from Number type to Integer type?
Yes. You can change as Integer is a sub class of Number type.
7) Can we override a super class method without throws clause as a method with throws clause in the sub class?
Yes, but only with unchecked type of exceptions.
8) Can we change an exception of a method with throws clause from SQLException to NumberFormatException while overriding it?
Yes. Overridden method may throw SQLException or it’s sub class exception or any unchecked type of exceptions.
9) Can we change an exception of a method with throws clause from unchecked to checked while overriding it?
No. We can’t change an exception of a method with throws clause from unchecked to checked.
10) How do you refer super class version of overridden method in the sub class?
Using super keyword, we can refer super class version of overridden method in the sub class.
11) Can we override private methods?
No question of overriding private methods. They are not at all inherited to sub class.
12) Can we remove throws clause of a method while overriding it?
Yes. You can remove throws clause of a method while overriding it.
13) Is it possible to override non-static methods as static?
No. You can’t override non-static methods as static.
14) Can we change an exception of a method with throws clause from checked to unchecked while overriding it?
Yes. We can change an exception from checked to unchecked but reverse is not possible.
15) Can we change the number of exceptions thrown by a method with throws clause while overriding it?
Yes, we can change. But, exceptions must be compatible with throws clause in the super class method.
*******************************************************************************
*******************************************************************************
1) Can you prevent overriding a method without using final modifier?
Yes, there are some funky ways to prevent method overriding in Java. Though final modifier is only for that purpose you can
use private keyword to prevent method overriding. How? If you remember correctly, in order to override a method, the class must
be extensible. If you make the constructor of parent class private then its not possible to extend that class because its
constructor will not be accessible in sub class, which is automatically invoked by sub class constructor, hence its not possible
to override any method from that class. This technique is used in Singleton design pattern, where constructor is purposefully
made private and a static getInstance() method is provided to access singleton instance. See here to learn more techniques to
prevent method overriding in Java.
2) What is co-variant method overriding?
One of the rule of method overriding is that return type of overriding method must be same as overridden method but this
restriction is relaxed little bit from Java 1.5 and now overridden method can return sub class of return type of original method.
This relaxation is known as co-variant method overriding and it allows you to remove casting at client end. One of the best
example of this comes when you override clone() method. Original Object.clone() method returns Object which needs to cast, but
with co-variant method overriding you can directly return relevant type e.g. Date class returns object of java.util.Date instead
of java.lang.Object
3) Can we change argument list of overridden method?
No, you cannot change the argument list of overridden method in Java. An overriding method must have same signature as original
method. Only return type can be changed that to only to sub type of return type of original method.
*/
public class Overriding1 {
public static void main(String [] args) throws IOException {
}
}
class Parent{
private String testMethod() throws IOException
{
System.out.println("Parent");
return "";
}
}
class Child extends Parent{
private String testMethod() throws IOException
{
System.out.println("Parent");
return "";
}
}
| true
|
ec48d76682c3eab26cac67df22d30329357f1ea5
|
Java
|
frsknalexis/crm-java
|
/crm_backend/src/main/java/com/dev/crm/core/facade/CargoFacade.java
|
UTF-8
| 216
| 1.804688
| 2
|
[
"Apache-2.0"
] |
permissive
|
package com.dev.crm.core.facade;
import java.util.List;
import com.dev.crm.core.dto.CargoDTO;
public interface CargoFacade {
List<CargoDTO> findAll();
List<CargoDTO> findByDescripcionCargo(String termino);
}
| true
|
649b8d4b645794a29a22131095845e8d7d198428
|
Java
|
fit2cloud-backup/execute-script-plugin
|
/src/test/java/BasicTest.java
|
UTF-8
| 700
| 1.828125
| 2
|
[] |
no_license
|
/**
* Created by zhangbohan on 15/10/23.
*/
import com.fit2cloud.sdk.Fit2CloudClient;
import com.google.gson.Gson;
import junit.framework.TestCase;
import org.junit.Test;
/**
* Created by zhangbohan on 15/10/23.
*/
public class BasicTest extends TestCase {
private String f2cApiKey;
private String f2cApiSecret;
private String f2cRestApiEndpoint;
private Gson gson;
@Override
protected void setUp() throws Exception {
super.setUp();
f2cApiKey = "";
f2cApiSecret = "";
f2cRestApiEndpoint = "https://console.fit2cloud.com:8443/rest/";
gson = new Gson();
}
//@Test
public void testEvent() throws Exception {
}
}
| true
|
5f159469cbbe36edc2d2a201313f1118903f469d
|
Java
|
bademux/murmur3_128md
|
/src/main/java/com/github/bademux/murmurmd/Murmur3_128MessageDigest.java
|
UTF-8
| 5,762
| 2.828125
| 3
|
[] |
no_license
|
package com.github.bademux.murmurmd;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.security.MessageDigestSpi;
/**
* GWT implementation of Murmur 3 128bit little endian.
*/
public final class Murmur3_128MessageDigest extends MessageDigestSpi {
public static final String NAME = "Murmur3_128";
public static final String DESCRIPTION = "GWT implementation of Murmur 3 128bit little endian";
public static final double VERSION = 0.1;
private final static long C1 = 0x87c37b91114253d5L;
private final static long C2 = 0x4cf5ad432745937fL;
private final static int DIGEST_LENGTH = (Long.SIZE * 2) / Byte.SIZE;
private final ByteBuffer tmpBuffer = ByteBuffer.allocate(DIGEST_LENGTH)
.order(ByteOrder.LITTLE_ENDIAN);
private long length = 0L;
private int seed = 0; // unused
private long h1;
private long h2;
public Murmur3_128MessageDigest(int seed) {
this();
this.seed = seed;
}
public Murmur3_128MessageDigest() {
engineReset();
}
@Override
protected byte[] engineDigest() {
// if tmpBuffer isn't empty
if (tmpBuffer.position() != 0) {
length += tmpBuffer.position();
tmpBuffer.flip();
processRemainingInput(tmpBuffer);
}
h1 ^= length;
h2 ^= length;
h1 += h2;
h2 += h1;
h1 = fmix(h1);
h2 = fmix(h2);
h1 += h2;
h2 += h1;
byte[] hash = ByteBuffer.allocate(DIGEST_LENGTH)
.order(ByteOrder.LITTLE_ENDIAN).putLong(h1).putLong(h2).array();
engineReset();
return hash;
}
@Override
protected int engineGetDigestLength() {
return DIGEST_LENGTH;
}
@Override
protected void engineReset() {
tmpBuffer.clear();
length = 0L;
h1 = seed;
h2 = seed;
}
@Override
protected void engineUpdate(byte input) {
engineUpdate(new byte[] { input }, 0, 1);
}
@Override
protected void engineUpdate(byte[] input, int offset, int len) {
engineUpdate(ByteBuffer.wrap(input, offset, len));
}
@Override
protected void engineUpdate(ByteBuffer aInput) {
ByteBuffer input = aInput.asReadOnlyBuffer().order(
ByteOrder.LITTLE_ENDIAN);
int numOfChunks = (tmpBuffer.position() + input.remaining())
/ DIGEST_LENGTH;
// combine tmpBuff and input buff
if (numOfChunks > 0) {
processBuffer(processFullChunks(input, numOfChunks));
}
// if sum tmpBuffer + inputBuff isn't match
// save unused bytes to buffer
if (input.remaining() > 0) {
tmpBuffer.put(input);
}
}
/**
* Prepare unused bytes in input buffer do be saved for further processing
* with tmpBuff
*
* @param input
* @param numOfChunks
* - number of full chunks
* @return buffer with full chunks
*/
private ByteBuffer processFullChunks(final ByteBuffer input, int numOfChunks) {
int fullChunkLength = numOfChunks * DIGEST_LENGTH;
// if tmpBuffer is empty
if (tmpBuffer.position() == 0) {
// if tmpBuffer is empty and inputBuff matched
if ((input.limit() % DIGEST_LENGTH) == 0) {
return input;
}
// make length fits to mixBody()
ByteBuffer buff = input.asReadOnlyBuffer().order(
ByteOrder.LITTLE_ENDIAN);
buff.limit(fullChunkLength);
// get unmatched "tail"
input.position(fullChunkLength);
return buff;
}
if ((tmpBuffer.position() + input.remaining()) == DIGEST_LENGTH) {
// if fits to tmp butter
tmpBuffer.put(input);
tmpBuffer.clear();
return tmpBuffer.asReadOnlyBuffer().order(ByteOrder.LITTLE_ENDIAN);
}
// leave unused bytes for further tmpBuffer operation
ByteBuffer buff = ByteBuffer.allocate(fullChunkLength).order(
ByteOrder.LITTLE_ENDIAN);
// respect input buff limit
int oldLimit = input.limit();
input.limit(fullChunkLength - tmpBuffer.position());
// put bytes from tmp buff first
if (tmpBuffer.position() > 0) {
tmpBuffer.flip();
buff.put(tmpBuffer);
tmpBuffer.clear();
}
buff.put(input);
input.limit(oldLimit);
return buff;
}
private void processBuffer(ByteBuffer byteBuff) {
length += byteBuff.remaining();
while (byteBuff.hasRemaining()) {
mixBody(byteBuff.getLong(), byteBuff.getLong());
}
}
protected void processRemainingInput(ByteBuffer bb) {
long k1 = 0;
long k2 = 0;
switch (bb.remaining()) {
case 15:
k2 ^= (bb.get(14) & 0xFFL) << 48; // fall through
case 14:
k2 ^= (bb.get(13) & 0xFFL) << 40; // fall through
case 13:
k2 ^= (bb.get(12) & 0xFFL) << 32; // fall through
case 12:
k2 ^= (bb.get(11) & 0xFFL) << 24; // fall through
case 11:
k2 ^= (bb.get(10) & 0xFFL) << 16; // fall through
case 10:
k2 ^= (bb.get(9) & 0xFFL) << 8; // fall through
case 9:
k2 ^= (bb.get(8)); // fall through
case 8:
k1 ^= bb.getLong();
break;
case 7:
k1 ^= (bb.get(6) & 0xFFL) << 48; // fall through
case 6:
k1 ^= (bb.get(5) & 0xFFL) << 40; // fall through
case 5:
k1 ^= (bb.get(4) & 0xFFL) << 32; // fall through
case 4:
k1 ^= (bb.get(3) & 0xFFL) << 24; // fall through
case 3:
k1 ^= (bb.get(2) & 0xFFL) << 16; // fall through
case 2:
k1 ^= (bb.get(1) & 0xFFL) << 8; // fall through
case 1:
k1 ^= (bb.get(0));
break;
default:
throw new AssertionError("Should never get here.");
}
h1 ^= mixK1(k1);
h2 ^= mixK2(k2);
}
private void mixBody(long k1, long k2) {
h1 ^= mixK1(k1);
h1 = Long.rotateLeft(h1, 27);
h1 += h2;
h1 = h1 * 5 + 0x52dce729;
h2 ^= mixK2(k2);
h2 = Long.rotateLeft(h2, 31);
h2 += h1;
h2 = h2 * 5 + 0x38495ab5;
}
private long mixK1(long k1) {
k1 *= C1;
k1 = Long.rotateLeft(k1, 31);
k1 *= C2;
return k1;
}
private long mixK2(long k2) {
k2 *= C2;
k2 = Long.rotateLeft(k2, 33);
k2 *= C1;
return k2;
}
private long fmix(long k) {
// avalanche bits
k ^= k >>> 33;
k *= 0xff51afd7ed558ccdL;
k ^= k >>> 33;
k *= 0xc4ceb9fe1a85ec53L;
k ^= k >>> 33;
return k;
}
}
| true
|
967047f668487f1c254b5c5fa494c82abb605f3b
|
Java
|
defrian8/EventOrganizer
|
/app/src/main/java/id/pens/eventorganizer/services/EventListAPI.java
|
UTF-8
| 288
| 1.882813
| 2
|
[] |
no_license
|
package id.pens.eventorganizer.services;
import id.pens.eventorganizer.model.EventResponse;
import retrofit2.Call;
import retrofit2.http.GET;
/**
* Created by MONKEY on 04/01/2018.
*/
public interface EventListAPI {
@GET("event/getevent")
Call<EventResponse> getEvents();
}
| true
|
2e12994132a226cbc75219a5ff138f29fbb86e09
|
Java
|
kbrnr/bit70
|
/Project01/src/main/java/org/nojo/mapper/MembershipMapper.java
|
UTF-8
| 1,004
| 2.140625
| 2
|
[] |
no_license
|
package org.nojo.mapper;
import java.util.List;
import org.apache.ibatis.annotations.Select;
import org.nojo.domain.MemberVO;
import org.nojo.util.SearchCriteria;
public interface MembershipMapper {
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//선생님관련
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//*선생님전체리스트
public List<MemberVO> selcetTeacher(SearchCriteria cri);
//*선생님 토탈수
public int selectTeacherTotalCnt(SearchCriteria cri) throws Exception;
//수업별(도메인별) 선생님 리스트
@Select("select tbl_member.mem_id, tbl_member.mem_name from tbl_course join tbl_member on tbl_course.mem_id = tbl_member.mem_id where tbl_course.clz_domain=#{domain} and tbl_member.mem_gb='member_teacher'")
public List<MemberVO> selectTeacherByDomain(String domain);
}
| true
|
026ffd173f58f5503b0f94230aad9c973f5382bb
|
Java
|
luoxue1107/java
|
/JavaSE/Cot/src/main/java/cn/kgc/tangcco/test/类与对象/abstract.java/TestAbtract.java
|
UTF-8
| 542
| 3.40625
| 3
|
[] |
no_license
|
public class TestAbstract {
//抽象
public static void main(String[] args){
//抽象父类是无法直接new对象的需要new父类类型 子类对象来实现
av a=new bv();
System.out.println(a.A);
System.out.println(a.B);
a.a();
}
}
//抽象父类
abstract class av{
int A=20;
int B=30;
//抽象方法 如果父类是抽象方法 子类必须覆盖此方法
public abstract void a();
}
//子类
class bv extends av{
public void a(){
System.out.println("子类方法a");
}
}
| true
|
e294071c9fd677f06d8a66b03a0a5562109183f8
|
Java
|
svata-novak/jboss-book
|
/jboss-book-web/src/main/java/cz/muni/fi/jboss/book/web/controller/IdentityBean.java
|
UTF-8
| 1,852
| 2.296875
| 2
|
[] |
no_license
|
package cz.muni.fi.jboss.book.web.controller;
import java.io.Serializable;
import javax.ejb.EJB;
import javax.enterprise.inject.Alternative;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import cz.muni.fi.jboss.book.ejb.security.AccountManager;
import cz.muni.fi.jboss.book.persistence.UserRole;
import cz.muni.fi.jboss.book.persistence.entity.User;
import cz.muni.fi.jboss.book.web.core.WebApplication;
import org.jboss.seam.security.IdentityImpl;
/**
* @author matejkobza
*/
@ManagedBean
@SessionScoped
@Alternative
public class IdentityBean extends IdentityImpl {
@EJB(name = "AccountManager")
private AccountManager accountManager;
private User user;
public User getUser() {
if(this.user == null) {
this.user = (User)super.getUser();
}
return this.user;
}
public void setUser(User user) {
this.user = user;
}
public boolean isManager() {
if (this.user != null) {
return this.user.isManager();
}
return false;
}
public boolean isLibrarian() {
if (this.user != null) {
return this.user.isLibrarian();
}
return false;
}
public boolean isReader() {
if (this.user != null) {
return this.user.isReader();
}
return false;
}
public void addLibrarian(User user) {
user.setUserRole(UserRole.LIBRARIAN);
accountManager.update(user);
WebApplication.getReference().addInfoMessage("Account settings", "librarian added successfully.");
}
public void removeLibrarian(User user) {
user.setUserRole(UserRole.READER);
accountManager.update(user);
WebApplication.getReference().addInfoMessage("Account settings", "librarian removed successfully.");
}
}
| true
|
48cccbe22d45e2805f64bd1a05784489afcbc93f
|
Java
|
Nurseli12/BasicGameSale
|
/SimpleGamesSales2/src/GamesSalesDemo/Main.java
|
ISO-8859-9
| 2,132
| 2.75
| 3
|
[] |
no_license
|
package GamesSalesDemo;
import java.time.LocalDate;
import GamesSalesDemo.Adapters.MernisServiceAdapter;
import GamesSalesDemo.Concrete.CampaignManager;
import GamesSalesDemo.Concrete.FinansManager;
import GamesSalesDemo.Concrete.GamerManager;
import GamesSalesDemo.Concrete.NewGamer;
import GamesSalesDemo.Concrete.ProductManager;
import GamesSalesDemo.Concrete.SaleManager;
import GamesSalesDemo.Entities.Campaign;
import GamesSalesDemo.Entities.Finans;
import GamesSalesDemo.Entities.Gamer;
import GamesSalesDemo.Entities.Product;
import GamesSalesDemo.Entities.Sale;
public class Main {
public static void main(String[] args) {
System.out.println("NEW USER INFORMATON");
GamerManager gamerManager = new NewGamer(new MernisServiceAdapter());
gamerManager.added(new Gamer(1,"Nurseli","Kaya",LocalDate.of(1997, 02, 12),"21734451760"));
System.out.println("PRODUCTS INFORMATION");
ProductManager productManager = new ProductManager();
productManager.added(new Product(1 ,"SNAKE GAMES"));
productManager.added(new Product(2 ,"MARO"));
System.out.println("PRODUCTS INFORMATION ABOUT PRICE");
FinansManager snakeGame = new FinansManager();
snakeGame.added(new Finans(1, 70, 20));
FinansManager mario = new FinansManager();
mario.added(new Finans(2, 80, 15));
System.out.println("CAMPAIGN INFORMATION");
CampaignManager snakeGameCampaign = new CampaignManager();
snakeGameCampaign.added(new Campaign(1,"Summer promotions"));
CampaignManager marioGameCampaign = new CampaignManager();
marioGameCampaign.added(new Campaign(2,"Bestselling"));
System.out.println("PRODUCTS ON SALE");
SaleManager snakeGameSale = new SaleManager();
snakeGameSale.productOnSale(new Product(1 ,"SNAKE GAMES"), new Finans(1, 70, 20),
new Sale(1,"Just Credit Card", LocalDate.now()), new Campaign(1,"Summer promotions"));
SaleManager marioGameSale = new SaleManager();
marioGameSale.productOnSale(new Product(2 ,"MARO"), new Finans(2, 80, 15),
new Sale(2,"Just Credit Card", LocalDate.now()), new Campaign(2,"Bestselling"));
}
}
| true
|
91580908db40454a2c914f8a1b7d75927c856522
|
Java
|
green-fox-academy/Tirikk-p2p
|
/src/main/java/com/greenfox/chat/model/Client.java
|
UTF-8
| 249
| 2.109375
| 2
|
[] |
no_license
|
package com.greenfox.chat.model;
import javax.validation.constraints.NotNull;
public class Client {
@NotNull
String id;
public String getId() {
return id;
}
public Client setId(String id) {
this.id = id;
return this;
}
}
| true
|
837c5690928d82356135da40a8a607d6e03fe2fe
|
Java
|
tedwon/JGroups
|
/tests/junit-functional/org/jgroups/tests/ExponentialIntervalTest.java
|
UTF-8
| 1,860
| 2.640625
| 3
|
[
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
] |
permissive
|
package org.jgroups.tests;
import org.jgroups.stack.ExponentialInterval;
import org.jgroups.Global;
import org.testng.Assert;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
/**
* @author Bela Ban
*/
public class ExponentialIntervalTest {
@Test(groups=Global.FUNCTIONAL)
public static void testInitialization() {
ExponentialInterval interval=new ExponentialInterval(10);
System.out.println("interval=" + interval);
long value=interval.next();
System.out.println("interval=" + interval);
Assert.assertEquals(10, value);
value=interval.next();
System.out.println("interval=" + interval);
Assert.assertEquals(20, value);
}
@Test(groups=Global.FUNCTIONAL)
public static void testNoargConstructor() {
ExponentialInterval interval=new ExponentialInterval();
Assert.assertEquals(30, interval.next());
Assert.assertEquals(60, interval.next());
}
@Test(groups=Global.FUNCTIONAL)
public static void testMax() {
ExponentialInterval interval=new ExponentialInterval(1000);
System.out.println("interval=" + interval);
Assert.assertEquals(1000, interval.next());
System.out.println("interval=" + interval);
Assert.assertEquals(2000, interval.next());
System.out.println("interval=" + interval);
Assert.assertEquals(4000, interval.next());
System.out.println("interval=" + interval);
Assert.assertEquals(8000, interval.next());
System.out.println("interval=" + interval);
Assert.assertEquals(15000, interval.next());
System.out.println("interval=" + interval);
Assert.assertEquals(15000, interval.next());
System.out.println("interval=" + interval);
}
}
| true
|
bb037a4ca695cfca46a3067e76ae6983cd054881
|
Java
|
topsycreed/Selenium-Java
|
/addressbook-selenium-test/src/com/example/tests/TestBase.java
|
UTF-8
| 2,261
| 2.5
| 2
|
[
"MIT"
] |
permissive
|
package com.example.tests;
import java.io.File;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Properties;
import java.util.Random;
import org.testng.annotations.AfterClass;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.DataProvider;
import com.example.fw.ApplicationManager;
import static com.example.tests.GroupDataGenerator.generateRandomGroups;
public class TestBase {
protected ApplicationManager app;
@BeforeClass
public void setUp() throws Exception {
Properties properties = new Properties();
properties.load(new FileReader (new File( "application.properties")) );
app=new ApplicationManager(properties);
}
@AfterClass
public void tearDown() throws Exception {
app.stop();
}
@DataProvider
public Iterator<Object[]> randomValidGroupGenerator(){
return wrapGroupsForDataProvider(generateRandomGroups(5)).iterator();
}
public static List<Object[]> wrapGroupsForDataProvider(List<GroupData> groups) {
List<Object[]>list= new ArrayList<Object[]>();
for(GroupData group: groups){
list.add(new Object[]{group});
}
return list;
}
public static List<Object[]> wrapContactsForDataProvider(List<ContactData> contacts) {
List<Object[]>list= new ArrayList<Object[]>();
for(ContactData contact: contacts){
list.add(new Object[]{contact});
}
return list;
}
public String generateRandomDay(){
Random rnd =new Random();
if(rnd.nextInt(3)==0){
return"-";
}
else return "1"+ rnd.nextInt(3);
}
public String generateRandomMonths(){
Random rnd =new Random();
String months[] = { "January", "February", "June", "July",
"December"};
int mon=rnd.nextInt(months.length);
return months[mon];
}
public String generateRandomYear(){
Random rnd =new Random();
return "198"+ rnd.nextInt(3);
}
public static String generateRandomString(){
Random rnd =new Random();
if(rnd.nextInt(3)==0){
return"";
}
else return "test"+ rnd.nextInt();
}
}
| true
|
82b5c3f0818f3eea3ad89d9825a73b9ab6a25443
|
Java
|
codingsf/appx_mainline
|
/src/test/java/T2.java
|
UTF-8
| 4,263
| 2.421875
| 2
|
[] |
no_license
|
import org.apache.http.HttpHost;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.protocol.HttpContext;
import org.apache.http.ssl.SSLContexts;
import org.jsoup.Jsoup;
import org.junit.Test;
import javax.net.ssl.SSLContext;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;
public class T2 {
public void ttt(){
}
@Test
public void t3()throws Exception{
String str = Jsoup.connect("https://twitter.com")
.proxy("news.appx.top",8118)
.get().html();
System.out.println(str);
}
@Test
public void t2(){
try {
String url="http://www.baidu.com/";
Map<String, String> headers = new HashMap<String, String>();
headers.put("Accept", "text/html, */*; q=0.01");
headers.put("Accept-Encoding", "gzip, deflate, sdch");
headers.put("Accept-Language", "zh-CN,zh;q=0.8");
headers.put("Referer", url);
headers.put("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.11; rv:46.0) Gecko/20100101 Firefox/46.0");
} catch (Exception e) {
e.printStackTrace();
}
}
@Test
public void t1()throws Exception{
Registry<ConnectionSocketFactory> reg = RegistryBuilder.<ConnectionSocketFactory>create()
.register("http", PlainConnectionSocketFactory.INSTANCE)
.register("https", new MyConnectionSocketFactory(SSLContexts.createDefault()))
.build();
PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(reg);
CloseableHttpClient httpclient = HttpClients.custom()
.setConnectionManager(cm)
.build();
try {
InetSocketAddress socksaddr = new InetSocketAddress("127.0.0.1", 1080);
HttpClientContext context = HttpClientContext.create();
context.setAttribute("socks.address", socksaddr);
HttpHost target = new HttpHost("twitter.com", 443,"https");
HttpGet request = new HttpGet("/");
System.out.println("Executing request " + request + " to " + target + " via SOCKS proxy " + socksaddr);
CloseableHttpResponse response = httpclient.execute(target, request, context);
try {
System.out.println("----------------------------------------");
System.out.println(response.getStatusLine());
BufferedReader in = new BufferedReader(new InputStreamReader(
response.getEntity().getContent()));
String result = "";
String line;
while ((line = in.readLine()) != null) {
result += line;
}
System.out.println(result);
}catch (Exception ex){
}
finally {
response.close();
}
} finally {
httpclient.close();
}
}
static class MyConnectionSocketFactory extends SSLConnectionSocketFactory {
public MyConnectionSocketFactory(final SSLContext sslContext) {
super(sslContext);
}
@Override
public Socket createSocket(final HttpContext context) throws IOException {
InetSocketAddress socksaddr = (InetSocketAddress) context.getAttribute("socks.address");
Proxy proxy = new Proxy(Proxy.Type.SOCKS, socksaddr);
return new Socket(proxy);
}
}
}
| true
|
fa04039730e0e1b3f405fbc8619ec159e4a61a10
|
Java
|
pietergmail/school
|
/2ejaar(2019-2020)/2e semester/OOO/examenoef/labo 4.1/src/domain/Subject.java
|
UTF-8
| 199
| 2.3125
| 2
|
[] |
no_license
|
package domain;
public interface Subject {
public void registerObserver(Events e, Observer o);
public void removeObserver(Events e, Observer o);
public void notifyObservers(Events e);
}
| true
|
31cb15eacffc42d61be190d6a540de9264f4c897
|
Java
|
online-code-bite-md-tanvir-mahtab/CREATE_READ_UPDATE_DELETE
|
/app/src/main/java/com/tanvircodder/crud/database/ListProvider.java
|
UTF-8
| 6,233
| 2.46875
| 2
|
[] |
no_license
|
package com.tanvircodder.crud.database;
import android.content.ContentProvider;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
public class ListProvider extends ContentProvider {
// now I need to create the code for the single anddouble...///\
private static final int CRUD = 100;
private static final int CRUD_WITH_ID = 101;
// now I am going to store the mathod to the UriMatcher variable..//
private static final UriMatcher sUriMatcher = buildUriMatcher();
// now i will crete the mathod that will create the urimatcher..//
public static UriMatcher buildUriMatcher(){
UriMatcher matcher = new UriMatcher(UriMatcher.NO_MATCH);
matcher.addURI(CURDContract.AUTHORITY, CURDContract.PATH,CRUD);
matcher.addURI(CURDContract.AUTHORITY,CURDContract.PATH + "/#",CRUD_WITH_ID);
return matcher;
}
// initializing the dbHelper class..//
private ListDbHelper mDbHelper;
@Override
public boolean onCreate() {
mDbHelper = new ListDbHelper(getContext());
return true;
}
@Nullable
@Override
public Cursor query(@NonNull Uri uri, @Nullable String[] projection, @Nullable String selection, @Nullable String[] selectionArgs, @Nullable String sortOrder) {
final SQLiteDatabase database = mDbHelper.getReadableDatabase();
Cursor cursor;
int match = sUriMatcher.match(uri);
switch(match){
case CRUD:
cursor = database.query(CURDContract.ListEntry.TABLE_NAME,
projection,
selection,
selectionArgs,
null,
null,
sortOrder);
break;
case CRUD_WITH_ID:
String id = uri.getLastPathSegment();
selection = CURDContract.ListEntry._ID + "=?";
selectionArgs = new String[]{String.valueOf(id)};
cursor = database.query(CURDContract.ListEntry.TABLE_NAME,
projection,
selection,
selectionArgs,
null,
null,
sortOrder);
break;
default:
throw new SQLException("faild to load data");
}
cursor.setNotificationUri(getContext().getContentResolver(),uri);
return cursor;
}
@Nullable
@Override
public String getType(@NonNull Uri uri) {
return null;
}
@Nullable
@Override
public Uri insert(@NonNull Uri uri, @Nullable ContentValues values) {
/*fir i will take the access of the data base to write it */
final SQLiteDatabase database = mDbHelper.getWritableDatabase();
// now to track of which table we inserted we are going to declare the long variable..//
int match = sUriMatcher.match(uri);
Uri newUri;
switch (match) {
case CRUD:
long id = database.insert(CURDContract.ListEntry.TABLE_NAME, null, values);
if (id > 0) {
newUri = ContentUris.withAppendedId(CURDContract.ListEntry.CONTENT_URI, id);
} else {
throw new android.database.SQLException("Faild to insert rows");
}
break;
default:
throw new UnsupportedOperationException("Unknown uri :" + uri);
}
getContext().getContentResolver().notifyChange(uri,null);
return newUri;
}
@Override
public int delete(@NonNull Uri uri, @Nullable String selection, @Nullable String[] selectionArgs) {
// geting the access from the cursor..//
final SQLiteDatabase database = mDbHelper.getWritableDatabase();
int match = sUriMatcher.match(uri);
int rowsDeleted;
switch (match){
case CRUD:
rowsDeleted = database.delete(CURDContract.ListEntry.TABLE_NAME,selection,selectionArgs);
break;
case CRUD_WITH_ID:
String id = uri.getPathSegments().get(1);
selection =CURDContract.ListEntry._ID +"=?";
selectionArgs = new String[]{String.valueOf(id)};
rowsDeleted = database.delete(CURDContract.ListEntry.TABLE_NAME,
selection,
selectionArgs);
break;
default:
throw new SQLException("Problem deleting the data to the uri :" + uri);
}
if (rowsDeleted !=0){
getContext().getContentResolver().notifyChange(uri,null);
}
return rowsDeleted;
}
@Override
public int update(@NonNull Uri uri, @Nullable ContentValues values, @Nullable String selection, @Nullable String[] selectionArgs) {
final SQLiteDatabase database = mDbHelper.getWritableDatabase();
int rowsUpdated;
int match = sUriMatcher.match(uri);
switch (match){
case CRUD:
rowsUpdated = database.update(CURDContract.ListEntry.TABLE_NAME,values,null,null);
break;
case CRUD_WITH_ID:
String id = uri.getLastPathSegment();
selection = CURDContract.ListEntry._ID + "=?";
selectionArgs = new String[]{String.valueOf(id)};
rowsUpdated = database.update(CURDContract.ListEntry.TABLE_NAME,
values,
selection,
selectionArgs);
break;
default:
throw new SQLException("The update is cann't be performed :" + uri);
}
if (rowsUpdated != 0){
getContext().getContentResolver().notifyChange(uri,null);
}
return rowsUpdated;
}
}
| true
|
7282a47ca30a8245d9d69740b04dad1c77ddd4b7
|
Java
|
wangzhenjjcn/Art1001
|
/aladdin-rest/src/main/java/com/aladdin/utils/DateUtils.java
|
UTF-8
| 327
| 2.421875
| 2
|
[
"Apache-2.0"
] |
permissive
|
package com.aladdin.utils;
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateUtils {
public static final String TYPE1="yyyy-MM-dd HH:mm:ss";
public static String dateToString(Date date){
SimpleDateFormat df = new SimpleDateFormat(TYPE1);
String res = df.format(date);
return res;
}
}
| true
|
a68c8b5567981201f8ed5e974319856897fc8c93
|
Java
|
manelBHM/EPEC_Alt
|
/Neyer/SprintTest1/src/main/java/com/example/demo/person/Person.java
|
UTF-8
| 1,962
| 2.796875
| 3
|
[] |
no_license
|
package com.example.demo.person;
import java.io.Serializable;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.Size;
import org.springframework.format.annotation.DateTimeFormat;
@Entity //il va chercher dans la base de donnée si une tab s'appelle "Person"
public class Person implements Serializable{
@Id
@GeneratedValue
private Long id;
@Column(name="NOM", length=30)
@NotEmpty
@Size(min=3,max=20,message="plus de 3 carateres")
private String nom;
@NotEmpty
@Size(min=3,max=20)
private String prenom;
@DateTimeFormat(pattern="yyyy-MM-dd")
private Date dateNaissance;
private int conteur;
//private byte[] photo;// stocker la photo dans la bese de donnée
private String photo;//stocker nom photo la photo est stocke dans un dossier
public Person() {
super();
// TODO Auto-generated constructor stub
}
public Person(String nom, String prenom, Date dateNaissance, int conteur, String photo) {
super();
this.nom = nom;
this.prenom = prenom;
this.dateNaissance = dateNaissance;
this.conteur = conteur;
this.photo = photo;
}
public String getNom() {
return nom;
}
public void setNom(String nom) {
this.nom = nom;
}
public String getPrenom() {
return prenom;
}
public void setPrenom(String prenom) {
this.prenom = prenom;
}
public Date getDateNaissance() {
return dateNaissance;
}
public void setDateNaissance(Date dateNaissance) {
this.dateNaissance = dateNaissance;
}
public int getConteur() {
return conteur;
}
public void setConteur(int conteur) {
this.conteur = conteur;
}
public String getPhoto() {
return photo;
}
public void setPhoto(String photo) {
this.photo = photo;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
}
| true
|
b4a37d91338b897a850b4ab2ea56e79287a3fbd2
|
Java
|
frankrb27/AESModValTaller
|
/SAPAuthorization/src/main/java/co/edu/javeriana/modval/SAPAutorizacionApplication.java
|
UTF-8
| 333
| 1.554688
| 2
|
[] |
no_license
|
package co.edu.javeriana.modval;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class SAPAutorizacionApplication {
public static void main(String[] args) {
SpringApplication.run(SAPAutorizacionApplication.class, args);
}
}
| true
|
06c1c89e428c4e0381542a137f6386ef555a18df
|
Java
|
DraganVeljovic/PCComponentMarket
|
/src/data/PremiumData.java
|
UTF-8
| 2,386
| 2.3125
| 2
|
[] |
no_license
|
package data;
import java.util.ArrayList;
import java.util.List;
import javax.sql.rowset.CachedRowSet;
import db.Company;
import db.Component;
import db.DBUtil;
public class PremiumData {
private DBUtil db = DBUtil.getInstance();
private List<Company> companies = new ArrayList<>();
//private List<Reservartions>
public PremiumData() {
updateCompanies();
}
public void updateCompanies() {
try {
CachedRowSet dbCompanies = db.executeQuery("SELECT * FROM Users, Company WHERE Id_User=Id_Company");
while(dbCompanies.next()) {
Company company = new Company();
company.setId(dbCompanies.getInt("Id_User"));
company.setUsername(dbCompanies.getString("Username"));
company.setPassword(dbCompanies.getString("Password"));
company.setEmail(dbCompanies.getString("Email"));
company.setPhone(dbCompanies.getString("Phone"));
company.setAddress(dbCompanies.getString("Address"));
company.setCity(dbCompanies.getString("City"));
company.setCountry(dbCompanies.getString("Country"));
company.setCompanyName(dbCompanies.getString("Company_Name"));
company.setCompanyPIB(dbCompanies.getInt("Company_PIB"));
company.setComponentTypes(dbCompanies.getInt("Component_Types"));
company.setComponentTypesPresent(dbCompanies.getInt("Component_Types_Present"));
CachedRowSet dbCompanyComponents =
db.executeQuery("SELECT * FROM Stock AS S, Component AS C "
+ "WHERE S.Id_Component=C.Id_Component AND "
+ "S.Id_Company=" + company.getId());
while(dbCompanyComponents.next()) {
Component component = new Component();
component.setId(dbCompanyComponents.getInt("Id_Component"));
component.setTypeId(dbCompanyComponents.getInt("Id_Type"));
component.setName(dbCompanyComponents.getString("Name"));
component.setDescription(dbCompanyComponents.getString("Description"));
component.setAmount(dbCompanyComponents.getInt("Amount"));
component.setPrice(dbCompanyComponents.getInt("Price"));
company.addComponent(component);
}
companies.add(company);
dbCompanyComponents.close();
}
dbCompanies.close();
} catch(Exception e) {
e.printStackTrace();
}
}
public List<Company> getCompanies() {
return companies;
}
public void setCompanies(List<Company> companies) {
this.companies = companies;
}
}
| true
|
7c59530d220fe9983b335a09e4926b3a9e6be9f7
|
Java
|
KMG0908/Study
|
/알고리즘/src/SWExpert/Solution_D3_9317_석찬이의받아쓰기.java
|
UTF-8
| 811
| 2.96875
| 3
|
[] |
no_license
|
package SWExpert;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Solution_D3_9317_석찬이의받아쓰기 {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int testCase = Integer.parseInt(br.readLine());
StringBuffer sb = new StringBuffer();
for(int t=1; t<=testCase; t++){
int n = Integer.parseInt(br.readLine());
char[] hear = new char[n];
char[] write = new char[n];
hear = br.readLine().toCharArray();
write = br.readLine().toCharArray();
int cnt = 0;
for(int i=0; i<n; i++){
if(hear[i] == write[i]) cnt++;
}
sb.append("#" + t + " " + cnt + "\n");
}
System.out.println(sb.toString());
}
}
| true
|
31c3e9f02c7e7a792180176bdcf580e3a58da934
|
Java
|
TOMProject/project_management
|
/src/main/java/com/shiroSpringboot/mapper/BaseMapper.java
|
UTF-8
| 497
| 1.773438
| 2
|
[] |
no_license
|
package com.shiroSpringboot.mapper;
import java.util.List;
import com.shiroSpringboot.vo.Page;
public interface BaseMapper<T,DIT> {
int deleteByPrimaryKey(Integer id);
int insert(T record);
int insertSelective(T record);
T selectByPrimaryKey(Integer id);
int updateByPrimaryKeySelective(T record);
int updateByPrimaryKey(T record);
List<T> selectListSelective(T recourd);
List<T> selectListSelectivePaging(Page page);
}
| true
|
3c3dbe6a0c21eef0b6d839a18fe9d37429ae3b13
|
Java
|
fastfed4j/fastfed4j
|
/src/main/java/org/fastfed4j/core/json/Jwt.java
|
UTF-8
| 3,332
| 2.25
| 2
|
[
"Apache-2.0"
] |
permissive
|
package org.fastfed4j.core.json;
import org.fastfed4j.core.configuration.FastFedConfiguration;
import org.fastfed4j.core.constants.JsonMember;
import org.fastfed4j.core.exception.ErrorAccumulator;
import org.fastfed4j.core.metadata.Metadata;
import org.fastfed4j.core.metadata.ProviderContactInformation;
import org.fastfed4j.profile.scim.enterprise.ProviderAuthenticationMethods;
import org.fastfed4j.profile.scim.enterprise.RegistrationRequestExtension;
import java.util.Date;
import java.util.Objects;
/**
* Base class for all FastFed messages that are represented as a Jwt.
*/
public abstract class Jwt extends Metadata {
private String issuer;
private String audience;
private Date expiration;
/**
* Constructs an empty instance
*/
public Jwt(FastFedConfiguration configuration) {
super(configuration);
}
/**
* Copy constructor
* @param other object to copy
*/
public Jwt(Jwt other) {
super(other);
this.issuer = other.issuer;
this.audience = other.audience;
this.expiration = other.expiration;
}
public String getIssuer() {
return issuer;
}
public void setIssuer(String issuer) {
this.issuer = issuer;
}
public String getAudience() {
return audience;
}
public void setAudience(String audience) {
this.audience = audience;
}
public Date getExpiration() {
return expiration;
}
public void setExpiration(Date expiration) {
this.expiration = expiration;
}
// TODO
//public static Jwt fromCompactSerialization(String s) {
// return new Jwt();
//
//}
public String toCompactSerialization() {
return ""; //TODO
}
@Override
public JsonObject toJson() {
JsonObject.Builder builder = new JsonObject.Builder();
builder.put(JsonMember.JWT_ISSUER, issuer);
builder.put(JsonMember.JWT_AUDIENCE, audience);
builder.put(JsonMember.JWT_EXPIRATION, expiration);
return builder.build();
}
@Override
public void hydrateFromJson(JsonObject json) {
if (json == null) return;
super.hydrateFromJson(json);
this.setIssuer(json.getString(JsonMember.JWT_ISSUER));
this.setAudience(json.getString(JsonMember.JWT_AUDIENCE));
this.setExpiration(json.getDate(JsonMember.JWT_EXPIRATION));
}
@Override
public void validate(ErrorAccumulator errorAccumulator) {
validateRequiredString(errorAccumulator, JsonMember.JWT_ISSUER, issuer);
validateRequiredString(errorAccumulator, JsonMember.JWT_AUDIENCE, audience);
validateRequiredDate(errorAccumulator, JsonMember.JWT_EXPIRATION, expiration);
//TODO - add full Jwt validation
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
if (!super.equals(o)) return false;
Jwt jwt = (Jwt) o;
return Objects.equals(issuer, jwt.issuer) &&
Objects.equals(audience, jwt.audience) &&
Objects.equals(expiration, jwt.expiration);
}
@Override
public int hashCode() {
return Objects.hash(super.hashCode(), issuer, audience, expiration);
}
}
| true
|
172e3ed3b420dfd8cf0cd78be903f2fd352c114c
|
Java
|
satuser/java
|
/Simple Java Programs/Task 08_02_2019/VowelsAndConsCount/VowelsAndConsCount.java
|
UTF-8
| 790
| 3.609375
| 4
|
[] |
no_license
|
import java.util.Scanner;
class VowelsAndConsCount{
public static void main(String[] args){
int vowels =0, consonents = 0;
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a String:");
String inputValue = scanner.nextLine();
char[] splitString = inputValue.toCharArray();
for(char singleChar: splitString){
if((singleChar=='a')||(singleChar=='e')||(singleChar=='i')||(singleChar=='o')||(singleChar=='u')||
(singleChar=='A')||(singleChar=='E')||(singleChar=='I')||(singleChar=='O')||(singleChar=='U')){
vowels++;
} else if(((singleChar>='a')&&(singleChar<='z'))||((singleChar>='A')&&(singleChar<='Z'))){
consonents++;
}
}
System.out.println("No of Vowels: "+ vowels+"\n"+"No of Consonants: "+consonents);
}
}
| true
|
ef853638e8e7234adb78aa28961abcbe1c9687fe
|
Java
|
AgedoCollins/ProjetJava
|
/src/be/collins/vues/Liste_Jeux_A_Preter.java
|
WINDOWS-1252
| 3,518
| 2.53125
| 3
|
[] |
no_license
|
package be.collins.vues;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.text.SimpleDateFormat;
import java.util.List;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import be.collins.pojo.Exemplaire;
import be.collins.pojo.Preteur;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JScrollPane;
import javax.swing.ListSelectionModel;
import java.awt.Font;
import javax.swing.border.BevelBorder;
import java.awt.Color;
public class Liste_Jeux_A_Preter extends JFrame {
private JPanel contentPane;
private Preteur currentPreteur;
private JList listJeux;
private JButton btnRetour;
/**
* Create the frame.
*/
public Liste_Jeux_A_Preter(Preteur currentPreteur) {
this.currentPreteur=currentPreteur;
initComponents();
createEvents();
}
private void createEvents() {
// TODO Auto-generated method stub
btnRetour.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
dispose();
Dashboard_Preteur dashboard_Preteur = new Dashboard_Preteur(currentPreteur);
dashboard_Preteur.setVisible(true);
dashboard_Preteur.setResizable(false);
}
});
}
private void initComponents() {
setBackground(Color.WHITE);
setTitle("Projet pr\u00EAt de jeu - Liste jeu louer");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 602, 501);
contentPane = new JPanel();
contentPane.setBackground(Color.WHITE);
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JLabel lblJeuxAPreter = new JLabel("Liste de mes exemplaires de jeux a pr\u00EAter");
lblJeuxAPreter.setFont(new Font("Tahoma", Font.BOLD | Font.ITALIC, 14));
lblJeuxAPreter.setBounds(10, 10, 314, 30);
contentPane.add(lblJeuxAPreter);
Exemplaire e = new Exemplaire();
List<Exemplaire> listExemplaires = e.findAll(currentPreteur);
currentPreteur.setListExamplaire(listExemplaires);
List<Exemplaire> listExemplaire = currentPreteur.getListExemplaire();
Object[] donnees = new Object[listExemplaire.size()];
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd-MM-yy");
for (int i = 0; i < listExemplaire.size(); i++) {
String dispo = " ";
if (listExemplaire.get(i).getJeu().isDispo()) {
dispo = "Disponible";
} else {
dispo = "Indisponible";
}
donnees[i] = "Exemplaire : "+listExemplaire.get(i).getNbrExemplaire() + " - Jeu : " + listExemplaire.get(i).getJeu().getNom()
+ " - Console" + listExemplaire.get(i).getJeu().getConsole().getNom() + " - " + dispo + " - " + "Tarif : "
+ listExemplaire.get(i).getJeu().getTarif() + " - " + "Date tarif : "
+ simpleDateFormat.format(listExemplaire.get(i).getJeu().getDateTarif());
}
btnRetour = new JButton("Retour");
btnRetour.setFont(new Font("Tahoma", Font.BOLD | Font.ITALIC, 12));
btnRetour.setBounds(466, 428, 89, 23);
contentPane.add(btnRetour);
JScrollPane scrollPane = new JScrollPane();
scrollPane.setBounds(10, 46, 564, 350);
contentPane.add(scrollPane);
listJeux = new JList(donnees);
listJeux.setBorder(new BevelBorder(BevelBorder.LOWERED, null, null, null, null));
listJeux.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
scrollPane.setViewportView(listJeux);
}
}
| true
|
958a1b9adea5cc4caa57fea33fd318655b054522
|
Java
|
atulanand206/Games
|
/java-problems/src/main/java/com/games/CodeForces/bitmasks/abcstring/Solution.java
|
UTF-8
| 2,500
| 3.0625
| 3
|
[] |
no_license
|
package com.games.CodeForces.bitmasks.abcstring;
import com.games.utils.I;
import com.games.utils.O;
import com.games.utils.S;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.Arrays;
import java.util.Stack;
/**
* Problem: CodeForces 1494A
*
* @author atulanand
*/
public class Solution {
public static boolean solve(char[] A) {
int len = A.length;
if (A[0] == A[len - 1]) return false;
char open = A[0];
char close = A[len - 1];
for (int i = 0; i < len; i++) {
if (A[i] == open) A[i] = '(';
if (A[i] == close) A[i] = ')';
}
char[] pos1 = new char[len];
char[] pos2 = new char[len];
for (int i = 0; i < len; i++) {
if (A[i] == '(' || A[i] == ')') {
pos1[i] = A[i];
pos2[i] = A[i];
} else {
pos1[i] = '(';
pos2[i] = ')';
}
}
int c1 = 0;
for (char ch : pos1)
c1 += (ch == '(') ? 1 : -1;
int c2 = 0;
for (char ch : pos2)
c2 += (ch == '(') ? 1 : -1;
return checkRegular(pos1) || checkRegular(pos2);
}
private static boolean checkRegular(char[] chars) {
Stack<Character> stack = new Stack<>();
for (char ch : chars) {
if (ch == '(') {
stack.push(ch);
} else {
char ch1 = stack.pop();
if (ch1 == ')')
return false;
}
}
return stack.isEmpty();
}
public static void main(String[] args) throws IOException {
O.attach();
BufferedReader br = new BufferedReader(I.reader(true));
// BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int t = inputInt(br);
StringBuilder sb = new StringBuilder();
while (t-- > 0) {
sb.append(solve(br.readLine().trim().toCharArray()) ? "YES" : "NO").append("\n");
}
System.out.println(sb);
}
public static int inputInt(BufferedReader br) throws IOException {
return Integer.parseInt(br.readLine().trim());
}
public static int[] inputIntArray(BufferedReader br) throws IOException {
String[] spec = br.readLine().split(" ");
int[] arr = new int[spec.length];
for (int i = 0; i < spec.length; i++)
arr[i] = Integer.parseInt(spec[i]);
return arr;
}
}
| true
|
c058e13e1abc4e7ce5c90f3b8c747d13e97493dd
|
Java
|
xiangcman/MvvM-master
|
/app/src/main/java/com/single/mvvm/adapter/RecyclerViewDatabingAdapter.java
|
UTF-8
| 4,767
| 2.375
| 2
|
[] |
no_license
|
package com.single.mvvm.adapter;
import android.databinding.DataBindingUtil;
import android.databinding.ViewDataBinding;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.single.mvvm.BR;
import com.single.mvvm.suspension.ISuspensionInterface;
import java.util.List;
/**
* Created by xiangcheng on 18/2/2.
*/
public abstract class RecyclerViewDatabingAdapter<T extends ISuspensionInterface, B extends ViewDataBinding, O extends ViewDataBinding> extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private static final String TAG = RecyclerViewDatabingAdapter.class.getSimpleName();
private List<T> list;
private B dataBing;
private O otherBing;
private static final int title = 0;
private static final int listItem = 1;
public RecyclerViewDatabingAdapter(List<T> list) {
this.list = list;
}
public void refreshData(List<T> list) {
if (this.list == null) {
this.list = list;
} else {
this.list.clear();
this.list.addAll(list);
}
notifyDataSetChanged();
}
@Override
public int getItemViewType(int position) {
return list.get(position).isShowSuspension() ? title : listItem;
}
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
//同样会根据布局生成一个相应的binding
RecyclerView.ViewHolder viewHolder;
if (viewType == title) {
otherBing = DataBindingUtil.inflate(
LayoutInflater.from(parent.getContext()), getTitleLayout(), parent, false);
viewHolder = new OtherBindingHolder(otherBing.getRoot());
((OtherBindingHolder) viewHolder).setBinding(otherBing);
} else {
dataBing = DataBindingUtil.inflate(
LayoutInflater.from(parent.getContext()), getItemLayout(), parent, false);
viewHolder = new BindingHolder(dataBing.getRoot());
((BindingHolder) viewHolder).setBinding(dataBing);
}
//这里getRoot会返回布局的根view
return viewHolder;
}
protected abstract int getTitleLayout();
protected abstract int getItemLayout();
protected abstract void itemClick(T item);
@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
//在绑定数据的时候是固定写法,就没什么好说的了
if (holder instanceof RecyclerViewDatabingAdapter.BindingHolder) {
((RecyclerViewDatabingAdapter.BindingHolder) holder).getBinding().setVariable(BR.item, list.get(position));
((RecyclerViewDatabingAdapter.BindingHolder) holder).getBinding().executePendingBindings();
((RecyclerViewDatabingAdapter.BindingHolder) holder).getBinding().getRoot().setOnClickListener(v -> {
itemClick(list.get(position));
});
} else {
Log.d(TAG, "getSuspensionTag:" + list.get(position).getSuspensionTag());
((RecyclerViewDatabingAdapter.OtherBindingHolder) holder).getBinding().setVariable(BR.listtitle_item, list.get(position));
((RecyclerViewDatabingAdapter.OtherBindingHolder) holder).getBinding().executePendingBindings();
}
}
@Override
public int getItemCount() {
return list.size();
}
public void loadMore(List<T> storiesBeans) {
if (this.list == null || this.list.size() <= 0) {
throw new RuntimeException("当前没有数据,请加载上一页");
} else {
int startIndex = this.list.size();
this.list.addAll(storiesBeans);
notifyItemInserted(startIndex);
notifyItemRangeChanged(startIndex, this.list.size() - startIndex);
}
}
public class BindingHolder extends RecyclerView.ViewHolder {
//这里在holder里面,传入一个binding对象就ok了
private B binding;
public BindingHolder(View itemView) {
super(itemView);
}
public B getBinding() {
return binding;
}
public void setBinding(B binding) {
this.binding = binding;
}
}
public class OtherBindingHolder extends RecyclerView.ViewHolder {
//这里在holder里面,传入一个binding对象就ok了
private O binding;
public OtherBindingHolder(View itemView) {
super(itemView);
}
public O getBinding() {
return binding;
}
public void setBinding(O binding) {
this.binding = binding;
}
}
}
| true
|
49a214f0615a9f4a22c33bb0aadec11c9363a655
|
Java
|
caiqiufu/eureka-ribbon-server
|
/src/main/java/com/unieap/base/vo/InfConfigVO.java
|
UTF-8
| 2,270
| 1.742188
| 2
|
[] |
no_license
|
package com.unieap.base.vo;
public class InfConfigVO {
private java.lang.Integer id;
private String bizCode;
private String appName;
private String infName;
private String url;
private String className;
private String activeFlag;
private String accessName;
private String password;
private String errorCodeIgnore;
private String successCode;
private byte[] responseSample;
private java.lang.Integer timeout;
public java.lang.Integer getId() {
return id;
}
public void setId(java.lang.Integer id) {
this.id = id;
}
public String getBizCode() {
return bizCode;
}
public void setBizCode(String bizCode) {
this.bizCode = bizCode;
}
public String getInfName() {
return infName;
}
public void setInfName(String infName) {
this.infName = infName;
}
public String getClassName() {
return className;
}
public void setClassName(String className) {
this.className = className;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public java.lang.Integer getTimeout() {
return timeout;
}
public void setTimeout(java.lang.Integer timeout) {
this.timeout = timeout;
}
public String getAppName() {
return appName;
}
public void setAppName(String appName) {
this.appName = appName;
}
public String getActiveFlag() {
return activeFlag;
}
public void setActiveFlag(String activeFlag) {
this.activeFlag = activeFlag;
}
public String getErrorCodeIgnore() {
return errorCodeIgnore;
}
public void setErrorCodeIgnore(String errorCodeIgnore) {
this.errorCodeIgnore = errorCodeIgnore;
}
public String getSuccessCode() {
return successCode;
}
public void setSuccessCode(String successCode) {
this.successCode = successCode;
}
public byte[] getResponseSample() {
return responseSample;
}
public void setResponseSample(byte[] responseSample) {
this.responseSample = responseSample;
}
public String getAccessName() {
return accessName;
}
public void setAccessName(String accessName) {
this.accessName = accessName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
| true
|
b1164aa5511b9e10b46c12f1c2c11b2b0322419d
|
Java
|
piyush2468/nearbychat
|
/app/src/main/java/com/rndtechnosoft/fynder/activity/ProfileEditActivity.java
|
UTF-8
| 38,639
| 1.53125
| 2
|
[] |
no_license
|
package com.rndtechnosoft.fynder.activity;
import android.Manifest;
import android.app.DatePickerDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.TextInputEditText;
import android.support.design.widget.TextInputLayout;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.Editable;
import android.text.InputType;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.DatePicker;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import com.facebook.drawee.backends.pipeline.Fresco;
import com.facebook.drawee.drawable.ScalingUtils;
import com.facebook.drawee.generic.RoundingParams;
import com.facebook.drawee.interfaces.DraweeController;
import com.facebook.drawee.view.SimpleDraweeView;
import com.facebook.imagepipeline.request.ImageRequest;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.auth.UserProfileChangeRequest;
import com.google.firebase.database.ChildEventListener;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;
import com.rndtechnosoft.fynder.R;
import com.rndtechnosoft.fynder.adapter.GalleryAdapter;
import com.rndtechnosoft.fynder.adapter.ItemAdapter;
import com.rndtechnosoft.fynder.dialog.GenderSelectDialog;
import com.rndtechnosoft.fynder.dialog.RelationshipStatusSelectDialog;
import com.rndtechnosoft.fynder.dialog.InterestedInSelectDialog;
import com.rndtechnosoft.fynder.dialog.YouLookingSelectDialog;
import com.rndtechnosoft.fynder.model.Item;
import com.rndtechnosoft.fynder.model.User;
import com.rndtechnosoft.fynder.model.UserImage;
import com.rndtechnosoft.fynder.utility.MyImageUtil;
import com.rndtechnosoft.fynder.utility.image.bottompicker.ImageBottomPicker;
import com.rndtechnosoft.fynder.utility.listener.OnSuccessUploadListener;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;
public class ProfileEditActivity extends AppCompatActivity implements View.OnClickListener,View.OnFocusChangeListener,GenderSelectDialog.AlertPositiveListener, RelationshipStatusSelectDialog.AlertPositiveListener, YouLookingSelectDialog.AlertPositiveListener, InterestedInSelectDialog.AlertPositiveListener {
private final String TAG = "ProfileEditActivity.log";
private final int OPEN_IMAGE = 536;
private String mainImage;
private String mainImageUrl;
private boolean isDefault = false;
private boolean setMainImage = false;
private SimpleDraweeView imageProfile;
private DatabaseReference profileRef;
private DatabaseReference imagesRef;
private StorageReference storageRef;
private UploadTask uploadThumbnailTask;
private ProgressDialog myProgressDialog;
private GalleryAdapter adapter;
private LinearLayout layoutGallery;
RecyclerView galleryView;
private List<UserImage> galleryList = new ArrayList<>();
//birthday
private int _year;
private int _month;
private int _day;
private int year, month, day;
private int gender,relationshipStatus, youLooking, youLike, allowShowMyBirthday;
private TextInputEditText etDisplayName, etStatus, etBirthday, etRelationStatus,etYouLooking, etInterestedIn,etGender;
private TextInputLayout layoutDisplayName, layoutetStatus, layoutBirthday, layoutRelationStatus, layoutYouLooking, layoutYouLike,layoutGender;
private ImageButton button_add_gallery;
private FloatingActionButton fab;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile_edit);
initView();
setDP();
LinearLayoutManager layoutManager = new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false);
galleryView.setLayoutManager(layoutManager);
galleryView.setAdapter(adapter);
setName();
setStatus();
storageRef = FirebaseStorage.getInstance().getReference();
FirebaseUser firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
if (firebaseUser != null) {
profileRef = FirebaseDatabase.getInstance().getReference("users").child(firebaseUser.getUid());
imagesRef = profileRef.child("images");
} else {
finish();
}
}
private void setDP() {
adapter = new GalleryAdapter(galleryList, new GalleryAdapter.OnItemClickListener() {
@Override
public void onItemClick(final UserImage item) {
Log.i(TAG, "Id: " + item.getId() + " | Image Url: " + item.getThumbPic());
final Item[] items = {
new Item(getString(R.string.option_view), android.R.drawable.ic_menu_view),
new Item(getString(R.string.option_set_main), android.R.drawable.ic_menu_more),
new Item(getString(R.string.option_remove), android.R.drawable.ic_menu_close_clear_cancel),
};
ItemAdapter adapter = new ItemAdapter(ProfileEditActivity.this, items);
new AlertDialog.Builder(ProfileEditActivity.this)
.setTitle(getString(R.string.title_select_image))
.setAdapter(adapter, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
if (i == 0) {
//view image
FirebaseUser firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
if (firebaseUser == null) {
return;
}
String uid = firebaseUser.getUid();
Intent intent = new Intent(ProfileEditActivity.this, FullProfileImageActivity.class);
intent.putExtra(FullProfileImageActivity.KEY_IMAGE, item.getId());
intent.putExtra(FullProfileImageActivity.KEY_IMAGE, item.getOriginalPic());
intent.putExtra(FullProfileImageActivity.KEY_UID, uid);
startActivity(intent);
} else if (i == 1) {
//set main image
profileRef.child("imageUrl").setValue(item.getId());
} else if (i == 2) {
new AlertDialog.Builder(ProfileEditActivity.this)
.setTitle(getString(R.string.title_delete_image))
.setMessage(getString(R.string.message_dialog_image))
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
FirebaseUser firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
if (firebaseUser == null) {
return;
}
String uid = firebaseUser.getUid();
profileRef.child("images").child(item.getId()).removeValue();
storageRef.child(uid + "/" + item.getId() + "_thumb.jpg").delete();
storageRef.child(uid + "/" + item.getId() + ".jpg").delete();
}
})
.setNegativeButton(getString(R.string.cancel), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
}
}).show();
}
}
}).create().show();
}
});
}
private void initView() {
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
fab = (FloatingActionButton) findViewById(R.id.fab);
myProgressDialog = new ProgressDialog(this);
myProgressDialog.setMessage(getString(R.string.uploading_image));
layoutGallery = (LinearLayout) findViewById(R.id.layout_gallery);
button_add_gallery = (ImageButton) findViewById(R.id.button_add_gallery);
etDisplayName = (TextInputEditText) findViewById(R.id.etFullname);
etStatus = (TextInputEditText) findViewById(R.id.etStatus);
etBirthday = (TextInputEditText) findViewById(R.id.etbirthday);
etRelationStatus = (TextInputEditText) findViewById(R.id.etrelationStatus);
etYouLooking = (TextInputEditText) findViewById(R.id.etYouLooking);
etInterestedIn = (TextInputEditText) findViewById(R.id.etYouLike);
etGender = (TextInputEditText) findViewById(R.id.etGender);
layoutDisplayName = (TextInputLayout) findViewById(R.id.input_layout_fullname);
layoutetStatus = (TextInputLayout) findViewById(R.id.input_layout_status);
layoutBirthday = (TextInputLayout) findViewById(R.id.input_layout_birthday);
layoutRelationStatus = (TextInputLayout) findViewById(R.id.input_layout_relationStatus);
layoutYouLooking = (TextInputLayout) findViewById(R.id.input_layout_YouLooking);
layoutYouLike = (TextInputLayout) findViewById(R.id.input_layout_YouLike);
layoutGender= (TextInputLayout) findViewById(R.id.input_layout_Gender);
imageProfile = (SimpleDraweeView) findViewById(R.id.image_profile);
RoundingParams circle = RoundingParams.asCircle()
.setRoundingMethod(RoundingParams.RoundingMethod.BITMAP_ONLY);
imageProfile.getHierarchy().setRoundingParams(circle);
imageProfile.getHierarchy().setActualImageScaleType(ScalingUtils.ScaleType.CENTER_CROP);
imageProfile.getHierarchy().setPlaceholderImage(R.drawable.ic_profile_default);
galleryView = (RecyclerView) findViewById(R.id.list_gallery);
etGender.setOnFocusChangeListener(this);
etRelationStatus.setOnFocusChangeListener(this);
etYouLooking.setOnFocusChangeListener(this);
etInterestedIn.setOnFocusChangeListener(this);
etBirthday.setOnFocusChangeListener(this);
button_add_gallery.setOnClickListener(this);
fab.setOnClickListener(this);
imageProfile.setOnClickListener(this);
etGender.setInputType(InputType.TYPE_NULL);
etRelationStatus.setInputType(InputType.TYPE_NULL);
etYouLooking.setInputType(InputType.TYPE_NULL);
etInterestedIn.setInputType(InputType.TYPE_NULL);
etBirthday.setInputType(InputType.TYPE_NULL);
}
private void setStatus() {
etStatus.addTextChangedListener(
new TextWatcher() {
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
private Timer timer = new Timer();
private final long DELAY = 3000; // milliseconds
@Override
public void afterTextChanged(final Editable s) {
timer.cancel();
timer = new Timer();
timer.schedule(
new TimerTask() {
@Override
public void run() {
profileRef.child("bio").setValue(etStatus.getText().toString());
// etStatus.setSelection(etStatus.getText().length());
}
},
DELAY
);
}
}
);
}
private void setName() {
etDisplayName.addTextChangedListener(
new TextWatcher() {
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
private Timer timer = new Timer();
private final long DELAY = 3000; // milliseconds
@Override
public void afterTextChanged(final Editable s) {
timer.cancel();
timer = new Timer();
timer.schedule(
new TimerTask() {
@Override
public void run() {
UserProfileChangeRequest profileUpdates = new UserProfileChangeRequest.Builder()
.setDisplayName(etDisplayName.getText().toString())
.build();
FirebaseAuth.getInstance().getCurrentUser().updateProfile(profileUpdates);
profileRef.child("name").setValue(etDisplayName.getText().toString());
// etDisplayName.setSelection(etDisplayName.getText().length());
}
},
DELAY
);
}
}
);
}
@Override
protected void onStart() {
super.onStart();
galleryList.clear();
adapter.notifyDataSetChanged();
if (profileRef != null) {
profileRef.addValueEventListener(profileListener);
imagesRef.addChildEventListener(imagesListener);
}
}
@Override
protected void onStop() {
super.onStop();
if (profileRef != null) {
profileRef.removeEventListener(profileListener);
imagesRef.removeEventListener(imagesListener);
}
if (uploadThumbnailTask != null && onSuccessUpload != null) {
uploadThumbnailTask.removeOnSuccessListener(onSuccessUpload);
}
}
private ValueEventListener profileListener = new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
User model = dataSnapshot.getValue(User.class);
if (model == null) {
return;
}
Log.i(TAG, "Name: " + model.getName());
etDisplayName.setText(model.getName());
etStatus.setText(model.getBio());
etBirthday.setText(model.getGender());
etRelationStatus.setText(model.getRelationshipStatus());
etYouLooking.setText(model.getLookingFor());
etInterestedIn.setText(model.getInterestedIn());
boolean isImageAvailable = false;
for (DataSnapshot election : dataSnapshot.getChildren()) {
if (election.getKey().equals("images")) {
Log.i(TAG, "count images: " + election.getChildrenCount());
isImageAvailable = election.getChildrenCount() > 0;
String key = model.getImageUrl() == null ? "default" : model.getImageUrl();
mainImage = key;
DataSnapshot defaultImage = election.child(key);
Log.i(TAG, "Main image is exist: " + defaultImage.exists());
if (defaultImage.exists()) {
UserImage userImage = defaultImage.getValue(UserImage.class);
DraweeController controller = Fresco.newDraweeControllerBuilder()
.setLowResImageRequest(ImageRequest.fromUri(userImage.getThumbPic()))
.setImageRequest(ImageRequest.fromUri(userImage.getOriginalPic()))
.setOldController(imageProfile.getController())
.build();
imageProfile.setController(controller);
mainImageUrl = userImage.getOriginalPic();
//set main image to adapter
for (UserImage images : galleryList) {
images.setMainImage(mainImage.equals(images.getId()));
}
adapter.notifyDataSetChanged();
break;
} else {
profileRef.child("imageUrl").setValue(null);
}
}
}
if (model.getBirthday() != null) {
try {
String year = model.getBirthday().substring(0, 4);
Log.i(TAG, "year: " + year);
String month = model.getBirthday().substring(4, 6);
Log.i(TAG, "month: " + month);
String day = model.getBirthday().substring(6, 8);
int yearInt = Integer.parseInt(year);
Log.i(TAG, "day: " + day);
int monthInt = Integer.parseInt(month);
int dayInt = Integer.parseInt(day);
etBirthday.setText(displayDate(yearInt, monthInt, dayInt));
_year = yearInt;
_month = monthInt;
_day = dayInt;
} catch (Exception e) {
Log.e(TAG, "Error parse date: " + e.getMessage());
}
}
if (model.getGender() != null) {
etGender.setText(model.getGender());
}
isDefault = !isImageAvailable;
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
};
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
// if (grantResults.length > 0 && grantResults[0] != PackageManager.PERMISSION_GRANTED) {
// return;
// }
if (requestCode == OPEN_IMAGE) {
if (grantResults.length < 1) {
return;
}
boolean permission1 = grantResults[0] == PackageManager.PERMISSION_GRANTED;
boolean permission2 = grantResults[1] == PackageManager.PERMISSION_GRANTED;
boolean permission3 = grantResults[2] == PackageManager.PERMISSION_GRANTED;
boolean isPermissionGranted = permission1 && permission2 && permission3;
if (isPermissionGranted) {
openImageBottomSheet();
}
}
}
private OnSuccessListener<UploadTask.TaskSnapshot> onSuccessUpload;
private ChildEventListener imagesListener = new ChildEventListener() {
@Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
layoutGallery.setVisibility(View.VISIBLE);
UserImage model = dataSnapshot.getValue(UserImage.class);
model.setId(dataSnapshot.getKey());
String imageMain = mainImage == null ? "default" : mainImage;
Log.i(TAG, "image id: " + model.getId() + " , main image: " + imageMain);
model.setMainImage(imageMain.equals(model.getId()));
galleryList.add(0, model);
adapter.notifyItemInserted(0);
}
@Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
Log.i(TAG, "On Child Changed");
}
@Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
Log.i(TAG, "REMOVED -> image id: " + dataSnapshot.getKey());
int position = 0;
for (UserImage userImage : galleryList) {
if (userImage.getId().equals(dataSnapshot.getKey())) {
galleryList.remove(position);
adapter.notifyItemRemoved(position);
break;
}
position++;
}
}
@Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
Log.i(TAG, "On Child Moved");
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
};
private String displayDate(int year, int month, int day) {
String month_array[] = getResources().getStringArray(R.array.month);
return month_array[month] + " " + String.valueOf(day) + ", " + String.valueOf(year);
}
//Do not call onCreate on Parent Activity
@Override
public boolean onSupportNavigateUp() {
onBackPressed();
return true;
}
private void doUploadImage(final String path) {
myProgressDialog.show();
FirebaseUser firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
if (firebaseUser == null) {
return;
}
String uid = firebaseUser.getUid();
String tempKey = isDefault ? "default" : profileRef.child("images").push().getKey();
StorageReference profileImagesRef = storageRef.child(uid + "/" + tempKey + "_thumb.jpg");
Bitmap bitmap = BitmapFactory.decodeFile(path);
Bitmap thumbnail = Bitmap.createScaledBitmap(bitmap, 90, 90, true);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
thumbnail.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] thumbData = baos.toByteArray();
uploadThumbnailTask = profileImagesRef.putBytes(thumbData);
onSuccessUpload = new OnSuccessUploadListener(tempKey) {
@Override
public void onSuccessUpload(final String key, UploadTask.TaskSnapshot taskSnapshot) {
@SuppressWarnings("VisibleForTests")
final Uri thumbUrl = taskSnapshot.getDownloadUrl();
Log.i(TAG, "Success to Upload thumbnail, url: " + thumbUrl);
FirebaseUser firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
if (firebaseUser == null) {
return;
}
String uid = firebaseUser.getUid();
StorageReference profileImagesRef = storageRef.child(uid + "/" + key + ".jpg");
UploadTask uploadTask = profileImagesRef.putFile(Uri.fromFile(new File(path)));
uploadTask.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
Log.e(TAG, "Error upload thumb image: " + e.getMessage());
myProgressDialog.dismiss();
}
}).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
@Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
@SuppressWarnings("VisibleForTests")
Uri downloadUrl = taskSnapshot.getDownloadUrl();
Log.i(TAG, "Success to Upload, url: " + downloadUrl);
UserImage userImage = new UserImage(thumbUrl.toString(), downloadUrl.toString());
Map<String, Object> postValues = userImage.toMap();
// profileRef.child("images").child(tempKey).setValue(userImage);
profileRef.child("images").child(key).updateChildren(postValues);
if (setMainImage) {
profileRef.child("imageUrl").setValue(key);
}
setMainImage = false;
myProgressDialog.dismiss();
}
});
}
};
uploadThumbnailTask.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
Log.e(TAG, "Failed to upload thumb: " + e.getMessage());
}
}).addOnSuccessListener(onSuccessUpload);
}
private void openImageBottomSheet() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if ((ContextCompat.checkSelfPermission(this, android.Manifest.permission.CAMERA)
!= PackageManager.PERMISSION_GRANTED) ||
(ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED) ||
(ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED)) {
requestPermissions(new String[]{android.Manifest.permission.CAMERA,
Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE}, OPEN_IMAGE);
return;
}
}
new ImageBottomPicker.Builder(this)
.setSquare(true)
.setOnImageSelectedListener(new ImageBottomPicker.OnImageSelectedListener() {
@Override
public void onImageSelected(String path) {
Log.i(TAG, "On Image success: " + path);
if (MyImageUtil.isImageFile(new File(path))) {
doUploadImage(path);
}
}
})
.create().show(getSupportFragmentManager());
}
public void selectYouLooking(int position) {
android.app.FragmentManager fm = getFragmentManager();
YouLookingSelectDialog alert = new YouLookingSelectDialog();
Bundle b = new Bundle();
b.putInt("position", position);
alert.setArguments(b);
alert.show(fm, "alert_dialog_select_you_looking");
}
public void selectRelationshipStatus(int position) {
android.app.FragmentManager fm = getFragmentManager();
RelationshipStatusSelectDialog alert = new RelationshipStatusSelectDialog();
Bundle b = new Bundle();
b.putInt("position", position);
alert.setArguments(b);
alert.show(fm, "alert_dialog_select_relationship_status");
}
public void getRelationshipStatus(int mRelationship) {
relationshipStatus = mRelationship;
switch (mRelationship) {
case 0: {
etRelationStatus.setText(getString(R.string.relationship_status_0));
if (profileRef != null) {
profileRef.child("relationshipStatus").setValue(getString(R.string.relationship_status_0));
}
break;
}
case 1: {
etRelationStatus.setText(getString(R.string.relationship_status_1));
if (profileRef != null) {
profileRef.child("relationshipStatus").setValue(getString(R.string.relationship_status_1));
}
break;
}
case 2: {
etRelationStatus.setText(getString(R.string.relationship_status_2));
if (profileRef != null) {
profileRef.child("relationshipStatus").setValue(getString(R.string.relationship_status_2));
}
break;
}
case 3: {
etRelationStatus.setText(getString(R.string.relationship_status_3));
if (profileRef != null) {
profileRef.child("relationshipStatus").setValue(getString(R.string.relationship_status_3));
}
break;
}
case 4: {
etRelationStatus.setText(getString(R.string.relationship_status_4));
if (profileRef != null) {
profileRef.child("relationshipStatus").setValue(getString(R.string.relationship_status_4));
}
break;
}
case 5: {
etRelationStatus.setText(getString(R.string.relationship_status_5));
if (profileRef != null) {
profileRef.child("relationshipStatus").setValue(getString(R.string.relationship_status_5));
}
break;
}
case 6: {
etRelationStatus.setText(getString(R.string.relationship_status_6));
if (profileRef != null) {
profileRef.child("relationshipStatus").setValue(getString(R.string.relationship_status_6));
}
break;
}
case 7: {
etRelationStatus.setText(getString(R.string.relationship_status_7));
if (profileRef != null) {
profileRef.child("relationshipStatus").setValue(getString(R.string.relationship_status_7));
}
break;
}
default: {
break;
}
}
}
public void getYouLooking(int mLooking) {
youLooking = mLooking;
switch (mLooking) {
case 0: {
etYouLooking.setText(getString(R.string.you_looking_0));
if (profileRef != null) {
profileRef.child("lookingFor").setValue(getString(R.string.you_looking_0));
}
break;
}
case 1: {
etYouLooking.setText(getString(R.string.you_looking_1));
if (profileRef != null) {
profileRef.child("lookingFor").setValue(getString(R.string.you_looking_1));
}
break;
}
case 2: {
etYouLooking.setText(getString(R.string.you_looking_2));
if (profileRef != null) {
profileRef.child("lookingFor").setValue(getString(R.string.you_looking_2));
}
break;
}
case 3: {
etYouLooking.setText(getString(R.string.you_looking_3));
if (profileRef != null) {
profileRef.child("lookingFor").setValue(getString(R.string.you_looking_3));
}
break;
}
default: {
break;
}
}
}
public void selectYouLike(int position) {
android.app.FragmentManager fm = getFragmentManager();
InterestedInSelectDialog alert = new InterestedInSelectDialog();
Bundle b = new Bundle();
b.putInt("position", position);
alert.setArguments(b);
alert.show(fm, "alert_dialog_select_you_like");
}
public void getYouLike(int mLike) {
youLike = mLike;
switch (mLike) {
case 0: {
etInterestedIn.setText(getString(R.string.you_like_0));
if (profileRef != null) {
profileRef.child("interestedIn").setValue(getString(R.string.you_like_0));
}
break;
}
case 1: {
etInterestedIn.setText(getString(R.string.male));
if (profileRef != null) {
profileRef.child("interestedIn").setValue(getString(R.string.male));
}
break;
}
case 2: {
etInterestedIn.setText(getString(R.string.female));
if (profileRef != null) {
profileRef.child("interestedIn").setValue(getString(R.string.female));
}
break;
}
default: {
break;
}
}
}
public void selectGender(int position) {
android.app.FragmentManager fm =getFragmentManager();
GenderSelectDialog alert = new GenderSelectDialog();
Bundle b = new Bundle();
b.putInt("position", position);
alert.setArguments(b);
alert.show(fm, "alert_dialog_select_gender");
}
public void setGender(int mSex) {
gender = mSex;
if (mSex == 0) {
if (profileRef != null) {
profileRef.child("gender").setValue(getResources().getString(R.string.male));
}
etGender.setText(getString(R.string.male));
} else {
if (profileRef != null) {
profileRef.child("gender").setValue(getResources().getString(R.string.female));
}
etGender.setText(getString(R.string.female));
}
}
@Override
public void onGenderSelect(int position) {
setGender(position);
}
@Override
public void onYouLikeSelect(int position) {
getYouLike(position);
}
@Override
public void onYouLookingSelect(int position) {
getYouLooking(position);
}
@Override
public void onRelationshipStatusSelect(int position) {
getRelationshipStatus(position);
}
@Override
public void onFocusChange(View v, boolean hasFocus) {
switch (v.getId()) {
case R.id.etbirthday:
if(hasFocus){
DatePickerDialog datePickerDialog = new DatePickerDialog(ProfileEditActivity.this,
R.style.style_date_picker_dialog
, new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker datePicker, int year, int monthOfYear, int dayOfMonth) {
_year = year;
_month = monthOfYear;
_day = dayOfMonth;
etBirthday.setText(displayDate(year, monthOfYear, dayOfMonth));
String stringYear = String.valueOf(year);
String stringMonth = monthOfYear < 10 ? "0" + String.valueOf(monthOfYear) : String.valueOf(monthOfYear);
String stringDay = dayOfMonth < 10 ? "0" + String.valueOf(dayOfMonth) : String.valueOf(dayOfMonth);
String birthday = stringYear + stringMonth + stringDay;
profileRef.child("birthday").setValue(birthday);
}
}, _year, _month, _day);
datePickerDialog.setTitle("");
datePickerDialog.show();
}
break;
case R.id.etrelationStatus:
if (hasFocus) {
selectRelationshipStatus(relationshipStatus);
}
break;
case R.id.etGender:
if (hasFocus) {
if(etGender.getText().toString().equalsIgnoreCase("MALE"))
selectGender(0);
else
selectGender(1);
}
break;
case R.id.etYouLooking:
if (hasFocus) {
selectYouLooking(youLooking);
}
break;
case R.id.etYouLike:
if (hasFocus) {
selectYouLike(youLike);
}
break;
}
}
@Override
public void onClick(View v) {
switch (v.getId()){
case R.id.button_add_gallery:
openImageBottomSheet();
break;
case R.id.fab:
openImageBottomSheet();
break;
case R.id.image_profile:
FirebaseUser firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
if (firebaseUser == null) {
return;
}
String uid = firebaseUser.getUid();
Intent intent = new Intent(ProfileEditActivity.this, FullProfileImageActivity.class);
intent.putExtra(FullProfileImageActivity.KEY_IMAGE, mainImage);
intent.putExtra(FullProfileImageActivity.KEY_IMAGE_URL, mainImageUrl);
intent.putExtra(FullProfileImageActivity.KEY_UID, uid);
startActivity(intent);
break;
}
}
}
| true
|
65c3bc1d203206c941e52e1089eb6e7bcaac5bb7
|
Java
|
lordimpi/ParkingApp
|
/ParkingApp/src/main/java/co/unicauca/parkingapp/domain/access/CamionRepository.java
|
UTF-8
| 4,666
| 2.859375
| 3
|
[] |
no_license
|
package co.unicauca.parkingapp.domain.access;
import co.unicauca.parkingapp.domain.Camion;
import co.unicauca.parkingapp.domain.service.Service;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* Es una implementación que tiene libertad de hacer una implementación del
* contrato. Lo puede hacer con Sqlite, postgres, mysql, u otra tecnología
*
* @author Santiago Acuña
*/
public class CamionRepository implements ICamionRepository {
/**
* Variable para crear el string de conexion con la base de datos
*/
private Connection conn;
/**
* Inicia una base de datos a partir de un constructor no parametrizado
*/
public CamionRepository() {
initDatabase();
}
/**
* Guarda un camion en la base de datos
*
* @param newCamion Camion que sera guardado en la base de datos
* @return Devuelve verdadero si puedo guardar el camion. false de lo
* contrario
*/
@Override
public boolean save(Camion newCamion) {
try {
//Validate product
if (newCamion == null || newCamion.getPlaca() == null) {
return false;
}
//this.connect();
String sql = "INSERT INTO Camion ( Placa, Tipo, Marca, Modelo, Dias ) "
+ "VALUES ( ?, ?, ? ,?, ?)";
PreparedStatement pstmt = conn.prepareStatement(sql);
pstmt.setString(1, newCamion.getPlaca());
pstmt.setString(2,newCamion.getTipo());
pstmt.setString(3, newCamion.getMarca());
pstmt.setInt(4, newCamion.getModelo());
pstmt.setString(5,newCamion.getTiempo() );
pstmt.executeUpdate();
//this.disconnect();
return true;
} catch (SQLException ex) {
Logger.getLogger(Service.class.getName()).log(Level.SEVERE, null, ex);
}
return false;
}
/**
* Crea una lista
*
* @return Devuelve una coleccion de camiones
*/
@Override
public List<Camion> list() {
List<Camion> camiones = new ArrayList<>();
try {
String sql = "SELECT Placa, Tipo, Marca, Modelo, Dias FROM Camion";
//this.connect();
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(sql);
while (rs.next()) {
Camion newCamion = new Camion();
newCamion.setPlaca(rs.getString("Placa"));
newCamion.setTipo(rs.getString("Tipo"));
newCamion.setMarca(rs.getString("Marca"));
newCamion.setModelo(rs.getInt("Modelo"));
newCamion.setTiempo(rs.getString("Dias"));
camiones.add(newCamion);
}
//this.disconnect();
} catch (SQLException ex) {
Logger.getLogger(Service.class.getName()).log(Level.SEVERE, null, ex);
}
return camiones;
}
/**
* Inicia la creacion de una base de datos
*/
private void initDatabase() {
// SQL statement for creating a new table
String sql = "CREATE TABLE IF NOT EXISTS Camion (\n"
+ " Placa text PRIMARY KEY,\n"
+ " Tipo text,\n"
+ " Marca text,\n"
+ " Modelo integer,\n"
+" Dias text NOT NULL\n"
+ ");";
try {
this.connect();
Statement stmt = conn.createStatement();
stmt.execute(sql);
//this.disconnect();
} catch (SQLException ex) {
Logger.getLogger(Service.class.getName()).log(Level.SEVERE, null, ex);
}
}
/**
* Crea la conexion a la base de datos
*/
public void connect() {
// SQLite connection string
//String url = "jdbc:sqlite:./mydatabase.db";
String url = "jdbc:sqlite::memory:";
try {
conn = DriverManager.getConnection(url);
} catch (SQLException ex) {
Logger.getLogger(Service.class.getName()).log(Level.SEVERE, null, ex);
}
}
/**
* Cierra la conexion a la base de datos
*/
public void disconnect() {
try {
if (conn != null) {
conn.close();
}
} catch (SQLException ex) {
System.out.println(ex.getMessage());
}
}
}
| true
|
bf08a3d0c081b163cff4ec278f2fca1fd41159ef
|
Java
|
mjh1583/Hustar03_eGov
|
/workspace/project/src/main/java/egovframework/com/cmm/service/impl/MainDAO.java
|
UTF-8
| 1,449
| 2.125
| 2
|
[] |
no_license
|
package egovframework.com.cmm.service.impl;
/**
*
*/
import javax.annotation.Resource;
import org.apache.ibatis.session.SqlSessionFactory;
import egovframework.rte.psl.dataaccess.EgovAbstractMapper;
/**
* EgovComAbstractDAO.java 클래스
*
* @author 서준식
* @since 2011. 9. 23.
* @version 1.0
* @see
*
* <pre>
* << 개정이력(Modification Information) >>
*
* 수정일 수정자 수정내용
* ------- ------------- ----------------------
* 2011. 9. 23. 서준식 최초 생성
* </pre>
*/
public abstract class MainDAO extends EgovAbstractMapper{
/**
* Annotation 형식으로 sqlSession(SqlSessionFactoryBean)을 받아와
* 이를 super(SqlSessionDaoSupport)의 setSqlSessionFactory 메서드를 호출하여 설정해 준다.
* <p>
* SqlSessionTemplate이 지정된 경우된 경우 이 SqlSessionFactory가 무시된다. (Batch 처리를 위해서는 SqlSessionTemplate가 필요)
*
*
* @param sqlSession SqlSessionFactory로 MyBatis와의 연계를 위한 기본 클래스
*/
@Resource(name = "sqlSession")
public void setSqlSessionFactory(SqlSessionFactory sqlSession) {
super.setSqlSessionFactory(sqlSession);
}
/*
extends EgovAbstractDAO{
@Resource(name="egov.sqlMapClient")
public void setSuperSqlMapClient(SqlMapClient sqlMapClient) {
super.setSuperSqlMapClient(sqlMapClient);
}
*/
}
| true
|
7ad417e8dd28bad0669e67dc069c390021797594
|
Java
|
srkapi/test1
|
/src/main/java/com/example/demo/application/service/FindByIdUserService.java
|
UTF-8
| 992
| 2.09375
| 2
|
[] |
no_license
|
package com.example.demo.application.service;
import com.example.demo.application.domain.UserDomain;
import com.example.demo.application.port.in.mapper.MapperDomainUser;
import com.example.demo.application.port.in.model.ResponseFindByIdUser;
import com.example.demo.application.port.in.usecases.FindByIdUserUseCases;
import com.example.demo.application.port.out.FindByIdUserPort;
import lombok.RequiredArgsConstructor;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;
@Service
@RequiredArgsConstructor
public class FindByIdUserService implements FindByIdUserUseCases {
final static Logger logger = Logger.getLogger(FindByIdUserService.class);
private final FindByIdUserPort findByIdUserPort;
private final MapperDomainUser mapperDomainUser;
@Override
public ResponseFindByIdUser getById(Long id) {
UserDomain userDomain = this.findByIdUserPort.findById(id);
return this.mapperDomainUser.toResponseById(userDomain);
}
}
| true
|
8d599f5a48632e21bf514b4668162e52a8d3e5f8
|
Java
|
Siva7845/BankingApp
|
/src/main/java/com/app/BankManagement/Model/Address.java
|
UTF-8
| 2,601
| 2.40625
| 2
|
[] |
no_license
|
package com.app.BankManagement.Model;
import java.sql.Timestamp;
import javax.persistence.*;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.Pattern;
import org.hibernate.annotations.CreationTimestamp;
import org.hibernate.annotations.UpdateTimestamp;
@Entity
@Table(name="address")
public class Address {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
private int id;
@NotEmpty(message = "Please provide a doorNo")
@Column(name = "doorNo", columnDefinition = "VARCHAR(20)")
private String doorNo;
@NotEmpty(message = "Please provide a landMark_Or_Street")
@Column(name = "landMark_Or_Street", columnDefinition = "VARCHAR(100)")
private String landMark_Or_Street;
@NotEmpty(message = "Please provide a city")
@Column(name = "city", columnDefinition = "VARCHAR(20)")
private String city;
@NotEmpty(message = "Please provide a pincode")
@Column(name = "pincode", columnDefinition = "VARCHAR(20)")
private String pincode;
@NotEmpty(message = "Please provide a state")
@Column(name = "state", columnDefinition = "VARCHAR(20)")
private String state;
@NotEmpty(message = "Please provide a mobileNumber")
@Column(name = "mobileNumber", columnDefinition = "VARCHAR(20)")
private String mobileNumber;
@CreationTimestamp
private Timestamp createdAt;
@UpdateTimestamp
private Timestamp updatedAt;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getDoorNo() {
return doorNo;
}
public void setDoorNo(String doorNo) {
this.doorNo = doorNo;
}
public String getLandMark_Or_Street() {
return landMark_Or_Street;
}
public void setLandMark_Or_Street(String landMark_Or_Street) {
this.landMark_Or_Street = landMark_Or_Street;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getPincode() {
return pincode;
}
public void setPincode(String pincode) {
this.pincode = pincode;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getMobileNumber() {
return mobileNumber;
}
public void setMobileNumber(String mobileNumber) {
this.mobileNumber = mobileNumber;
}
public Timestamp getCreatedAt() {
return createdAt;
}
public void setCreatedAt(Timestamp createdAt) {
this.createdAt = createdAt;
}
public Timestamp getUpdatedAt() {
return updatedAt;
}
public void setUpdatedAt(Timestamp updatedAt) {
this.updatedAt = updatedAt;
}
public Address() {
super();
// TODO Auto-generated constructor stub
}
}
| true
|
47e25f74aa389352c9a231fc25a7987d71397489
|
Java
|
1c3m4n/sysstate
|
/sysstate-jenkins/src/main/java/nl/unionsoft/sysstate/plugins/jenkins/JenkinsServerStateResolverImpl.java
|
UTF-8
| 2,168
| 2.21875
| 2
|
[
"MIT"
] |
permissive
|
package nl.unionsoft.sysstate.plugins.jenkins;
import static nl.unionsoft.sysstate.common.util.XmlUtil.getCharacterDataFromObjectWithKey;
import java.util.Map;
import javax.inject.Named;
import org.apache.commons.lang.StringUtils;
import org.apache.xmlbeans.XmlObject;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import nl.unionsoft.sysstate.common.dto.InstanceDto;
import nl.unionsoft.sysstate.common.dto.StateDto;
import nl.unionsoft.sysstate.common.enums.StateType;
import nl.unionsoft.sysstate.plugins.http.XMLBeanStateResolverImpl;
@Named("jenkinsServerStateResolver")
public class JenkinsServerStateResolverImpl extends XMLBeanStateResolverImpl {
private static final String API_XML = "/api/xml";
@Override
protected void handleXmlObject(final XmlObject xmlObject, final StateDto state, final Map<String, String> properties, final InstanceDto instance) {
final Node node = xmlObject.getDomNode();
final Document document = (Document) node;
final String offline = getCharacterDataFromObjectWithKey(document, "offline");
final String temporarilyOffline = getCharacterDataFromObjectWithKey(document, "temporarilyOffline");
final String numExecutors = getCharacterDataFromObjectWithKey(document, "numExecutors");
state.appendMessage("Instance has '" + numExecutors + "' executors.");
if (Boolean.valueOf(offline)) {
state.setState(StateType.ERROR);
state.setDescription("OFFLINE");
if (Boolean.valueOf(temporarilyOffline)) {
state.appendMessage("Instance is temporarily offline!");
} else {
state.appendMessage("Instance is offline!");
}
} else {
state.setState(StateType.STABLE);
state.setDescription("ONLINE");
}
}
@Override
public String processUri(final String uri) {
final StringBuilder uriBuilder = new StringBuilder();
uriBuilder.append(super.processUri(uri));
if (!StringUtils.endsWith(uri, API_XML)) {
uriBuilder.append(API_XML);
}
return uriBuilder.toString();
}
}
| true
|
46370d0476814360cdb373db1708a66157c9ca6f
|
Java
|
ekaterinaStep/Testing123
|
/src/testing/Testing.java
|
UTF-8
| 683
| 3
| 3
|
[] |
no_license
|
package testing;
import java.util.ArrayList;
import java.util.Collections;
public class Testing {
static int x;
StringBuilder sb = new StringBuilder();
static StringBuilder sb2 = new StringBuilder();
public Testing() {
m1();
m2();
}
public void m1(){
x += 5;
sb.append(x);
}
public void m2(){
x += 10;
sb2.append(x);
}
public static void main(String[] args){
Testing t1 = new Testing();
Testing t2 = new Testing();
Testing t3 = new Testing();
String s = t2.sb + "-" + t2.sb2;
System.out.println(s);
}
}
| true
|
4bd59900cf530233307770285d31f9ab5643a505
|
Java
|
changhengy/persimmoncake
|
/src/main/java/org/persimmon/cake/controller/DemoAddUserController.java
|
UTF-8
| 1,170
| 2.25
| 2
|
[] |
no_license
|
package org.persimmon.cake.controller;
/*
* @time 2021/5/20 10:10
* @author chy
*/
import org.persimmon.cake.model.RespBean;
import org.persimmon.cake.model.User;
import org.persimmon.cake.service.PostgresConService;
import org.persimmon.cake.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import java.io.IOException;
@RestController
public class DemoAddUserController {
// @Autowired
// UserService userService;
@Autowired
PostgresConService postgresConService;
@GetMapping("/login")
public RespBean login() {
return RespBean.error("尚未登录,请登录!");
}
@GetMapping("/adduser")
// public RespBean addUser(@RequestBody User user) {
public RespBean addUser() throws IOException {
postgresConService.dbInit();
// if (userService.addSalary(user) == 1) {
// return RespBean.ok("添加成功!");
// }
return RespBean.error("添加失败!");
}
}
| true
|
535fe0b34d2313a6c7e99024885cc8042cfe3440
|
Java
|
xeon-ye/jk-kq
|
/jk-gen/src/main/java/com/jk/gen/enums/TemplatePathEnum.java
|
UTF-8
| 530
| 2.421875
| 2
|
[] |
no_license
|
package com.jk.gen.enums;
/**
* 模板路径
*
* @author 缪隽峰
* @version 1.0
* @date 2018年05月04日
*/
public enum TemplatePathEnum {
/**
* 单表
*/
COMMON("common"),
/**
* 树表
*/
TREE("tree"),
/**
* 左树右表
*/
TREELIST("treeList"),
/**
* 一对多
*/
OTMFORM("otmForm");
TemplatePathEnum(String value) {
this.value = value;
}
private String value;
public String getValue() {
return value;
}
}
| true
|
8d943be050a57e625209278a13e74f31a5d291d4
|
Java
|
dcoraboeuf/jsido
|
/sido-gen-model-pojo/src/test/java/net/sf/sido/gen/model/pojo/POJOGenerationModelTest.java
|
UTF-8
| 1,795
| 2.28125
| 2
|
[] |
no_license
|
package net.sf.sido.gen.model.pojo;
import static org.junit.Assert.assertEquals;
import net.sf.sido.schema.SidoProperty;
import net.sf.sido.schema.model.DefaultSidoAnonymousProperty;
import net.sf.sido.schema.model.DefaultSidoSimpleProperty;
import net.sf.sido.schema.support.SimpleType;
import org.junit.Test;
public class POJOGenerationModelTest {
private final POJOGenerationModel model = new POJOGenerationModel();
@Test
public void getGetMethodName_not_simple() {
SidoProperty property = new DefaultSidoAnonymousProperty("test", false, false);
String name = model.getGetMethodName(property);
assertEquals("getTest", name);
}
@Test
public void getGetMethodName_not_boolean() {
SidoProperty property = new DefaultSidoSimpleProperty<String>("test",
SimpleType.get("string", String.class, "\"\""), false, false);
String name = model.getGetMethodName(property);
assertEquals("getTest", name);
}
@Test
public void getGetMethodName_boolean_collection() {
SidoProperty property = new DefaultSidoSimpleProperty<Boolean>("test",
SimpleType.get("boolean", Boolean.class, "false"), false, true);
String name = model.getGetMethodName(property);
assertEquals("getTest", name);
}
@Test
public void getGetMethodName_boolean_nullable() {
SidoProperty property = new DefaultSidoSimpleProperty<Boolean>("test",
SimpleType.get("boolean", Boolean.class, "false"), true, false);
String name = model.getGetMethodName(property);
assertEquals("getTest", name);
}
@Test
public void getGetMethodName_boolean_not_nullable() {
SidoProperty property = new DefaultSidoSimpleProperty<Boolean>("test",
SimpleType.get("boolean", Boolean.class, "false"), false, false);
String name = model.getGetMethodName(property);
assertEquals("isTest", name);
}
}
| true
|
7f9405a9d6dbc0197e2664bfce7d4c020617a39a
|
Java
|
csquillgit/paging
|
/src/main/java/com/billing/billing/LedgerHeader.java
|
UTF-8
| 699
| 2.09375
| 2
|
[] |
no_license
|
package com.billing.billing;
import java.math.BigInteger;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
@Entity
public class LedgerHeader {
@Id
@GeneratedValue
private BigInteger id;
@Column
private String head;
private BigInteger transUuid;
public BigInteger getId() {
return id;
}
public void setId(BigInteger id) {
this.id = id;
}
public String getHead() {
return head;
}
public void setHead(String head) {
this.head = head;
}
public BigInteger getTransUuid() {
return transUuid;
}
public void setTransUuid(BigInteger transUuid) {
this.transUuid = transUuid;
}
}
| true
|
5e283423084fc60ce6010265aa7ba1c07d394f3e
|
Java
|
yeman/springsecuritydemo
|
/demo/src/main/java/com/yjt/springcloud/demo01/validatecode/generator/SmsCodeGenerator.java
|
UTF-8
| 1,336
| 2.15625
| 2
|
[] |
no_license
|
package com.yjt.springcloud.demo01.validatecode.generator;
import com.yjt.springcloud.demo01.config.properties.SecurityProperties;
import com.yjt.springcloud.demo01.validatecode.CustomImageCaptcha;
import com.yjt.springcloud.demo01.validatecode.bean.ValidateCode;
import com.yjt.springcloud.demo01.validatecode.exception.ValidateCodeException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.ServletWebRequest;
import java.io.IOException;
/**
* @author YM
* @version V1.0
* @className ImageCodeGenerator
* @description 短信验证码生成器
* @date 2021-06-02 15:24
* @since 1.0
**/
@Slf4j
@Component(value = "smsValidateCodeGenerator")
public class SmsCodeGenerator implements ValidateCodeGenerator {
@Value("${captcha.wordSize:5}")
private int wordSize;
@Value("${captcha.expireTime:50}")
private int validateCodeExpire;
@Override
public ValidateCode generate(ServletWebRequest request) {
String code = RandomStringUtils.randomNumeric(wordSize,validateCodeExpire);
return new ValidateCode(code,validateCodeExpire);
}
}
| true
|
513229bad4ff8df6dd9fb37e28111f685cbbd9c0
|
Java
|
killbus/jd_decompile
|
/com/jd/fridge/friends/IFollowedFragment.java
|
UTF-8
| 7,443
| 1.539063
| 2
|
[] |
no_license
|
package com.jd.fridge.friends;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Message;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import com.jd.fridge.GlobalVariable;
import com.jd.fridge.R;
import com.jd.fridge.a;
import com.jd.fridge.base.BaseFragment;
import com.jd.fridge.bean.ConcernListDataBean;
import com.jd.fridge.bean.FriendInfo;
import com.jd.fridge.bean.requestBody.CancelConcern;
import com.jd.fridge.bean.requestBody.ConcernBody;
import com.jd.fridge.util.d.b;
import com.jd.fridge.util.y;
import com.jd.fridge.widget.EmptyLayout;
import com.jd.fridge.widget.zxing.activity.QRCaptureActivity;
import java.util.ArrayList;
import java.util.List;
/* compiled from: TbsSdkJava */
public class IFollowedFragment extends BaseFragment implements d {
FriendInfo d;
private Context e;
@BindView(2131558950)
TextView empty_hint_textview;
@BindView(2131558951)
ImageView empty_icon_imageview;
@BindView(2131558576)
View empty_layout;
private IFollowedAdapter f;
@BindView(2131558904)
EmptyLayout friends_content_empty;
@BindView(2131558903)
RecyclerView friends_recycler_view;
private List<FriendInfo> g = new ArrayList();
private final BroadcastReceiver h = new BroadcastReceiver(this) {
final /* synthetic */ IFollowedFragment a;
{
this.a = r1;
}
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
Object obj = -1;
switch (action.hashCode()) {
case 1591869745:
if (action.equals("ACTION_MAKE_FRIENDS_SUCCESS")) {
obj = null;
break;
}
break;
}
switch (obj) {
case null:
this.a.g.clear();
if (y.d(this.a.getActivity())) {
a.a().a(this.a.a, new ConcernBody(GlobalVariable.I(), Long.parseLong(GlobalVariable.C())));
return;
}
this.a.f.notifyDataSetChanged();
this.a.friends_content_empty.setErrorType(1);
return;
default:
return;
}
}
};
public View onCreateView(LayoutInflater layoutInflater, ViewGroup viewGroup, Bundle bundle) {
View inflate = layoutInflater.inflate(R.layout.fragment_friends_content, viewGroup, false);
this.e = getContext();
ButterKnife.bind((Object) this, inflate);
return inflate;
}
public void onActivityCreated(Bundle bundle) {
super.onActivityCreated(bundle);
a();
c();
a("亲友页面-我关注的");
}
private void a() {
this.empty_hint_textview.setText(R.string.activity_friends_list_no_following_hint);
this.empty_icon_imageview.setImageResource(R.drawable.scan_icon);
this.friends_recycler_view.setLayoutManager(new LinearLayoutManager(getContext()));
this.friends_recycler_view.setHasFixedSize(true);
}
private void c() {
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction("ACTION_MAKE_FRIENDS_SUCCESS");
getActivity().registerReceiver(this.h, intentFilter);
this.f = new IFollowedAdapter(getContext(), this.g);
this.f.setOnNotifyDataSetChangeListener(this);
this.friends_recycler_view.setAdapter(this.f);
this.friends_content_empty.setRefresh(new OnClickListener(this) {
final /* synthetic */ IFollowedFragment a;
{
this.a = r1;
}
public void onClick(View view) {
if (y.d(this.a.getActivity())) {
a.a().a(this.a.a, new ConcernBody(GlobalVariable.I(), Long.parseLong(GlobalVariable.C())));
return;
}
this.a.friends_content_empty.setErrorType(1);
}
});
if (y.d(getActivity())) {
a.a().a(this.a, new ConcernBody(GlobalVariable.I(), Long.parseLong(GlobalVariable.C())));
return;
}
this.friends_content_empty.setErrorType(1);
}
@OnClick({2131558576})
void goToQrScanAcitivity() {
b.a(this.e, "android.permission.CAMERA", new com.jd.fridge.util.d.a(this) {
final /* synthetic */ IFollowedFragment a;
{
this.a = r1;
}
public void a() {
this.a.e.startActivity(new Intent(this.a.e, QRCaptureActivity.class));
}
});
}
public boolean handleMessage(Message message) {
switch (message.what) {
case 2000:
this.friends_content_empty.setErrorType(4);
ConcernListDataBean concernListDataBean = (ConcernListDataBean) message.obj;
if (concernListDataBean.getStatus() == 0) {
if (concernListDataBean.getResult() != null && concernListDataBean.getResult().size() != 0) {
this.g.clear();
this.g.addAll(concernListDataBean.getResult());
this.f.notifyDataSetChanged();
this.friends_recycler_view.setVisibility(0);
this.empty_layout.setVisibility(8);
break;
}
this.empty_layout.setVisibility(0);
this.friends_recycler_view.setVisibility(8);
break;
}
break;
case 2001:
this.friends_content_empty.setErrorType(8);
break;
case 2014:
this.friends_content_empty.setErrorType(4);
d();
break;
case 2015:
((FriendsListActivity) getActivity()).a(10);
break;
}
return super.handleMessage(message);
}
public void a(FriendInfo friendInfo) {
a("APP_我的_亲友页_不再关注Ta按钮", "fridgeapp_201609146|35");
this.d = friendInfo;
if (y.d(getActivity())) {
((FriendsListActivity) getActivity()).a(4);
a.a().a(this.a, new CancelConcern(GlobalVariable.I(), friendInfo.getPin(), friendInfo.getFeedId()));
return;
}
((FriendsListActivity) getActivity()).a(11);
}
private void d() {
if (this.d != null) {
this.g.remove(this.d);
this.f.notifyDataSetChanged();
if (this.f.getItemCount() == 0) {
this.friends_recycler_view.setVisibility(8);
this.empty_layout.setVisibility(0);
}
this.d = null;
}
}
public void onDestroy() {
super.onDestroy();
getActivity().unregisterReceiver(this.h);
}
}
| true
|
af80a8139cb6a9a16524b07316e9089117305d73
|
Java
|
Android-Modularity/gallery
|
/src/main/java/com/march/gallery/ui/GalleryPreviewFragment.java
|
UTF-8
| 6,884
| 1.976563
| 2
|
[] |
no_license
|
package com.march.gallery.ui;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.march.common.Common;
import com.march.common.exts.EmptyX;
import com.march.common.exts.SizeX;
import com.march.gallery.Gallery;
import com.march.gallery.R;
import com.march.gallery.adapter.LightPagerAdapter;
import com.march.gallery.model.GalleryItem;
import com.zfy.adapter.LightHolder;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
/**
* CreateAt : 2018/3/2
* Describe : 图片预览界面
*
* @author chendong
*/
public class GalleryPreviewFragment extends Fragment {
private LightPagerAdapter<GalleryItem> mImagePagerAdapter;
private ViewPager mImageVp;
private TextView mEnsureTv;
private ImageView mSelectSiv;
private List<GalleryItem> mAllImages;
private List<GalleryItem> mSelectImages;
private int mInitIndex;
private int mMaxNum;
private int width, height;
public static GalleryPreviewFragment newInst(Bundle bundle) {
GalleryPreviewFragment fragment = new GalleryPreviewFragment();
fragment.setArguments(bundle);
return fragment;
}
public void update(List<GalleryItem> allImages, List<GalleryItem> selectImages, int index) {
mAllImages = new ArrayList<>(allImages);
mSelectImages = new ArrayList<>(selectImages);
mInitIndex = index;
if (mImageVp == null) {
return;
}
if (mImagePagerAdapter != null) {
mImagePagerAdapter.notifyDataSetChanged();
} else {
mImagePagerAdapter = new LightPagerAdapter<GalleryItem>(mAllImages, R.layout.gallery_preview_item) {
@Override
public void onBindView(LightHolder holder, GalleryItem data) {
ImageView view = holder.getView(R.id.iv_image);
Common.exports.imageLoader.loadImg(view.getContext(), data.getPath(), width, height, view);
}
};
mImageVp.setAdapter(mImagePagerAdapter);
}
mImageVp.setCurrentItem(mInitIndex);
if (mSelectSiv != null) {
GalleryItem GalleryImageInfo = mAllImages.get(mInitIndex);
updateSelectStatus(GalleryImageInfo);
}
updateEnsureText();
}
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
width = SizeX.WIDTH;
height = SizeX.HEIGHT - SizeX.dp2px(90);
View view = inflater.inflate(R.layout.gallery_preview_fragment, container, false);
Bundle arguments = getArguments();
mAllImages = new ArrayList<>();
mSelectImages = new ArrayList<>();
if (arguments != null) {
ArrayList<GalleryItem> allImgs = arguments.getParcelableArrayList(Gallery.KEY_ALL_IMG);
if (!EmptyX.isEmpty(allImgs)) {
mAllImages.addAll(allImgs);
}
ArrayList<GalleryItem> selectImgs = arguments.getParcelableArrayList(Gallery.KEY_SELECT_IMG);
if (!EmptyX.isEmpty(selectImgs)) {
mSelectImages.addAll(selectImgs);
}
mInitIndex = arguments.getInt(Gallery.KEY_INDEX, 0);
mMaxNum = arguments.getInt(Gallery.KEY_MAX_NUM, 0);
}
initView(view);
return view;
}
// 更新选中图标
private void updateSelectStatus(GalleryItem GalleryImageInfo) {
if (!mSelectImages.contains(GalleryImageInfo)) {
mSelectSiv.setImageResource(Gallery.getInst().getCfg().previewUnSelectIcon);
} else {
mSelectSiv.setImageResource(Gallery.getInst().getCfg().previewSelectIcon);
}
}
public void initView(View view) {
mImageVp = (ViewPager) view.findViewById(R.id.vp_image);
mEnsureTv = (TextView) view.findViewById(R.id.tv_ensure);
mSelectSiv = (ImageView) view.findViewById(R.id.detail_select_iv);
mSelectSiv.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
updateEnsureText();
GalleryItem imageInfo = mAllImages.get(mImageVp.getCurrentItem());
if (mMaxNum == 1) {
mSelectImages.clear();
mSelectImages.add(imageInfo);
} else {
if (mSelectImages.contains(imageInfo)) {
mSelectImages.remove(imageInfo);
} else if (mSelectImages.size() < mMaxNum) {
mSelectImages.add(imageInfo);
}
}
updateSelectStatus(imageInfo);
updateEnsureText();
// MsgBus.getInst().post(Gallery.EVENT_SELECT, imageInfo);
}
});
// ViewX.click(view, R.id.siv_back, v -> {
// if (getActivity() != null) {
// getActivity().finish();
// }
// });
mEnsureTv.setOnClickListener(v -> publish());
mImageVp.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
@Override
public void onPageSelected(int position) {
GalleryItem GalleryImageInfo = mAllImages.get(position);
updateSelectStatus(GalleryImageInfo);
}
@Override
public void onPageScrollStateChanged(int state) {
}
});
update(mAllImages, mSelectImages, mInitIndex);
}
public void updateEnsureText() {
if (mSelectImages.size() == 0) {
mEnsureTv.setSelected(false);
mEnsureTv.setText("未选择");
} else {
mEnsureTv.setText(String.format(Locale.CHINA, "完成(%d)", mSelectImages.size()));
mEnsureTv.setSelected(true);
}
}
private void publish() {
Intent intent = new Intent();
intent.putExtra(Gallery.KEY_COMPLETE, true);
intent.putParcelableArrayListExtra(Gallery.KEY_SELECT_IMG, new ArrayList<>(mSelectImages));
if (getActivity() != null) {
getActivity().setResult(Activity.RESULT_OK, intent);
getActivity().finish();
}
}
}
| true
|
cdc2909a0401dd4c59745b499c8e57e297424062
|
Java
|
wangzhaoning/DesginPatterns
|
/Iteratorpattern/Waitress.java
|
UTF-8
| 815
| 3.53125
| 4
|
[] |
no_license
|
package Iteratorpattern;
import java.util.Iterator;
public class Waitress {
Menu pancakeHouseMenu;
Menu dinerMenu;
public Waitress(Menu pancakeHouseMenu,Menu dinerMenu)
{
this.pancakeHouseMenu=pancakeHouseMenu;
this.dinerMenu=dinerMenu;
}
public void printMenu() {
Iterator pancakeIterator =pancakeHouseMenu.createIterator();
Iterator dinerIterator=dinerMenu.createIterator();
System.out.println("--------breakfast----------");
printMenu(pancakeIterator);
System.out.println("--------lunch----------");
printMenu(dinerIterator);
}
private void printMenu(Iterator iterator) {
while(iterator.hasNext())
{
MenuItem menuitem =(MenuItem)iterator.next();
System.out.print(menuitem.name+", ");
System.out.print(menuitem.desc+", ");
System.out.print(menuitem.price+".");
}
}
}
| true
|
65d0ef24ff4f43003aa92946b739d514a8a93ac7
|
Java
|
wgalanciak/wp
|
/com.zend.thym.wp.core/src/com/zend/thym/wp/internal/core/vstudio/WPCopyFileAction.java
|
UTF-8
| 3,583
| 2.40625
| 2
|
[] |
no_license
|
package com.zend.thym.wp.internal.core.vstudio;
import java.io.File;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.Path;
import org.eclipse.thym.core.plugin.actions.CopyFileAction;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
public class WPCopyFileAction extends CopyFileAction {
private static final String DOT_CS = ".cs";
private static final String DOT_XAML = ".xaml";
private File rootFolder;
private Document document;
public WPCopyFileAction(File source, File target, File rootFolder) {
super(source, target);
this.rootFolder = rootFolder;
}
@Override
public void install() throws CoreException {
super.install();
File csprojFile = WPProjectUtils.getCsrojFile(rootFolder);
if (csprojFile != null) {
setDocument(WPProjectUtils.readXML(csprojFile));
Element root = getDocument().getDocumentElement();
Element itemGroup = getItemGroup();
String name = target.getName();
if (name.endsWith(DOT_CS)) {
itemGroup.appendChild(getCompileInclude());
if (name.endsWith(DOT_XAML + DOT_CS)) {
itemGroup.appendChild(getPageInclude());
}
} else if (!name.endsWith(DOT_XAML)) {
itemGroup.appendChild(getContentInclude());
}
root.appendChild(itemGroup);
WPProjectUtils.writeXML(csprojFile, getDocument());
}
}
private Document getDocument() {
return document;
}
private void setDocument(Document document) {
this.document = document;
}
private Element getItemGroup() {
return getDocument().createElement("ItemGroup"); //$NON-NLS-1$
}
private Node getPageInclude() {
Element pageInclude = getDocument().createElement("Page"); //$NON-NLS-1$
String relativePath = getRelativePath(target);
relativePath = relativePath.substring(0, relativePath.indexOf(DOT_CS));
pageInclude.setAttribute("Include", relativePath); //$NON-NLS-1$
Element subType = getDocument().createElement("SubType");
subType.setTextContent("Designer");
pageInclude.appendChild(subType);
Element generator = getDocument().createElement("Generator");
generator.setTextContent("MSBuild:Compile");
pageInclude.appendChild(generator);
return pageInclude;
}
private Element getCompileInclude() {
Element compileInclude = getDocument().createElement("Compile"); //$NON-NLS-1$
String relativePath = getRelativePath(target);
compileInclude.setAttribute("Include", relativePath); //$NON-NLS-1$
if (relativePath.endsWith(DOT_XAML + DOT_CS)) {
compileInclude.appendChild(getDependetUpon(relativePath));
}
return compileInclude;
}
private Element getContentInclude() {
Element contentInclude = getDocument().createElement("Content"); //$NON-NLS-1$
String relativePath = getRelativePath(target);
contentInclude.setAttribute("Include", relativePath); //$NON-NLS-1$
return contentInclude;
}
private Element getDependetUpon(String fullPath) {
Element dependUpon = getDocument().createElement("DependentUpon");
IPath path = new Path(fullPath);
String fileName = path.lastSegment();
fileName = fileName.substring(0, fileName.indexOf(DOT_CS));
dependUpon.setTextContent(fileName);
return dependUpon;
}
private String getRelativePath(File target) {
IPath targetPath = new Path(target.getAbsolutePath());
IPath rootPath = new Path(rootFolder.getAbsolutePath());
targetPath = targetPath.makeRelativeTo(rootPath);
return targetPath.toString().replace('/', '\\');
}
}
| true
|
44af20e43464f2f6ed071048dcdbb840cfef1358
|
Java
|
okou19900722/databasefx
|
/database/src/main/java/com/openjfx/database/base/AbstractDatabaseSource.java
|
UTF-8
| 5,159
| 2.234375
| 2
|
[
"Apache-2.0"
] |
permissive
|
package com.openjfx.database.base;
import com.openjfx.database.DataCharset;
import com.openjfx.database.DataType;
import com.openjfx.database.SQLGenerator;
import com.openjfx.database.common.VertexUtils;
import com.openjfx.database.model.ConnectionParam;
import io.vertx.sqlclient.Pool;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;
/**
* Database connection pool superclass
*
* @author yangkui
* @since 1.0
*/
public abstract class AbstractDatabaseSource {
/**
* Database connection pool cache map
*/
protected ConcurrentHashMap<String, AbstractDataBasePool> pools = new ConcurrentHashMap<>();
/**
* Heartbeat ID
*/
protected Long timerId;
/**
* data charset
*/
protected DataCharset charset;
/**
* current database support data type
*/
protected DataType dataType;
/**
* current database local sql generator
*/
protected SQLGenerator generator;
/**
* Get database connection pool according to UUID
*
* @param uuid uuid
* @return Back to database connection pool
*/
public AbstractDataBasePool getDataBaseSource(String uuid) {
Objects.requireNonNull(uuid);
return pools.get(uuid);
}
/**
* New database connection pool
*
* @param params Connection parameters
* @return Return to pool
*/
public abstract AbstractDataBasePool createPool(ConnectionParam params);
/**
* Create database connection pool
*
* @param param Create database connection pool connection parameters
* @param uuid Connection identification
* @param initPoolSize Initialize dimensions
* @return Back to connection pool
*/
public abstract AbstractDataBasePool createPool(ConnectionParam param, String uuid, String database, int initPoolSize);
/**
* Create database connection pool
*
* @param param connection param
* @param uuid Connection identification
* @param initPoolSize Initialize dimensions
* @return Back to connection pool
*/
public abstract AbstractDataBasePool createPool(ConnectionParam param, String uuid, int initPoolSize);
/**
* Close a connection pool
*
* @param uuid uuid
*/
public void close(String uuid) {
var pool = pools.get(uuid);
if (pool == null) {
return;
}
pool.close();
//Move out of database connection cache
pools.remove(uuid);
var param = pool.getConnectionParam();
System.out.println(
"================Connection pool is closed===============\r\n" +
"uuid:" + param.getUuid() + "\r\n" +
"connection name:" + param.getName() + "\r\n" +
"host:" + param.getHost() + "\r\n" +
"========================================================");
}
/**
* close resource
*/
public void closeAll() {
pools.forEach((uuid, pool) -> close(uuid));
//close timer
if (timerId != null) {
VertexUtils.getVertex().cancelTimer(timerId);
}
}
/**
* Prevent the database server from losing response without interaction for a long time
*/
public abstract void heartBeat();
/**
* create pool after must check current pool can use,else call {@link Pool#close()}
* close current database source pool
*
* @param pool wait test database pool
* @param param connection param
*/
protected void _createPool(AbstractDataBasePool pool, ConnectionParam param) {
pool.setConnectionParam(param);
//Make sure the link is available before joining the cache
var fut = pool.getDql().heartBeatQuery();
fut.onSuccess(r -> {
pools.put(param.getUuid(), pool);
System.out.println(
"================Connection pool was created===============\r\n" +
"uuid:" + param.getUuid() + "\r\n" +
"connection name:" + param.getName() + "\r\n" +
"host:" + param.getHost() + "\r\n" +
"========================================================="
);
});
fut.onFailure(t -> {
pool.close();
System.out.println(
"================Connection pool create failed===============\r\n" +
"uuid:" + param.getUuid() + "\r\n" +
"connection name:" + param.getName() + "\r\n" +
"host:" + param.getHost() + "\r\n" +
"failed cause:" + t.getMessage() + "\r\n" +
"========================================================="
);
});
}
public DataCharset getCharset() {
return charset;
}
public DataType getDataType() {
return dataType;
}
public SQLGenerator getGenerator() {
return generator;
}
}
| true
|
a4fb15f03357a1f78be924db1da40f68ff168579
|
Java
|
Himmele/My-Blog-Repository
|
/Algorithms and Data Structures/LinkedList/src/LinkedListExample1.java
|
UTF-8
| 1,780
| 3.5625
| 4
|
[] |
no_license
|
public class LinkedListExample1 {
static class Message {
Message(int id) {
mId = id;
}
public String toString() {
return String.valueOf(mId);
}
private int mId;
public Message mNextMessage;
}
static class MessageQueue {
public void enqueueMessage(Message message) {
Message curMessage = mHeadMessage;
if (curMessage == null) {
message.mNextMessage = curMessage;
mHeadMessage = message;
} else {
Message prevMessage = null;
while (curMessage != null) {
prevMessage = curMessage;
curMessage = curMessage.mNextMessage;
}
message.mNextMessage = prevMessage.mNextMessage;
prevMessage.mNextMessage = message;
}
}
public Message dequeueMessage() {
Message message = mHeadMessage;
if (message != null) {
mHeadMessage = message.mNextMessage;
}
return message;
}
private Message mHeadMessage;
}
public static void main(String[] args) {
LinkedList<Integer> ll = new LinkedList<Integer>();
ll.put(4);
ll.put(3);
ll.put(2);
ll.put(1);
System.out.println(ll.take());
System.out.println(ll.take());
System.out.println(ll.take());
System.out.println(ll.take());
System.out.println(ll.take());
MessageQueue mq = new MessageQueue();
mq.enqueueMessage(new Message(1));
mq.enqueueMessage(new Message(2));
mq.enqueueMessage(new Message(3));
mq.enqueueMessage(new Message(4));
System.out.println(mq.dequeueMessage());
System.out.println(mq.dequeueMessage());
System.out.println(mq.dequeueMessage());
System.out.println(mq.dequeueMessage());
System.out.println(mq.dequeueMessage());
}
}
| true
|
5a10758958eb1fbf8f8e5322d989c345955e9f1a
|
Java
|
meta-pranjal-agrawal/software_fundamentals
|
/assignment_3/Stringoperations/src/StringOperations.java
|
UTF-8
| 3,558
| 3.765625
| 4
|
[] |
no_license
|
import java.util.Scanner;
public class StringOperations
{
/**
*
* @param first string s1
* @param first string s2
* @return 1 if both strings are equals and 0 if unequal
*/
public int comparision(String s1,String s2)
{
char c1[]= new char[s1.length()];
char c2[]= new char[s2.length()];
c1=s1.toCharArray();
c2=s2.toCharArray();
if(c1.length==c2.length)
{
int flag=0;
for(int i=0;i<c1.length;i++)
{
if(c1[i]!=c2[i])
{
flag=1;
return 0;
}
}
if(flag==0)
{
return 1;
}
}
else
{
return 0;
}
return 0;
}
/**
*
* @param String s1 which is to be reversed
* @return reversed string
*/
public String stringReversal(String s1)
{
char c1[]= new char[s1.length()];
char c2[]= new char[s1.length()];
c1=s1.toCharArray();
int j=0;
for(int i=s1.length()-1;i>=0;i--)
{
c2[j]=c1[i];
j++;
}
String Srev=new String(c2);
return Srev;
}
/**
*
* @param string str whose case is to be changed
* @return string with uppercase converted to lower and lowercase to upper
*/
public String changeCase(String str)
{
char s[]= new char[str.length()];
s=str.toCharArray();
for(int i=0;i<s.length;i++)
{
int ascii=(int) s[i];
if(ascii>='a' && ascii <='z')
{
char c= (char) (s[i]-32);
s[i]=c;
}
else if(ascii>='A' && ascii <='Z')
{
char c=(char) (s[i]+32);
s[i]=c;
}
else
{
char c=(char)(s[i]);
s[i]=c;
}
}
String caseconvertedstring=new String(s);
return caseconvertedstring;
}
/**
*
* @param sentence
* @return largest word in the sentence
*/
public String findLongestWord(String sentence)
{
String Schar[]= new String[100];
Schar=sentence.split(" ");
int max=Schar[0].length();
String longest="";
for(int i=0;i<Schar.length;i++)
{
if(max<=Schar[i].length())
{
longest=Schar[i];
max=Schar[i].length();
}
}
return longest;
}
public static void main(String[] args)
{
Scanner sc= new Scanner(System.in);
System.out.println("Enter 2 strings");
String s1;
String s2;
try
{
s1= sc.nextLine();
s2= sc.nextLine();
}
catch(Exception e)
{
System.out.println("please enter correct input and try again");
s1="";
s2="";
System.exit(0);
}
StringOperations stringoperations= new StringOperations();
//calls the comparison method
int result=stringoperations.comparision(s1, s2);
if(result==1)
{
System.out.println("Strings are equal");
}
else
{
System.out.println("String are not equal");
}
//calls the stringReversal method
String Srev= stringoperations.stringReversal(s1);
System.out.println("first string when reversed becomes "+Srev);
//calls the changeCase method
System.out.println("enter the string to change cases");
String str;
try
{
str= sc.nextLine();
}
catch(Exception e)
{
System.out.println("please enter correct input");
str="";
System.exit(0);
}
//calls the case conversion method
String caseconvertedstring=stringoperations.changeCase(str);
System.out.println(caseconvertedstring);
System.out.println("Enter a sentence");
String sentence;
try
{
sentence= sc.nextLine();
}
catch(Exception e)
{
System.out.println("Incorrect input");
sentence="";
System.exit(0);
}
// calls the find longest word method
String longestword=stringoperations.findLongestWord(sentence);
System.out.println(longestword);
}
}
| true
|
fdb73765ef297fc5c45344e455a4f186fdc2cdf2
|
Java
|
rakeshgn31/Distributed-systems-Kompics
|
/Code/DistributedKVStore/src/main/java/DataStoreNode/Node.java
|
UTF-8
| 5,033
| 2.265625
| 2
|
[] |
no_license
|
/*
* Welcome to NetBeans...!!!
*/
package DataStoreNode;
import DKVNetwork.DKVAddress;
import DKVNetwork.DKVMessage;
import DKVUtilities.OperationsHelper;
import Operations.CASRequest;
import Operations.GetRequest;
import Operations.GetResponse;
import Operations.HeartbeatRequest;
import Operations.HeartbeatResponse;
import Operations.JoinApprove;
import Operations.JoinRequest;
import Operations.PutRequest;
import Operations.PutResponse;
import java.util.ArrayList;
import java.util.HashMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import se.sics.kompics.ClassMatchedHandler;
import se.sics.kompics.ComponentDefinition;
import se.sics.kompics.Handler;
import se.sics.kompics.Positive;
import se.sics.kompics.Start;
import se.sics.kompics.network.Network;
import se.sics.kompics.network.Transport;
import se.sics.kompics.timer.Timer;
/**
*
* @author admin
*/
public class Node extends ComponentDefinition {
private static final Logger LOG = LoggerFactory.getLogger(Node.class);
Positive<Network> net = requires(Network.class);
Positive<Timer> timer = requires(Timer.class);
private final DKVAddress selfAddress;
private final DKVAddress trackerAddress;
private int m_nNodeID;
private HashMap<String, ArrayList<String>> m_mapNodeData;
public Node(Init init) {
m_nNodeID = 0;
this.selfAddress = init.self;
this.trackerAddress = init.tracker;
m_mapNodeData = new HashMap<>();
// Subscribe to the required ports
{
subscribe(startHandler, control);
subscribe(joinApprHandler, net);
subscribe(hbReqHandler, net);
subscribe(putReqHandler, net);
subscribe(getReqHandler, net);
}
}
Handler<Start> startHandler = new Handler<Start>() {
@Override
public void handle(Start event) {
LOG.info("Sending JOIN REQ to tracker. Address - " + selfAddress.getIp().toString());
trigger( new DKVMessage(selfAddress, trackerAddress, Transport.TCP, new JoinRequest()), net );
}
};
ClassMatchedHandler<JoinApprove, DKVMessage> joinApprHandler = new ClassMatchedHandler<JoinApprove, DKVMessage>() {
@Override
public void handle(JoinApprove content, DKVMessage context) {
m_nNodeID = content.nNodeID;
LOG.info("JOIN Request Approved. Assigned ID - " + m_nNodeID);
}
};
ClassMatchedHandler<HeartbeatRequest, DKVMessage> hbReqHandler = new ClassMatchedHandler<HeartbeatRequest, DKVMessage>() {
@Override
public void handle(HeartbeatRequest req, DKVMessage msg) {
LOG.info("Received Heartbeat request from tracker");
trigger( new DKVMessage(selfAddress, trackerAddress, Transport.TCP,
new HeartbeatResponse(m_nNodeID)), net );
}
};
ClassMatchedHandler<PutRequest, DKVMessage> putReqHandler = new ClassMatchedHandler<PutRequest, DKVMessage>() {
@Override
public void handle(PutRequest req, DKVMessage msg) {
LOG.info("Received PUT Request to store Key: " + req.Key);
try {
// Check if the key already exists and then add/update accordingly
m_mapNodeData.put(req.Key, req.listValues);
trigger( new DKVMessage(selfAddress, trackerAddress, Transport.TCP, new PutResponse(
req.RequestID, req.Key, OperationsHelper.OperationExitCode.OP_SUCCESS)), net );
} catch(Exception ex) {
trigger( new DKVMessage(selfAddress, trackerAddress, Transport.TCP, new PutResponse(
req.RequestID, req.Key, OperationsHelper.OperationExitCode.OP_EXCEPTION)), net);
}
}
};
ClassMatchedHandler<GetRequest, DKVMessage> getReqHandler = new ClassMatchedHandler<GetRequest, DKVMessage>() {
@Override
public void handle(GetRequest req, DKVMessage msg) {
LOG.info("Received GET Request to retrieve Key: " + req.Key);
if(m_mapNodeData.containsKey(req.Key)) {
trigger( new DKVMessage(selfAddress, trackerAddress, Transport.TCP, new GetResponse(
req.RequestID, req.Key, m_mapNodeData.get(req.Key),
OperationsHelper.OperationExitCode.OP_SUCCESS)), net);
}
}
};
ClassMatchedHandler<CASRequest, DKVMessage> casReqHandler = new ClassMatchedHandler<CASRequest, DKVMessage>() {
@Override
public void handle(CASRequest v, DKVMessage e) {
// trigger
}
};
public static class Init extends se.sics.kompics.Init<Node> {
public final DKVAddress self;
public final DKVAddress tracker;
public Init(DKVAddress self, DKVAddress tracker) {
this.self = self;
this.tracker = tracker;
}
}
}
| true
|
0eaacb9b4f154c18f2dfc6080c10e3efaa8995f8
|
Java
|
erlv/googlemapshack
|
/app/src/main/java/com/geovictoria/supervisor/Helper/DateHelper.java
|
UTF-8
| 693
| 2.609375
| 3
|
[] |
no_license
|
package com.geovictoria.supervisor.Helper;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
/**
* Created by Maximiliano on 6/25/2015.
*/
public class DateHelper {
static SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
public static Date parseFromServer(String dateString) throws ParseException {
return format.parse(dateString);
}
public static String formatDate(Date date){
String dateString = format.format(date);
return dateString;
}
public static String formatCalendar(Calendar calendar){
return formatDate(calendar.getTime());
}
}
| true
|
cd45bb8e2ab78927f6bff07c4f7ebe29b0d243f6
|
Java
|
yinxianren/flightreservation
|
/src/main/java/com/yilvtong/first/flightreservation/entity/frontdesk/LoginLog.java
|
UTF-8
| 342
| 1.617188
| 2
|
[] |
no_license
|
package com.yilvtong.first.flightreservation.entity.frontdesk;
import com.yilvtong.first.flightreservation.entity.EntityModule;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
@Getter
@Setter
@NoArgsConstructor
public class LoginLog extends EntityModule{
private String account;
private String ipAddr;
}
| true
|
bc89421104ad5ca3d4b8efef95af41772d45ae59
|
Java
|
sarathkaleswaram/java-projectmatrix-portfolio
|
/com/projectMatrix/model/JobStage.java
|
UTF-8
| 1,289
| 2.03125
| 2
|
[] |
no_license
|
package com.projectMatrix.model;
// Generated Jul 23, 2017 3:14:16 PM by Hibernate Tools 4.0.0
import java.util.HashSet;
import java.util.Set;
/**
* JobStage generated by hbm2java
*/
public class JobStage implements java.io.Serializable {
private Long jobStageId;
private Job job;
private Integer hoursSpent;
private String jobStatus;
private Set uomStoreds = new HashSet(0);
public JobStage() {
}
public JobStage(Job job, Integer hoursSpent, String jobStatus,
Set uomStoreds) {
this.job = job;
this.hoursSpent = hoursSpent;
this.jobStatus = jobStatus;
this.uomStoreds = uomStoreds;
}
public Long getJobStageId() {
return this.jobStageId;
}
public void setJobStageId(Long jobStageId) {
this.jobStageId = jobStageId;
}
public Job getJob() {
return this.job;
}
public void setJob(Job job) {
this.job = job;
}
public Integer getHoursSpent() {
return this.hoursSpent;
}
public void setHoursSpent(Integer hoursSpent) {
this.hoursSpent = hoursSpent;
}
public String getJobStatus() {
return this.jobStatus;
}
public void setJobStatus(String jobStatus) {
this.jobStatus = jobStatus;
}
public Set getUomStoreds() {
return this.uomStoreds;
}
public void setUomStoreds(Set uomStoreds) {
this.uomStoreds = uomStoreds;
}
}
| true
|
7260bcbf547cde01b401b439f4b0ff968383f934
|
Java
|
zhuwx2018/wx201801
|
/wx201801/src/main/java/com/wx/dao/WxproCartMapper.java
|
UTF-8
| 1,368
| 1.835938
| 2
|
[] |
no_license
|
package com.wx.dao;
import com.wx.model.WxproCart;
import com.wx.model.WxproCartExample;
import java.util.List;
import org.apache.ibatis.annotations.Param;
public interface WxproCartMapper {
int countByExample(WxproCartExample example);
int deleteByExample(WxproCartExample example);
int deleteByPrimaryKey(Integer id);
int insert(WxproCart record);
int insertSelective(WxproCart record);
List<WxproCart> selectByExample(WxproCartExample example);
WxproCart selectByPrimaryKey(Integer id);
int updateByExampleSelective(@Param("record") WxproCart record, @Param("example") WxproCartExample example);
int updateByExample(@Param("record") WxproCart record, @Param("example") WxproCartExample example);
int updateByPrimaryKeySelective(WxproCart record);
int updateByPrimaryKey(WxproCart record);
WxproCart selectCartByUserIdProductId(@Param("userId")Integer userId,@Param("productId") Integer productId);
List<WxproCart> selectCartByUserId(Integer userId);
int deleteByUserIdProductId(@Param("userId")Integer userId, @Param("productId")Integer productId);
int deleteByUserIdProductIds(@Param("userId")Integer userId, @Param("productIdlist")List<String> productIdlist);
int updateByUserId4Checked(@Param("userId")Integer userId, @Param("checked")Integer checked,@Param("productId")Integer productId);
}
| true
|
cb512d546aed63141c00ad36550c6fbd7103009b
|
Java
|
andykeem/nyc_school
|
/NYCSchoolApp/app/src/main/java/com/example/andyk/nycschoolapp/helper/SchoolDetailFetcher.java
|
UTF-8
| 2,286
| 2.796875
| 3
|
[] |
no_license
|
package com.example.andyk.nycschoolapp.helper;
import android.util.Log;
import com.example.andyk.nycschoolapp.model.SchoolDetail;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;
/**
* class that fetchs school detail information. most likely school SAT scores which makes the request
* to "https://data.cityofnewyork.us/resource/97mf-9njv.json". Once response is back we parse the
* JSON and stores its data to SchoolDetail object and sends to UI.
*/
public class SchoolDetailFetcher extends HttpRequest {
protected static final String TAG = SchoolDetailFetcher.class.getSimpleName();
protected static final String PARAM_DETAIL_KEY = "dbn";
protected String mPath = "resource/734v-jeq5.json";
protected String getPath() {
return mPath;
}
public SchoolDetail getDetailByDbn(String dbn) {
this.setParam(PARAM_DETAIL_KEY, dbn);
String url = this.getRequestUrl();
String resp = this.getUrlString(url);
SchoolDetail detail = this.getSchoolDetail(resp);
return detail;
}
/**
* parses JSON response and stores its data to SchoolDetail object
* @param resp
* @return
*/
protected SchoolDetail getSchoolDetail(String resp) {
try {
JSONArray arr = (JSONArray) new JSONTokener(resp).nextValue();
int numItems = arr.length();
for (int i = 0; i < numItems; i++) {
JSONObject json = (JSONObject) arr.get(i);
if (json != null) {
SchoolDetail detail = new SchoolDetail();
detail.setDbn(json.getString("dbn"));
detail.setNumSatTakers(json.getString("num_of_sat_test_takers"));
detail.setSatReading(json.getString("sat_critical_reading_avg_score"));
detail.setSatMath(json.getString("sat_math_avg_score"));
detail.setSatWriting(json.getString("sat_writing_avg_score"));
detail.setName(json.getString("school_name"));
return detail;
}
}
} catch (JSONException je) {
Log.e(TAG, je.getMessage(), je);
}
return null;
}
}
| true
|
fdca09feaee50a1c43ba4443b75133de5852e9df
|
Java
|
Kuangcp/JavaBase
|
/gui/src/main/java/com/github/kuangcp/notepad/handler/FileHandler.java
|
UTF-8
| 3,301
| 2.734375
| 3
|
[
"MIT"
] |
permissive
|
package com.github.kuangcp.notepad.handler;
import com.github.kuangcp.io.ResourceTool;
import com.github.kuangcp.notepad.Note;
import com.github.kuangcp.notepad.base.ActionCommand;
import java.awt.event.ActionEvent;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Objects;
import java.util.Optional;
import javax.swing.JFileChooser;
import lombok.extern.slf4j.Slf4j;
/**
* @author https://github.com/kuangcp on 2019-07-28 13:10
*/
@Slf4j
class FileHandler extends BaseHandler {
private String currentPath;
@Override
void handle(ActionEvent event) {
switch (event.getActionCommand()) {
case ActionCommand.OPEN_FILE:
openFile();
break;
case ActionCommand.SAVE_FILE:
saveFile();
break;
case ActionCommand.SAVE_AS_FILE:
saveAsFile();
break;
default:
log.info("not supported command");
break;
}
}
private void openFile() {
//推荐JFileChooser 组件
JFileChooser jc = new JFileChooser();
//设置名字
jc.setDialogTitle("Please select file...");
//默认方式
jc.showOpenDialog(null);
jc.setVisible(true);
//得知道用户选择的文件 绝对路径
File selectedFile = jc.getSelectedFile();
if (Objects.isNull(selectedFile)) {
log.warn("not select any file");
return;
}
String filePath = selectedFile.getAbsolutePath();
currentPath = filePath;
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader(filePath));
//从文件读取信息显示到jta
String s;
StringBuilder result = new StringBuilder();
while ((s = br.readLine()) != null) {
result.append(s).append("\n");
}
//输出到 textArea
Note.textArea.setText(result.toString());
} catch (Exception e) {
log.error(e.getMessage(), e);
} finally {
try {
ResourceTool.close(br);
} catch (IOException e) {
log.error(e.getMessage(), e);
}
}
}
private void saveFile() {
if (Objects.isNull(currentPath)) {
log.warn("not open any file");
Optional<String> pathOpt = saveAsFile();
pathOpt.ifPresent(v -> currentPath = v);
return;
}
try (BufferedWriter bw = new BufferedWriter(new FileWriter(currentPath))) {
bw.write(Note.textArea.getText());
} catch (Exception e) {
log.error(e.getMessage(), e);
}
}
private Optional<String> saveAsFile() {
JFileChooser chooser = new JFileChooser();
chooser.setDialogTitle("Save as ");
//按默认方式显示
chooser.showSaveDialog(null);
chooser.setVisible(true);
//得到用户希望把文件保存到何处
File file = chooser.getSelectedFile();
if (Objects.isNull(file)) {
log.warn("please select file: chooser={}", chooser);
return Optional.empty();
}
//准备写入到指定目录下
String path = file.getAbsolutePath();
try (BufferedWriter bw = new BufferedWriter(new FileWriter(path))) {
bw.write(Note.textArea.getText());
} catch (Exception e) {
log.error(e.getMessage(), e);
}
return Optional.of(path);
}
}
| true
|
b6727d2bc92f90ca07bd9370555ea8a549631681
|
Java
|
oyghdit/MyCookBook
|
/app/src/main/java/com/study/mycookbook/category/CategoryDaoImpl.java
|
UTF-8
| 1,109
| 2.171875
| 2
|
[] |
no_license
|
package com.study.mycookbook.category;
import android.content.Context;
import android.util.Log;
import com.android.volley.VolleyError;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.study.mycookbook.category.beans.Category;
import com.study.mycookbook.networking.MyVolley;
import org.json.JSONException;
public class CategoryDaoImpl implements CategoryDao, MyVolley.CallBack {
CategoryDaoListener listener;
@Override
public void getCategory(Context ctx, CategoryDaoListener listener) {
this.listener = listener;
String url = "http://apis.juhe.cn/cook/category?key=338c432f0e92e2357d57ea78e907cb29";
MyVolley myVolley = MyVolley.newMyVolley();
myVolley.stringRequestGet(ctx,url,this);
}
@Override
public void onStringSuccess(String response) throws JSONException {
Gson gson = new Gson();
Category c = gson.fromJson(response,new TypeToken<Category>(){}.getType());
listener.onSuccess(c);
}
@Override
public void onFailure(VolleyError error) {
listener.onFail();
}
}
| true
|
d64e061e8f4b75cb96ab0ce7e2976a2d07b18033
|
Java
|
espinard/gourmet
|
/src/com/gourmet/adapters/RestaurantAdapter.java
|
UTF-8
| 1,567
| 2.53125
| 3
|
[] |
no_license
|
package com.gourmet.adapters;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import com.gourmet.R;
import com.gourmet.model.Restaurant;
public class RestaurantAdapter extends ArrayAdapter<Restaurant> {
private Context context;
private int layoutResId;
Restaurant [] restaurants;
public RestaurantAdapter(Context context, int layoutResourceId, Restaurant[] dataRest) {
super(context, layoutResourceId, dataRest);
this.context = context;
this.layoutResId = layoutResourceId;
this.restaurants = dataRest;
}
/* (non-Javadoc)
* @see android.widget.ArrayAdapter#getView(int, android.view.View, android.view.ViewGroup)
*/
@Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) this.context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflater.inflate(this.layoutResId, parent, false);
TextView nameView = (TextView) rowView.findViewById(R.id.rest_name);
TextView descrView = (TextView) rowView.findViewById(R.id.rest_description);
TextView localityView = (TextView) rowView.findViewById(R.id.rest_locality);
nameView.setText(this.restaurants[position].getName());
descrView.setText(this.restaurants[position].getFoodType());
localityView.setText("Location: " + this.restaurants[position].getLocality());
return rowView;
}
}
| true
|
1b4b7a7c1ff0de1dd5319e1992895cc8842a2560
|
Java
|
rench/orm-querydsl
|
/src/main/java/com/lowang/ormquerydsl/AiChat.java
|
UTF-8
| 623
| 2.515625
| 3
|
[] |
no_license
|
package com.lowang.ormquerydsl;
import java.util.Scanner;
/**
* Ai智能对话核心代码,估值上亿
* @author wang.ch
* @date 2018-12-13 16:59:37
*/
public class AiChat {
public static void main(String[] args) {
try (Scanner sc = new Scanner(System.in); ) {
String input;
while (true) {
input = sc.next();
input = input
.replace("你能", "我能")
.replace("了吗", "")
.replace("吗", "")
.replace("?", "!")
.replace("?", "!")
.replace("? ", "!");
System.out.println(input);
}
}
}
}
| true
|
b25bdb873ff373847c519e834a399598f4d66c03
|
Java
|
PaniAnnie/QA7NewMavenTest
|
/src/test/java/ru/stqa/selenium/pages/LoginPageHelper.java
|
UTF-8
| 3,074
| 2.4375
| 2
|
[] |
no_license
|
package ru.stqa.selenium.pages;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
public class LoginPageHelper extends PageBase {
@FindBy(id = "user")
WebElement loginField;
@FindBy(id = "password")
WebElement passwordField;
@FindBy(id = "login")
WebElement loginButton;
@FindBy(id = "error")
WebElement errorMessage;
@FindBy(xpath = "//div[@id='password-error']//p[@class='error-message']")
WebElement errorLoginMessage;
@FindBy (xpath = "//div[@role='alert']")
WebElement errorMessageAtl;
@FindBy (id = "login-submit")
WebElement loginButtonAtl;
@FindBy (xpath = "//input[@value='Войти с помощью Atlassian']")
//(xpath = "//input[@value='Log in with Atlassian']")
WebElement loginUserAtl;
public LoginPageHelper(WebDriver driver){
super(driver);
this.driver = driver;
}
public LoginPageHelper loginNotAtlassianUser(String login, String password) {
loginNotAtlassianUsername(login);
enterPassword(password);
pressLoginButton();
return this;
}
public LoginPageHelper loginAtlassianUser(String login, String password) {
loginAtlassianUsername(login);
loginUserAsAtlassian();
enterPassword(password);
pressAtlassianLoginButton();
return this;
}
public LoginPageHelper waitUntilPageIsLoaded() {
waitUntilElementIsClickable(loginField, 15);
waitUntilElementIsClickable(passwordField, 15);
waitUntilElementIsClickable(loginButton, 10);
return this;
}
public LoginPageHelper loginNotAtlassianUsername(String login) {
editField(loginField, login);
return this;
}
public LoginPageHelper loginAtlassianUsername(String login) {
editField(loginField, login);
return this;
}
public LoginPageHelper enterPassword(String password) {
waitUntilElementIsClickable(passwordField, 15);
editField(passwordField, password);
return this;
}
public LoginPageHelper pressLoginButton() {
waitUntilElementIsClickable(loginButton, 15);
loginButton.click();
return this;
}
public LoginPageHelper loginUserAsAtlassian() {
waitUntilElementIsClickable(loginUserAtl, 10);
loginUserAtl.click();
return this;
}
public LoginPageHelper pressAtlassianLoginButton() {
waitUntilElementIsClickable(loginButtonAtl, 10);
loginButtonAtl.click();
return this;
}
public String getErrorMessage(){
waitUntilElementIsClickable(errorMessage, 10);
return errorMessage.getText();
}
public String getWrongLoginErrorMessage(){
waitUntilElementIsClickable(errorLoginMessage, 20);
return errorLoginMessage.getText();
}
public String getAtlassianErrorMessage(){
waitUntilElementIsClickable(errorMessageAtl, 20);
return errorMessageAtl.getText();
}
}
| true
|
981bd6d08dbf3df5e4f5d53a429f0b8c874d29a2
|
Java
|
weiqiangzheng/fresco
|
/drawee-backends/drawee-pipeline/src/main/java/com/facebook/drawee/backends/pipeline/info/internal/ImagePerfControllerListener.java
|
UTF-8
| 2,522
| 1.804688
| 2
|
[
"MIT"
] |
permissive
|
/*
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
package com.facebook.drawee.backends.pipeline.info.internal;
import android.graphics.drawable.Animatable;
import com.facebook.common.time.MonotonicClock;
import com.facebook.drawee.backends.pipeline.info.ImageLoadStatus;
import com.facebook.drawee.backends.pipeline.info.ImagePerfMonitor;
import com.facebook.drawee.backends.pipeline.info.ImagePerfState;
import com.facebook.drawee.controller.BaseControllerListener;
import com.facebook.imagepipeline.image.ImageInfo;
import javax.annotation.Nullable;
public class ImagePerfControllerListener extends BaseControllerListener<ImageInfo> {
private final MonotonicClock mClock;
private final ImagePerfState mImagePerfState;
private final ImagePerfMonitor mImagePerfMonitor;
public ImagePerfControllerListener(
MonotonicClock clock, ImagePerfState imagePerfState, ImagePerfMonitor imagePerfMonitor) {
mClock = clock;
mImagePerfState = imagePerfState;
mImagePerfMonitor = imagePerfMonitor;
}
@Override
public void onSubmit(String id, Object callerContext) {
mImagePerfState.setControllerSubmitTimeMs(mClock.now());
mImagePerfState.setRequestId(id);
mImagePerfState.setCallerContext(callerContext);
mImagePerfMonitor.notifyListeners(mImagePerfState, ImageLoadStatus.REQUESTED);
}
@Override
public void onIntermediateImageSet(String id, @Nullable ImageInfo imageInfo) {
mImagePerfState.setControllerIntermediateImageSetTimeMs(mClock.now());
mImagePerfState.setRequestId(id);
mImagePerfState.setImageInfo(imageInfo);
mImagePerfMonitor.notifyListeners(mImagePerfState, ImageLoadStatus.INTERMEDIATE_AVAILABLE);
}
@Override
public void onFinalImageSet(
String id, @Nullable ImageInfo imageInfo, @Nullable Animatable animatable) {
mImagePerfState.setControllerFinalImageSetTimeMs(mClock.now());
mImagePerfState.setRequestId(id);
mImagePerfState.setImageInfo(imageInfo);
mImagePerfState.setSuccessful(true);
mImagePerfMonitor.notifyListeners(mImagePerfState, ImageLoadStatus.SUCCESS);
}
@Override
public void onFailure(String id, Throwable throwable) {
mImagePerfState.setControllerFailureTimeMs(mClock.now());
mImagePerfState.setRequestId(id);
mImagePerfState.setSuccessful(false);
mImagePerfMonitor.notifyListeners(mImagePerfState, ImageLoadStatus.ERROR);
}
}
| true
|
20f7ad9a71355018a12162ff283758b0e6f4fc76
|
Java
|
JasonLeeKing/sample_xutils_framework
|
/src/com/lidroid/xutils/sample/GroupThereActivity.java
|
UTF-8
| 6,787
| 1.9375
| 2
|
[] |
no_license
|
package com.lidroid.xutils.sample;
import java.util.ArrayList;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.format.DateUtils;
import android.view.View;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.alibaba.fastjson.JSON;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnLastItemVisibleListener;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener;
import com.lidroid.xutils.BaseActivity;
import com.lidroid.xutils.bean.ResearchBean;
import com.lidroid.xutils.config.AppContext;
import com.lidroid.xutils.custom.textview.JustifyTextView;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;
import com.lidroid.xutils.list.XListView;
import com.lidroid.xutils.simple.basead.apter.SimpleBaseAdapter;
import com.lidroid.xutils.util.LogUtils;
public class GroupThereActivity extends BaseActivity {
private PullToRefreshListView xListView_reseash;
private TextView add_research;
public List<ResearchBean> resList=new ArrayList<ResearchBean>();
private MyResearchAdaper adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentLayout(R.layout.activity_group_there);
hideTitleView();
initView();
http_get_research();
}
private Handler handler=new Handler(){
public void handleMessage(android.os.Message msg) {
switch (msg.what) {
case 0:
@SuppressWarnings("unchecked")
ArrayList<ResearchBean> researchBeans=(ArrayList<ResearchBean>) msg.obj;
if(researchBeans!=null&&researchBeans.size()>0){
resList.clear();
resList.addAll(researchBeans);
}
if(adapter==null){
adapter=new MyResearchAdaper(getApplicationContext(), resList);
}
xListView_reseash.setAdapter(adapter);
break;
case 1:
showToast("删除成功");
http_get_research();
break;
case 2:
showToast("删除失败");
break;
case 3:
break;
default:
break;
}
};
};
public void initView(){
xListView_reseash=(PullToRefreshListView)findViewById(R.id.researchs_lv_data);
xListView_reseash.setOnRefreshListener(new OnRefreshListener<ListView>() {
@Override
public void onRefresh(PullToRefreshBase<ListView> refreshView) {
String label = DateUtils.formatDateTime(getApplicationContext(), System.currentTimeMillis(),
DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_ABBREV_ALL);
// Update the LastUpdatedLabel
refreshView.getLoadingLayoutProxy().setLastUpdatedLabel(label);
// Do work to refresh the list here.
}
});
// Add an end-of-list listener
xListView_reseash.setOnLastItemVisibleListener(new OnLastItemVisibleListener() {
@Override
public void onLastItemVisible() {
Toast.makeText(GroupThereActivity.this, "End of List!", Toast.LENGTH_SHORT).show();
}
});
add_research=(TextView) findViewById(R.id.add_research);
}
private class MyResearchAdaper extends SimpleBaseAdapter<ResearchBean>{
public MyResearchAdaper(Context context, List<ResearchBean> data) {
super(context, data);
}
@Override
public int getItemResource() {
return R.layout.xlist_view_reseach;
}
@Override
public View getItemView(int position,View convertView,ViewHolder holder) {
JustifyTextView research_name = holder.getView(R.id.research_name);
JustifyTextView research_patient_count = holder.getView(R.id.research_patient_count);
research_name.setText(resList.get(position).getName());
research_patient_count.setText(resList.get(position).getPatient_count()+"");
return convertView;
}
}
public void http_get_research(){
RequestParams params=new RequestParams();
params.addBodyParameter("remember_token", AppContext.REMEMBER_TOKEN);
params.addBodyParameter("version",AppContext.version);
params.addBodyParameter("sys",AppContext.sys);
httpUtils.send(HttpMethod.GET, AppContext.BASE_URL+AppContext.DOCROT_RESEARCH, params, new RequestCallBack<String>() {
public void onLoading(long total, long current, boolean isUploading) {
}
@Override
public void onSuccess(ResponseInfo<String> responseInfo) {
String doctor_patients=responseInfo.result;
JSONObject jsonObject;
ArrayList<ResearchBean> researchBeans=new ArrayList<ResearchBean>();
try {
jsonObject = new JSONObject(doctor_patients);
if (jsonObject.optBoolean("success")){
JSONArray jsonArray = jsonObject.getJSONArray("data");
for(int i=0; i<jsonArray.length(); i++){
ResearchBean researchBean =JSON.parseObject(jsonArray.getJSONObject(i).toString(),
ResearchBean.class);
researchBeans.add(researchBean);
}
Message msg=new Message();
msg.what=0;
msg.obj=researchBeans;
handler.sendMessage(msg);
}
} catch (JSONException e) {
e.printStackTrace();
}
LogUtils.e(doctor_patients);
}
@Override
public void onFailure(HttpException error, String msg) {
}
});
}
public void delete_research(String research_id){
RequestParams params=new RequestParams();
params.addBodyParameter("remember_token", AppContext.REMEMBER_TOKEN);
params.addBodyParameter("version",AppContext.version);
params.addBodyParameter("sys",AppContext.sys);
params.addBodyParameter("id",research_id);
httpUtils.send(HttpMethod.POST, AppContext.BASE_URL+AppContext.DOCTOR_RESEARCH_DELETE, params, new RequestCallBack<String>() {
public void onLoading(long total, long current, boolean isUploading) {
}
@Override
public void onSuccess(ResponseInfo<String> responseInfo) {
String doctor_patients=responseInfo.result;
JSONObject jsonObject;
ArrayList<ResearchBean> researchBeans=new ArrayList<ResearchBean>();
try {
jsonObject = new JSONObject(doctor_patients);
Message msg=new Message();
if (jsonObject.optBoolean("success")){
msg.what=1;
}else{
msg.what=2;
}
handler.sendMessage(msg);
} catch (JSONException e) {
e.printStackTrace();
}
LogUtils.e(doctor_patients);
}
@Override
public void onFailure(HttpException error, String msg) {
}
});
}
}
| true
|
8f0be3131c2cee82d30fd4d055f019a9625c6395
|
Java
|
jamo/tmc-core
|
/src/test/java/hy/tmc/core/updates/ReviewHandlerTest.java
|
UTF-8
| 2,634
| 2.5
| 2
|
[] |
no_license
|
package hy.tmc.core.updates;
import hy.tmc.core.communication.TmcJsonParser;
import hy.tmc.core.communication.updates.ReviewHandler;
import hy.tmc.core.domain.Course;
import hy.tmc.core.domain.Review;
import hy.tmc.core.testhelpers.builders.ReviewListBuilder;
import java.io.IOException;
import java.util.List;
import org.junit.After;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.mockito.Matchers.anyString;
import static org.mockito.Matchers.eq;
import org.mockito.Mockito;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
public class ReviewHandlerTest {
private ReviewHandler handler;
private TmcJsonParser tmcJsonParser;
@Before
public void setUp() throws IOException {
tmcJsonParser = Mockito.mock(TmcJsonParser.class);
handler = new ReviewHandler(tmcJsonParser);
Mockito.when(tmcJsonParser.getReviews(anyString()))
.thenReturn(
new ReviewListBuilder()
.withExercise(3, true)
.withExercise(123, false)
.withExercise(52, false)
.build()
);
}
@After
public void tearDown() {
}
@Test
public void fetchReviewReturnsEmptyListIfServerSendsNull() throws IOException {
Mockito.when(tmcJsonParser.getReviews(anyString())).thenReturn(null);
assertNotNull(handler.fetchFromServer(new Course()));
assertEquals(0, handler.fetchFromServer(new Course()).size());
}
@Test
public void reviewsFetchedFromCorrectUrl() throws Exception {
String url = "www.tmc.mooc.fi.duck/reviews";
Course course = new Course();
course.setReviewsUrl(url);
handler.getNewObjects(course);
tmcJsonParser.getReviews(Mockito.eq(url));
}
@Test
public void returnsOnlyUnreadReviews() throws Exception {
List<Review> reviews = handler.getNewObjects(new Course());
assertTrue(listHasReview(reviews, 123));
assertTrue(listHasReview(reviews, 52));
assertFalse(listHasReview(reviews, 3));
}
private boolean listHasReview(List<Review> reviews, int id) {
for (Review review : reviews) {
if (review.getId() == id) {
return true;
}
}
return false;
}
}
| true
|
51bbe8311b84bd136fa00ef9388c72784bb97a3f
|
Java
|
sean220/ssdev-rpc
|
/src/main/java/ctd/net/rpc/transport/http/codec/ByteToHttpRequestEncoder.java
|
UTF-8
| 871
| 2.28125
| 2
|
[] |
no_license
|
package ctd.net.rpc.transport.http.codec;
import java.util.List;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToMessageEncoder;
import io.netty.handler.codec.http.DefaultFullHttpRequest;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.HttpHeaders;
import io.netty.handler.codec.http.HttpMethod;
import io.netty.handler.codec.http.HttpVersion;
public class ByteToHttpRequestEncoder extends MessageToMessageEncoder<ByteBuf> {
@Override
protected void encode(ChannelHandlerContext ctx, ByteBuf msg,List<Object> out) throws Exception {
FullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1,HttpMethod.POST,"/",msg);
request.headers().set(HttpHeaders.Names.CONTENT_LENGTH,msg.readableBytes());
out.add(request);
msg.retain();
}
}
| true
|
a1fab8599ccf19e3f28fa231e4f5e1499c81d78b
|
Java
|
rahul189git/send_secure
|
/app/src/main/java/com/pb/riskanalysisforsmb/georisk/tasks/CSVBatchWritingTask.java
|
UTF-8
| 6,004
| 2.21875
| 2
|
[] |
no_license
|
package com.pb.riskanalysisforsmb.georisk.tasks;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.TaskStackBuilder;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Environment;
import com.pb.riskanalysisforsmb.R;
import com.pb.riskanalysisforsmb.activity.CSVFileSelectActivity;
import com.pb.riskanalysisforsmb.activity.NotificationActivity;
import com.pb.riskanalysisforsmb.csv.utils.CSVWriter;
import com.pb.riskanalysisforsmb.risk.type.CrimeRisk;
import java.io.InputStream;
import java.util.List;
import static com.pb.riskanalysisforsmb.csv.utils.CSVWriter.getAddressesWithScores;
public class CSVBatchWritingTask extends AsyncTask<InputStream, Integer, List<CrimeRisk>> {
private static final int NOTIFICATION_ID = 1;
private Context context;
// private ProgressDialog progressDialog;
private String outputFilePath;
public CSVBatchWritingTask(Context context) {
this.context = context;
// progressDialog = new ProgressDialog(context);
}
@Override
protected void onPreExecute() {
/* Called before task execution; from UI thread, so you can access your widgets */
super.onPreExecute();
/* progressDialog.setMessage("Calculating Risk for addresses...");
progressDialog.setIndeterminate(false);
progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progressDialog.setCancelable(false);
progressDialog.show();*/
}
@Override
protected List doInBackground(InputStream... inputStream) {
List<CrimeRisk> addressList = getAddressesWithScores(inputStream[0]);
return addressList;
}
@Override
protected void onPostExecute(List<CrimeRisk> addressList) {
super.onPostExecute(addressList);
if (isExternalStorageWritable()) {
outputFilePath = CSVWriter.writeCsvFile(addressList);
}
// progressDialog.dismiss();
createNotification(context, addressList);
//Toast.makeText(context, "Risk has been calculated", Toast.LENGTH_SHORT).show();
}
/* Checks if external storage is available for read and write */
private boolean isExternalStorageWritable() {
String state = Environment.getExternalStorageState();
return Environment.MEDIA_MOUNTED.equals(state);
}
/* Checks if external storage is available to at least read */
public boolean isExternalStorageReadable() {
String state = Environment.getExternalStorageState();
return Environment.MEDIA_MOUNTED.equals(state) || Environment.MEDIA_MOUNTED_READ_ONLY.equals(state);
}
private void createNotification(Context context, List<CrimeRisk> addressList) {
//Log.d("createNotification", "title is [" + contentTitle +"]");
NotificationManager nm = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
//Build the notification using Notification.Builder
Notification.Builder builder = new Notification.Builder(context)
.setSmallIcon(R.mipmap.ic_launcher)
.setAutoCancel(true)
.setContentTitle("Risk result")
.setContentText("Risk analysis is complete.");
int counter = 0;
int lowCrimeCount = 0, moderateCrimeCount = 0, highCrimeCount = 0;
int weatherRiskCount = 0;
for (CrimeRisk crimeRisk : addressList) {
if (crimeRisk != null) {
String riskSeverity = crimeRisk.getRiskSeverity();
if ("High".equalsIgnoreCase(riskSeverity)) {
highCrimeCount++;
}
if ("Moderate".equalsIgnoreCase(riskSeverity)) {
moderateCrimeCount++;
}
if ("Low".equalsIgnoreCase(riskSeverity)) {
lowCrimeCount++;
}
}
boolean isExtremeWeatherRequired = (counter% 3 == 0);
if (isExtremeWeatherRequired) {
weatherRiskCount++;
}
counter++;
//Not Needed
//WeatherVO weatherDetails = MockWeatherAPI.getWeatherDetails(crimeRisk.getAddressVO(), isExtremeWeatherRequired);
}
int totalCount = addressList != null ? addressList.size() : 0;
// Creates an explicit intent for an Activity in your app
Intent resultIntent = new Intent(context, NotificationActivity.class);
resultIntent.putExtra("HIGH_RISK_PERCENT", totalCount != 0 ? String.valueOf((highCrimeCount * 100 / totalCount)) : 0 + "%");
resultIntent.putExtra("MODERATE_RISK_PERCENT", totalCount != 0 ? String.valueOf((moderateCrimeCount * 100 / totalCount)) : 0 + "%");
resultIntent.putExtra("LOW_RISK_PERCENT", totalCount != 0 ? String.valueOf((lowCrimeCount * 100 / totalCount)) : 0 + "%");
resultIntent.putExtra("WEATHER_RISK_PERCENT", totalCount != 0 ? String.valueOf((weatherRiskCount * 100 / totalCount)) : 0 + "%");
resultIntent.putExtra("OUTPUT_FILE_PATH", outputFilePath);
// The stack builder object will contain an artificial back stack for the
// started Activity.This ensures that navigating backward from the Activity leads out of
// your app to the Home screen.
TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
// Adds the back stack for the Intent (but not the Intent itself)
stackBuilder.addParentStack(CSVFileSelectActivity.class);
// Adds the Intent that starts the Activity to the top of the stack
stackBuilder.addNextIntent(resultIntent);
PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
builder.setContentIntent(resultPendingIntent);
//Show the notification
nm.notify(NOTIFICATION_ID, builder.build());
}
}
| true
|
8ddfc2567910332cdb974a7c7a281b4971b1d618
|
Java
|
kevenLeandro/jornada-dev-eficiente
|
/mercado-livre/src/main/java/io/tacsio/mercadolivre/config/security/AuthenticationService.java
|
UTF-8
| 841
| 2.203125
| 2
|
[
"MIT"
] |
permissive
|
package io.tacsio.mercadolivre.config.security;
import io.tacsio.mercadolivre.data.UserRepository;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
@Service
public class AuthenticationService implements UserDetailsService {
private final UserRepository repository;
public AuthenticationService(UserRepository repository) {
this.repository = repository;
}
@Override
public UserDetails loadUserByUsername(String login) throws UsernameNotFoundException {
return repository.findByLogin(login)
.orElseThrow(() -> new UsernameNotFoundException("User not found."));
}
}
| true
|
0f3a7aece38102bf2fdc727e7f2f2d1ed7c11c1a
|
Java
|
Interrupt/delverengine
|
/Dungeoneer/src/com/interrupt/dungeoneer/overlays/OptionsKeysOverlay.java
|
UTF-8
| 9,316
| 1.90625
| 2
|
[
"Zlib",
"LicenseRef-scancode-free-unknown",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
package com.interrupt.dungeoneer.overlays;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Input;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.scenes.scene2d.Actor;
import com.badlogic.gdx.scenes.scene2d.InputEvent;
import com.badlogic.gdx.scenes.scene2d.InputListener;
import com.badlogic.gdx.scenes.scene2d.ui.Cell;
import com.badlogic.gdx.scenes.scene2d.ui.Label;
import com.badlogic.gdx.scenes.scene2d.ui.Table;
import com.badlogic.gdx.scenes.scene2d.ui.TextButton;
import com.badlogic.gdx.scenes.scene2d.utils.ClickListener;
import com.badlogic.gdx.utils.Align;
import com.badlogic.gdx.utils.Array;
import com.badlogic.gdx.utils.ArrayMap;
import com.interrupt.dungeoneer.Audio;
import com.interrupt.dungeoneer.game.Colors;
import com.interrupt.dungeoneer.game.Game;
import com.interrupt.dungeoneer.game.GameData;
import com.interrupt.dungeoneer.game.Options;
import com.interrupt.dungeoneer.input.Actions;
import com.interrupt.dungeoneer.input.ReadableKeys;
import com.interrupt.dungeoneer.ui.UiSkin;
import com.interrupt.managers.StringManager;
import com.interrupt.utils.JsonUtil;
import java.text.MessageFormat;
public class OptionsKeysOverlay extends WindowOverlay {
private Table content = new Table();
private Table mainTable;
private Table changeKeyTable;
private ArrayMap<Integer, Actions.Action> existingActions = new ArrayMap<Integer, Actions.Action>();
boolean ignoreEscape = false;
public OptionsKeysOverlay() {
animateBackground = false;
}
public OptionsKeysOverlay(boolean dimScreen, boolean showBackground)
{
animateBackground = false;
this.dimScreen = dimScreen;
this.showBackground = showBackground;
}
@Override
public Table makeContent() {
// check if the Jump option should be enabled
try {
GameData gameData = JsonUtil.fromJson(GameData.class, Game.findInternalFileInMods("data/game.dat"));
if (gameData != null && gameData.playerJumpEnabled) {
if (!Actions.keyOrder.contains(Actions.Action.JUMP, false)) {
Actions.keyOrder.add(Actions.Action.JUMP);
}
}
}
catch(Exception ex) {
Gdx.app.log("KeysOverlay", ex.getMessage());
}
setupTable();
return content;
}
public void setupTable() {
changeKeyTable = null;
buttonOrder.clear();
buttonLabels.clear();
existingActions.clear();
lastGamepadSelectionIndex = null;
mainTable = new Table();
mainTable.setFillParent(true);
Label header = new Label(StringManager.get("screens.OptionsKeysScreen.keyboardControlsLabel"),skin.get(Label.LabelStyle.class));
header.setFontScale(1.1f);
mainTable.add(header);
mainTable.row();
for(final Actions.Action action : Actions.keyOrder) {
Integer keyBinding = Actions.keyBindings.get(action);
if(keyBinding != null)
existingActions.put(keyBinding, action);
final String readableAction = "screens.OptionsScreen.readableActions." + action.toString().replace('_', ' ');
final Table t = new Table(UiSkin.getSkin());
t.setBackground("table-no-hover");
t.addListener(new ClickListener() {
@Override
public void clicked(InputEvent event, float x, float y) {
changeKey(readableAction, action);
Audio.playSound("/ui/ui_button_click.mp3", 0.1f);
}
@Override
public void enter(InputEvent event, float x, float y, int pointer, Actor fromActor) {
t.setBackground("table-hover");
}
@Override
public void exit(InputEvent event, float x, float y, int pointer, Actor toActor) {
t.setBackground("table-no-hover");
}
});
float rowHeight = 11;
Label label = new Label(StringManager.get(readableAction) + " ", skin.get(Label.LabelStyle.class));
label.setFontScale(0.8f);
t.add(label).height(rowHeight).width(100);
String labelText = null;
if(keyBinding != null && keyBinding != -1) {
labelText = ReadableKeys.keyNames.get(keyBinding);
}
if(labelText == null)
labelText = "";
final Label setKeyButton = new Label(labelText, skin.get(Label.LabelStyle.class));
setKeyButton.setColor(new Color(Colors.PARALYZE));
setKeyButton.setFontScale(0.8f);
t.add(setKeyButton).height(rowHeight).width(100);
t.pack();
addGamepadButtonOrder(t, null);
mainTable.add(t).fillX().height(rowHeight);
mainTable.row();
}
TextButton backBtn = new TextButton(StringManager.get("screens.OptionsKeysScreen.backButton"), skin.get(TextButton.TextButtonStyle.class));
backBtn.setWidth(200);
backBtn.setHeight(50);
backBtn.addListener(new ClickListener() {
@Override
public void clicked(InputEvent event, float x, float y) {
saveAndClose();
}
});
mainTable.add(backBtn);
// Left align everything
Array<Cell> cells = mainTable.getCells();
for(Cell c : cells) {
c.align(Align.left);
}
mainTable.getCell(backBtn).padTop(4);
mainTable.getCell(header).align(Align.center).padBottom(4);
content.clear();
content.add(mainTable);
mainTable.pack();
content.pack();
buttonOrder.add(backBtn);
}
public void tick(float delta) {
// back
if(Gdx.input.isKeyJustPressed(Input.Keys.ESCAPE) || Gdx.input.isKeyJustPressed(Input.Keys.BACK)) {
if(!ignoreEscape) {
if (changeKeyTable == null) {
saveAndClose();
} else {
setupTable();
}
}
}
super.tick(delta);
ignoreEscape = false;
}
public int getKeyBinding(Actions.Action action) {
Integer f = Actions.keyBindings.get(action);
return f != null ? f : -1;
}
@Override
public void back() {
saveAndClose();
}
public void saveAndClose() {
Options.instance.key_use = getKeyBinding(Actions.Action.USE);
Options.instance.key_attack = getKeyBinding(Actions.Action.ATTACK);
Options.instance.key_forward = getKeyBinding(Actions.Action.FORWARD);
Options.instance.key_backward = getKeyBinding(Actions.Action.BACKWARD);
Options.instance.key_strafe_left = getKeyBinding(Actions.Action.STRAFE_LEFT);
Options.instance.key_strafe_right = getKeyBinding(Actions.Action.STRAFE_RIGHT);
Options.instance.key_map = getKeyBinding(Actions.Action.MAP);
Options.instance.key_inventory = getKeyBinding(Actions.Action.INVENTORY);
Options.instance.key_next_item = getKeyBinding(Actions.Action.ITEM_NEXT);
Options.instance.key_previous_item = getKeyBinding(Actions.Action.ITEM_PREVIOUS);
Options.instance.key_drop = getKeyBinding(Actions.Action.DROP);
Options.instance.key_look_up = getKeyBinding(Actions.Action.LOOK_UP);
Options.instance.key_look_down = getKeyBinding(Actions.Action.LOOK_DOWN);
Options.instance.key_turn_left = getKeyBinding(Actions.Action.TURN_LEFT);
Options.instance.key_turn_right = getKeyBinding(Actions.Action.TURN_RIGHT);
Options.instance.key_jump = getKeyBinding(Actions.Action.JUMP);
Options.saveOptions();
OverlayManager.instance.replaceCurrent(new OptionsInputOverlay(dimScreen, showBackground));
}
public void changeKey(final String readableAction, final Actions.Action action) {
content.clear();
changeKeyTable = new Table();
String localizedReadableAction = StringManager.get(readableAction);
String localizedKeyPrompt = MessageFormat.format(StringManager.get("screens.OptionsKeysScreen.pressKeyLabel"), localizedReadableAction);
changeKeyTable.add(new Label(localizedKeyPrompt, skin.get(Label.LabelStyle.class))).padBottom(4f);
changeKeyTable.row();
changeKeyTable.add(new Label(StringManager.get("screens.OptionsKeysScreen.pressEscToCancelLabel"),skin.get(Label.LabelStyle.class)));
changeKeyTable.row();
content.add(changeKeyTable);
content.pack();
ui.addListener(new InputListener() {
public boolean keyDown(InputEvent event, int keycode) {
if (keycode != Input.Keys.BACK && keycode != Input.Keys.ESCAPE) {
if(existingActions.containsKey(keycode)) {
Actions.Action existing = existingActions.get(keycode);
Actions.keyBindings.remove(existing);
}
Actions.keyBindings.put(action, keycode);
}
setupTable();
ui.removeListener(this);
ignoreEscape = true;
return true;
}
});
}
}
| true
|
4df13af183497552917546ecd1629bebb1120134
|
Java
|
UnitecSPS/Programacion2_1_1_2012
|
/src/programacion2_1_1_2012/Sortea.java
|
UTF-8
| 534
| 2.6875
| 3
|
[] |
no_license
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package programacion2_1_1_2012;
import java.util.Random;
/**
*
* @author Gotcha
*/
public class Sortea {
public static void main(String args[]){
Random m = new Random();
//g1 = canamel
//g2 = danny
//g3 = oscarmon
//g4 = marariel
//g5 = denwill
System.out.println("EXPO " + (m.nextInt(5)));
System.out.println("1 oro extra " + (m.nextInt(5)));
}
}
| true
|
769b06212957869fe3969035cb4a463c2ac9263c
|
Java
|
bellmit/YttxPS
|
/YttxPS/src/com/yttx/yttxps/mapper/TRouteArrangeMapper.java
|
UTF-8
| 4,100
| 1.640625
| 2
|
[] |
no_license
|
package com.yttx.yttxps.mapper;
import java.util.List;
import java.util.Map;
import org.apache.ibatis.annotations.Param;
import com.yttx.yttxps.model.RouteCCType;
import com.yttx.yttxps.model.TRouteArrange;
import com.yttx.yttxps.model.TRouteArrangeExample;
import com.yttx.yttxps.model.TRouteArrangeWithBLOBs;
import com.yttx.yttxps.model.VResSnapshot;
public interface TRouteArrangeMapper<T> extends IBaseMapper<T> {
/**
* This method was generated by MyBatis Generator. This method corresponds to the database table TROUTEARRANGE
* @mbggenerated Thu Feb 04 10:26:31 CST 2016
*/
int countByExample(TRouteArrangeExample example);
/**
* This method was generated by MyBatis Generator. This method corresponds to the database table TROUTEARRANGE
* @mbggenerated Thu Feb 04 10:26:31 CST 2016
*/
int deleteByExample(TRouteArrangeExample example);
/**
* This method was generated by MyBatis Generator. This method corresponds to the database table TROUTEARRANGE
* @mbggenerated Thu Feb 04 10:26:31 CST 2016
*/
int deleteByPrimaryKey(String fsId);
/**
* This method was generated by MyBatis Generator. This method corresponds to the database table TROUTEARRANGE
* @mbggenerated Thu Feb 04 10:26:31 CST 2016
*/
int insert(TRouteArrangeWithBLOBs record);
/**
* This method was generated by MyBatis Generator. This method corresponds to the database table TROUTEARRANGE
* @mbggenerated Thu Feb 04 10:26:31 CST 2016
*/
int insertSelective(TRouteArrangeWithBLOBs record);
/**
* This method was generated by MyBatis Generator. This method corresponds to the database table TROUTEARRANGE
* @mbggenerated Thu Feb 04 10:26:31 CST 2016
*/
List<TRouteArrangeWithBLOBs> selectByExampleWithBLOBs(
TRouteArrangeExample example);
/**
* This method was generated by MyBatis Generator. This method corresponds to the database table TROUTEARRANGE
* @mbggenerated Thu Feb 04 10:26:31 CST 2016
*/
List<TRouteArrange> selectByExample(TRouteArrangeExample example);
/**
* This method was generated by MyBatis Generator. This method corresponds to the database table TROUTEARRANGE
* @mbggenerated Thu Feb 04 10:26:31 CST 2016
*/
TRouteArrangeWithBLOBs selectByPrimaryKey(String fsId);
/**
* This method was generated by MyBatis Generator. This method corresponds to the database table TROUTEARRANGE
* @mbggenerated Thu Feb 04 10:26:31 CST 2016
*/
int updateByExampleSelective(
@Param("record") TRouteArrangeWithBLOBs record,
@Param("example") TRouteArrangeExample example);
/**
* This method was generated by MyBatis Generator. This method corresponds to the database table TROUTEARRANGE
* @mbggenerated Thu Feb 04 10:26:31 CST 2016
*/
int updateByExampleWithBLOBs(
@Param("record") TRouteArrangeWithBLOBs record,
@Param("example") TRouteArrangeExample example);
/**
* This method was generated by MyBatis Generator. This method corresponds to the database table TROUTEARRANGE
* @mbggenerated Thu Feb 04 10:26:31 CST 2016
*/
int updateByExample(@Param("record") TRouteArrange record,
@Param("example") TRouteArrangeExample example);
/**
* This method was generated by MyBatis Generator. This method corresponds to the database table TROUTEARRANGE
* @mbggenerated Thu Feb 04 10:26:31 CST 2016
*/
int updateByPrimaryKeySelective(TRouteArrangeWithBLOBs record);
/**
* This method was generated by MyBatis Generator. This method corresponds to the database table TROUTEARRANGE
* @mbggenerated Thu Feb 04 10:26:31 CST 2016
*/
int updateByPrimaryKeyWithBLOBs(TRouteArrangeWithBLOBs record);
/**
* This method was generated by MyBatis Generator. This method corresponds to the database table TROUTEARRANGE
* @mbggenerated Thu Feb 04 10:26:31 CST 2016
*/
int updateByPrimaryKey(TRouteArrange record);
List<RouteCCType> selectRouteCCType(Map<String, Object> map);
List<VResSnapshot> selectRessnapshot(Map<String, Object> map);
/**
* @author marongcai
* 查询线路报价
*/
List<Map<String,Object>> selectCost(Map<String,String> map);
int selectFsId();
}
| true
|
9b33527aa9ff106a7d4777bcb09382a3a90d377b
|
Java
|
isseu/jmonkeyengine
|
/jme3-core/src/main/java/com/jme3/texture/image/ImageRasterFactory.java
|
UTF-8
| 1,947
| 3.296875
| 3
|
[
"BSD-3-Clause"
] |
permissive
|
package com.jme3.texture.image;
import com.jme3.texture.Image;
public class ImageRasterFactory {
/**
* Create new image reader / writer.
*
* @param image The image to read / write to.
* @param slice Which slice to use. Only applies to 3D images, 2D image
* arrays or cubemaps.
* @param mipMapLevel The mipmap level to read / write to. To access levels
* other than 0, the image must have
* {@link Image#setMipMapSizes(int[]) mipmap sizes} set.
* @param convertToLinear If true, the application expects read or written
* colors to be in linear color space (<code>ImageRaster</code> will
* automatically perform a conversion as needed). If false, the application expects
* colors to be in the image's native {@link Image#getColorSpace() color space}.
* @return An ImageRaster to read / write to the image.
*/
public static ImageRaster create(Image image, int slice, int mipMapLevel, boolean convertToLinear) {
return new DefaultImageRaster(image, slice, mipMapLevel, convertToLinear);
}
/**
* Create new image reader / writer.
*
* @param image The image to read / write to.
* @param slice Which slice to use. Only applies to 3D images, 2D image
* arrays or cubemaps.
* @return An ImageRaster to read / write to the image.
*/
public static ImageRaster create(Image image, int slice) {
return create(image, slice, 0, false);
}
/**
* Create new image reader / writer for 2D images.
*
* @param image The image to read / write to.
* @return An ImageRaster to read / write to the image.
*/
public static ImageRaster create(Image image) {
if (image.getData().size() > 1) {
throw new IllegalStateException("Use constructor that takes slices argument to read from multislice image");
}
return create(image, 0, 0, false);
}
}
| true
|
1061f97d6543f2c323d63ca021d037e2c42b7f71
|
Java
|
franzlpz/exchange-rate-quarkus
|
/src/main/java/ni/org/jug/exchangerate/boundary/CentralBankExchangeRateResource.java
|
UTF-8
| 2,354
| 2.3125
| 2
|
[] |
no_license
|
package ni.org.jug.exchangerate.boundary;
import ni.org.jug.exchangerate.entity.CentralBankExchangeRate;
import javax.ws.rs.DefaultValue;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import java.time.LocalDate;
import java.time.YearMonth;
/**
* @author aalaniz
*/
@Path("/api/centralBankExchangeRates")
@Produces(MediaType.APPLICATION_JSON)
public class CentralBankExchangeRateResource {
@GET
public ResponseAsCollection findAll() {
return new ResponseAsCollection(CentralBankExchangeRate.listAll());
}
@GET
@Path("/{year:\\d+}-{month:\\d+}-{day:\\d+}")
public CentralBankExchangeRate findById(@PathParam("year") int year, @PathParam("month") int month, @PathParam("day") int day) {
return CentralBankExchangeRate.findById(year, month, day);
}
@GET
@Path("/today")
public CentralBankExchangeRate today() {
return CentralBankExchangeRate.findById(LocalDate.now());
}
@GET
@Path("/id")
public ResponseAsCollection findByIdBetween(@QueryParam("start") @DefaultValue("today") LocalDate start,
@QueryParam("end") @DefaultValue("today") LocalDate end) {
return new ResponseAsCollection(CentralBankExchangeRate.findByIdBetween(start, end));
}
@GET
@Path("/{year:\\d+}-{month:\\d+}")
public ResponseAsCollection findByPeriod(@PathParam("year") int year, @PathParam("month") int month) {
return new ResponseAsCollection(CentralBankExchangeRate.findByPeriod(year, month));
}
@GET
@Path("/period")
public ResponseAsCollection findByPeriodBetween(@QueryParam("start") @DefaultValue("today") LocalDate start,
@QueryParam("end") @DefaultValue("today") LocalDate end) {
return new ResponseAsCollection(CentralBankExchangeRate.findByPeriodBetween(start, end));
}
@GET
@Path("/period/current")
public ResponseAsCollection findByCurrentPeriod() {
return new ResponseAsCollection(CentralBankExchangeRate.findByPeriod(YearMonth.now()));
}
@GET
@Path("/period/next")
public ResponseAsCollection findByNextPeriod() {
return new ResponseAsCollection(CentralBankExchangeRate.findByPeriod(YearMonth.now().plusMonths(1)));
}
}
| true
|
bcd9a46e81fb7b3814bb23034cd41bed653d2c88
|
Java
|
enthyp/survey-app
|
/app/src/main/java/com/hfad/survey/data/db/entity/AnswerEntity.java
|
UTF-8
| 1,460
| 2.359375
| 2
|
[] |
no_license
|
package com.hfad.survey.data.db.entity;
import android.arch.persistence.room.ColumnInfo;
import android.arch.persistence.room.Entity;
import android.arch.persistence.room.ForeignKey;
import android.arch.persistence.room.Index;
import android.arch.persistence.room.PrimaryKey;
/**
* Created by jlanecki on 07.02.18.
*/
@Entity(tableName = "answers",
foreignKeys = {
@ForeignKey(entity = QuestionEntity.class,
parentColumns = "id",
childColumns = "question_id",
onDelete = ForeignKey.CASCADE)},
indices = {@Index(value = "question_id")
})
public class AnswerEntity {
@PrimaryKey(autoGenerate = true)
private int id;
@ColumnInfo(name = "question_id")
private long questionId;
@ColumnInfo(name = "content")
private String content;
public AnswerEntity() {}
public AnswerEntity(long questionId, String content) {
this.questionId = questionId;
this.content = content;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public long getQuestionId() {
return questionId;
}
public void setQuestionId(long questionId) {
this.questionId = questionId;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
}
| true
|
9d99806ceb7ce4af2e966ba5467f4561df7198d6
|
Java
|
Sheba1990/CVdatabase
|
/src/main/java/com/cvdatabase/project/api/services/ICVService.java
|
UTF-8
| 911
| 2.125
| 2
|
[] |
no_license
|
package com.cvdatabase.project.api.services;
import com.cvdatabase.project.dto.CVDto;
import com.cvdatabase.project.dto.ContactDataDto;
import com.cvdatabase.project.dto.PersonDto;
import com.cvdatabase.project.dto.TechnologyDto;
import java.util.List;
public interface ICVService {
public List<CVDto> getAllCVs();
CVDto addCV(CVDto cvDto, PersonDto personDto, ContactDataDto contactDataDto, int[] technologies);
CVDto getCVbyId(long id);
public List<CVDto> getByTechnologyName(String name);
public List<CVDto> getCVByPersonFirstName(String firstName);
public List<CVDto> getCVByPersonLastName(String lastName);
public List<CVDto> getCVByPersonFullName(String firstName, String lastName);
void updateCV(long id, CVDto cvDto, PersonDto personDto, ContactDataDto contactDataDto);
void deleteCV(long id);
public CVDto addPersonToCV(long personId, long cvId);
}
| true
|
91f8c4ab4a23bf75e995e39e1c335a08f21f6a93
|
Java
|
justincook951/mobile-app-c196
|
/app/src/main/java/com/example/c196project/database/assessment/AssessmentEntity.java
|
UTF-8
| 2,207
| 2.421875
| 2
|
[] |
no_license
|
package com.example.c196project.database.assessment;
import androidx.room.Entity;
import androidx.room.Ignore;
import androidx.room.PrimaryKey;
import java.util.Date;
@Entity(tableName = "assessment")
public class AssessmentEntity
{
@PrimaryKey(autoGenerate = true)
private int id;
private String title, assessmentType;
private Date endDate;
private int courseId;
@Ignore
public AssessmentEntity() {
}
public AssessmentEntity(int id, String title, Date endDate, int courseId, String assessmentType)
{
this.id = id;
this.title = title;
this.endDate = endDate;
this.courseId = courseId;
this.assessmentType = assessmentType;
}
@Ignore
public AssessmentEntity(String title, Date endDate, int courseId, String assessmentType)
{
this.title = title;
this.endDate = endDate;
this.courseId = courseId;
this.assessmentType = assessmentType;
}
@Ignore
public AssessmentEntity(String title, Date endDate) {
this.title = title;
this.endDate = endDate;
this.courseId = 0;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public int getCourseId()
{
return courseId;
}
public void setCourseId(int courseId)
{
this.courseId = courseId;
}
public Date getEndDate() {
return endDate;
}
public void setEndDate(Date endDate) {
this.endDate = endDate;
}
public String getAssessmentType()
{
return assessmentType;
}
public void setAssessmentType(String assessmentType)
{
this.assessmentType = assessmentType;
}
@Override
public String toString()
{
return "CourseEntity{" +
"id=" + id +
", title='" + title + '\'' +
", endDate=" + endDate +
", courseId=" + courseId +
", assessmentType=" + assessmentType +
'}';
}
}
| true
|
27cf4aea15035ddee3507d4f314eecba79fbe7ff
|
Java
|
knalli/visualdependencies
|
/vdb-release-2009/trunk/src/main/java/de/unibonn/inf/dbdependenciesui/ui/views/common/graph/renderer/DatabaseObjectComponent.java
|
UTF-8
| 24,733
| 1.796875
| 2
|
[] |
no_license
|
package de.unibonn.inf.dbdependenciesui.ui.views.common.graph.renderer;
import java.awt.AlphaComposite;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Composite;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GradientPaint;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.RenderingHints;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Observable;
import javax.swing.BorderFactory;
import javax.swing.ButtonGroup;
import javax.swing.Icon;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JLayeredPane;
import javax.swing.JPanel;
import javax.swing.JTable;
import javax.swing.JToggleButton;
import javax.swing.SwingConstants;
import javax.swing.border.Border;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;
import de.unibonn.inf.dbdependenciesui.hibernate.models.DatabaseObject;
import de.unibonn.inf.dbdependenciesui.hibernate.models.DatabaseProcedure;
import de.unibonn.inf.dbdependenciesui.hibernate.models.DatabaseTable;
import de.unibonn.inf.dbdependenciesui.hibernate.models.DatabaseTrigger;
import de.unibonn.inf.dbdependenciesui.hibernate.models.DatabaseView;
import de.unibonn.inf.dbdependenciesui.hibernate.models.DatabaseObject.ViewState;
import de.unibonn.inf.dbdependenciesui.hibernate.models.helpers.ProcedureSchema;
import de.unibonn.inf.dbdependenciesui.hibernate.models.helpers.TriggerSchema;
import de.unibonn.inf.dbdependenciesui.misc.Icons;
import de.unibonn.inf.dbdependenciesui.misc.Internationalization;
import de.unibonn.inf.dbdependenciesui.ui.factory.ViewFactory;
/**
* This is the panel compontent for a jung graph visualization. The visual component is a rectangle displaying any type
* of the database models: {@link DatabaseTable}, {@link DatabaseTrigger} and {@link DatabaseView}. The renderer uses a
* slight gradient, the object's title and a type specific main color. Additionally, the component is available to show
* additional information. That is disabled because jung does not support this right now (and in ways of more
* efficiency).
*
* @author Andre Kasper
* @author Jan Philipp
*/
@SuppressWarnings("serial")
public class DatabaseObjectComponent extends JLayeredPane {
protected DatabaseObject userObject = null;
protected JPanel header = null;
protected JPanel headerControls = null;
protected JPanel body = null;
protected JLabel lblTitle;
protected JLabel lblType;
protected String keyIconTable;
protected String keyIconTrigger;
protected String keyIconProcedure;
protected String keyIconView;
protected String keyIconBack;
protected String keyIconInformation;
protected String keyIconData;
protected String keyIconTriggers;
protected String keyIconClose;
protected TranslucentButton btnBack;
protected TranslucentButton btnInformation;
protected TranslucentButton btnData;
protected TranslucentButton btnTriggers;
protected TranslucentButton btnClose;
protected int iconTypeSize;
protected int iconControlSize;
protected int titleSize;
protected int width;
protected int height;
protected int iconPadding;
protected int iconControlsPadding;
protected String tooltipBack;
protected String tooltipInformation;
protected String tooltipData;
protected String tooltipTriggers;
protected String tooltipClose;
protected MyActionListener actionListener;
protected JComponent tableData;
protected JLabel frontLabel;
protected JLabel tableDataPreview;
protected ButtonGroup group;
protected List<String> recursiveTriggers = new ArrayList<String>();
protected final String appKey = "application.graph.hierarchicalview.";
public DatabaseObjectComponent() {
loadIcons();
loadStrings();
initialize();
}
protected void loadIcons() {
keyIconTable = "icons/table.png";
keyIconView = "icons/view.png";
keyIconTrigger = "icons/trigger.png";
keyIconProcedure = "icons/procedure.png";
keyIconBack = "icons/back.png";
keyIconInformation = "icons/info.png";
keyIconData = "icons/txt.png";
keyIconTriggers = "icons/trigger.png";
keyIconClose = "icons/button_cancel.png";
}
protected void loadStrings() {
tooltipBack = "Back";
tooltipInformation = "Information";
tooltipData = "Data";
tooltipTriggers = "Triggers";
tooltipClose = "Close";
}
protected void initialize() {
actionListener = new MyActionListener();
setPreferredSize(new Dimension(100, 30));
this.setSize(new Dimension(100, 30));
setOpaque(true);
setBackground(Color.gray);
this.add(getHeader(), 0);
this.add(getBody(), 0);
// this.add(getHeaderControls(), 1);
}
public DatabaseObject getUserObject() {
return userObject;
}
public void resetUserObject() {
setUserObject(userObject);
}
public void setUserObject(final DatabaseObject obj) {
setUserObject(obj, false);
}
public void setUserObject(final DatabaseObject obj, final boolean picked) {
userObject = obj;
width = (int) getPreferredSize().getWidth();
height = (int) getPreferredSize().getHeight();
// Compute the icon type size which should be 30% of the component's
// height.
iconTypeSize = (int) (height * 0.3);
// Compute the icon controls size which should be 20& of the component's
// height;
iconControlSize = (int) (height * 0.2);
// Compute the font size as fonzt size which should be 40% of the
// component's height.
titleSize = (int) (height * 0.2);
// Compute the icon's border (left/right padding) which should be 10% of
// the component's height.
iconPadding = (int) (height * 0.1);
// Compute the icon's border (left/right padding) which should be 10% of
// the component's height.
iconControlsPadding = (int) (height * 0.05);
Color backgroundColor = null;
String keyIcon = null;
if (isView(obj)) {
backgroundColor = Color.orange;
keyIcon = keyIconView;
if ((headerControls != null) && !btnTriggers.isVisible()) {
group.add(btnTriggers);
btnTriggers.setVisible(true);
}
} else if (isTrigger(obj)) {
if (checkMutatingTable((DatabaseTrigger) obj)) {
backgroundColor = new Color(233, 139, 52); // dark red-orange
} else if (recursiveTriggers.contains(obj.getTitle())) {
backgroundColor = Color.red.brighter().brighter(); // red
} else {
backgroundColor = new Color(108, 197, 69); // green (default trigger)
}
if ((headerControls != null) && btnTriggers.isVisible()) {
group.remove(btnTriggers);
btnTriggers.setVisible(false);
}
keyIcon = keyIconTrigger;
} else if (isTable(obj)) {
backgroundColor = new Color(75, 170, 228); // blue
keyIcon = keyIconTable;
if ((headerControls != null) && !btnTriggers.isVisible()) {
group.add(btnTriggers);
btnTriggers.setVisible(true);
}
} else if (isProcedure(obj)) {
backgroundColor = new Color(180, 20, 180); // violett
keyIcon = keyIconProcedure;
if ((headerControls != null) && !btnTriggers.isVisible()) {
group.add(btnTriggers);
btnTriggers.setVisible(true);
}
} else {
backgroundColor = Color.gray;
keyIcon = null;
if ((headerControls != null) && !btnTriggers.isVisible()) {
group.add(btnTriggers);
btnTriggers.setVisible(true);
}
}
// Make colors brighter if selected/picked.
if (picked) {
backgroundColor = backgroundColor.brighter().brighter();
}
setBackground(backgroundColor);
lblType.setIcon(Icons.getScaledIcon(keyIcon, iconTypeSize));
lblType.setBorder(BorderFactory.createEmptyBorder(0, iconPadding, 0, iconPadding));
if (headerControls != null) {
headerControls.setBorder(BorderFactory.createEmptyBorder(iconControlsPadding, iconControlsPadding,
iconControlsPadding, iconControlsPadding));
final Border border = BorderFactory.createEmptyBorder(0, 0, 0, iconControlsPadding);
btnBack.setIcon(Icons.getScaledIcon(keyIconBack, iconControlSize));
btnBack.setBorder(border);
btnInformation.setIcon(Icons.getScaledIcon(keyIconInformation, iconControlSize));
btnInformation.setBorder(border);
btnData.setIcon(Icons.getScaledIcon(keyIconData, iconControlSize));
btnData.setBorder(border);
btnTriggers.setIcon(Icons.getScaledIcon(keyIconTriggers, iconControlSize));
btnTriggers.setBorder(border);
btnClose.setIcon(Icons.getScaledIcon(keyIconClose, iconControlSize));
}
lblTitle.setText("<html><b>" + obj.getTitle());
if (headerControls != null) {
getBody().removeAll();
switch (obj.getState()) {
case INFORMATION:
if (!btnBack.isVisible()) {
group.add(btnBack);
btnBack.setVisible(true);
}
break;
case DATA:
if (height >= 80) {
getBody().add(this.getTableData(), BorderLayout.CENTER);
} else {
getBody().add(this.getTableDataPreview(), BorderLayout.CENTER);
this.getTableDataPreview().setText(
"<html><center>Please zoom in for a<br/> preview of this object's data.");
}
if (!btnBack.isVisible()) {
group.add(btnBack);
btnBack.setVisible(true);
}
break;
case TRIGGERS:
if (!btnBack.isVisible()) {
group.add(btnBack);
btnBack.setVisible(true);
}
break;
case NORMAL:
getBody().add(getFront(), BorderLayout.CENTER);
if (btnBack.isVisible()) {
group.remove(btnBack);
btnBack.setVisible(false);
}
default:
}
try {
// getBody().updateUI();
} catch (final Throwable e) {}
} else {
if (!Arrays.asList(getComponents()).contains(getFront())) {
getBody().add(getFront(), BorderLayout.CENTER);
}
}
String text = null;
if (isView(userObject)) {
if (((DatabaseView) userObject).isMaterialized()) {
text = Internationalization.getTextFormatted(appKey + "vertex.info.mview", ((DatabaseView) userObject)
.getDdlSchemaObject().getColumns().size());
} else {
text = Internationalization.getTextFormatted(appKey + "vertex.info.view", ((DatabaseView) userObject)
.getDdlSchemaObject().getColumns().size());
}
} else if (isTable(userObject)) {
text = Internationalization.getTextFormatted(appKey + "vertex.info.table", ((DatabaseTable) userObject)
.getDdlSchemaObject().getColumns().size());
} else if (userObject instanceof DatabaseTrigger) {
final TriggerSchema schema = ((DatabaseTrigger) userObject).getTriggerSchemaObject();
if (checkMutatingTable((DatabaseTrigger) userObject)) {
text = Internationalization.getTextFormatted(appKey + "vertex.info.triggermutated", schema
.getTableName());
} else {
text = Internationalization.getTextFormatted(appKey + "vertex.info.trigger", schema.getTableName());
}
} else if (userObject instanceof DatabaseProcedure) {
final ProcedureSchema schema = ((DatabaseProcedure) userObject).getProcedureSchemaObject();
text = schema.getType().equalsIgnoreCase("PROCEDURE") ? Internationalization.getText(appKey
+ "vertex.info.procedure") : Internationalization.getText(appKey + "vertex.info.function");
}
getFront().setText("<html><center>" + text);
recalibrate();
}
protected boolean checkMutatingTable(final DatabaseTrigger trigger) {
final TriggerSchema schema = trigger.getTriggerSchemaObject();
if (schema.isAfterRow()) {
if (schema.getTableName() != null) {
final List<String> affectedTables = schema.getAffectedTables();
final List<String> usedTables = schema.getUsedTables();
if (affectedTables.contains(schema.getTableName()) || usedTables.contains(schema.getTableName())) { return true; }
}
}
return false;
}
public void setRecursiveTrigger(final List<String> triggerName) {
recursiveTriggers = triggerName;
}
protected JLabel getFront() {
if (frontLabel == null) {
frontLabel = new JLabel();
}
return frontLabel;
}
protected JLabel getTableDataPreview() {
return this.getTableDataPreview(true);
}
protected JLabel getTableDataPreview(final boolean force) {
if (tableDataPreview == null) {
tableDataPreview = new JLabel();
}
return tableDataPreview;
}
protected JComponent getTableData() {
return this.getTableData(true);
}
/**
* Create and return a swing component display the table data of this object.
*
* @param force
* if true and already the table exists the swing component will rebuild
* @return
*/
protected JComponent getTableData(final boolean force) {
if (force && (tableData == null)) {
final TableModel model = new DefaultTableModel(new Object[][] {
new Object[] {
1, 2, 3, 4 }, new Object[] {
1, 2, 3, 4 }, new Object[] {
1, 2, 3, 4 }, new Object[] {
1, 2, 3, 4 }, new Object[] {
1, 2, 3, 4 } }, new Object[] {
"Spalte A", "Spalte B", "Spalte 3", "Spalte 4" }) {
@Override
public boolean isCellEditable(final int row, final int column) {
return false;
}
};
final JTable table = ViewFactory.createTable(model);
ViewFactory.makeSortableTable(table);
table.setOpaque(false);
tableData = ViewFactory.createScrollableTable(table);
tableData.setOpaque(false);
}
return tableData;
}
/**
* Create and return a header component.
*
* @return
*/
protected JPanel getHeader() {
if (header == null) {
header = new JPanel();
header.setLayout(new BorderLayout());
header.setOpaque(false);
lblType = new JLabel((Icon) null);
lblTitle = new JLabel("Unknown table name");
header.add(lblType, BorderLayout.WEST);
header.add(lblTitle, BorderLayout.CENTER);
}
return header;
}
/**
* Create and return a body component.
*
* @return
*/
protected JPanel getBody() {
if (body == null) {
body = new JPanel();
body.setLayout(new BorderLayout());
body.setOpaque(false);
}
return body;
}
/**
* Create and return a header controls section component.
*
* @return
*/
protected JPanel getHeaderControls() {
if (headerControls == null) {
headerControls = new JPanel() {
@Override
public void paintComponent(final Graphics g) {
// Set rendering mode using antialiase.
final Graphics2D g2 = (Graphics2D) g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
// Paint a semitransparent (70%) white base "layer". The
// height and width is doubled because the
// rect has round corners.
final Color ppColor = new Color(255, 255, 255, 70);
g2.setColor(ppColor);
final int width = (int) getPreferredSize().getWidth();
final int height = (int) getPreferredSize().getHeight();
final int arc = 4 * iconControlsPadding;
g2.fillRoundRect(0, -height, 2 * width, 2 * height, arc, arc);
// Delegate painting the actual components of the panel.
super.paintComponent(g2);
}
};
headerControls.setLayout(new GridBagLayout());
headerControls.setOpaque(false);
final Border border = BorderFactory.createEmptyBorder();
group = new ButtonGroup();
btnBack = new TranslucentButton((Icon) null);
btnBack.setToolTipText(tooltipBack);
btnBack.setBorder(border);
btnBack.setActionCommand(Command.BACK);
btnBack.addActionListener(actionListener);
group.add(btnBack);
btnInformation = new TranslucentButton((Icon) null);
btnInformation.setToolTipText(tooltipInformation);
btnInformation.setBorder(border);
btnInformation.setActionCommand(Command.INFORMATION);
btnInformation.addActionListener(actionListener);
group.add(btnInformation);
btnData = new TranslucentButton((Icon) null);
btnData.setToolTipText(tooltipData);
btnData.setBorder(border);
btnData.setActionCommand(Command.DATA);
btnData.addActionListener(actionListener);
group.add(btnData);
btnTriggers = new TranslucentButton((Icon) null);
btnTriggers.setToolTipText(tooltipTriggers);
btnTriggers.setBorder(border);
btnTriggers.setActionCommand(Command.TRIGGERS);
btnTriggers.addActionListener(actionListener);
group.add(btnTriggers);
btnClose = new TranslucentButton((Icon) null);
btnClose.setToolTipText(tooltipClose);
btnClose.setBorder(border);
btnClose.setActionCommand(Command.CLOSE);
btnClose.addActionListener(actionListener);
group.add(btnClose);
final GridBagConstraints column1 = new GridBagConstraints();
final GridBagConstraints column2 = new GridBagConstraints();
final GridBagConstraints column3 = new GridBagConstraints();
final GridBagConstraints column4 = new GridBagConstraints();
final GridBagConstraints column5 = new GridBagConstraints();
column1.gridx = 0;
column1.gridy = 0;
column2.gridx = 1;
column2.gridy = 0;
column3.gridx = 2;
column3.gridy = 0;
column4.gridx = 3;
column4.gridy = 0;
column5.gridx = 4;
column5.gridy = 0;
headerControls.add(btnBack, column1);
headerControls.add(btnInformation, column2);
headerControls.add(btnData, column3);
headerControls.add(btnTriggers, column4);
headerControls.add(btnClose, column5);
}
return headerControls;
}
/**
* Recalibrate the swing elements' sizes, locations and orders for the new layout/setup and size of the main window.
*/
protected void recalibrate() {
final int headerHeight = (int) (height * 0.3);
final int bodyHeight = height - headerHeight;
final int bodyX = getBody().getX();
getHeader().setSize(new Dimension(width, headerHeight));
getHeader().setPreferredSize(new Dimension(width, headerHeight));
getBody().setLocation(bodyX, headerHeight);
getBody().setSize(new Dimension(width, bodyHeight));
getBody().setPreferredSize(new Dimension(width, bodyHeight));
if (headerControls != null) {
final int cntIcons = group.getButtonCount();
final int controlsWidth = cntIcons * iconControlSize + (cntIcons + 1) * iconControlsPadding;
final int controlsHeight = iconControlSize + 2 * iconControlsPadding;
getHeaderControls().setSize(new Dimension(controlsWidth, controlsHeight));
final int controlsX = width - controlsWidth;
final int controlsY = getHeaderControls().getY();
getHeaderControls().setLocation(controlsX, controlsY);
switch (userObject.getState()) {
case INFORMATION:
btnInformation.setSelected(true);
break;
case DATA:
btnData.setSelected(true);
break;
case TRIGGERS:
btnTriggers.setSelected(true);
break;
default:
btnInformation.setSelected(false);
btnData.setSelected(false);
btnTriggers.setSelected(false);
btnClose.setSelected(false);
break;
}
}
lblTitle.setFont(new Font("Sans-Serif", Font.PLAIN, titleSize));
if (getFront() != null) {
getFront().setPreferredSize(new Dimension(width, bodyHeight));
getFront().setFont(new Font("Sans-Serif", Font.PLAIN, (int) (titleSize * 0.9)));
getFront().setVerticalAlignment(SwingConstants.TOP);
getFront().setHorizontalAlignment(SwingConstants.CENTER);
getFront().setHorizontalTextPosition(SwingConstants.CENTER);
}
if (headerControls != null) {
if (this.getTableDataPreview(false) != null) {
this.getTableDataPreview().setPreferredSize(new Dimension(width, bodyHeight));
this.getTableDataPreview().setFont(new Font("Sans-Serif", Font.PLAIN, (int) (titleSize * 0.7)));
this.getTableDataPreview().setHorizontalAlignment(SwingConstants.CENTER);
this.getTableDataPreview().setHorizontalTextPosition(SwingConstants.CENTER);
}
}
}
@Override
public void paintComponent(final Graphics g) {
try {
super.paintComponent(g);
final Graphics2D g2d = (Graphics2D) g;
final int w = getWidth();
final int h = getHeight();
final Color color1 = getBackground();
final Color color2 = color1.darker();
// Paint a gradient from top to bottom
final GradientPaint gp = new GradientPaint(0, 0, color1, 0, h, color2);
g2d.setPaint(gp);
g2d.fillRect(0, 0, w, h);
} catch (final Throwable e) {
// Print out the exception, but forget it then.
System.err.println("Just catch an exception: " + e.getLocalizedMessage());
}
}
public String getTitleText() {
return lblTitle.getText();
}
public Observable getObservable() {
return actionListener;
}
/**
* This class is a special variant of a standard Swing {@link JToggleButton}. This button is complete
* transparent/translucent for the given alpha value. Please note the three different possible values for selected,
* normal and disabled.
*/
final public static class TranslucentButton extends JToggleButton {
protected float alpha = 0.7f;
protected float disabledAlpha = 0.2f;
protected float selectedAlpha = 1f;
public TranslucentButton(final Icon image) {
super(image);
}
public void setActionCommand(final Command mode) {
this.setActionCommand(mode.toString());
}
@Override
public void setIcon(final Icon defaultIcon) {
super.setIcon(defaultIcon);
}
public void setAlpha(final float alpha) {
this.alpha = alpha;
}
public void setDisabledAlpha(final float alpha) {
disabledAlpha = alpha;
}
public void setSelectedAlpha(final float alpha) {
selectedAlpha = alpha;
}
@Override
public void paint(final Graphics g) {
try {
float alpha = this.alpha;
if (!isEnabled()) {
alpha = disabledAlpha;
} else if (isSelected()) {
alpha = selectedAlpha;
}
final Graphics2D g2 = (Graphics2D) g;
final Composite oldComposite = g2.getComposite();
g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, alpha));
super.paint(g);
g2.setComposite(oldComposite);
} catch (final Throwable e) {}
}
}
/**
* This class is a special variant of a standard Swing {@link JLabel}. This button is complete
* transparent/translucent for the given alpha value.
*/
final public static class TranslucentLabel extends JLabel {
protected float alpha = 1f;
public TranslucentLabel(final Icon image) {
super(image);
}
public void setAlpha(final float alpha) {
this.alpha = alpha;
}
@Override
public void paint(final Graphics g) {
try {
final Graphics2D g2 = (Graphics2D) g;
final Composite oldComposite = g2.getComposite();
g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, alpha));
super.paint(g);
g2.setComposite(oldComposite);
} catch (final Throwable e) {}
}
}
/**
* Internal {@link ActionListener} used by DatabaseObjectComponent.
*/
final public static class MyActionListener extends Observable implements ActionListener {
@Override
public void actionPerformed(final ActionEvent e) {
Object component = e.getSource();
if (component instanceof JComponent) {
component = ((JComponent) component).getParent();
if (component instanceof JComponent) {
component = ((JComponent) component).getParent();
if (component instanceof DatabaseObjectComponent) {
final String actionCommand = e.getActionCommand();
final DatabaseObject userObject = ((DatabaseObjectComponent) component).getUserObject();
final Command command = Command.valueOf(actionCommand);
switch (command) {
case INFORMATION:
if (userObject.getState().equals(ViewState.INFORMATION)) {
userObject.setState(ViewState.NORMAL);
} else {
userObject.setState(ViewState.INFORMATION);
}
break;
case DATA:
if (userObject.getState().equals(ViewState.DATA)) {
userObject.setState(ViewState.NORMAL);
} else {
userObject.setState(ViewState.DATA);
}
break;
case TRIGGERS:
if (userObject.getState().equals(ViewState.TRIGGERS)) {
userObject.setState(ViewState.NORMAL);
} else {
userObject.setState(ViewState.TRIGGERS);
}
break;
case CLOSE:
if (userObject.getState().equals(ViewState.CLOSED)) {
userObject.setState(ViewState.NORMAL);
} else {
userObject.setState(ViewState.CLOSED);
}
break;
case BACK:
userObject.setState(ViewState.NORMAL);
break;
}
setChanged();
this.notifyObservers(component);
} else {
System.err.println("No DatabaseObjectComponent (3)");
}
} else {
System.err.println("No JComponent (2)");
}
} else {
System.err.println("No JComponent (1)");
}
}
}
public boolean isTable(final DatabaseObject object) {
return (object instanceof DatabaseTable);
}
public boolean isView(final DatabaseObject object) {
return (object instanceof DatabaseView);
}
public boolean isTrigger(final DatabaseObject object) {
return (object instanceof DatabaseTrigger);
}
public boolean isProcedure(final DatabaseObject object) {
return (object instanceof DatabaseProcedure);
}
}
| true
|
68f187d5aadf69ea2c806ad2f940a69d92384b6a
|
Java
|
gres-ufpr/r-nsga-ii
|
/src/main/java/ufpr/gres/rnsgaii/gui/LinePlot.java
|
UTF-8
| 3,098
| 2.484375
| 2
|
[] |
no_license
|
package ufpr.gres.rnsgaii.gui;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.List;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
import javax.swing.WindowConstants;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.axis.NumberAxis;
import org.jfree.chart.plot.CategoryPlot;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.data.category.DefaultCategoryDataset;
import org.uma.jmetal.util.point.PointSolution;
public class LinePlot extends JFrame {
private static final long serialVersionUID = -5222514150598155420L;
public LinePlot(List<DataSet> datasets, double[] yRange) {
super("Populations");
ChartPanel panel = new ChartPanel(createChart(datasets, yRange));
setContentPane(panel);
}
public static JFreeChart createChart(List<DataSet> datasets, double[] yRange) {
// Create dataset
DefaultCategoryDataset dataset = createDataset(datasets);
// Create chart
JFreeChart chart = ChartFactory.createLineChart(
null,
"Objectives","Values",
dataset,
PlotOrientation.VERTICAL,
false, // Legend
true, false);
// Changes background color
CategoryPlot plot = (CategoryPlot) chart.getPlot();
((NumberAxis) plot.getRangeAxis()).setRange(yRange[0], yRange[1]);
plot.setBackgroundPaint(new Color(255, 228, 196));
return chart;
}
public static void exportAsPNG(String filename, List<DataSet> datasets, double[] xRange, double[] yRange) {
JFreeChart chart = createChart(datasets, yRange);
BufferedImage image = new BufferedImage(400, 400, BufferedImage.TYPE_INT_ARGB);
Graphics2D g2 = image.createGraphics();
g2.setRenderingHint(JFreeChart.KEY_SUPPRESS_SHADOW_GENERATION, true);
Rectangle r = new Rectangle(0, 0, 400, 400);
chart.draw(g2, r);
File f = new File(filename);
BufferedImage chartImage = chart.createBufferedImage(400, 400, null);
try {
ImageIO.write(chartImage, "png", f);
} catch (IOException e) {
e.printStackTrace();
}
}
private static DefaultCategoryDataset createDataset(List<DataSet> datasets) {
DefaultCategoryDataset dataset = new DefaultCategoryDataset();
for (DataSet d : datasets) {
for (int i = 0; i < d.getSolutions().size(); i++) {
PointSolution point = d.getSolutions().get(i);
for (int j = 0; j < point.getNumberOfObjectives(); j++) {
dataset.addValue(point.getObjective(j), String.valueOf(i), String.valueOf(j));
}
}
}
return dataset;
}
public static void show(List<DataSet> datasets, double[] yRange) {
SwingUtilities.invokeLater(() -> {
LinePlot example = new LinePlot(datasets, yRange);
example.setSize(400, 400);
example.setLocationRelativeTo(null);
example.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
example.setVisible(true);
});
}
}
| true
|
576351345eb6d5d7f9a5886886e6a6774efbdef4
|
Java
|
727016437/yyy
|
/app/src/main/java/com/example/mymirror/activity/MainActivity.java
|
UTF-8
| 12,179
| 1.601563
| 2
|
[
"Apache-2.0"
] |
permissive
|
package com.example.mymirror.activity;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.ContentResolver;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.ImageFormat;
import android.hardware.Camera;
import android.provider.Settings;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.MotionEvent;
import android.view.Surface;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.SeekBar;
import android.widget.Toast;
import com.example.mymirror.utils.SetBrightness;
import com.example.mymirror.R;
import com.example.mymirror.view.DrawView;
import com.example.mymirror.view.FunctionView;
import com.example.mymirror.view.PictureView;
import java.io.IOException;
import java.util.List;
public class MainActivity extends AppCompatActivity implements SurfaceHolder.Callback,SeekBar.OnSeekBarChangeListener,View.OnTouchListener,View.OnClickListener,FunctionView.onFunctionViewItemClickListener {
private static final String TAG = MainActivity.class.getSimpleName();
private SurfaceHolder holder;
private SurfaceView surfaceView;
private PictureView pictureView;
private FunctionView functionView;
private SeekBar seekBar;
private ImageView add, minus;
private LinearLayout bottom;
private ProgressDialog dialog;
private DrawView drawView;
private boolean havaCamera;
private int mCurrentCamIndex;
private int ROTATE;
private int minFcous;
private int maxFocus;
private int everyFcous;
private int nowFcous;
private Camera camera;
private int frame_index;
private int[] frame_index_ID;
private static final int PHOTO=1;
private int brightnessValue;
private boolean isAutoBrightness;
private int SegmentLengh;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initViews();
setViews();
frame_index=0;
frame_index_ID=new int[]{R.mipmap.mag_0001,R.mipmap.mag_0003,R.mipmap.mag_0005,R.mipmap.mag_0006,R.mipmap.mag_0007,R.mipmap.mag_0008,R.mipmap.mag_0009,R.mipmap.mag_0011,R.mipmap.mag_0012,R.mipmap.mag_0014};
getBrightnessFromWindow();
}
private void initViews() {
surfaceView = (SurfaceView) findViewById(R.id.surface);
pictureView = (PictureView) findViewById(R.id.picture);
//ImageView imageView = (ImageView) findViewById(R.id.picture);
functionView = (FunctionView) findViewById(R.id.function);
seekBar = (SeekBar) findViewById(R.id.seekbar);
add = (ImageView) findViewById(R.id.add);
minus = (ImageView) findViewById(R.id.minus);
bottom = (LinearLayout) findViewById(R.id.bottom_bar);
drawView = (DrawView) findViewById(R.id.draw_glasses);
}
private void setViews(){
holder=surfaceView.getHolder();
holder.addCallback(this);
add.setOnTouchListener(this);
minus.setOnTouchListener(this);
seekBar.setOnSeekBarChangeListener(this);
functionView.setonFunctionViewItemClickListener(this);
}
private boolean checkCameraHardware() {
if (getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA)) {
return true;
} else {
return false;
}
}
private Camera openFrontFacingCameraGingerbread() {
int cameraCount;
Camera mCamera = null;
Camera.CameraInfo cameraInfo = new Camera.CameraInfo();
cameraCount = Camera.getNumberOfCameras();
for (int camIdx = 0; camIdx < cameraCount; camIdx++) {
Camera.getCameraInfo(camIdx, cameraInfo);
if (cameraInfo.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
try {
mCamera = Camera.open(camIdx);
mCurrentCamIndex = camIdx;
} catch (Exception e) {
Log.e(TAG, "相机失败:" + e.getLocalizedMessage());
}
}
}
return mCamera;
}
private void setCameraDisplayOrientation(Activity activity, int cameraId, Camera camera) {
Camera.CameraInfo info = new Camera.CameraInfo();
Camera.getCameraInfo(cameraId, info);
int rotation = activity.getWindowManager().getDefaultDisplay().getRotation();
int degrees = 0;
switch (rotation) {
case Surface.ROTATION_0:
degrees = 0;
break;
case Surface.ROTATION_90:
degrees = 90;
break;
case Surface.ROTATION_180:
degrees = 180;
break;
case Surface.ROTATION_270:
degrees = 270;
break;
}
int result = 0;
if (info.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
result = (info.orientation + degrees) % 360;
result = (360 - result) % 360;
} else {
result = (info.orientation - degrees) % 360;
}
ROTATE = result +180;
camera.setDisplayOrientation(result);
}
private void setCamera(){
if(checkCameraHardware()){
camera=openFrontFacingCameraGingerbread();
setCameraDisplayOrientation(this,mCurrentCamIndex,camera);
Camera.Parameters parameters=camera.getParameters();
parameters.setPictureFormat(ImageFormat.JPEG);
List<String> list=parameters.getSupportedFocusModes();
for (String str:list){
Log.e(TAG,"支持的对焦模式:"+str);
}
List<Camera.Size> pictureList=parameters.getSupportedPictureSizes();
List<Camera.Size> previewList=parameters.getSupportedPreviewSizes();
parameters.setPictureSize(pictureList.get(0).width,pictureList.get(0).height);
parameters.setPictureSize(previewList.get(0).width,previewList.get(0).height);
minFcous=parameters.getZoom();
maxFocus=parameters.getMaxZoom();
everyFcous=1;
nowFcous=minFcous;
seekBar.setMax(maxFocus);
Log.e(TAG,"当前镜头距离是多少呢:"+ minFcous+"获取最大距离为"+maxFocus);
camera.setParameters(parameters);
}
}
@Override
public void surfaceCreated(SurfaceHolder surfaceHolder) {
Log.e("surfaceCreated","绘制开始");
try {
setCamera();
camera.setPreviewDisplay(holder);
camera.startPreview();
} catch (IOException e) {
camera.release();
camera=null;
e.printStackTrace();
}
}
@Override
public void surfaceChanged(SurfaceHolder surfaceHolder, int i, int i1, int i2) {
try {
camera.stopPreview();
camera.setPreviewDisplay(holder);
camera.startPreview();
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void surfaceDestroyed(SurfaceHolder surfaceHolder) {
Log.e("surfaceDestroyed","绘制结束");
toRelease();
}
private void toRelease(){
camera.setPreviewCallback(null);
camera.stopPreview();
camera.release();
camera=null;
}
private void setZoomValues(int want){
Camera.Parameters parameters=camera.getParameters();
seekBar.setProgress(want);
parameters.setZoom(want);
camera.setParameters(parameters);
}
private int getZoomValues(){
Camera.Parameters parameters=camera.getParameters();
int values=parameters.getZoom();
return values;
}
private void addZoomValues(){
if(nowFcous==maxFocus){
Log.e(TAG,"大于maxFocus是不可能的");
}else if(nowFcous==maxFocus){
}else {
setZoomValues(getZoomValues()+everyFcous);
Log.i("ddd","当前焦距为");
}
}
private void minusZoomValues(){
if(nowFcous<0){
Log.e(TAG,"小于0是不可能的");
}else if(nowFcous==0){
}else {
setZoomValues(getZoomValues()-everyFcous);
}
}
public void onProgressChanged(SeekBar seekBar,int progress,boolean fromUser){
Camera.Parameters parameters=camera.getParameters();
nowFcous=progress;
parameters.setZoom(progress);
camera.setParameters(parameters);
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
@Override
public boolean onTouch(View v, MotionEvent event){
switch (v.getId()){
case R.id.add:
addZoomValues();
break;
case R.id.minus:
minusZoomValues();
break;
case R.id.picture:
break;
default:
break;
}
return true;
}
@Override
public void onClick(View view) {
}
@Override
public void hint() {
Intent intent=new Intent(this,HintActivity.class);
startActivity(intent);
}
@Override
public void choose() {
Intent intent=new Intent(MainActivity.this,PhotoFrameActivity.class);
startActivityForResult(intent,PHOTO);
Toast.makeText(this, "选择!", Toast.LENGTH_SHORT).show();
}
@Override
public void down() {
downCurrentActivityBrightnessValues();
}
@Override
public void up() {
upCurrentActivityBrightnessValues();
}
@Override
protected void onActivityResult(int requsetCode,int resultCode,Intent data){
super.onActivityResult(requsetCode,resultCode,data);
Log.e(TAG,"返回值"+resultCode+"\t\t请求值"+requsetCode);
if(resultCode==RESULT_OK&&requsetCode==PHOTO){
int position=data.getIntExtra("POSITION",0);
frame_index=position;
Log.i("接收到的为","position="+position);
pictureView.setPhotoFrame(position);
}
}
private void setMyActivityBright(int brightnessValues) {
SetBrightness.setBrightness(this, brightnessValues);//调用SetBrightness类方法设置亮度
//保存亮度
SetBrightness.saveBrightness(SetBrightness.getResolver(this), brightnessValues);
}
private void getAfterMySetBrightnessValues() {
brightnessValue = SetBrightness.getScreenBrightness(this); //获得亮度
Log.e(TAG, "当前手机屏幕亮度值:"+ brightnessValue);
}
public void getBrightnessFromWindow() {
//获得是否自动调节亮度
isAutoBrightness = SetBrightness.isAutoBrigtness(SetBrightness.getResolver(this));
Log.e(TAG, "当前手机是否是自动调节屏幕亮度:"+ isAutoBrightness);
if (isAutoBrightness) { //如果是自动调节亮度
SetBrightness.stopAutoBrightness(this); //关闭自动调节亮度
Log.e(TAG, "关闭了自动调节!");
setMyActivityBright(255 / 2 + 1);
}
//亮度值0~256
SegmentLengh = (255 / 2 + 1) / 4; //每32为一个区间
getAfterMySetBrightnessValues(); //获取设置后的亮度
}
private void downCurrentActivityBrightnessValues(){
if (brightnessValue >0) {
setMyActivityBright(brightnessValue - SegmentLengh); //减少亮度
}
getAfterMySetBrightnessValues(); //获取设置后的屏幕亮度
}
private void upCurrentActivityBrightnessValues(){
if (brightnessValue <255) {
if (brightnessValue + SegmentLengh >= 256){ //最大值256
return;
}
setMyActivityBright(brightnessValue + SegmentLengh );//调高亮度
}
getAfterMySetBrightnessValues(); //获取设置后的屏幕亮度
}
}
| true
|
f6ba8856584015fdb848328c80b7c1e27bc3d103
|
Java
|
nvmr6/BIGDATA
|
/java/ch11_inheritance/ex04_abc/A.java
|
UTF-8
| 136
| 2.25
| 2
|
[] |
no_license
|
package com.lec.ex04_abc;
public class A extends S {
public A() {
System.out.println("A클래스 생성자");
s = 1;
}
}
| true
|
d7ad74b057e74823ff6ba8ccf537ed41e35daa65
|
Java
|
maciey24/pl-java2019
|
/projekt/src/main/java/main/controller/Window.java
|
UTF-8
| 6,100
| 2.65625
| 3
|
[] |
no_license
|
package main.controller;
import javafx.fxml.FXML;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.GridPane;
import javafx.scene.shape.Circle;
import javafx.scene.shape.Rectangle;
import javafx.scene.shape.Shape;
import javafx.scene.text.Text;
import main.model.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Repository;
import org.w3c.dom.css.Rect;
import java.util.ArrayList;
@Controller
public class Window {
//wiem ze to brzydki hardcoding - zapisane granice wspolrzednych na ktore reaguje klikniecie
public static final double firstColumnCoord1 = 140.0;
public static final double firstColumnCoord2 = 233.0;
public static final double secondColumnCoord1 = 237.0;
public static final double secondColumnCoord2 = 335.0;
public static final double thirdColumnCoord1 = 339.0;
public static final double thirdColumnCoord2 = 432.0;
public static final double firstRowCoord1 = 97.0;
public static final double firstRowCoord2 = 172.0;
public static final double secondRowCoord1 = 179.0;
public static final double secondRowCoord2 = 250.0;
public static final double thirdRowCoord1 = 258.0;
public static final double thirdRowCoord2 = 342.0;
@Autowired
Game game;
@FXML
GridPane gridpane = new GridPane();
@FXML
Text text;
@FXML
Circle c00, c01, c02,
c10, c11, c12,
c20, c21, c22;
@FXML
Rectangle r00, r01, r02,
r10, r11, r12,
r20, r21, r22;
ArrayList<Shape> shapes = new ArrayList<>();
ArrayList<ArrayList<Circle>> circles = new ArrayList<>();
ArrayList<ArrayList<Rectangle>> rectangles = new ArrayList<>();
@FXML
public void initialize() {
System.out.println("Window init");
addAll();
hideAll(shapes);
text.setVisible(false);
gridpane.addEventHandler(MouseEvent.MOUSE_PRESSED, e -> {
Coord x = new Coord(e.getX());
Coord y = new Coord(e.getY());
System.out.println("x: " + x + "y: " + y);
game.putItemOnBoard(x, y);
});
}
public GridIndex getGridIndex(Coord x, Coord y) throws CannotPutElementException {
if (x.between(firstColumnCoord1, firstColumnCoord2) && y.between(firstRowCoord1, firstRowCoord2))
return new GridIndex(0, 0);
if (x.between(secondColumnCoord1, secondColumnCoord2) && y.between(firstRowCoord1, firstRowCoord2))
return new GridIndex(0, 1);
if (x.between(thirdColumnCoord1, thirdColumnCoord2) && y.between(firstRowCoord1, firstRowCoord2))
return new GridIndex(0, 2);
if (x.between(firstColumnCoord1, firstColumnCoord2) && y.between(secondRowCoord1, secondRowCoord2))
return new GridIndex(1, 0);
if (x.between(secondColumnCoord1, secondColumnCoord2) && y.between(secondRowCoord1, secondRowCoord2))
return new GridIndex(1, 1);
if (x.between(thirdColumnCoord1, thirdColumnCoord2) && y.between(secondRowCoord1, secondRowCoord2))
return new GridIndex(1, 2);
if (x.between(firstColumnCoord1, firstColumnCoord2) && y.between(thirdRowCoord1, thirdRowCoord2))
return new GridIndex(2, 0);
if (x.between(secondColumnCoord1, secondColumnCoord2) && y.between(thirdRowCoord1, thirdRowCoord2))
return new GridIndex(2, 1);
if (x.between(thirdColumnCoord1, thirdColumnCoord2) && y.between(thirdRowCoord1, thirdRowCoord2))
return new GridIndex(2, 2);
throw new CannotPutElementException("no element to display at these coords");
}
private void addAll() {
//first row
ArrayList<Circle> circles0 = new ArrayList<>();
circles0.add(c00);
circles0.add(c01);
circles0.add(c02);
circles.add(circles0);
//second row
ArrayList<Circle> circles1 = new ArrayList<>();
circles1.add(c10);
circles1.add(c11);
circles1.add(c12);
circles.add(circles1);
//third row
ArrayList<Circle> circles2 = new ArrayList<>();
circles2.add(c20);
circles2.add(c21);
circles2.add(c22);
circles.add(circles2);
//first row
ArrayList<Rectangle> rectangles0 = new ArrayList<>();
rectangles0.add(r00);
rectangles0.add(r01);
rectangles0.add(r02);
rectangles.add(rectangles0);
//second row
ArrayList<Rectangle> rectangles1 = new ArrayList<>();
rectangles1.add(r10);
rectangles1.add(r11);
rectangles1.add(r12);
rectangles.add(rectangles1);
//second row
ArrayList<Rectangle> rectangles2 = new ArrayList<>();
rectangles2.add(r20);
rectangles2.add(r21);
rectangles2.add(r22);
rectangles.add(rectangles2);
addAll(circles);
addAll(rectangles);
}
//generic functions
private <T extends Shape> void addAll(ArrayList<ArrayList<T>> listOfLists) {
for (ArrayList<T> list : listOfLists) {
shapes.addAll(list);
}
}
private void hideAll(ArrayList<Shape> shapes) {
for (Shape shape : shapes) {
shape.setVisible(false);
}
}
//nie wiem dlaczego polimorfizm tak nie dziala, ale chcialem zaimplementowac
//wzorzec strategii
public void update(int i, int j, Circle element) {
this.circles.get(i).get(j).setVisible(true);
}
public void update(int i, int j, Rectangle element) {
this.rectangles.get(i).get(j).setVisible(true);
}
public <T extends Shape> void update(int i, int j, Shape element) {
if (element instanceof Circle)
this.circles.get(i).get(j).setVisible(true);
else if (element instanceof Rectangle)
this.rectangles.get(i).get(j).setVisible(true);
}
public void printWinner(String string) {
this.text.setText(string);
this.text.setVisible(true);
}
}
| true
|
caf9be4d1c4a8f009d2fb107746a9b286d3ba00c
|
Java
|
codeanddonuts/java-ladder
|
/src/test/java/laddergame/model/game/RewardsTest.java
|
UTF-8
| 1,019
| 2.75
| 3
|
[] |
no_license
|
package laddergame.model.game;
import org.junit.jupiter.api.Test;
import java.util.Arrays;
import static org.assertj.core.api.Assertions.assertThat;
class RewardsTest {
private final Players players = new Players(Arrays.asList("abc", "def", "ghi"));
@Test
void initTestA() {
assertThat(new Rewards(Arrays.asList("ABC"), players).toString()).isEqualTo("ABC, 꽝, 꽝");
}
@Test
void initTestB() {
assertThat(new Rewards(Arrays.asList(), players).toString()).isEqualTo("꽝, 꽝, 꽝");
}
@Test
void initTestC() {
assertThat(new Rewards(Arrays.asList("ABC", "12 ", "34", "56"), players).toString()).isEqualTo("ABC, 12, 34");
}
@Test
void initTestD() {
assertThat(new Rewards(Arrays.asList(" ABC ", "123 "), players).toString()).isEqualTo("ABC, 123, 꽝");
}
@Test
void longestLengthTest() {
assertThat(new Rewards(Arrays.asList("abc", "bcd", "cdef", "g"), players).longestNameLength()).isEqualTo(4);
}
}
| true
|
624f9cc2862c60827af0b81fe002cb8c0234ec7c
|
Java
|
epavlovskaya/rcfTestBase
|
/src/main/java/com/selectica/Perfectpackage/definitions/CSALESBO/actions/ExecuteActivationCAActionScript.java
|
UTF-8
| 370
| 1.570313
| 2
|
[] |
no_license
|
package com.selectica.Perfectpackage.definitions.CSALESBO.actions;
import com.selectica.rcfscripts.AbstractBOWriteScript;
/**SetStatusAwtSig: Contract Status = Awaiting Signature*/
public class ExecuteActivationCAActionScript extends AbstractBOWriteScript<Boolean> {
@Override
public Boolean process() {
//TODO generated;
return null;
}
}
| true
|
570230c8dca1bd476c3f52438db2109d2f475480
|
Java
|
TangShaoquan/TBlog
|
/TBlog/src/main/java/cn/betterts/blog/service/Impl/ArticleServiceImpl.java
|
UTF-8
| 8,714
| 1.921875
| 2
|
[] |
no_license
|
package cn.betterts.blog.service.Impl;
import cn.betterts.blog.dao.ArticleCategoryRefDao;
import cn.betterts.blog.dao.ArticleDao;
import cn.betterts.blog.dao.ArticleTagRefDao;
import cn.betterts.blog.domain.*;
import cn.betterts.blog.enums.ArticleCommentStatus;
import cn.betterts.blog.service.ArticleService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
@Service("articleService")
@Slf4j
public class ArticleServiceImpl implements ArticleService {
@Autowired
private ArticleDao articleDao;
@Autowired
private ArticleCategoryRefDao articleCategoryRefDao;
@Autowired
private ArticleTagRefDao articleTagRefDao;
@Override
public List<Article> listArticle(HashMap<String, Object> criteria) {
return articleDao.findAll(criteria);
}
@Override
public List<Article> listAllNotWithContent() {
return articleDao.listAllNotWithContent();
}
@Override
public List<Article> listArticle() {
return articleDao.listArticle();
}
@Override
public PageInfo<Article> pageArticle(Integer pageIndex,
Integer pageSize,
HashMap<String, Object> criteria) {
PageHelper.startPage(pageIndex,pageSize);
List<Article> articleList = articleDao.findAll(criteria);
for (int i = 0; i < articleList.size(); i++) {
//封装CategoryList
List<Category> categoryList = articleCategoryRefDao.listCategoryByArticleId(articleList.get(i).getArticleId());
if (categoryList == null || categoryList.size() == 0) {
categoryList = new ArrayList<>();
categoryList.add(Category.Default());
}
articleList.get(i).setCategoryList(categoryList);
}
PageInfo pageInfo =new PageInfo(articleList,pageSize);
return pageInfo;
}
@Override
public List<Article> listArticleByViewCount(Integer limit) {
return articleDao.listArticleByViewCount(limit);
}
@Override
public Article getAfterArticle(Integer id) {
return articleDao.getAfterArticle(id);
}
@Override
public Article getPreArticle(Integer id) {
return articleDao.getPreArticle(id);
}
@Override
public List<Article> listRandomArticle(Integer limit) {
return articleDao.listRandomArticle(limit);
}
@Override
public List<Article> listArticleByCommentCount(Integer limit) {
return articleDao.listArticleByCommentCount(limit);
}
@Override
public List<Article> findArticleByCategoryId(Integer categoryId, Integer limit) {
return articleDao.findArticleByCategoryId(categoryId,limit);
}
@Override
public List<Article> findArticleByCategoryIds(List<Integer> categoryIds, Integer limit) {
if ( categoryIds == null || categoryIds.size() == 0) {
return null;
}
return articleDao.findArticleByCategoryIds(categoryIds,limit);
}
@Override
public List<Article> listRecentArticle(Integer limit) {
return articleDao.listArticleByLimit(limit);
}
@Override
public void deleteBatch(List<Integer> ids) {
articleDao.deleteBatch(ids);
}
@Override
public Article getLastUpdateArticle() {
return articleDao.getLastUpdateArticle();
}
@Override
public Article getArticleByStatusAndId(Integer status, Integer id) {
Article article = articleDao.getArticleByStatusAndId(status, id);
if (article != null) {
List<Category> categoryList = articleCategoryRefDao.listCategoryByArticleId(article.getArticleId());
List<Tag> tagList = articleTagRefDao.listTagByArticleId(article.getArticleId());
article.setCategoryList(categoryList);
article.setTagList(tagList);
}
return article;
}
@Override
public Integer countArticleByUser(Integer id) {
return articleDao.countArticleByUser(id);
}
@Override
public void deleteById(Integer articleId) {
articleDao.deleteById(articleId);
}
@Override
public Integer countArticle(Integer status) {
Integer count = 0;
try {
count = articleDao.countArticle(status);
} catch (Exception e) {
e.printStackTrace();
log.error("根据状态统计文章数, status:{}, cause:{}", status, e);
}
return count;
}
@Override
public Integer countArticleComment() {
Integer count = 0;
try {
count = articleDao.countArticleComment();
} catch (Exception e) {
e.printStackTrace();
log.error("统计文章评论数失败, cause:{}", e);
}
return count;
}
@Override
public Integer countArticleView() {
Integer count = 0;
try {
count = articleDao.countArticleView();
} catch (Exception e) {
e.printStackTrace();
log.error("统计文章访问量失败, cause:{}", e);
}
return count;
}
@Override
public Integer countArticleByCategoryId(Integer categoryId) {
Integer count = 0;
try {
count = articleCategoryRefDao.countArticleByCategoryId(categoryId);
} catch (Exception e) {
e.printStackTrace();
log.error("根据分类统计文章数量失败, categoryId:{}, cause:{}", categoryId, e);
}
return count;
}
@Override
public Integer countArticleByTagId(Integer tagId) {
return articleTagRefDao.countArticleByTagId(tagId);
}
@Override
public void insert(Article article) {
//添加文章
article.setArticleCreateTime(new Date());
article.setArticleUpdateTime(new Date());
article.setArticleIsComment(ArticleCommentStatus.ALLOW.getValue());
article.setArticleViewCount(0);
article.setArticleLikeCount(0);
article.setArticleCommentCount(0);
article.setArticleOrder(1);
Integer id = articleDao.insert(article);
//添加分类和文章关联
for (int i = 0; i < article.getCategoryList().size(); i++) {
ArticleCategoryRef articleCategoryRef = new ArticleCategoryRef(article.getArticleId(), article.getCategoryList().get(i).getCategoryId());
articleCategoryRefDao.insert(articleCategoryRef);
}
//添加标签和文章关联
for (int i = 0; i < article.getTagList().size(); i++) {
ArticleTagRef articleTagRef = new ArticleTagRef(article.getArticleId(), article.getTagList().get(i).getTagId());
articleTagRefDao.insert(articleTagRef);
}
}
@Override
@Transactional(rollbackFor = Exception.class)
public void updateArticleDetail(Article article) {
article.setArticleUpdateTime(new Date());
articleDao.update(article);
if (article.getTagList() != null) {
//删除标签和文章关联
articleTagRefDao.deleteByArticleId(article.getArticleId());
//添加标签和文章关联
for (int i = 0; i < article.getTagList().size(); i++) {
ArticleTagRef articleTagRef = new ArticleTagRef(article.getArticleId(), article.getTagList().get(i).getTagId());
articleTagRefDao.insert(articleTagRef);
}
}
if (article.getCategoryList() != null) {
//添加分类和文章关联
articleCategoryRefDao.deleteByArticleId(article.getArticleId());
//删除分类和文章关联
for (int i = 0; i < article.getCategoryList().size(); i++) {
ArticleCategoryRef articleCategoryRef = new ArticleCategoryRef(article.getArticleId(), article.getCategoryList().get(i).getCategoryId());
articleCategoryRefDao.insert(articleCategoryRef);
}
}
}
@Override
public List<Integer> listCategoryIdByArticleId(Integer articleId) {
return articleCategoryRefDao.selectCategoryIdByArticleId(articleId);
}
@Override
public void update(Article article) {
articleDao.update(article);
}
@Override
public void updateCommentCount(Integer articleId) {
articleDao.updateCommentCount(articleId);
}
}
| true
|
59607f3a6d7fecd4f1e69a5c5b77135960cc9503
|
Java
|
NewProjectHN/internal_management
|
/Internal_Tool/src/main/java/Com/IFI/InternalTool/DS/DAO/Impl/AllocationDAOImpl.java
|
UTF-8
| 15,968
| 2.03125
| 2
|
[] |
no_license
|
//package Com.IFI.InternalTool.DS.DAO.Impl;
//
//import Com.IFI.InternalTool.DS.DAO.AllocationDAO;
//import Com.IFI.InternalTool.DS.Model.Allocation;
//import Com.IFI.InternalTool.Utils.Business;
//import org.hibernate.Session;
//import org.hibernate.SessionFactory;
//import org.hibernate.Transaction;
//import org.hibernate.query.Query;
//import org.slf4j.Logger;
//import org.slf4j.LoggerFactory;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.stereotype.Repository;
//
//import javax.persistence.EntityManagerFactory;
//import javax.transaction.Transactional;
//import java.sql.Date;
//import java.time.LocalDate;
//import java.util.List;
//
///*import com.jayway.jsonpath.Criteria;*/
//
//@Repository("AllocationDAO")
//@Transactional
//public class AllocationDAOImpl implements AllocationDAO {
// @Autowired
// private EntityManagerFactory entityManagerFactory;
// private static final Logger logger = LoggerFactory.getLogger(AllocationDAOImpl.class);
//
// @Autowired
// AllocationDetailDAOImpl allocationDetailDAO;
// private boolean success = false;
//
// @Override
// public List<Allocation> getAllocations(final long employee_id, final int page, final int pageSize) {
// Session session = entityManagerFactory.unwrap(SessionFactory.class).openSession();
// String hql = "FROM Allocation where employee_id= :employee_id ";
//
// Query query = session.createQuery(hql);
// query.setParameter("employee_id", employee_id);
// query.setFirstResult((page - 1) * pageSize);
// query.setMaxResults((page + 1) * pageSize - 1);
// List<Allocation> list = query.getResultList();
// session.close();
// return list;
// }
//
// @Override
// public List<Allocation> getAllocatedOfManager(final long employee_id, final int page, final int pageSize) {
// Session session = entityManagerFactory.unwrap(SessionFactory.class).openSession();
// String hql = "Select a FROM Allocation a where a.project_id in (select pm.project_id from ProjectMembers pm where pm.manager_id = :employee_id)";
// Query query = session.createQuery(hql);
// query.setParameter("employee_id", employee_id);
// query.setFirstResult((page - 1) * pageSize);
// query.setMaxResults((page + 1) * pageSize - 1);
// List<Allocation> list = query.getResultList();
// session.close();
// return list;
//
// }
//
// @Override
// public Long NumRecordsAllocatedOfManager(long employee_id) {
// Session session = entityManagerFactory.unwrap(SessionFactory.class).openSession();
// String hql = "Select count(*) FROM Allocation a where a.project_id in (select pm.project_id from ProjectMembers pm where pm.manager_id = :employee_id)";
// Query query = session.createQuery(hql);
// query.setParameter("employee_id", employee_id);
// Long count = (Long) query.uniqueResult();
// session.close();
// return count;
// }
//
// @Override
// public Boolean saveAllocation(final Allocation allocation) {
// Session session = entityManagerFactory.unwrap(SessionFactory.class).openSession();
// Transaction tx = null;
// try {
// tx = session.beginTransaction();
// session.save(allocation);
//
// //sinh allocation detail
// allocationDetailDAO.autoCreateAllocationDetail(allocation);
//
// success = true;
// tx.commit();
// } catch (Exception e) {
// throw e;
// } finally {
// session.close();
// }
// return success;
//
// }
//
// @Override
// public Boolean updateAllocation(Allocation allocation) {
// Session session = entityManagerFactory.unwrap(SessionFactory.class).openSession();
// boolean success = false;
// Transaction tx = null;
// try {
// tx = session.beginTransaction();
// Allocation currentAllocation = session.get(Allocation.class, allocation.getAllocation_id());
// // currentAllocation.setAllocation_plan(allocation.getAllocation_plan());
// currentAllocation.setEmployee_id(allocation.getEmployee_id());
// currentAllocation.setEnd_date(allocation.getEnd_date());
// currentAllocation.setMonth(allocation.getMonth());
// currentAllocation.setProject_id(allocation.getProject_id());
// currentAllocation.setStart_date(allocation.getStart_date());
// currentAllocation.setYear(allocation.getYear());
// currentAllocation.setHalf_day(allocation.isHalf_day());
// currentAllocation.setPm(allocation.isPm());
// //tinh lai allcation plan (copy code)
//
// // get distance Time between start_date vs end_date not set Weekends;
// LocalDate start_date = currentAllocation.getStart_date().toLocalDate();
// LocalDate end_date = currentAllocation.getEnd_date().toLocalDate();
// int distanceTime = Business.getDistanceTime(start_date, end_date);
// // get number days of month // get nums days weekend of month
// int numDaysOfMonth = currentAllocation.getStart_date().toLocalDate().lengthOfMonth();
// int numDaysWeekOfMonth = Business.numberWeekendOfMonth(start_date.getMonthValue(), start_date.getYear());
// // set allocation_plan
// double allocation_plan = Business.getAllocation_Plan(numDaysOfMonth, numDaysWeekOfMonth, distanceTime);
// //tinh allocation_plan theo nua ngay
// if (allocation.isHalf_day()) {
// allocation_plan = allocation_plan/2.0;
// }
// currentAllocation.setAllocation_plan(Business.getAllocation_Plan(numDaysOfMonth, numDaysWeekOfMonth, distanceTime));
// //xoa va tao lai allocation detail
// allocationDetailDAO.deleteAllocationDetailByAllocationId(allocation.getAllocation_id());
// allocationDetailDAO.autoCreateAllocationDetail(allocation);
//
// tx.commit();
// success = true;
// } catch (Exception e) {
// throw e;
// } finally {
// session.close();
// }
// return success;
// }
//
// @Override
// public Boolean deleteById(long allocation_id) {
// Session session = entityManagerFactory.unwrap(SessionFactory.class).openSession();
// Transaction tx = null;
// tx = session.beginTransaction();
// // xoa cac detail allocation
// allocationDetailDAO.deleteAllocationDetailByAllocationId(allocation_id);
// /*String hqlDeleteDetail = "delete from AllocationDetail where allocation_id = :allocation_id";
// Query queryDeleteDetail = session.createQuery(hqlDeleteDetail);
// queryDeleteDetail.setParameter("allocation_id", allocation_id);
// queryDeleteDetail.executeUpdate();*/
// // xoa allocation
// String hql = "Delete from Allocation where allocation_id=:allocation_id";
// Query query = session.createQuery(hql);
// query.setParameter("allocation_id", allocation_id);
// int row = query.executeUpdate();
// tx.commit();
// session.close();
// if (row > 0) {
// return true;
// } else {
// return false;
// }
// }
//
// @Override
// public Allocation findById(final long allocation_id) {
// Session session = entityManagerFactory.unwrap(SessionFactory.class).openSession();
// String hql = "FROM Allocation where allocation_id=:allocation_id ";
// Query query = session.createQuery(hql);
// query.setParameter("allocation_id", allocation_id);
// Allocation allocation = (Allocation) query.uniqueResult();
// session.close();
// return allocation;
// }
//
// @Override
// public Date findMaxEndDate(long employee_id, int month, int year) {
// Session session = entityManagerFactory.unwrap(SessionFactory.class).openSession();
// String hql = "SELECT end_date FROM Allocation a where a.employee_id = :employee_id";
// if (year > 0) {
// hql += " and year = :year";
// if (month >= 1 && month <= 12) {
// hql += " and month = :month";
// }
// }else {
// if (month >= 1 && month <= 12) {
// hql += "and month = :month ";
// }
// }
// hql += " order by date(end_date) desc";
// Query query = session.createQuery(hql);
// query.setParameter("employee_id", employee_id);
// if (year > 0) {
// query.setParameter("year", year);
// }
// if (month >= 1 && month <= 12) {
// query.setParameter("month", month);
// }
// query.setMaxResults(1);
// if (query.uniqueResult() != null) {
// return (Date) query.uniqueResult();
// }
// return null;
// }
//
// public List<Allocation> searchAllocationWithTime(final int year, final int month, final int page,
// final int pageSize) {
// Session session = entityManagerFactory.unwrap(SessionFactory.class).openSession();
// String hql = "select a FROM Allocation a where ";
//
// if (year > 0) {
// hql += " and year = :year";
// if (month >= 1 && month <= 12) {
// hql += " and month = :month";
// }
// }else {
// if (month >= 1 && month <= 12) {
// hql += "and month = :month ";
// }
// }
//
// Query query = session.createQuery(hql);
//
// if (year > 0) {
// query.setParameter("year", year);
// }
// if (month >= 1 && month <= 12) {
// query.setParameter("month", month);
// }
//
// query.setFirstResult((page - 1) * pageSize);
// query.setMaxResults(pageSize);
//
// List<Allocation> list = query.getResultList();
// session.close();
// return list;
// }
//
// @Override
// public List<Allocation> findAllocationByEmployeeID(final long employee_id, final int page, final int pageSize, boolean isDESC) {
//
// Session session = entityManagerFactory.unwrap(SessionFactory.class).openSession();
// String hql = "select a FROM Allocation a where a.employee_id = :employee_id order by a.allocation_id ";
// if (isDESC) {
// hql += "desc";
// }else {
// hql += "asc";
// }
// Query query = session.createQuery(hql);
// query.setParameter("employee_id", employee_id);
// query.setFirstResult((page - 1) * pageSize);
// query.setMaxResults(pageSize);
// List<Allocation> list = query.getResultList();
// session.close();
// return list;
//
// }
//
// @Override
// public Long NumRecordsAllocationByEmployeeID(long employee_id) {
// Session session = entityManagerFactory.unwrap(SessionFactory.class).openSession();
// String hql = "select count(*) FROM Allocation a where a.employee_id = :employee_id ";
// Query query = session.createQuery(hql);
// query.setParameter("employee_id", employee_id);
// Long count = (Long) query.uniqueResult();
// session.close();
// return count;
// }
//
// @Override
// public List<Allocation> findAllocationByProjectID(final long project_id, final int page, final int pageSize, boolean isDESC) {
// Session session = entityManagerFactory.unwrap(SessionFactory.class).openSession();
// String hql = "select a FROM Allocation a where a.project_id = :project_id order by a.allocation_id ";
// if (isDESC) {
// hql += "desc";
// }else {
// hql += "asc";
// }
// Query query = session.createQuery(hql);
// query.setParameter("project_id", project_id);
//
// query.setFirstResult((page - 1) * pageSize);
// query.setMaxResults(pageSize);
//
// List<Allocation> list = query.getResultList();
// session.close();
// return list;
// }
//
// @Override
// public Long NumRecordsAllocationByProjectID(long project_id) {
// Session session = entityManagerFactory.unwrap(SessionFactory.class).openSession();
// String hql = "select count(*) FROM Allocation a where a.project_id = :project_id";
// Query query = session.createQuery(hql);
// query.setParameter("project_id", project_id);
// Long count = (Long) query.uniqueResult();
// session.close();
// return count;
// }
//
// @Override
// public List<Allocation> findAllocationFromDateToDate(Date fromDate, Date toDate, final int page,
// final int pageSize) {
// Session session = entityManagerFactory.unwrap(SessionFactory.class).openSession();
// String hql = "from Allocation where allocation_id in (select allocation_id from AllocationDetail where date between :fromDate and :toDate) order by allocation_id";
// Query query = session.createQuery(hql);
// query.setParameter("fromDate", fromDate);
// query.setParameter("toDate", fromDate);
//
// query.setFirstResult((page - 1) * pageSize);
// query.setMaxResults(pageSize);
//
// List<Allocation> list = query.getResultList();
// session.close();
// return list;
// }
//
// @Override
// public Long NumRecordsllocationFromDateToDate(Date fromDate, Date toDate) {
// Session session = entityManagerFactory.unwrap(SessionFactory.class).openSession();
// String hql = "from Allocation where allocation_id in (select allocation_id from AllocationDetail where date between :fromDate and :toDate)";
// Query query = session.createQuery(hql);
// query.setParameter("fromDate", fromDate);
// query.setParameter("toDate", fromDate);
// Long count = (Long) query.uniqueResult();
// session.close();
// return count;
// }
//
// @Override
// public List<Allocation> searchAllocation(int year, int month, long project_id, long employee_id, int page,
// int pageSize) {
// Session session = entityManagerFactory.unwrap(SessionFactory.class).openSession();
// String hql = "select a FROM Allocation a where a.year = :year";
// if (month >= 1 && month <= 12) {
// hql += " and a.month = :month ";
// }
// if (project_id > 0) {
// hql += " and a.project_id =: project_id";
// }
// if (employee_id > 0) {
// hql += " and a.employee_id =: employee_id";
// }
// Query query = session.createQuery(hql);
// query.setParameter("year", year);
// if (month >= 1 && month <= 12) {
// query.setParameter("month", month);
// }
// if (project_id > 0) {
// query.setParameter("project_id", project_id);
// }
// if (employee_id > 0) {
// query.setParameter("employee_id", employee_id);
// }
// query.setFirstResult((page - 1) * pageSize);
// query.setMaxResults(pageSize);
// List<Allocation> list = query.getResultList();
// session.close();
// return list;
// }
//
// @Override
// public Long NumRecordssearchAllocation(int year, int month, long project_id, long employee_id) {
// Session session = entityManagerFactory.unwrap(SessionFactory.class).openSession();
// String hql = "select count(*) FROM Allocation where year = :year";
// if (month >= 1 && month <= 12) {
// hql += " and month = :month ";
// }
// if (project_id > 0) {
// hql += " and project_id =: project_id";
// }
// if (employee_id > 0) {
// hql += " and employee_id =: employee_id";
// }
// Query query = session.createQuery(hql);
// query.setParameter("year", year);
// if (month >= 1 && month <= 12) {
// query.setParameter("month", month);
// }
// if (project_id > 0) {
// query.setParameter("project_id", project_id);
// }
// if (employee_id > 0) {
// query.setParameter("employee_id", employee_id);
// }
// Long count = (Long) query.uniqueResult();
// session.close();
// return count;
// }
//
// @Override
// public Date findMaxEndDateInPoint(final long employee_id, final Date datePoint) {
// Session session = entityManagerFactory.unwrap(SessionFactory.class).openSession();
// String hql = "SELECT MAX(a.end_date) FROM Allocation a where a.employee_id = :employee_id and end_date < :datePoint";
// Query query = session.createQuery(hql);
// query.setParameter("employee_id", employee_id);
// if (query.uniqueResult() != null) {
// return (Date) query.uniqueResult();
// }
// return null;
// }
//
// @Override
// public Date findMinStartDateInPoint(long employee_id, Date datePoint) {
// Session session = entityManagerFactory.unwrap(SessionFactory.class).openSession();
// String hql = "SELECT MIN(a.start_date) FROM Allocation a where a.employee_id = :employee_id and start_date > :datePoint";
// Query query = session.createQuery(hql);
// query.setParameter("employee_id", employee_id);
// if (query.uniqueResult() != null) {
// return (Date) query.uniqueResult();
// }
// return null;
// }
//
// @Override
// public List<Allocation> findAllocationByEmpIdProId(long employeeId, long projectId) {
// Session session = entityManagerFactory.unwrap(SessionFactory.class).openSession();
// String hql = "from Allocation where employee_id = :employee_id and project_id = :project_id";
// Query query = session.createQuery(hql);
// query.setParameter("employee_id", employeeId);
// query.setParameter("project_id", projectId);
// List<Allocation> result = query.getResultList();
// session.close();
// return result;
// }
//
//}
| true
|
91b04539ffd3bb719700245d390eb63ae7ff1f74
|
Java
|
Jstarfish/starfish
|
/starfish-mall/starfish-mall-dao/src/main/java/priv/starfish/mall/dao/market/AdvertLinkDao.java
|
UTF-8
| 882
| 1.976563
| 2
|
[] |
no_license
|
package priv.starfish.mall.dao.market;
import java.util.List;
import priv.starfish.common.annotation.IBatisSqlTarget;
import priv.starfish.mall.dao.base.BaseDao;
import priv.starfish.mall.market.entity.AdvertLink;
@IBatisSqlTarget
public interface AdvertLinkDao extends BaseDao<AdvertLink, Integer> {
AdvertLink selectById(Integer id);
int insert(AdvertLink advertLink);
int update(AdvertLink advertLink);
int deleteById(Integer id);
/**
* 根据广告Id查询广告链接
* @author zjl
* @date 2015年7月7日 下午12:42:04
*
* @param advertId 广告Id
* @return List<AdvertLink>
*/
List<AdvertLink> selectByAdvertId(Integer advertId);
/**
* 获取每个广告的最大日期最小日期
* @author zjl
* @date 2015年7月8日 上午9:23:44
*
* @param id 广告Id
* @return AdvertLink
*/
AdvertLink selectMinMaxDate(Integer advertId);
}
| true
|
6042725c71fda85525807b2ad88d541f37db9001
|
Java
|
zloyby/zete
|
/src/main/java/by/zloy/tests/TestBigDecimal.java
|
UTF-8
| 1,086
| 2.78125
| 3
|
[] |
no_license
|
package by.zloy.tests;
import java.math.BigDecimal;
public class TestBigDecimal {
public static void main(String[] args) {
String a = "2303.4250000000004";
BigDecimal bd = new BigDecimal(a);
System.out.println(a);
System.out.println(bd.setScale(2, BigDecimal.ROUND_HALF_EVEN).toPlainString());
a = "2303.4240000000004";
bd = new BigDecimal(a);
System.out.println(a);
System.out.println(bd.setScale(2, BigDecimal.ROUND_HALF_EVEN).toPlainString());
a = "2303.4248000000004";
bd = new BigDecimal(a);
System.out.println(a);
System.out.println(bd.setScale(2, BigDecimal.ROUND_HALF_EVEN).toPlainString());
a = "2303.4250000000004";
bd = new BigDecimal(a);
System.out.println(a);
System.out.println(bd.setScale(2, BigDecimal.ROUND_HALF_EVEN).toPlainString());
a = "2303.4249999999999";
bd = new BigDecimal(a);
System.out.println(a);
System.out.println(bd.setScale(2, BigDecimal.ROUND_HALF_EVEN).toPlainString());
}
}
| true
|
8c76db65994c4636ddb0c023808665547e2e854a
|
Java
|
danilovalente/spring-richclient
|
/spring-richclient-core/src/main/java/org/springframework/richclient/selection/binding/ListSelectionDialogBinder.java
|
UTF-8
| 7,366
| 1.882813
| 2
|
[
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
/*
* Copyright 2002-2008 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
*
* 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.springframework.richclient.selection.binding;
import org.springframework.binding.form.FormModel;
import org.springframework.binding.value.ValueModel;
import org.springframework.richclient.form.binding.Binding;
import org.springframework.richclient.form.binding.support.AbstractBinder;
import org.springframework.richclient.selection.binding.support.LabelProvider;
import org.springframework.richclient.selection.binding.support.SimpleSelectField;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.ListCellRenderer;
import java.util.Comparator;
import java.util.Map;
/**
* Binder for <code>SelectField</code>.
* <p>
* The context can contain the following items:
* <ul>
* <li><code>SELECTABLE_ITEMS_HOLDER_KEY</code>: The ValueModel holding the collection of selectable items</li>
* <li><code>LABEL_PROVIDER_KEY</code>: the label provider to provide the text of a given item</li>
* <li><code>FILTERED_KEY</code>: boolean value indicating whether the selection dialog will contain a filter field. If
* this value is <code>true</code> and the filter properties are not given, the string representation of the item will
* be used as filter value.</li>
* <li><code>FILTER_PROPERTIES_KEY</code>: array of properties that will be used for filtering</li>
* <li><code>RENDERER_KEY</code>: custom ListCellRenderer that will be used in the selection dialog</li>
* </ul>
*
* @author Peter De Bruycker
*/
public class ListSelectionDialogBinder extends AbstractBinder {
public static final String SELECTABLE_ITEMS_HOLDER_KEY = "selectableItemsHolder";
public static final String FILTER_PROPERTIES_KEY = "filterProperties";
public static final String FILTERED_KEY = "filtered";
public static final String RENDERER_KEY = "renderer";
public static final String COMPARATOR_KEY = "comparator";
public static final String LABEL_PROVIDER_KEY = "lavelProvider";
public static final String DESCRIPTION_KEY_KEY = "descriptionKey";
public static final String TITLE_KEY_KEY = "titleKey";
public static final String NULLABLE_KEY = "nullable";
private ValueModel selectableItemsHolder;
private String[] filterProperties;
private boolean filtered;
private LabelProvider labelProvider;
private ListCellRenderer renderer;
private Comparator comparator;
private String descriptionKey;
private String titleKey;
private boolean nullable = true;
public ListSelectionDialogBinder() {
super(null, new String[] { SELECTABLE_ITEMS_HOLDER_KEY, FILTER_PROPERTIES_KEY, FILTERED_KEY, RENDERER_KEY,
LABEL_PROVIDER_KEY, COMPARATOR_KEY, DESCRIPTION_KEY_KEY, TITLE_KEY_KEY, NULLABLE_KEY });
}
protected JComponent createControl(Map context) {
// not used
return new JLabel("dummy");
}
protected void applyContext(ListSelectionDialogBinding binding, Map context) {
if (context.containsKey(SELECTABLE_ITEMS_HOLDER_KEY)) {
binding.setSelectableItemsHolder((ValueModel) context.get(SELECTABLE_ITEMS_HOLDER_KEY));
} else if (selectableItemsHolder != null) {
binding.setSelectableItemsHolder(selectableItemsHolder);
}
if (context.containsKey(FILTER_PROPERTIES_KEY)) {
binding.setFilterProperties((String[]) context.get(FILTER_PROPERTIES_KEY));
} else if (filterProperties != null) {
binding.setFilterProperties(filterProperties);
}
if (context.containsKey(FILTERED_KEY)) {
binding.setFiltered(((Boolean) context.get(FILTERED_KEY)).booleanValue());
} else if (filterProperties != null) {
binding.setFiltered(filtered);
}
if (context.containsKey(RENDERER_KEY)) {
binding.setRenderer((ListCellRenderer) context.get(RENDERER_KEY));
} else if (renderer != null) {
binding.setRenderer(renderer);
}
if (context.containsKey(COMPARATOR_KEY)) {
binding.setComparator((Comparator) context.get(COMPARATOR_KEY));
} else if (comparator != null) {
binding.setComparator(comparator);
}
if (context.containsKey(LABEL_PROVIDER_KEY)) {
binding.setLabelProvider((LabelProvider) context.get(LABEL_PROVIDER_KEY));
} else if (labelProvider != null) {
binding.setLabelProvider(labelProvider);
}
if (context.containsKey(DESCRIPTION_KEY_KEY)) {
binding.setDescriptionKey((String) context.get(DESCRIPTION_KEY_KEY));
} else if (descriptionKey != null) {
binding.setDescriptionKey(descriptionKey);
}
if (context.containsKey(TITLE_KEY_KEY)) {
binding.setTitleKey((String) context.get(TITLE_KEY_KEY));
} else if (titleKey != null) {
binding.setTitleKey(titleKey);
}
if (context.containsKey(NULLABLE_KEY)) {
binding.setNullable(((Boolean) context.get(NULLABLE_KEY)).booleanValue());
} else {
binding.setNullable(nullable);
}
}
protected Binding doBind(JComponent notUsed, FormModel formModel, String formPropertyPath, Map context) {
ListSelectionDialogBinding binding = new ListSelectionDialogBinding(new SimpleSelectField(), formModel,
formPropertyPath);
applyContext(binding, context);
return binding;
}
public void setSelectableItemsHolder(ValueModel selectableItemsHolder) {
this.selectableItemsHolder = selectableItemsHolder;
}
public void setFilterProperties(String[] filterProperties) {
this.filterProperties = filterProperties;
}
public void setFiltered(boolean filtered) {
this.filtered = filtered;
}
public void setRenderer(ListCellRenderer renderer) {
this.renderer = renderer;
}
public void setLabelProvider(LabelProvider labelProvider) {
this.labelProvider = labelProvider;
}
public void setComparator(Comparator comparator) {
this.comparator = comparator;
}
public void setDescriptionKey(String descriptionKey) {
this.descriptionKey = descriptionKey;
}
public void setTitleKey(String titleKey) {
this.titleKey = titleKey;
}
/**
* May return null if no value is set!
*
* @return whether the field shall be nullable
*/
public Boolean isNullable() {
return nullable;
}
public void setNullable(Boolean nullable) {
this.nullable = nullable;
}
}
| true
|