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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
d701b8a7f74d707d1a57eee8a0ab0fa29030ea68
|
Java
|
jendap/qibernate
|
/qibernate-jpa/src/test/java/com/github/jendap/qibernate/dao/jpa/CatDAOJPATest.java
|
UTF-8
| 258
| 1.640625
| 2
|
[] |
no_license
|
package com.github.jendap.qibernate.dao.jpa;
import org.junit.jupiter.api.Test;
public class CatDAOJPATest extends CatDAOJPATestBase {
@Test
public void testCatDAOJPA() {
this.testCatDao(new CatDAOJPAImpl(this.getEntityManager()));
}
}
| true
|
967c70d3734c8cca39b9e01725b9acbebb51c557
|
Java
|
cckmit/leleooche
|
/src/main/java/com/jeecg/wechat/service/CoreService.java
|
UTF-8
| 4,720
| 2.03125
| 2
|
[] |
no_license
|
package com.jeecg.wechat.service;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
//import com.shenzhenair.cargo.freight.wechat.booking.app.IKeyWordApp;
//import com.shenzhenair.cargo.freight.wechat.booking.app.IWaybillApp;
//import com.shenzhenair.cargo.freight.wechat.controller.LoginCtr;
import com.jeecg.wechat.entity.MessageUtil;
import com.jeecg.wechat.entity.TextMessage;
import com.jeecg.wechat.util.KeyWordUtil;
public class CoreService {
private static final Logger LOGGER = LoggerFactory.getLogger(CoreService.class);
/**
* 处理微信发来的请求
*
* @param request
* @param keyWordAppImpl
* @param waybillAppImpl
* @return
*/
@SuppressWarnings({ "unchecked" })
//public static String processRequest(HttpServletRequest request, IKeyWordApp keyWordAppImpl, IWaybillApp waybillAppImpl) {
//public static String processRequest(HttpServletRequest request, IKeyWordApp keyWordAppImpl) {
public static String processRequest(HttpServletRequest request, String testStr) {
LOGGER.info("CoreService.processRequest【入口】");
String respMessage = null;
try {
// 默认返回的文本消息内容
String respContent = "请求处理异常,请稍候尝试!";
// xml请求解析
Map<String, String> requestMap = MessageUtil.parseXml(request);
// 发送方帐号(open_id)
String fromUserName = requestMap.get("FromUserName");
// 公众帐号
String toUserName = requestMap.get("ToUserName");
// 消息类型
String msgType = requestMap.get("MsgType");
// 消息内容
String content = requestMap.get("Content");
List<Object> keyPops = request.getSession().getServletContext().getAttribute(fromUserName) == null
? new ArrayList<>()
: (List<Object>) request.getSession().getServletContext().getAttribute(fromUserName);
// 回复文本消息
TextMessage textMessage = new TextMessage();
textMessage.setToUserName(fromUserName);
textMessage.setFromUserName(toUserName);
textMessage.setCreateTime(new Date().getTime());
textMessage.setMsgType(MessageUtil.RESP_MESSAGE_TYPE_TEXT);
textMessage.setFuncFlag(0);
System.out.println("keyPops====>"+keyPops);
// 文本消息
if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_TEXT)) {
//respContent=KeyWordUtil.keyToMsg(content, request, fromUserName, keyPops,keyWordAppImpl,waybillAppImpl);
//respContent=KeyWordUtil.keyToMsg(content, request, fromUserName, keyPops,keyWordAppImpl);
respContent = "您发送的是文本消息!";
}
// 图片消息
else if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_IMAGE)) {
respContent = "您发送的是图片消息!";
}
// 地理位置消息
else if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_LOCATION)) {
respContent = "您发送的是地理位置消息!";
}
// 链接消息
else if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_LINK)) {
respContent = "您发送的是链接消息!";
}
// 音频消息
else if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_VOICE)) {
respContent = "您发送的是音频消息!";
}
// 事件推送
else if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_EVENT)) {
// 事件类型
String eventType = requestMap.get("Event");
/*
* 订阅
*/
if (eventType.equals(MessageUtil.EVENT_TYPE_SUBSCRIBE)) {
respContent = "欢迎关注乐乐集团公众号\n"
+ "官网:<a href=\"http://www.baidu.com/\">深圳市乐乐网络科技有限公司</a>\n";
}
/*
* 取消订阅
*/
else if (eventType.equals(MessageUtil.EVENT_TYPE_UNSUBSCRIBE)) {
// 取消订阅后用户再收不到公众号发送的消息,因此不需要回复消息
}
/*
* 自定义菜单点击事件
*/
else if (eventType.equals(MessageUtil.EVENT_TYPE_CLICK)) {
// 事件KEY值,与创建自定义菜单时指定的KEY值对应
String eventKey = requestMap.get("EventKey");
keyPops.clear();
keyPops.add(eventKey);
request.getSession().getServletContext().setAttribute(fromUserName,keyPops);
if (eventKey.equals("YDQRY")) {
//respContent= KeyWordUtil.getKeyInfo(keyWordAppImpl,"2");
respContent= "this is a telephone";
} else if (eventKey.equals("HBHQRY")) {
//respContent= KeyWordUtil.getKeyInfo(keyWordAppImpl,"1");
respContent= "we need food";
}
}
}
textMessage.setContent(respContent);
respMessage = MessageUtil.textMessageToXml(textMessage);
} catch (Exception e) {
e.printStackTrace();
}
return respMessage;
}
}
| true
|
d6f23db3605c2605d615b39d44da0ff424ca5ec1
|
Java
|
ttt9912/prospringboot2
|
/11-integration-cloudstream/spring-integration/todo-file-integration/src/main/java/ch11/file/integration/messageendpoints/TodoHandler.java
|
UTF-8
| 298
| 1.851563
| 2
|
[] |
no_license
|
package ch11.file.integration.messageendpoints;
import ch11.file.integration.data.Todo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
@Slf4j
@Component
public class TodoHandler {
public void process(Todo todo) {
log.info(">>> {}", todo);
}
}
| true
|
9f434a1d283d8e8330003821c428800ce9b75fdd
|
Java
|
juziluanwu/pp
|
/ppManager/src/main/java/app/pp/mapper/ModelMapper.java
|
UTF-8
| 501
| 1.976563
| 2
|
[] |
no_license
|
package app.pp.mapper;
import app.pp.entity.Model;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.stereotype.Component;
import java.util.List;
@Component
@Mapper
public interface ModelMapper {
int deleteByPrimaryKey(Integer id);
int insert(Model record);
int insertSelective(Model record);
Model selectByPrimaryKey(Integer id);
int updateByPrimaryKeySelective(Model record);
int updateByPrimaryKey(Model record);
List<Model> selectAll();
}
| true
|
5febbeb8d06179f85817eab8a069888bcef815ff
|
Java
|
ldh85246/Rong
|
/bit/javaExam/day0106/src/com/bit/exam09/Producer.java
|
UTF-8
| 273
| 2.765625
| 3
|
[] |
no_license
|
package com.bit.exam09;
public class Producer extends Thread {
Product p;
public Producer(Product p) {
this.p = p;
}
public void run() {
for (int i = 1; i <= 10; i++) {
p.makeNumber();
try {
Thread.sleep(200);
} catch (Exception e) {
}
}
}
}
| true
|
1e8ae2a97c03975aeb7d324055a98cbe7faafccb
|
Java
|
FernandoBasteiro/TDA
|
/Conjuntos/src/algoritmos/Algoritmos.java
|
UTF-8
| 721
| 3.3125
| 3
|
[] |
no_license
|
package algoritmos;
import java.util.Random;
import tda.TDAConjunto;
public class Algoritmos {
/** Muestra todos los elementos del conjunto. Destruye el conjunto */
public void mostrarConjunto(TDAConjunto conjunto) {
int temp;
while (! conjunto.conjuntoVacio()) {
temp = conjunto.elegir();
System.out.println(temp);
conjunto.eliminar(temp);
}
}
/** Agrega "cantValores" elementos (Entre 0 y 63) al conjunto */
public void llenarConjunto(TDAConjunto conjunto, int cantValores) {
Random r = new Random();
int aux;
for (int i = 0; i < cantValores; i++){
aux = r.nextInt(64);
System.out.println("Agregando: " + aux);
conjunto.agregar(aux);
}
}
}
| true
|
7bbe93538640fe393fc3296e14e615816198a01a
|
Java
|
shantojoseph/warehouse-api-service
|
/src/main/java/com/vios/enterprise/warehouse/model/exception/SimNotActivatedException.java
|
UTF-8
| 194
| 1.890625
| 2
|
[] |
no_license
|
package com.vios.enterprise.warehouse.model.exception;
public class SimNotActivatedException extends Exception {
public SimNotActivatedException(String msg) {
super(msg);
}
}
| true
|
01db48f5110cd308893c53276d185a84e9064e05
|
Java
|
BernardoGrigiastro/IBE-Editor
|
/guapi/base/src/main/java/com/github/franckyi/guapi/base/node/LabelImpl.java
|
UTF-8
| 858
| 2.5625
| 3
|
[
"MIT"
] |
permissive
|
package com.github.franckyi.guapi.base.node;
import com.github.franckyi.gameadapter.api.common.text.IText;
import com.github.franckyi.guapi.api.node.builder.LabelBuilder;
import com.github.franckyi.guapi.api.util.NodeType;
public class LabelImpl extends AbstractLabel implements LabelBuilder {
public LabelImpl() {
}
public LabelImpl(String text) {
super(text);
}
public LabelImpl(IText text) {
super(text);
}
public LabelImpl(String text, boolean shadow) {
super(text, shadow);
}
public LabelImpl(IText label, boolean shadow) {
super(label, shadow);
}
@Override
@SuppressWarnings("unchecked")
protected NodeType<?> getType() {
return NodeType.LABEL;
}
@Override
public String toString() {
return "Label{\"" + getLabel() + "\"}";
}
}
| true
|
fed96ba33b1406d81bd54e10b9d7db662bd7c316
|
Java
|
Tophwells/fresco
|
/src/main/java/dk/alexandra/fresco/lib/helper/builder/NumericIOBuilder.java
|
UTF-8
| 10,521
| 1.96875
| 2
|
[
"MIT"
] |
permissive
|
/*******************************************************************************
* Copyright (c) 2015 FRESCO (http://github.com/aicis/fresco).
*
* This file is part of the FRESCO project.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
* FRESCO uses SCAPI - http://crypto.biu.ac.il/SCAPI, Crypto++, Miracl, NTL,
* and Bouncy Castle. Please see these projects for any further licensing issues.
*******************************************************************************/
package dk.alexandra.fresco.lib.helper.builder;
import java.math.BigInteger;
import dk.alexandra.fresco.framework.ProtocolProducer;
import dk.alexandra.fresco.framework.value.OInt;
import dk.alexandra.fresco.framework.value.OIntFactory;
import dk.alexandra.fresco.framework.value.SInt;
import dk.alexandra.fresco.framework.value.SIntFactory;
import dk.alexandra.fresco.lib.field.integer.generic.IOIntProtocolFactory;
import dk.alexandra.fresco.lib.helper.AbstractRepeatProtocol;
/**
* A builder handling input/output related protocols for protocol suites
* supporting arithmetic.
*
* @author psn
*
*/
public class NumericIOBuilder extends AbstractProtocolBuilder {
private IOIntProtocolFactory iof;
private SIntFactory sif;
private OIntFactory oif;
/**
* Constructs a new builder
*
* @param iop
* factory of input/output protocols
* @param sip
* factory of SInts
* @param oip
* factory of OInts
*/
public NumericIOBuilder(IOIntProtocolFactory iop, SIntFactory sip, OIntFactory oip) {
super();
this.iof = iop;
this.sif = sip;
this.oif = oip;
}
/**
* A convenient constructor when one factory implements all the needed
* interfaces (which will usually be the case)
*
* @param factory
* a factory providing SInt/OInt and input/output ciruicts.
*/
public <T extends IOIntProtocolFactory & SIntFactory & OIntFactory> NumericIOBuilder(T factory) {
super();
this.iof = factory;
this.sif = factory;
this.oif = factory;
}
/**
* Appends a protocol to input a matrix of BigIntegers.
*
* @param is
* the BigInteger values
* @param targetID
* the party to input
* @return SInt's that will be loaded with the corresponding inputs, by the
* appended protocol.
*/
public SInt[][] inputMatrix(BigInteger[][] is, int targetID) {
SInt[][] sis = new SInt[is.length][is[0].length];
beginParScope();
for (int i = 0; i < is.length; i++) {
sis[i] = inputArray(is[i], targetID);
}
endCurScope();
return sis;
}
/**
* Appends a protocol to input an matrix of values by an other party. I.e.,
* the values or not held by this party.
*
* @param h
* height of matrix
* @param w
* width of matrix
* @param targetID
* the id of the inputing party
* @return SInts to be loaded with the inputted values.
*/
public SInt[][] inputMatrix(int h, int w, int targetID) {
SInt[][] sis = new SInt[h][w];
beginParScope();
for (int i = 0; i < h; i++) {
sis[i] = inputArray(w, targetID);
}
endCurScope();
return sis;
}
/**
* Appends a protocol to input a array of BigIntegers.
*
* @param is
* the BigInteger values
* @param targetID
* the party to input
* @return SInt's that will be loaded with the corresponding inputs, by the
* appended protocol.
*/
public SInt[] inputArray(BigInteger[] is, int targetID) {
SInt[] sis = new SInt[is.length];
for (int i = 0; i < sis.length; i++) {
sis[i] = sif.getSInt();
}
append(new InputArray(is, sis, targetID));
return sis;
}
/**
* Appends a protocol to input a array of BigIntegers.
*
* @param is
* the BigInteger values
* @param targetID
* the party to input
* @return SInt's that will be loaded with the corresponding inputs, by the
* appended protocol.
*/
public SInt[] inputArray(int[] is, int targetID) {
BigInteger[] tmp = new BigInteger[is.length];
for (int i = 0; i < tmp.length; i++) {
tmp[i] = BigInteger.valueOf(is[i]);
}
return inputArray(tmp, targetID);
}
/**
* Appends a protocol to input a matrix of int's
*
* @param m
* A matrix of integers
* @param targetID
* The party to input
* @return SInt's that will be loaded with the corresponding inputs by the
* appended protocol.
*/
public SInt[][] inputMatrix(int[][] m, int targetID) {
BigInteger[][] tmp = new BigInteger[m.length][m[0].length];
for (int i = 0; i < tmp.length; i++) {
for (int j = 0; j < tmp[0].length; j++) {
tmp[i][j] = BigInteger.valueOf(m[i][j]);
}
}
return inputMatrix(tmp, targetID);
}
/**
* Appends a protocol to input an array of value by an other party. I.e., the
* values or not held by this party.
*
* @param length
* the length of the array
* @param targetID
* the id of the party to input
* @return SInt's to be loaded with the input
*/
public SInt[] inputArray(int length, int targetID) {
SInt[] sis = new SInt[length];
for (int i = 0; i < length; i++) {
sis[i] = sif.getSInt();
}
append(new InputArray(sis, targetID));
return sis;
}
/**
* A class to efficiently handle large amounts of inputs.
*
* @author psn
*/
private class InputArray extends AbstractRepeatProtocol {
BigInteger[] is;
SInt[] sis;
int length;
int targetID;
int i = 0;
public InputArray(SInt[] sis, int targetID) {
this.length = sis.length;
this.is = null;
this.sis = sis;
this.targetID = targetID;
}
public InputArray(BigInteger[] is, SInt[] sis, int targetID) {
if (is.length != sis.length) {
throw new IllegalArgumentException("Array dimensions do not match.");
}
this.is = is;
this.length = sis.length;
this.sis = sis;
this.targetID = targetID;
}
@Override
protected ProtocolProducer getNextProtocolProducer() {
ProtocolProducer input = null;
if (i < length) {
OInt oi = oif.getOInt();
if (is != null) {
oi.setValue(is[i]);
}
input = iof.getCloseProtocol(targetID, oi, sis[i]);
i++;
}
return input;
}
}
/**
* Appends a protocol to input a single BigInteger
*
* @param i
* the BigInteger value
* @param targetID
* the party to input
* @return the SInt to be loaded with the input
*/
public SInt input(BigInteger i, int targetID) {
SInt si = sif.getSInt();
OInt oi = oif.getOInt();
oi.setValue(i);
append(iof.getCloseProtocol(targetID, oi, si));
return si;
}
/**
* Appends a protocol to input a single BigInteger
*
* @param i
* the integer value
* @param targetID
* the party to input
* @return the SInt to be loaded with the input
*/
public SInt input(int i, int targetID) {
SInt si = sif.getSInt();
OInt oi = oif.getOInt();
oi.setValue(BigInteger.valueOf(i));
append(iof.getCloseProtocol(targetID, oi, si));
return si;
}
/**
* Appends a protocol to input a single value from an other party. I.e., the
* value is not given.
*
* @param targetID
* the id of the party inputting.
* @return SInt to be loaded with the input.
*/
public SInt input(int targetID) {
SInt si = sif.getSInt();
append(iof.getCloseProtocol(targetID, null, si));
return si;
}
/**
* Appends a protocol to open a matrix of SInts. Output should be given to
* all parties.
*
* @param sis
* SInts to open
* @return the OInts to be loaded with the opened SInts
*/
public OInt[][] outputMatrix(SInt[][] sis) {
OInt[][] ois = new OInt[sis.length][sis[0].length];
beginParScope();
for (int i = 0; i < sis.length; i++) {
ois[i] = outputArray(sis[i]);
}
endCurScope();
return ois;
}
/**
* Appends a protocol to open an array of SInts. Output should be given to
* all parties.
*
* @param sis
* SInts to open
* @return the OInts to be loaded with the opened SInts
*/
public OInt[] outputArray(SInt sis[]) {
OInt[] ois = new OInt[sis.length];
for (int i = 0; i < sis.length; i++) {
ois[i] = oif.getOInt();
}
append(new OutputArray(sis, ois));
return ois;
}
/**
* A class to efficiently handle large amounts of outputs.
*
* @author psn
*/
private class OutputArray extends AbstractRepeatProtocol {
OInt[] ois;
SInt[] sis;
int i = 0;
public OutputArray(SInt[] sis, OInt[] ois) {
this.ois = ois;
this.sis = sis;
}
@Override
protected ProtocolProducer getNextProtocolProducer() {
ProtocolProducer output = null;
if (i < ois.length) {
output = iof.getOpenProtocol(sis[i], ois[i]);
i++;
}
return output;
}
}
/**
* Appends a protocol to open a single SInt. Output should be given to all
* parties.
*
* @param sis
* SInt to open
* @return the OInt to be loaded with the opened SInt
*/
public OInt output(SInt si) {
OInt oi = oif.getOInt();
append(iof.getOpenProtocol(si, oi));
return oi;
}
/**
* Appends a protocol to open a single SInt. Output is given only to the
* target ID.
*
* @param target
* the party to receive the output.
* @param si
* the SInt to open.
* @return
*/
public OInt outputToParty(int target, SInt si) {
OInt oi = oif.getOInt();
append(iof.getOpenProtocol(target, si, oi));
return oi;
}
@Override
public void addProtocolProducer(ProtocolProducer gp) {
append(gp);
}
}
| true
|
8a2c4d383d93cb16e74568012995ed6c22390c03
|
Java
|
sneham30/Cisco_Training
|
/Banking System/src/Exceptions/LowBalanceException.java
|
UTF-8
| 369
| 2.734375
| 3
|
[] |
no_license
|
package Exceptions;
/*
* Exception Class for LowBalance
*/
public class LowBalanceException extends Exception {
/**
*
*/
private static final long serialVersionUID = 1L;
/* constrcutor for LowBalanceException */
public LowBalanceException() {
super();
System.out.println("Your balance is Low to withDraw this Amount!!!");
}
}
| true
|
6f1e8ab28aba100e5aa53ec3eb8c990aac875df3
|
Java
|
sinetznjr11/load-from-api
|
/app/src/main/java/com/example/sinet/androidclassapp/LoadActivity.java
|
UTF-8
| 3,884
| 2.328125
| 2
|
[] |
no_license
|
package com.example.sinet.androidclassapp;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
public class LoadActivity extends AppCompatActivity {
Button button;
TextView textView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_load);
textView=findViewById(R.id.textView);
button=findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//add_data(null);
}
});
// Instantiate the RequestQueue.
RequestQueue queue = Volley.newRequestQueue(this);
String url ="https://merogyan.com/college/request.php?datacount=1";
// Request a string response from the provided URL.
StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
// Display the first 500 characters of the response string.
try {
JSONArray jsonArray= new JSONArray(response);
for(int i=0; i<jsonArray.length();i++){
Log.d("Server Data: ", response);
String name= jsonArray.getJSONObject(i).getString("name");
String email=jsonArray.getJSONObject(i).getString("email");
String url=jsonArray.getJSONObject(i).getString("url");
//server ko string name in json
textView.setText(name+" "+email+" "+url);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
textView.setText("That didn't work!");
}
});
// Add the request to the RequestQueue.
queue.add(stringRequest);
}
public void add_data(View view) {
Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
String source = msg.obj.toString();
Log.d("Server Data: ", source);
// Toast.makeText(LoadActivity.this, "Server data"+source, Toast.LENGTH_SHORT).show();
try {
JSONArray jsonArray= new JSONArray(source);
for(int i=0; i<jsonArray.length();i++){
String name= jsonArray.getJSONObject(i).getString("name");
String email=jsonArray.getJSONObject(i).getString("email");//server ko string name in json
}
} catch (JSONException e) {
e.printStackTrace();
}
}
};
HttpSourceRequest httpSourceRequest =
new HttpSourceRequest(handler, "https://merogyan.com/college/request.php?datacount=all");
}
}
| true
|
a2baf5997669201f7af8a8db1a6c6f2197d13d6c
|
Java
|
onfsdn/atrium-onos
|
/protocols/netconf/ctl/src/main/java/org/onosproject/netconf/ctl/NetconfStreamThread.java
|
UTF-8
| 9,103
| 1.953125
| 2
|
[
"Apache-2.0"
] |
permissive
|
/*
* Copyright 2015 Open Networking Laboratory
*
* 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.onosproject.netconf.ctl;
import com.google.common.base.Preconditions;
import com.google.common.collect.Lists;
import org.onosproject.netconf.NetconfDeviceInfo;
import org.onosproject.netconf.NetconfDeviceOutputEvent;
import org.onosproject.netconf.NetconfDeviceOutputEventListener;
import org.onosproject.netconf.NetconfException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.List;
import java.util.concurrent.CompletableFuture;
/**
* Thread that gets spawned each time a session is established and handles all the input
* and output from the session's streams to and from the NETCONF device the session is
* established with.
*/
public class NetconfStreamThread extends Thread implements NetconfStreamHandler {
private static final Logger log = LoggerFactory
.getLogger(NetconfStreamThread.class);
private static final String HELLO = "hello";
private static final String END_PATTERN = "]]>]]>";
private static final String RPC_REPLY = "rpc-reply";
private static final String RPC_ERROR = "rpc-error";
private static final String NOTIFICATION_LABEL = "<notification>";
private static PrintWriter outputStream;
private static NetconfDeviceInfo netconfDeviceInfo;
private static NetconfSessionDelegate sessionDelegate;
private static NetconfMessageState state;
private static List<NetconfDeviceOutputEventListener> netconfDeviceEventListeners
= Lists.newArrayList();
public NetconfStreamThread(final InputStream in, final OutputStream out,
final InputStream err, NetconfDeviceInfo deviceInfo,
NetconfSessionDelegate delegate) {
super(handler(in, err));
outputStream = new PrintWriter(out);
netconfDeviceInfo = deviceInfo;
state = NetconfMessageState.NO_MATCHING_PATTERN;
sessionDelegate = delegate;
log.debug("Stream thread for device {} session started", deviceInfo);
start();
}
@Override
public CompletableFuture<String> sendMessage(String request) {
outputStream.print(request);
outputStream.flush();
return new CompletableFuture<>();
}
public enum NetconfMessageState {
NO_MATCHING_PATTERN {
@Override
NetconfMessageState evaluateChar(char c) {
if (c == ']') {
return FIRST_BRAKET;
} else {
return this;
}
}
},
FIRST_BRAKET {
@Override
NetconfMessageState evaluateChar(char c) {
if (c == ']') {
return SECOND_BRAKET;
} else {
return NO_MATCHING_PATTERN;
}
}
},
SECOND_BRAKET {
@Override
NetconfMessageState evaluateChar(char c) {
if (c == '>') {
return FIRST_BIGGER;
} else {
return NO_MATCHING_PATTERN;
}
}
},
FIRST_BIGGER {
@Override
NetconfMessageState evaluateChar(char c) {
if (c == ']') {
return THIRD_BRAKET;
} else {
return NO_MATCHING_PATTERN;
}
}
},
THIRD_BRAKET {
@Override
NetconfMessageState evaluateChar(char c) {
if (c == ']') {
return ENDING_BIGGER;
} else {
return NO_MATCHING_PATTERN;
}
}
},
ENDING_BIGGER {
@Override
NetconfMessageState evaluateChar(char c) {
if (c == '>') {
return END_PATTERN;
} else {
return NO_MATCHING_PATTERN;
}
}
},
END_PATTERN {
@Override
NetconfMessageState evaluateChar(char c) {
return NO_MATCHING_PATTERN;
}
};
abstract NetconfMessageState evaluateChar(char c);
}
private static Runnable handler(final InputStream in, final InputStream err) {
BufferedReader bufferReader = new BufferedReader(new InputStreamReader(in));
return () -> {
try {
boolean socketClosed = false;
StringBuilder deviceReplyBuilder = new StringBuilder();
while (!socketClosed) {
int cInt = bufferReader.read();
if (cInt == -1) {
socketClosed = true;
NetconfDeviceOutputEvent event = new NetconfDeviceOutputEvent(
NetconfDeviceOutputEvent.Type.DEVICE_UNREGISTERED,
null, null, -1, netconfDeviceInfo);
netconfDeviceEventListeners.forEach(
listener -> listener.event(event));
}
char c = (char) cInt;
state = state.evaluateChar(c);
deviceReplyBuilder.append(c);
if (state == NetconfMessageState.END_PATTERN) {
String deviceReply = deviceReplyBuilder.toString()
.replace(END_PATTERN, "");
if (deviceReply.contains(RPC_REPLY) ||
deviceReply.contains(RPC_ERROR) ||
deviceReply.contains(HELLO)) {
NetconfDeviceOutputEvent event = new NetconfDeviceOutputEvent(
NetconfDeviceOutputEvent.Type.DEVICE_REPLY,
null, deviceReply, getMsgId(deviceReply), netconfDeviceInfo);
sessionDelegate.notify(event);
netconfDeviceEventListeners.forEach(
listener -> listener.event(event));
} else if (deviceReply.contains(NOTIFICATION_LABEL)) {
final String finalDeviceReply = deviceReply;
netconfDeviceEventListeners.forEach(
listener -> listener.event(new NetconfDeviceOutputEvent(
NetconfDeviceOutputEvent.Type.DEVICE_NOTIFICATION,
null, finalDeviceReply, getMsgId(finalDeviceReply), netconfDeviceInfo)));
} else {
log.info("Error on replay from device {} ", deviceReply);
}
deviceReplyBuilder.setLength(0);
}
}
} catch (IOException e) {
log.warn("Error in reading from the session for device " + netconfDeviceInfo, e);
throw new RuntimeException(new NetconfException("Error in reading from the session for device {}" +
netconfDeviceInfo, e));
//TODO should we send a socket closed message to listeners ?
}
};
}
private static int getMsgId(String reply) {
if (!reply.contains(HELLO)) {
String[] outer = reply.split("message-id=");
Preconditions.checkArgument(outer.length != 1,
"Error in retrieving the message id");
String messageID = outer[1].substring(0, 3).replace("\"", "");
Preconditions.checkNotNull(Integer.parseInt(messageID),
"Error in retrieving the message id");
return Integer.parseInt(messageID);
} else {
return 0;
}
}
public void addDeviceEventListener(NetconfDeviceOutputEventListener listener) {
if (!netconfDeviceEventListeners.contains(listener)) {
netconfDeviceEventListeners.add(listener);
}
}
public void removeDeviceEventListener(NetconfDeviceOutputEventListener listener) {
netconfDeviceEventListeners.remove(listener);
}
}
| true
|
d56d0cf32bd9f3368eda2314ea808b87fd06e322
|
Java
|
logobalk/initial-java-spring-boot
|
/src/main/java/com/siampharm/sampling/model/PoItemsConfirmationDnBatch.java
|
UTF-8
| 4,682
| 1.984375
| 2
|
[] |
no_license
|
package com.siampharm.sampling.model;
// Generated Feb 25, 2019 2:45:54 PM by Hibernate Tools 5.2.11.Final
import javax.persistence.*;
import java.util.Date;
/**
* PoItemsConfirmationDnBatch generated by hbm2java
*/
@Entity
@Table(name = "po_items_confirmation_dn_batch", schema = "bpi" )
public class PoItemsConfirmationDnBatch implements java.io.Serializable {
private static final long serialVersionUID = 2620159661845577905L;
private Integer id;
private PoItems poItems;
private PoItemsBatch poItemsBatch;
private PoItemsConfirmation poItemsConfirmation;
private Integer lineItem;
private String deliveryNote;
private String batch;
private String changeRemark;
private Boolean isDeleted;
private String createdBy;
private Date createdDate;
private String updatedBy;
private Date updatedDate;
public PoItemsConfirmationDnBatch() {
}
public PoItemsConfirmationDnBatch(Integer id, PoItemsConfirmation poItemsConfirmation, Integer lineItem,
Boolean isDeleted, String createdBy, Date createdDate) {
this.id = id;
this.poItemsConfirmation = poItemsConfirmation;
this.lineItem = lineItem;
this.isDeleted = isDeleted;
this.createdBy = createdBy;
this.createdDate = createdDate;
}
public PoItemsConfirmationDnBatch(Integer id, PoItems poItems, PoItemsBatch poItemsBatch,
PoItemsConfirmation poItemsConfirmation, Integer lineItem, String deliveryNote, String batch,
String changeRemark, Boolean isDeleted, String createdBy, Date createdDate, String updatedBy,
Date updatedDate) {
this.id = id;
this.poItems = poItems;
this.poItemsBatch = poItemsBatch;
this.poItemsConfirmation = poItemsConfirmation;
this.lineItem = lineItem;
this.deliveryNote = deliveryNote;
this.batch = batch;
this.changeRemark = changeRemark;
this.isDeleted = isDeleted;
this.createdBy = createdBy;
this.createdDate = createdDate;
this.updatedBy = updatedBy;
this.updatedDate = updatedDate;
}
@Id
@Column(name = "id", unique = true, nullable = false)
public Integer getId() {
return this.id;
}
public void setId(Integer id) {
this.id = id;
}
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "po_items_id")
public PoItems getPoItems() {
return this.poItems;
}
public void setPoItems(PoItems poItems) {
this.poItems = poItems;
}
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "po_items_batch_id")
public PoItemsBatch getPoItemsBatch() {
return this.poItemsBatch;
}
public void setPoItemsBatch(PoItemsBatch poItemsBatch) {
this.poItemsBatch = poItemsBatch;
}
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "po_items_confirmation_id", nullable = false)
public PoItemsConfirmation getPoItemsConfirmation() {
return this.poItemsConfirmation;
}
public void setPoItemsConfirmation(PoItemsConfirmation poItemsConfirmation) {
this.poItemsConfirmation = poItemsConfirmation;
}
@Column(name = "line_item", nullable = false)
public Integer getLineItem() {
return this.lineItem;
}
public void setLineItem(Integer lineItem) {
this.lineItem = lineItem;
}
@Column(name = "delivery_note", length = 30)
public String getDeliveryNote() {
return this.deliveryNote;
}
public void setDeliveryNote(String deliveryNote) {
this.deliveryNote = deliveryNote;
}
@Column(name = "batch", length = 30)
public String getBatch() {
return this.batch;
}
public void setBatch(String batch) {
this.batch = batch;
}
@Column(name = "change_remark", length = 250)
public String getChangeRemark() {
return this.changeRemark;
}
public void setChangeRemark(String changeRemark) {
this.changeRemark = changeRemark;
}
@Column(name = "is_deleted", nullable = false)
public Boolean getIsDeleted() {
return this.isDeleted;
}
public void setIsDeleted(Boolean isDeleted) {
this.isDeleted = isDeleted;
}
@Column(name = "created_by", nullable = false, length = 50)
public String getCreatedBy() {
return this.createdBy;
}
public void setCreatedBy(String createdBy) {
this.createdBy = createdBy;
}
@Temporal(TemporalType.TIMESTAMP)
@Column(name = "created_date", nullable = false, length = 23)
public Date getCreatedDate() {
return this.createdDate;
}
public void setCreatedDate(Date createdDate) {
this.createdDate = createdDate;
}
@Column(name = "updated_by", length = 50)
public String getUpdatedBy() {
return this.updatedBy;
}
public void setUpdatedBy(String updatedBy) {
this.updatedBy = updatedBy;
}
@Temporal(TemporalType.TIMESTAMP)
@Column(name = "updated_date", length = 23)
public Date getUpdatedDate() {
return this.updatedDate;
}
public void setUpdatedDate(Date updatedDate) {
this.updatedDate = updatedDate;
}
}
| true
|
df35b2e5815a9df7373cb225fc6e571abbce8656
|
Java
|
Liuzihao169/learn-spring-security
|
/spring-security/chap08/uaa/src/main/java/com/imooc/uaa/domain/Auth.java
|
UTF-8
| 305
| 1.851563
| 2
|
[] |
no_license
|
package com.imooc.uaa.domain;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.io.Serializable;
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Auth implements Serializable {
private String accessToken;
private String refreshToken;
}
| true
|
c4bfc5960f42ac926cc26c66c41b5366df011075
|
Java
|
singhaniatanay/Competitive-Programming
|
/Stack + Queue/D7_parsing_ternary_expression.java
|
UTF-8
| 1,138
| 3.71875
| 4
|
[
"MIT"
] |
permissive
|
import java.util.*;
class D7_parsing_ternary_expression {
public static String parseTernary(String s) {
Stack<String> st = new Stack<>();
for(int i=s.length()-1;i>=0;i--){
if(s.charAt(i)==':')
continue;
if(s.charAt(i)=='?'&&(s.charAt(i-1)=='T'||s.charAt(i-1)=='F')){
if(s.charAt(--i)=='F'){
st.pop();
}else{
String a =st.pop();
st.pop();
st.push(a);
}
continue;
}
else{
st.push(s.charAt(i)+"");
while(i>0&&(s.charAt(i-1)!=':'&&s.charAt(i-1)!='?')){
st.push(s.charAt(--i)+st.pop()); //If 2 or more digits come
}
continue;
}
}
return st.peek();
}
// Dont make chsnges here
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print(parseTernary(sc.next()));
}
}
| true
|
52b9f69061c061fc356ec09ac30b06b2edc46aaa
|
Java
|
bangmac/CityHunter
|
/src/main/java/com/bmv/kiemtramodule4/service/CityService.java
|
UTF-8
| 254
| 1.78125
| 2
|
[] |
no_license
|
package com.bmv.kiemtramodule4.service;
import com.bmv.kiemtramodule4.model.City;
import java.util.List;
public interface CityService {
Iterable<City> findAll();
City findById(Long id);
void save(City city);
void delete(Long id);
}
| true
|
16e69ed587d27c5e6064768dbfa23160d8949651
|
Java
|
fera0013/PrincetonAlgorithms1
|
/src/KdTree.java
|
UTF-8
| 5,703
| 3.421875
| 3
|
[] |
no_license
|
public class KdTree {
private static class Node {
private Point2D p; // the point
private RectHV rect; // the axis-aligned rectangle corresponding to this node
private Node left; // the left/bottom subtree
private Node right; // the right/top subtree
}
private enum orientation {
HORIZONTAL, VERTICAL
}
private int numberOfPoints=0;
private Node root=null;
// construct an empty set of points
public KdTree()
{
}
// is the set empty?
public boolean isEmpty()
{
return size()==0;
}
// number of points in the set
public int size()
{
return numberOfPoints;
}
// add the point to the set (if it is not already in the set)
public void insert(Point2D p)
{
if(!contains(p))
{
RectHV rect= new RectHV(0, 0, 1, 1);
root = put(root, p,orientation.VERTICAL,rect);
this.numberOfPoints++;
}
}
private Node put(Node node, Point2D p,orientation o,RectHV rect) {
if (node == null)
{
Node newNode = new Node();
newNode.p=p;
newNode.rect=rect;
return newNode;
}
if(node.p.equals(p))
{
return node;
}
if(o==orientation.VERTICAL)
{
if(p.x()<node.p.x())
{
node.left = put(node.left,p,orientation.HORIZONTAL,new RectHV(rect.xmin(),rect.ymin(),node.p.x(),rect.ymax()));
}
else
{
node.right = put(node.right,p,orientation.HORIZONTAL,new RectHV(node.p.x(),rect.ymin(),rect.xmax(),rect.ymax()));
}
}
else
{
if(p.y()<node.p.y())
{
node.left = put(node.left,p,orientation.VERTICAL,new RectHV(rect.xmin(),rect.ymin(),rect.xmax(),node.p.y()));
}
else
{
node.right = put(node.right,p,orientation.VERTICAL,new RectHV(rect.xmin(),node.p.y(),rect.xmax(),rect.ymax()));
}
}
return node;
}
// does the set contain point p?
public boolean contains(Point2D p)
{
return get(p,orientation.VERTICAL)!=null;
}
private Point2D get(Point2D key,orientation o)
{
return get(root, key,o);
}
private Point2D get(Node node, Point2D point,orientation o)
{
if (node == null)
{
return null;
}
if(node.p.equals(point))
{
return node.p;
}
if(o==orientation.VERTICAL)
{
if(point.x()<node.p.x())
{
return get(node.left, point,orientation.HORIZONTAL);
}
else
{
return get(node.right, point,orientation.HORIZONTAL);
}
}
else
{
if(point.y()<node.p.y())
{
return get(node.left, point,orientation.VERTICAL);
}
else
{
return get(node.right, point,orientation.VERTICAL);
}
}
}
// draw all points to standard draw
public void draw()
{
drawHelper(root,orientation.VERTICAL);
}
private void drawHelper(Node node,orientation o)
{
if(node == null)
{
return;
}
StdDraw.setPenColor(StdDraw.BLACK);
StdDraw.setPenRadius(.01);
node.p.draw();
StdDraw.setPenRadius(0.001);
if(o==orientation.VERTICAL)
{
StdDraw.setPenColor(StdDraw.RED);
Point2D pointFrom = new Point2D(node.p.x(),node.rect.ymin());
Point2D pointTo = new Point2D(node.p.x(),node.rect.ymax());
pointFrom.drawTo(pointTo);
drawHelper(node.left,orientation.HORIZONTAL);
drawHelper(node.right,orientation.HORIZONTAL);
}
else
{
StdDraw.setPenColor(StdDraw.BLUE);
Point2D pointFrom = new Point2D(node.rect.xmin(),node.p.y());
Point2D pointTo = new Point2D(node.rect.xmax(),node.p.y());
pointFrom.drawTo(pointTo);
drawHelper(node.left,orientation.VERTICAL);
drawHelper(node.right,orientation.VERTICAL);
}
}
private void rangeHelper(Node node, RectHV rect,SET<Point2D> result )
{
if (node == null)
return;
if (!rect.intersects(node.rect))
return;
if (rect.contains(node.p))
result.add(node.p);
rangeHelper(node.left, rect, result);
rangeHelper(node.right, rect, result);
}
// all points that are inside the rectangle
public Iterable<Point2D> range(RectHV rect)
{
SET<Point2D> result = new SET<Point2D>();
rangeHelper(root, rect,result);
return result;
}
// a nearest neighbor in the set to point p; null if the set is empty
public Point2D nearest(Point2D p)
{
if(this.numberOfPoints==0)
{
return null;
}
return findNearest(p,root.p,root);
}
private Point2D findNearest(Point2D queryPoint,Point2D nearest,Node node)
{
if(node==null||nearest.distanceTo(queryPoint)<node.rect.distanceTo(queryPoint))
{
return nearest;
}
if(node.p.distanceTo(queryPoint)<nearest.distanceTo(queryPoint))
{
nearest=node.p;
}
nearest=findNearest(queryPoint,nearest,node.left);
nearest=findNearest(queryPoint,nearest,node.right);
return nearest;
}
// unit testing of the methods (optional)
public static void main(String[] args)
{
String filename = args[0];
In in = new In(filename);
// initialize the data structures with N points from standard input
KdTree kdtree = new KdTree();
while (!in.isEmpty()) {
double x = in.readDouble();
double y = in.readDouble();
Point2D p = new Point2D(x, y);
kdtree.insert(p);
}
Point2D p=new Point2D(0.500000, 1.000000);
kdtree.insert(p);
Out out = new Out();
out.println(kdtree.size());
// draw the points
kdtree.draw();
StdDraw.show(1);
}
}
| true
|
7d588def639468502b3ce8f6311913b292fb7e67
|
Java
|
MaximKlameth/MaximsRepo1
|
/src/ButtonBarView.java
|
UTF-8
| 1,448
| 2.859375
| 3
|
[] |
no_license
|
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridLayout;
import javax.swing.JButton;
import javax.swing.JPanel;
public class ButtonBarView extends JPanel {
private static final long serialVersionUID = 1L;
private JButton startButton;
private JButton leichtButton;
private JButton schwerButton;
private JButton spielBeendenButton;
private final SnakeController snakeController;
public ButtonBarView(SnakeController snakeController) {
this.snakeController = snakeController;
createButtons();
}
public void createButtons() {
this.setPreferredSize(new Dimension(SnakeUtils.BREITE, 30));
startButton = new JButton("Spiel Starten");
startButton.addActionListener(snakeController.getStartGameListener());
add(startButton);
leichtButton = new JButton("Schwierigkeit verringern");
leichtButton.addActionListener(snakeController.getSchwierigkeitVerringernListener());
add(leichtButton);
schwerButton = new JButton("Schwierigkeit erhöhen");
schwerButton.addActionListener(snakeController.getSchwierigkeitErhoehenListener());
add(schwerButton);
spielBeendenButton = new JButton("Spiel abbrechen"); spielBeendenButton.addActionListener(snakeController.getExitGameListener()); add(spielBeendenButton);
setLayout(new GridLayout());
}
public void setPauseButton() {
startButton.setText("PAUSE");
}
public void setStartButton() {
startButton.setText("START!");
}
}
| true
|
18ed65fd3f5c8cf117ec29af820374aa3e328ddd
|
Java
|
health-information-exchange/openncp
|
/tsam-sync/src/main/java/epsos/ccd/carecom/tsam/synchronizer/statistics/FileStatisticsGatherer.java
|
UTF-8
| 3,073
| 2.65625
| 3
|
[] |
no_license
|
package epsos.ccd.carecom.tsam.synchronizer.statistics;
import epsos.ccd.carecom.tsam.synchronizer.ApplicationController;
import org.slf4j.event.Level;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintStream;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
/**
* Implements a gatherer that maintains all statistics records and at the end prints them to
* some specified print stream which can either be a file or <code>System.out</code>.
*/
public class FileStatisticsGatherer implements Gatherer {
private List<ActionRecord> records;
private ActionRecord current;
private String fileName;
private boolean handleError;
private Level logLevel;
private long accumulatedDuration;
/**
* Default constructor.
*
* @param fileName Name of the file to write to.
* @param handleError Indicates if an error should be handled or ignored.
*/
public FileStatisticsGatherer(String fileName, boolean handleError, Level logLevel) {
this.records = new LinkedList<ActionRecord>();
this.fileName = fileName;
this.handleError = handleError;
this.logLevel = logLevel;
this.accumulatedDuration = 0;
}
public void registerActionStart(String webMethodName,
Map<String, Long> filters) {
this.current = new ActionRecord();
this.current.setActionName(webMethodName);
this.current.setFilters(filters);
this.current.setStartTime(new Date());
}
public void registerActionEnd(String actionName, int numberOfRecords) {
this.current.setEndTime(new Date());
this.current.setNumberOfRecordsFetched(numberOfRecords);
this.records.add(this.current);
this.accumulatedDuration += this.current.getEndTime().getTime() - this.current.getStartTime().getTime();
}
public void registerGatheringComplete() {
ApplicationController.LOG.info("Accumulated Webservice duration: " + new TimeSpan(this.accumulatedDuration));
if (this.fileName != null && this.fileName.length() > 0) {
File file = new File(this.fileName);
try {
if (file.exists()) {
file.delete();
}
} catch (SecurityException e) {
if (this.handleError) {
printToStream(System.out);
}
// Else ignore
}
try {
PrintStream ps = new PrintStream(file);
printToStream(ps);
ps.close();
} catch (FileNotFoundException e) {
if (this.handleError) {
printToStream(System.out);
}
// Else ignore
}
} else {
printToStream(System.out);
}
}
private void printToStream(PrintStream ps) {
for (ActionRecord record : this.records) {
ps.println(record);
}
}
}
| true
|
dd96040180ce367822321e69404c431cb5912fe4
|
Java
|
sstokic-tgm/Decorator_FileSharing
|
/src/stokic/server/Connection.java
|
UTF-8
| 646
| 3.1875
| 3
|
[] |
no_license
|
package stokic.server;
import java.io.IOException;
/**
* Ein Interface fuer den Server. Beinhaltet das Vorbereiten der Server Connection(hostname, port) und
* das Starten des Servers.
*
* @author Stefan Stokic
* @version 0.1
*/
public interface Connection {
/**
* @param hostname der Name des Hosts, auf dem der MulticastSocket laufen soll
* @param port der Port, auf dem der Socket laufen soll
*
* Dient zum Herstellen der Verbindung zum Socket.
*/
public void setupConnection(String hostname, int port);
/**
* Dient zum Starten des Servers
* @throws IOException
*/
public void startConnection() throws IOException;
}
| true
|
bf57e63d6faf55b525a8cf8cd6aecfa79f628a41
|
Java
|
blopez24/UC-Santa-Cruz
|
/SophomoreYear/CMPS12B/HW3/CPLinkedList.java
|
UTF-8
| 1,041
| 3.546875
| 4
|
[] |
no_license
|
class CPLinkedList
{
Node head;
int length;
CPLinkedList()
{
this.head = null;
this.length = 0;
}
int size()
{
return length;
}
Node find(int index)
{
Node current = head;
for(int i = 0; i < index; i++)
{
current = current.next;
}
return current;
}
void add(int index, ChessPiece cp)
{
if(index >= 0 && index < length + 1)
{
if(index == 0)
{
Node newNode = new Node(cp, head);
head = newNode;
}
else
{
Node previous = find(index-1);
Node newNode = new Node(cp, previous.next);
previous.next = newNode;
}
length++;
}
}
public void remove(int index)
{
if(index == 0)
head = head.next;
else
{
Node prev = find(index-1);
Node curr = prev.next;
prev.next = curr.next;
}
length--;
}
public void removeAll()
{
head = null;
length = 0;
}
Object get(int index)
{
if(index >= 0 && index < length)
{
Node current = find(index);
ChessPiece cpData = current.data;
return cpData;
}
return null;
}
}
| true
|
f88bcbc6f7468a5ade296b7c324a7ce957d79e43
|
Java
|
SushanthNandan/CucumberWithRestAssured
|
/src/test/java/User.java
|
UTF-8
| 937
| 2.3125
| 2
|
[] |
no_license
|
import java.util.Arrays;
import com.fasterxml.jackson.annotation.JsonIgnoreType;
//@JsonIgnoreType
public class User {
private String authToken;
public String appId;
private String appTypeUid;
// Getter Methods
public String getAuthToken() {
return authToken;
}
public String getAppId() {
return appId;
}
public String getAppTypeUid() {
return appTypeUid;
}
// Setter Methods
public void setAuthToken(String authToken) {
this.authToken = authToken;
}
public void setAppId(String appId) {
this.appId = appId;
}
public void setAppTypeUid(String appTypeUid) {
this.appTypeUid = appTypeUid;
}
@Override
public String toString() {
return Arrays.asList(authToken, appId, appTypeUid).toString();
// return new ToStringBuilder(this).append("authToken", authToken).append("appId", appId).append("appTypeUid", appTypeUid)..toString();
}
}
| true
|
f95f9416cdc725288c0a5295b1096f3e4a50a1b8
|
Java
|
rlabyk-cartera/citi-tests
|
/src/main/java/com/cartera/citi/pages/MyPriceRewindPage.java
|
UTF-8
| 6,543
| 2
| 2
|
[] |
no_license
|
package com.cartera.citi.pages;
import com.cartera.citi.framework.decorator.CustomFieldDecorator;
import com.cartera.citi.framework.elements.*;
import com.cartera.citi.framework.logger.Logger;
import org.openqa.selenium.*;
//import org.openqa.selenium.support.CacheLookup;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;
import java.util.LinkedList;
import java.util.List;
/**
* Created by Roman_Labyk on 10/5/2015.
*/
public class MyPriceRewindPage extends BasePage {
@FindBy(id = "myPriceRewinds")
private Html html;
@FindBy(css = "div#cpr_header a.cpr_logInOutLink")
private Button logoutBtn;
@FindBy(css = ".cpr_grid>h1")
private Message headerMsg;
@FindBy(css = ".cpr_select.cpr_filter")
private SelectBox filterByTrackStatus;
@FindBy(css = "ul.cpr_filterOptions li a")
private List<WebElement> filterOptions;
@FindBy(css = ".cpr_select.cpr_filter .cpr_inner")
private Button filterBtn;
//PerPageView:
@FindBy(css = ".cpr_select.cpr_limit")
private SelectBox viewItemsPerPage;
@FindBy(css = "ul.cpr_limitOptions li a")
private List<WebElement> perPageOptions;
@FindBy(css = ".cpr_select.cpr_limit .cpr_inner")
private Button perPageFilterBtn;
//Tracks:
@FindBy(css = ".cpr_trackContent")
private List<WebElement> trackList;
@FindBy(css = ".cpr_productName")
private List<WebElement> trackNamesLst;
@FindBy(css = ".cpr_trackBtn")
private List<WebElement> trackStatuses;
//pagination
@FindBy(css = ".cpr_currentPage")
private Link curPage;
@FindBy(css = ".cpr_lastLink")
private Link lastPage;
////*[@class='cpr_pageLinks']//a[contains(@class, 'cpr_nextPage')]
@FindBy(css = ".cpr_nextPage")
private Link nextPage;
public MyPriceRewindPage(WebDriver driver) {
super(driver);
PageFactory.initElements(new CustomFieldDecorator(driver), this);
}
private String getMyPRWPageRelativeURL() {
return testData.getData("my_prw_page_relative_path");
}
public void open() {
open(getMyPRWPageRelativeURL());
}
public Boolean isPageOpened() {
try {
return html.isDisplayed();
} catch (NoSuchElementException e) {
e.printStackTrace();
return false;
}
}
public void logout() {
logoutBtn.waitForElement();
logoutBtn.click();
}
public String getUrl() {
return getBaseUrl() + getMyPRWPageRelativeURL();
}
public String getHeaderMessage() {
headerMsg.waitForElement();
return headerMsg.getText().replaceAll("\n", " ").trim();
}
//FilterBy options
public List<String> getAllFilterByOptions() {
List<String> optionList = new LinkedList<String>();
for (WebElement webElement : filterOptions) {
optionList.add(webElement.getAttribute("innerHTML").replaceAll("[\\d]", ""));
}
return optionList;
}
public void selectTrackStatus(String status) {
clickFilterByButton();
for (WebElement webElement : filterOptions) {
if (webElement.getAttribute("innerHTML").contains(status)) {
try {
webElement.click();
break;
} catch (ElementNotVisibleException ex) {
Logger.logStep("ElementNotVisibleException happened because of foresee pop-up, closing it!");
driver.findElement(By.cssSelector("a.fsrCloseBtn")).click();
continue;
}
}
}
}
public String getDefaultFilterOption() {
String option = null;
for (WebElement webElement : filterOptions) {
if (webElement.getAttribute("class").contains("cpr_active")) {
option = webElement.getAttribute("innerHTML").replaceAll("[\\d]", "");
break;
}
}
return option;
}
public void clickFilterByButton() {
filterBtn.click();
}
//PerPage:
public List<String> getAllPerPageOptions() {
List<String> optionList = new LinkedList<String>();
for (WebElement webElement : perPageOptions) {
optionList.add(webElement.getAttribute("innerHTML"));
}
return optionList;
}
public void selectPerPageView(String itemPerPage) {
clickPerPageButton();
for (WebElement webElement : perPageOptions) {
webElement.isDisplayed();
if (webElement.getAttribute("innerHTML").contains(itemPerPage)) {
webElement.click();
break;
}
}
}
public String getDefaultPerPageView() {
String option = null;
for (WebElement webElement : perPageOptions) {
if (webElement.getAttribute("class").contains("cpr_active"))
option = webElement.getAttribute("innerHTML");
}
return option;
}
public void clickPerPageButton() {
perPageFilterBtn.waitForElement();
perPageFilterBtn.click();
}
public List<String> getTrackNames() {
List<String> trackNames = new LinkedList<String>();
for (WebElement webElement : trackNamesLst) {
trackNames.add(webElement.getAttribute("innerHTML"));
}
return trackNames;
}
public List<String> getTrackStatuses() {
List<String> trackStatusLst = new LinkedList<String>();
for (WebElement webElement : trackStatuses) {
trackStatusLst.add(webElement.getAttribute("innerHTML"));
}
return trackStatusLst;
}
public void clickRefundRequestPending(Integer index){
trackStatuses.get(index).click();
}
public Integer getTracksCount() {
if (!trackList.isEmpty()) {
return trackList.size();
} else {
return 0;
}
}
public void clickNextPage() {
Logger.logStep("Clicking 'Next' page link.");
nextPage.waitForElement();
nextPage.click();
}
public void clickLastPage() {
Logger.logStep("Clicking 'Last' page link.");
lastPage.waitForElement();
lastPage.click();
}
public Integer getCurPage() {
return Integer.parseInt(curPage.getWebElement().getAttribute("innerHTML"));
}
public Integer getLastPage() {
return Integer.parseInt(lastPage.getWebElement().getAttribute("innerHTML"));
}
}
| true
|
d71700dc476fba0ac26d9273f760fdf8c4402cc8
|
Java
|
fabixneytor/Utp
|
/Ciclo 2/Proyecto_avion/src/AvionCarga.java
|
UTF-8
| 447
| 2.625
| 3
|
[] |
no_license
|
public class AvionCarga extends Avion{
/*********************
* Método constructor
*********************/
public AvionCarga(String color, int tamanio){
super(color, tamanio);
}
/************
* Métodos
***********/
public void cargar(){
System.out.println("Cargando...");
}
public void descargar(){
System.out.println("Descargando...");
}
}
| true
|
26e6b23a7ee6d7b5960d974a78cf72c9a0682b96
|
Java
|
Speawtr/LobbySystem
|
/src/me/lusu007/lobbysystem/System/main.java
|
UTF-8
| 5,477
| 1.609375
| 2
|
[] |
no_license
|
package me.lusu007.lobbysystem.System;
import de.slikey.effectlib.EffectLib;
import de.slikey.effectlib.EffectManager;
import me.lusu007.lobbysystem.AdminSettings.RequestMOTD;
import me.lusu007.lobbysystem.Boots.Boots_Aggro;
import me.lusu007.lobbysystem.Boots.Boots_Jump;
import me.lusu007.lobbysystem.Boots.Boots_YOLO;
import me.lusu007.lobbysystem.Boots.RemoveBoots;
import me.lusu007.lobbysystem.Commands.*;
import me.lusu007.lobbysystem.Features.Feature_DoppelJump;
import me.lusu007.lobbysystem.Features.Feature_Druckplatte;
import me.lusu007.lobbysystem.Features.Feature_Title;
import me.lusu007.lobbysystem.ItemManager.*;
import me.lusu007.lobbysystem.Listener.*;
import me.lusu007.lobbysystem.Villager.VillagerClick;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.scheduler.BukkitRunnable;
import java.util.ArrayList;
import java.util.HashMap;
/**
* Created by Lukas on 24.12.2014.
*/
public class main extends JavaPlugin {
/*
* Permission:
*
* server.join.message
* server.quit.message
*
* server.getitem.schutzschild
* server.getitem.autonicker
* server.getitem.silentlobby
* server.getitem.flugstab
* server.getitem.lobbyswitcher
*
* server.locations.set
* server.see.death
* server.build
* server.teleport
* server.pl.command
* server.furnace.extract
* server.set.gamemode
*
* server.visible
* server.bypass.schild
*
* server.feature.doubleJump
* server.feature.blockdestroy
*
* server.inventory.serversettings
*
* server.modt
*
*/
//==========[Integer]==========
public int timecountdown;
//==========[ArrayList]==========
public static ArrayList<String> flying = new ArrayList<String>();
public static ArrayList<String> saving = new ArrayList<String>();
public static ArrayList<String> hidden1 = new ArrayList<String>();
public static ArrayList<String> hidden2 = new ArrayList<String>();
//==========[HashMap]==========
public static HashMap<String, BukkitRunnable> jumper = new HashMap<String, BukkitRunnable>();
public static HashMap<String, BukkitRunnable> schild = new HashMap<String, BukkitRunnable>();
//==========[String]==========
public static String prefix = "";
public static String noperm = prefix + "§cDu hast keine Permissions.";
//==========[EffectManager]==========
public static EffectManager em;
public void onEnable(){
em = new EffectManager(EffectLib.instance());
new PlayerJoinEvent_Listener(this);
new BlockBreakEvent_Listener(this);
new BlockPlaceEvent_Listener(this); //Arbeitet noch nicht so, wei ich das will
new EntityDamageByEntityEvent_Listener(this);
new EntityDamageEvent_Listener(this);
new EntityDeathEvent_Listener(this);
new FoodLevelChangeEvent_Listener(this);
new PlayerDeathEvent_Listener(this);
new PlayerInteractEntityEvent_Listener(this);
new PlayerInteractEvent_Listener(this);
new PlayerKickEvent_Listener(this);
new PlayerPortalEvent_Listener(this);
new PlayerQuitEvent_Listener(this);
new EntityDamageByBlockEvent_Listener(this);
new PotionSplashEvent_Listener(this);
new PrepareItemEnchantEvent_Listener(this);
new CreatureSpawnEvent_Listener(this);
new EntityExplodeEvent_Listener(this);
new EntityPortalEvent_Listener(this);
new EntityShotBowEvent_Listener(this);
new ExpBottleEvent_Listener(this);
new ProjectileLaunchEvent_Listener(this);
new SlimeSplitEvent_Listener(this);
new PlayerBedEnterEvent_Listener(this);
new PlayerBukketEmptyEvent_Listener(this);
new PlayerCommandPreprocessEvent_Listener(this);
new PlayerDropItemEvent_Listener(this);
new PlayerEggThrowEvent_Listener(this);
new PlayerExpChangeEvent_Listener(this);
new BrewEvent_Listener(this);
new CraftItemEvent_Listener(this);
new FurnaceExtractEvent_Listener(this); //Arbeitet noch nicht so, wei ich das will
new InventoryMoveItemEvent_Listener(this);
new InventoryClickEvent_Listener(this);
new ExplosionPrimeEvent_Listener(this);
new PlayerFishEvent_Listener(this);
new WeatherChangeEvent_Listener(this);
new WorldSaveEvent_Listener(this);
new PlayerGameModeChangeEvent_Listener(this);
new HangingBreakByEntityEvent_Listener(this);
new PlayerItemConsumeEvent_Listener(this);
new Feature_Druckplatte(this);
new Feature_DoppelJump(this);
new Feature_Title(this);
new Item_Navigator(this);
new Item_Flugstab(this);
new Item_Hider(this);
new Item_Schild(this);
new Item_Settings(this);
new Boots_Jump(this);
new RemoveBoots(this);
new Boots_Aggro(this);
new Boots_YOLO(this);
new RequestMOTD(this);
new VillagerClick();
getCommand("set").setExecutor(new COMMAND_Set(this));
getCommand("teleport").setExecutor(new COMMAND_Teleport(this));
getCommand("gamemode").setExecutor(new COMMAND_Gamemode(this));
getCommand("villager").setExecutor(new COMMAND_Villager(this));
getCommand("spawn").setExecutor(new COMMANDS_Spawn(this));
getCommand("motd").setExecutor(new COMMAND_Modt(this));
}
}
| true
|
9502e0abf2e0f3671f7517ed1304972dd726df49
|
Java
|
panpanliuBJ/flash-stream
|
/src/main/java/com/finley/flash/stream/kafka/serializer/JsonDeserializer.java
|
UTF-8
| 1,625
| 2.40625
| 2
|
[] |
no_license
|
package com.finley.flash.stream.kafka.serializer;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
import java.util.Map;
import org.apache.kafka.common.serialization.Deserializer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class JsonDeserializer<T> implements Deserializer<T> {
private static Logger logger = LoggerFactory.getLogger(JsonDeserializer.class);
private ObjectMapper jsonMapper;
private Class<T> deserializerClass;
/**
* Default constructor needed by Kafka
*/
public JsonDeserializer() {
this.jsonMapper = new ObjectMapper().configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
}
public JsonDeserializer(Class<T> deserializerClass) {
this.deserializerClass = deserializerClass;
this.jsonMapper = new ObjectMapper().configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
}
@Override
public void configure(Map<String, ?> map, boolean b) {
if (deserializerClass == null) {
deserializerClass = (Class<T>) map.get("serializedClass");
}
}
@Override
public T deserialize(String s, byte[] bytes) {
if (bytes == null) {
return null;
}
try {
return jsonMapper.readValue(bytes, deserializerClass);
} catch (IOException e) {
logger.error("deserialize from json error|value={}", new String(bytes), e);
return null;
}
}
@Override
public void close() {
}
}
| true
|
59509336577f1511d1c8f30ce27f77d07e671d00
|
Java
|
fhrm2018/zbj
|
/dhlive-prd-all/dhlive-prd-bms/src/main/java/com/qiyou/dhlive/prd/room/controller/GoodsRemoteController.java
|
UTF-8
| 6,735
| 1.882813
| 2
|
[] |
no_license
|
package com.qiyou.dhlive.prd.room.controller;
import com.qiyou.dhlive.core.room.outward.model.RoomArticle;
import com.qiyou.dhlive.core.room.outward.model.RoomFile;
import com.qiyou.dhlive.core.room.outward.model.RoomVideo;
import com.qiyou.dhlive.core.room.outward.service.IRoomArticleService;
import com.qiyou.dhlive.core.room.outward.service.IRoomFileService;
import com.qiyou.dhlive.core.room.outward.service.IRoomVideoService;
import com.qiyou.dhlive.core.user.outward.model.UserVipInfo;
import com.qiyou.dhlive.core.user.outward.service.IUserVipInfoService;
import com.qiyou.dhlive.prd.component.annotation.UnSecurity;
import com.yaozhong.framework.base.common.utils.EmptyUtil;
import com.yaozhong.framework.base.common.utils.MD5Util;
import com.yaozhong.framework.base.database.domain.returns.DataResponse;
import com.yaozhong.framework.base.database.domain.search.RangeCondition;
import com.yaozhong.framework.base.database.domain.search.RangeConditionType;
import com.yaozhong.framework.base.database.domain.search.SearchCondition;
import com.yaozhong.framework.web.annotation.session.UnSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
/**
* Created by fish on 2018/9/12.
*/
@CrossOrigin(origins = "*", maxAge = 3600)
@Controller
@RequestMapping("remote")
public class GoodsRemoteController {
@Autowired
private IRoomVideoService roomVideoService;
@Autowired
private IRoomArticleService roomArticleService;
@Autowired
private IRoomFileService roomFileService;
@Autowired
private IUserVipInfoService userVipInfoService;
//----------------------------------登录----------------------------------
@UnSession
@UnSecurity
@RequestMapping("login")
@ResponseBody
public DataResponse userLogin(UserVipInfo user, HttpServletRequest request) {
UserVipInfo vip = this.userVipInfoService.getVipUserByLoginName(user.getUserTel());
String pwd = MD5Util.MD5Encode(user.getUserPass(), "utf-8");
if (EmptyUtil.isNotEmpty(vip)) {
if (pwd.equals(vip.getUserPass())) {
request.getSession().setAttribute("USER_VIP_INFO", vip);
return new DataResponse(1000, "success");
} else {
return new DataResponse(1001, "用户名或密码不正确");
}
} else {
return new DataResponse(1001, "用户名或密码不正确");
}
}
//----------------------------------文档----------------------------------
/**
* 文件列表
*
* @param params
* @return
*/
@UnSession
@UnSecurity
@RequestMapping("getFileList")
@ResponseBody
public DataResponse getFileList(RoomFile params) {
try {
params.setStatus(0);
SearchCondition<RoomFile> condition = new SearchCondition<RoomFile>(params);
List<RoomFile> result = this.roomFileService.findByCondition(condition);
return new DataResponse(1000, result);
} catch (Exception e) {
return new DataResponse(1001, e.getMessage());
}
}
//----------------------------------文章----------------------------------
/**
* 文章列表
*
* @param params
* @return
*/
@UnSession
@UnSecurity
@RequestMapping("getArticleList")
@ResponseBody
public DataResponse getArticleList(RoomArticle params, HttpServletRequest request) {
try {
params.setStatus(0);
UserVipInfo vip = (UserVipInfo) request.getSession().getAttribute("USER_VIP_INFO");
List<RoomArticle> result = new ArrayList<RoomArticle>();
//登录之后查看所有
if (EmptyUtil.isNotEmpty(vip)) {
SearchCondition<RoomArticle> condition = new SearchCondition<RoomArticle>(params);
result = this.roomArticleService.findByCondition(condition);
} else {
SearchCondition<RoomArticle> condition = new SearchCondition<RoomArticle>(params);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
condition.buildRangeConditions(new RangeCondition("createTime", sdf.format(new Date()), RangeConditionType.LessThan));
result = this.roomArticleService.findByCondition(condition);
}
return new DataResponse(1000, result);
} catch (Exception e) {
return new DataResponse(1001, e.getMessage());
}
}
/**
* 文章详情
*
* @param params
* @return
*/
@UnSession
@UnSecurity
@RequestMapping("getArticleDetail")
@ResponseBody
public DataResponse getFileDetail(RoomArticle params) {
try {
params = this.roomArticleService.findById(params.getArticleId());
return new DataResponse(1000, params);
} catch (Exception e) {
return new DataResponse(1001, e.getMessage());
}
}
//----------------------------------视频----------------------------------
/**
* 视频列表
*
* @param params
* @return
*/
@UnSession
@UnSecurity
@RequestMapping("getVideoList")
@ResponseBody
public DataResponse getVideoList(RoomVideo params) {
try {
params.setStatus(0);
SearchCondition<RoomVideo> condition = new SearchCondition<RoomVideo>(params);
List<RoomVideo> result = this.roomVideoService.findByCondition(condition);
return new DataResponse(1000, result);
} catch (Exception e) {
return new DataResponse(1001, e.getMessage());
}
}
/**
* 视频详情
*
* @param params
* @return
*/
@UnSession
@UnSecurity
@RequestMapping("getVideoDetail")
@ResponseBody
public DataResponse getVideoDetail(RoomVideo params) {
try {
params = this.roomVideoService.findById(params.getVideoId());
return new DataResponse(1000, params);
} catch (Exception e) {
return new DataResponse(1001, e.getMessage());
}
}
}
| true
|
0baa9687513f257e8303c080acf48f6d3433319b
|
Java
|
cleancoindev/voxelshop
|
/src/main/java/com/vitco/app/layout/content/colorchooser/components/ColorSliderPrototype.java
|
UTF-8
| 5,904
| 2.640625
| 3
|
[
"Apache-2.0"
] |
permissive
|
package com.vitco.app.layout.content.colorchooser.components;
import com.vitco.app.layout.content.colorchooser.basic.Settings;
import javax.swing.*;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.image.BufferedImage;
import java.util.ArrayList;
/**
* A custom color slider prototype that allows for custom thumbs (cursor) and background generation.
*/
public abstract class ColorSliderPrototype extends JSlider {
// holds the listeners
private final ArrayList<ValueChangeListener> listener = new ArrayList<ValueChangeListener>();
// add a listener
public final void addValueChangeListener(ValueChangeListener vcl) {
listener.add(vcl);
}
// notify listeners
private boolean blockNotify = false;
private void notifyListeners() {
if (!blockNotify) {
for (ValueChangeListener vcl : listener) {
vcl.onChange(this.changeEvent);
}
}
}
// this will NOT trigger the listeners to be notified
public final void setValueWithoutRefresh(int value) {
if (getValue() != value) {
blockNotify = true;
setValue(value);
blockNotify = false;
}
}
// allow to set a specific fixed height
private Integer height = null;
public void setHeight(int height) {
this.height = height;
}
// return the set height (setHeight(...))
@Override
public int getHeight() {
if (height == null) {
return super.getHeight();
} else {
return height;
}
}
// draw the background
protected abstract void drawBackground(Graphics2D g, SliderUI sliderUI);
// thumb image that is drawn
private BufferedImage thumbBuffer;
// setter for the thumb image
public final void setThumb(BufferedImage thumb) {
thumbBuffer = thumb;
}
// constructor
public ColorSliderPrototype(final int orientation, int min, int max, int current) {
super(orientation, min, max, current);
// notification
addChangeListener(new ChangeListener() {
@Override
public void stateChanged(ChangeEvent e) {
notifyListeners();
}
});
// ================
// create default thumb
{
final int size = 5;
thumbBuffer = new BufferedImage(size * 2 + 1, size * 2 + 1, BufferedImage.TYPE_INT_ARGB);
Graphics2D ig = (Graphics2D) thumbBuffer.getGraphics();
// Anti-alias
ig.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
if (orientation != JSlider.HORIZONTAL) {
//ig.rotate(-Math.PI/2, size, size);
ig.setColor(Color.BLACK);
ig.fillOval(0, 0, thumbBuffer.getWidth() - 1, thumbBuffer.getHeight() - 1);
ig.setColor(Color.WHITE);
ig.drawOval(0,0,thumbBuffer.getWidth()-1,thumbBuffer.getHeight()-1);
} else {
ig.setPaint(new GradientPaint(0, 1, Settings.SLIDER_KNOB_COLOR_TOP,
0, size * 2, Settings.SLIDER_KNOB_COLOR_BOTTOM, false));
ig.fillPolygon(new int[]{1, size * 2, size * 2, size, 1}, new int[]{size * 2, size * 2, size, 1, size}, 5);
ig.setColor(Settings.SLIDER_KNOB_OUTLINE_COLOR);
ig.setStroke(new BasicStroke(0.7f, BasicStroke.CAP_ROUND, BasicStroke.JOIN_BEVEL)); // line size
ig.drawPolygon(new int[]{0, size * 2, size * 2, size, 0}, new int[]{size * 2, size * 2, size, 0, size}, 5);
}
ig.dispose();
}
// ===============
// create ui
final SliderUI sliderUI = new SliderUI(this) {
@Override
public void paint(Graphics g, JComponent c) {
super.paint(g, c);
// draw the background
drawBackground((Graphics2D) g, this);
// draw the thumb
if (g.getClipBounds().intersects(thumbRect)) {
if (orientation == JSlider.HORIZONTAL) {
// make sure the thumbRect covers the whole height
thumbRect.y = 0;
thumbRect.height = slider.getHeight();
// draw the thumb
g.drawImage(thumbBuffer,
xPositionForValue(slider.getValue()) - thumbBuffer.getWidth() / 2,
slider.getHeight() - thumbBuffer.getHeight() - 1, null
);
} else {
// make sure the thumbRect covers the whole width
thumbRect.x = 0;
thumbRect.width = slider.getWidth();
// draw the thumb
g.drawImage(thumbBuffer,
slider.getWidth() - thumbBuffer.getWidth() - 1,
yPositionForValue(slider.getValue()) - thumbBuffer.getHeight() / 2, null
);
}
}
}
};
// move the thumb to the position we pressed (instantly)
addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
if (orientation == JSlider.HORIZONTAL) {
setValue(sliderUI.valueForXPosition(e.getX()));
} else {
setValue(sliderUI.valueForYPosition(e.getY()));
}
repaint();
}
});
// register - needs to go last
setUI(sliderUI);
}
}
| true
|
b862712626c47f3f62f98eede08284271e812db9
|
Java
|
DST135/helloIDEA
|
/src/IO_work801/FileInputStream/casePicture.java
|
UTF-8
| 780
| 2.75
| 3
|
[] |
no_license
|
package IO_work801.FileInputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
/**
* Created with IntelliJ IDEA.
*
* @author : 铁铁
* @Project : helloIDEA
* @Package : IO_work801.FileInputStream
* @ClassName : casePicture.java
* @createTime : 2021/8/4 16:56
* @Description :案例:复制图片
*/
public class casePicture {
public static void main(String[] args) throws IOException {
FileInputStream fis=new FileInputStream("C:\\Users\\chen9\\Desktop\\tie.jpg");
FileOutputStream fos=new FileOutputStream("tieCopy.jpg");
byte[] b=new byte[1024];
int len;
while((len=fis.read(b))!=-1){
fos.write(b);
}
fis.close();
fos.close();
}
}
| true
|
b1a476c6ef94c08c8a9798768085a84110fa8d52
|
Java
|
kuribu99/SrsTool-Java-Obsolete
|
/src/test/java/com/kongmy/tests/SentencesTest.java
|
UTF-8
| 1,743
| 2.484375
| 2
|
[] |
no_license
|
/*
*/
package com.kongmy.tests;
import com.kongmy.util.Sentences;
import java.util.ArrayList;
import java.util.List;
import junitparams.JUnitParamsRunner;
import junitparams.Parameters;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
import org.junit.runner.RunWith;
/**
*
* @author Kong My
*/
@RunWith(JUnitParamsRunner.class)
public class SentencesTest {
public Object[] getParamsForTestJoinArray() {
String[][] arr = new String[][]{
{"", ""},
{"a", "a"},
{"a and b", "a", "b"},
{"a, b and c", "a", "b", "c"},
{"a, b, c and d", "a", "b", "c", "d"}
};
List<String> list;
Object[] results = new Object[5];
for (int i = 0; i < arr.length; i++) {
list = new ArrayList<>();
for (int j = 1; j < arr[i].length; j++) {
list.add(arr[i][j]);
}
results[i] = new Object[]{arr[i][0], list};
}
return results;
}
public Object[] getParamsForTestFormatAsSentence() {
return new Object[]{
new String[]{"test run", "Test run."},
new String[]{"testrun", "Testrun."},
new String[]{"a b c", "A b c."}
};
}
@Test
@Parameters(method = "getParamsForTestJoinArray")
public void TestJoinArray(String afterJoin, List<String> array) {
assertEquals(afterJoin, Sentences.JoinArray(array));
}
@Test
@Parameters(method = "getParamsForTestFormatAsSentence")
public void TestFormatAsSentence(String before, String after) {
assertEquals(after, Sentences.FormatAsSentence(before));
}
}
| true
|
bf3748d5c473fcdfed851d0c430643d706bcd20e
|
Java
|
zhangyanzheng999/usefulToCopy
|
/myweb/src/main/java/cn/neu/his/bean/Medrecord.java
|
UTF-8
| 5,163
| 2.171875
| 2
|
[] |
no_license
|
package cn.neu.his.bean;
public class Medrecord {
private Integer medrecordId;
private Integer medrecordCode;
private Integer registerId;
private String chiefComplaint;
private String nowIllness;
private String nowMedicalStatus;
private String pastIllness;
private String allergyHistory;
private String physicalExamination;
public Medrecord() {
super();
// TODO Auto-generated constructor stub
}
public Medrecord(Integer medrecordId, Integer medrecordCode, Integer registerId, String chiefComplaint,
String nowIllness, String nowMedicalStatus, String pastIllness, String allergyHistory,
String physicalExamination, String inspectionRecommendation, String attention, String examResult,
String diagnosticResult, String opinionRecommendation, Integer medrecordState) {
super();
this.medrecordId = medrecordId;
this.medrecordCode = medrecordCode;
this.registerId = registerId;
this.chiefComplaint = chiefComplaint;
this.nowIllness = nowIllness;
this.nowMedicalStatus = nowMedicalStatus;
this.pastIllness = pastIllness;
this.allergyHistory = allergyHistory;
this.physicalExamination = physicalExamination;
this.inspectionRecommendation = inspectionRecommendation;
this.attention = attention;
this.examResult = examResult;
this.diagnosticResult = diagnosticResult;
this.opinionRecommendation = opinionRecommendation;
this.medrecordState = medrecordState;
}
private String inspectionRecommendation;
private String attention;
private String examResult;
private String diagnosticResult;
private String opinionRecommendation;
private Integer medrecordState;
public Integer getMedrecordId() {
return medrecordId;
}
public void setMedrecordId(Integer medrecordId) {
this.medrecordId = medrecordId;
}
public Integer getMedrecordCode() {
return medrecordCode;
}
public void setMedrecordCode(Integer medrecordCode) {
this.medrecordCode = medrecordCode;
}
public Integer getRegisterId() {
return registerId;
}
public void setRegisterId(Integer registerId) {
this.registerId = registerId;
}
public String getChiefComplaint() {
return chiefComplaint;
}
public void setChiefComplaint(String chiefComplaint) {
this.chiefComplaint = chiefComplaint == null ? null : chiefComplaint.trim();
}
public String getNowIllness() {
return nowIllness;
}
public void setNowIllness(String nowIllness) {
this.nowIllness = nowIllness == null ? null : nowIllness.trim();
}
public String getNowMedicalStatus() {
return nowMedicalStatus;
}
public void setNowMedicalStatus(String nowMedicalStatus) {
this.nowMedicalStatus = nowMedicalStatus == null ? null : nowMedicalStatus.trim();
}
public String getPastIllness() {
return pastIllness;
}
public void setPastIllness(String pastIllness) {
this.pastIllness = pastIllness == null ? null : pastIllness.trim();
}
public String getAllergyHistory() {
return allergyHistory;
}
public void setAllergyHistory(String allergyHistory) {
this.allergyHistory = allergyHistory == null ? null : allergyHistory.trim();
}
public String getPhysicalExamination() {
return physicalExamination;
}
public void setPhysicalExamination(String physicalExamination) {
this.physicalExamination = physicalExamination == null ? null : physicalExamination.trim();
}
public String getInspectionRecommendation() {
return inspectionRecommendation;
}
public void setInspectionRecommendation(String inspectionRecommendation) {
this.inspectionRecommendation = inspectionRecommendation == null ? null : inspectionRecommendation.trim();
}
public String getAttention() {
return attention;
}
public void setAttention(String attention) {
this.attention = attention == null ? null : attention.trim();
}
public String getExamResult() {
return examResult;
}
public void setExamResult(String examResult) {
this.examResult = examResult == null ? null : examResult.trim();
}
public String getDiagnosticResult() {
return diagnosticResult;
}
public void setDiagnosticResult(String diagnosticResult) {
this.diagnosticResult = diagnosticResult == null ? null : diagnosticResult.trim();
}
public String getOpinionRecommendation() {
return opinionRecommendation;
}
public void setOpinionRecommendation(String opinionRecommendation) {
this.opinionRecommendation = opinionRecommendation == null ? null : opinionRecommendation.trim();
}
public Integer getMedrecordState() {
return medrecordState;
}
public void setMedrecordState(Integer medrecordState) {
this.medrecordState = medrecordState;
}
}
| true
|
41c4078b6ffc46daeee025769995601c2128d1b2
|
Java
|
PalomaMobile/paloma-android-sdk
|
/palomamobile-android-sdk-user/android-sdk-user-library/src/main/java/com/palomamobile/android/sdk/user/IUserManager.java
|
UTF-8
| 1,116
| 2.25
| 2
|
[
"Apache-2.0"
] |
permissive
|
package com.palomamobile.android.sdk.user;
import android.support.annotation.Nullable;
import com.palomamobile.android.sdk.auth.IUserCredentialsProvider;
import com.palomamobile.android.sdk.core.IServiceManager;
import com.palomamobile.android.sdk.core.qos.BaseRetryPolicyAwareJob;
/**
* Methods in this interface provide convenient job creation methods that provide easy access
* to the underlying {@link IUserService} functionality. App developers can either use {@link BaseRetryPolicyAwareJob}
* job instances returned by the {@code createJob...()} methods, or create custom jobs that invoke
* methods of the {@link IUserService} returned by {@link IServiceManager#getService()}
*
* <br/>
* To get a concrete implementation of this interface call
* {@code ServiceSupport.Instance.getServiceManager(IUserManager.class)}
* <br/>
*
* <br/>
*
*/
public interface IUserManager extends IUserCredentialsProvider, IServiceManager<IUserService> {
/**
* Synchronous call returns the current {@link User} from local cache.
*
* @return current user
*/
@Nullable User getUser();
}
| true
|
8ecf8b08dd1a2b62f77903bd57d939cc4da7d92c
|
Java
|
5l1v3r1/dev-spring-boot
|
/src/main/java/com/mdms/app/mgmt/controller/LoginOtpController.java
|
UTF-8
| 2,991
| 2.234375
| 2
|
[] |
no_license
|
//Developed By: Anshu Sharma , Date 08/Oct/2020
package com.mdms.app.mgmt.controller;
import java.util.ArrayList;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.mdms.app.mgmt.model.LoginOtpModel;
import com.mdms.app.mgmt.model.MenuIdResponseModel;
import com.mdms.app.mgmt.service.LoginOtpService;
import com.mdms.app.mgmt.service.ShowMenuRightsService;
@CrossOrigin(origins = {"http://localhost:4200","http://mdms-ng-dev.s3-website.ap-south-1.amazonaws.com"}, maxAge = 4800, allowCredentials = "false")
@RestController
public class LoginOtpController {
@Autowired
private LoginOtpService otpService;
@Autowired
private ShowMenuRightsService menuRightService;
Logger logger=LoggerFactory.getLogger(LoginOtpController.class);
@RequestMapping(method=RequestMethod.POST, value="/sendotp")
public String sendOTP(@RequestParam("user_id") String user_id){
logger.info("Controller : LoginOtpController || Method : sendOTP ||user_id: "+user_id);
String response= otpService.getOtp(user_id);
//code to send otp, on hold because of Api for sending otp
logger.info("Controller : LoginOtpController || Method : sendOTP ||user_id: "+user_id);
return response;
}
@RequestMapping(method=RequestMethod.POST, value="/verifyotp")
public MenuIdResponseModel verifyOtp(@RequestParam("user_id") String user_id,@RequestParam("otp") Integer otp){
MenuIdResponseModel obj=new MenuIdResponseModel();
logger.info("Controller : LoginOtpController || Method : verifyOtp || user_id: "+user_id +" ||otp: " +otp);
List<String> response= new ArrayList<String>();
List<LoginOtpModel> result=otpService.verifyOtp(user_id,otp);
if(result.size()>0) {
response= menuRightService.showMenuRights(result.get(0).getUser_id());
if(response.size()>0)
{
obj.setMenuid_list(response);
obj.setStatus("success");
obj.setMessage("otp is correct");
logger.info("Controller : LoginOtpController || Method : sendOTP ||showMenuRights:user_id "+user_id +" ||menuId list size"+ response.size() +"|| otp is correct");
}else {
obj.setMenuid_list(response);
obj.setStatus("success");
obj.setMessage("no menu rights for this user");
logger.info("Controller : LoginOtpController || Method : sendOTP ||showMenuRights:user_id "+user_id +" ||no menu rights");
}
}else {
obj.setMenuid_list(response);
obj.setStatus("failed");
obj.setMessage("otp is wrong");
logger.info("Controller : LoginOtpController || Method : sendOTP ||showMenuRights:user_id "+user_id +" ||otp is wrong");
}
return obj;
}
}
| true
|
7850bed1f9210378786b302037eb3c06e0a20df6
|
Java
|
cesarvenancio/customer-challenge
|
/src/main/java/com/challenge/customer/vo/Customer.java
|
UTF-8
| 347
| 1.820313
| 2
|
[] |
no_license
|
package com.challenge.customer.vo;
import com.fasterxml.jackson.annotation.JsonGetter;
import lombok.Getter;
@Getter
public class Customer {
private Long userId;
private String name;
private Double latitude;
private Double longitude;
@JsonGetter(value = "user_id")
public Long getUserId() {
return userId;
}
}
| true
|
7377262dc31125cd076b1a067f74cb0516a9a06b
|
Java
|
fossabot/netflix-evcache-spring
|
/netflix-evcache-client-spring-cloud-autoconfigure/src/main/java/com/github/aafwu00/spring/cloud/netflix/evcache/client/MyOwnEurekaNodeListProvider.java
|
UTF-8
| 9,636
| 1.65625
| 2
|
[
"Apache-2.0"
] |
permissive
|
/*
* Copyright 2017-2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.aafwu00.spring.cloud.netflix.evcache.client;
import java.net.InetSocketAddress;
import java.util.HashSet;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import com.netflix.appinfo.ApplicationInfoManager;
import com.netflix.appinfo.DataCenterInfo;
import com.netflix.appinfo.InstanceInfo;
import com.netflix.config.ChainedDynamicProperty;
import com.netflix.config.DeploymentContext;
import com.netflix.config.DynamicStringProperty;
import com.netflix.discovery.EurekaClient;
import com.netflix.discovery.shared.Application;
import com.netflix.evcache.metrics.EVCacheMetricsFactory;
import com.netflix.evcache.pool.EVCacheNodeList;
import com.netflix.evcache.pool.EVCacheServerGroupConfig;
import com.netflix.evcache.pool.ServerGroup;
import com.netflix.evcache.util.EVCacheConfig;
import com.netflix.spectator.api.Id;
import static com.netflix.config.ConfigurationManager.getDeploymentContext;
import static java.util.Collections.emptyMap;
import static java.util.Objects.isNull;
import static java.util.Objects.requireNonNull;
import static org.apache.commons.lang3.StringUtils.defaultIfBlank;
import static org.apache.commons.lang3.StringUtils.defaultString;
import static org.apache.commons.lang3.StringUtils.isNotEmpty;
import static org.apache.commons.lang3.math.NumberUtils.toInt;
/**
* {@link EVCacheNodeList} implementation defaults to be Eureka based for MyOWN DataCenter.
*
* @author Taeho Kim
* @see com.netflix.evcache.pool.eureka.EurekaNodeListProvider
*/
public class MyOwnEurekaNodeListProvider implements EVCacheNodeList {
private static final int DEFAULT_EVCACHE_PORT = 11211;
private final ApplicationInfoManager applicationInfoManager;
private final EurekaClient eurekaClient;
public MyOwnEurekaNodeListProvider(final ApplicationInfoManager applicationInfoManager,
final EurekaClient eurekaClient) {
this.applicationInfoManager = requireNonNull(applicationInfoManager);
this.eurekaClient = requireNonNull(eurekaClient);
}
@Override
public Map<ServerGroup, EVCacheServerGroupConfig> discoverInstances(final String appName) {
if (applicationInfoManager.getInfo().getStatus() == InstanceInfo.InstanceStatus.DOWN) {
return emptyMap();
}
final Application app = eurekaClient.getApplication(appName);
if (app == null) {
return emptyMap();
}
final Map<ServerGroup, EVCacheServerGroupConfig> result = new ConcurrentHashMap<>();
for (final InstanceInfo instanceInfo : app.getInstances()) {
if (isAvailable(appName, instanceInfo)) {
addInstance(result, appName, instanceInfo);
}
}
return result;
}
private DynamicStringProperty ignoreHost(final String appName) {
return EVCacheConfig.getInstance().getDynamicStringProperty(appName + ".ignore.hosts", "");
}
private boolean isAvailable(final String appName, final InstanceInfo instanceInfo) {
return isAvailableStatus(instanceInfo)
&& isNotIgnoreHost(appName, instanceInfo)
&& isMyOwnDataCenter(instanceInfo);
}
private boolean isAvailableStatus(final InstanceInfo instanceInfo) {
return instanceInfo.getStatus() != null
&& InstanceInfo.InstanceStatus.OUT_OF_SERVICE != instanceInfo.getStatus()
&& InstanceInfo.InstanceStatus.DOWN != instanceInfo.getStatus();
}
private boolean isNotIgnoreHost(final String appName, final InstanceInfo instanceInfo) {
final DynamicStringProperty ignoreHost = ignoreHost(appName);
return !ignoreHost.get().contains(instanceInfo.getIPAddr())
&& !ignoreHost.get().contains(instanceInfo.getHostName());
}
private boolean isMyOwnDataCenter(final InstanceInfo instanceInfo) {
return isNull(instanceInfo.getDataCenterInfo())
|| DataCenterInfo.Name.MyOwn == instanceInfo.getDataCenterInfo().getName();
}
private void addInstance(final Map<ServerGroup, EVCacheServerGroupConfig> result,
final String appName,
final InstanceInfo instanceInfo) {
final int rendPort = rendPort(instanceInfo);
final int port = port(appName, instanceInfo, rendPort);
final ServerGroup serverGroup = serverGroup(instanceInfo);
result.computeIfAbsent(serverGroup, key -> createServerGroupConfig(key, appName, instanceInfo, rendPort, port));
result.get(serverGroup)
.getInetSocketAddress()
.add(address(instanceInfo, port));
}
private String groupName(final InstanceInfo instanceInfo) {
return defaultIfBlank(getString(instanceInfo.getMetadata(), "evcache.group"),
defaultString(instanceInfo.getASGName(), "Default"));
}
private String getString(final Map<String, String> metadata, final String key) {
if (isNull(metadata)) {
return "";
}
return metadata.getOrDefault(key, "");
}
private int rendPort(final InstanceInfo instanceInfo) {
return getIntValue(instanceInfo.getMetadata(), "rend.port", 0);
}
private int port(final String appName, final InstanceInfo instanceInfo, final int rendPort) {
final int evcachePort = evcachePort(instanceInfo);
if (rendPort == 0) {
return evcachePort;
}
if (useBatchPort(appName).get()) {
return rendBatchPort(instanceInfo);
}
return rendPort;
}
private int evcachePort(final InstanceInfo instanceInfo) {
return getIntValue(instanceInfo.getMetadata(), "evcache.port", DEFAULT_EVCACHE_PORT);
}
private int rendBatchPort(final InstanceInfo instanceInfo) {
return getIntValue(instanceInfo.getMetadata(), "rend.batch.port", 0);
}
private ChainedDynamicProperty.BooleanProperty useBatchPort(final String appName) {
return EVCacheConfig.getInstance()
.getChainedBooleanProperty(appName + ".use.batch.port",
"evcache.use.batch.port",
Boolean.FALSE,
null);
}
private ServerGroup serverGroup(final InstanceInfo instanceInfo) {
final String zone = zone(instanceInfo);
final String groupName = groupName(instanceInfo);
return new ServerGroup(zone, groupName);
}
private String zone(final InstanceInfo instanceInfo) {
final String zone = getDeploymentContext().getValue(DeploymentContext.ContextKey.zone);
if (isNotEmpty(zone)) {
return zone;
}
if (instanceInfo.getMetadata() != null) {
final String availabilityZone = instanceInfo.getMetadata().get("zone");
if (isNotEmpty(availabilityZone)) {
return availabilityZone;
}
}
return "UNKNOWN";
}
private EVCacheServerGroupConfig createServerGroupConfig(final ServerGroup serverGroup,
final String appName,
final InstanceInfo instanceInfo,
final int rendPort,
final int port) {
EVCacheMetricsFactory.getInstance().getRegistry().gauge(spectatorId(serverGroup, appName), port);
return new EVCacheServerGroupConfig(serverGroup,
new HashSet<>(),
rendPort,
udsproxyMemcachedPort(instanceInfo),
udsproxyMementoPort(instanceInfo));
}
private Id spectatorId(final ServerGroup serverGroup, final String appName) {
return EVCacheMetricsFactory.getInstance()
.getRegistry()
.createId(appName + "-port", "ServerGroup", serverGroup.getName(), "APP", appName);
}
private int udsproxyMemcachedPort(final InstanceInfo instanceInfo) {
return getIntValue(instanceInfo.getMetadata(), "udsproxy.memcached.port", 0);
}
private int getIntValue(final Map<String, String> metadata, final String key, final int defaultValue) {
if (metadata == null) {
return defaultValue;
}
return toInt(metadata.get(key), defaultValue);
}
private int udsproxyMementoPort(final InstanceInfo instanceInfo) {
return getIntValue(instanceInfo.getMetadata(), "udsproxy.memento.port", 0);
}
private InetSocketAddress address(final InstanceInfo instanceInfo, final int port) {
return new InetSocketAddress(instanceInfo.getHostName(), port);
}
}
| true
|
bf695c128a6b9bcbbb6254b7ccbbd3b91cf16161
|
Java
|
uphwa98/GearUp
|
/src/com/shim/gearup/BluetoothEventReceiver.java
|
UTF-8
| 2,151
| 2.28125
| 2
|
[] |
no_license
|
package com.shim.gearup;
import java.text.SimpleDateFormat;
import java.util.Date;
import android.bluetooth.BluetoothAdapter;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.content.SharedPreferences;
public class BluetoothEventReceiver extends BroadcastReceiver {
private final String TAG = "BluetoothEventReceiver";
@Override
public void onReceive(Context context, Intent intent) {
String intentAction = intent.getAction();
Log.v(TAG, "onReceive() action : " + intentAction);
if (intentAction == null)
return;
int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, BluetoothAdapter.STATE_OFF);
Log.v(TAG, "onReceive() state : " + state);
int previousState = intent.getIntExtra(BluetoothAdapter.EXTRA_PREVIOUS_STATE, BluetoothAdapter.STATE_OFF);
Log.v(TAG, "onReceive() previousState : " + previousState);
// Intent newIntent = new Intent(context, MainActivity.class);
// newIntent.putExtra("")
// context.start
long now = System.currentTimeMillis();
Date date = new Date(now);
SimpleDateFormat dateFormat = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss");
String strDate = dateFormat.format(date);
SharedPreferences pref = context.getSharedPreferences("pref", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = pref.edit();
String inout = pref.getString("inout", "");
StringBuilder sb = new StringBuilder(inout);
sb.append('\n');
if (state == BluetoothAdapter.STATE_ON) {
// intent.setClass(context, MainActivity.class);
// intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// // intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
// context.startActivity(intent);
sb.append("On/" + strDate);
} else if (state == BluetoothAdapter.STATE_OFF) {
sb.append("Off/" + strDate);
}
editor.putString("inout", sb.toString());
editor.commit();
}
}
| true
|
d538dda96852773489198d4aeb0a2d95ac2a6949
|
Java
|
AdrianCazacu/qaweeklymeet
|
/src/test/java/APIConnections/AddAPIConnections.java
|
UTF-8
| 676
| 1.734375
| 2
|
[] |
no_license
|
package APIConnections;
import org.junit.Test;
import org.junit.rules.TestWatcher;
import org.junit.runner.Description;
import org.junit.runners.model.Statement;
/**
* Created by pc on 3/8/2017.
*/
public class AddAPIConnections {
@Test
public void startDriver() throws InterruptedException {
System.setProperty("webdriver.chrome.driver", "D:\\Automation\\chromedriver_win322\\chromedriver.exe");
Library library = new Library();
library.manageWindow();
library.Login("http://adrian.thrive-dev.bitstoneint.com/wp-admin","admin","asdasd");
library.GoToAPIConnections();
library.AddAPIConnections();
}
}
| true
|
c91136e5215e9c179afe5a3d3a72f3795ff4575c
|
Java
|
tabdelrhman/E-Learning-System
|
/E-Learning/src/main/java/com/task/entities/Course.java
|
UTF-8
| 2,634
| 2.375
| 2
|
[] |
no_license
|
package com.task.entities;
import java.util.Date;
import java.util.Set;
import javax.persistence.Entity;
import javax.persistence.EntityListeners;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToMany;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import org.hibernate.validator.constraints.NotBlank;
import org.springframework.data.annotation.LastModifiedDate;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;
@Entity
@Table(name="course" )
@EntityListeners(AuditingEntityListener.class)
public class Course {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private Long courseId;
@NotBlank
private String courseName;
private String description;
@NotBlank
private String instructor;
private int total_hours;
@Temporal(TemporalType.TIMESTAMP)
private Date publishDate;
@Temporal(TemporalType.TIMESTAMP)
@LastModifiedDate
private Date lastupdated;
@ManyToMany(fetch = FetchType.LAZY, mappedBy = "studentCourses")
private Set<Student> students;
public Course(){}
public Course(String courseName, String instructor, int total_hours) {
super();
this.courseName = courseName;
this.instructor = instructor;
this.total_hours = total_hours;
}
public Long getCourseId() {
return courseId;
}
public void setCourseId(Long courseId) {
this.courseId = courseId;
}
public String getCourseName() {
return courseName;
}
public void setCourseName(String courseName) {
this.courseName = courseName;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getInstructor() {
return instructor;
}
public void setInstructor(String instructor) {
this.instructor = instructor;
}
public int getTotal_hours() {
return total_hours;
}
public void setTotal_hours(int total_hours) {
this.total_hours = total_hours;
}
public Date getPublishDate() {
return publishDate;
}
public void setPublishDate(Date publishDate) {
this.publishDate = publishDate;
}
public Date getLastupdated() {
return lastupdated;
}
public void setLastupdated(Date lastupdated) {
this.lastupdated = lastupdated;
}
public void setStudents(Set<Student> students) {
this.students = students;
}
}
| true
|
c486f59d9ab26a05d79cb9dac6359caa676d7f4d
|
Java
|
bageta/UtekZMuzea
|
/src/game/items/DogItem.java
|
UTF-8
| 703
| 2.828125
| 3
|
[] |
no_license
|
package game.items;
import com.jme3.asset.AssetManager;
import com.jme3.scene.Spatial;
import game.ObstacleType;
import game.Room;
/**
* Reprezentace věci na odstranění překážky typu pes. Nahrává model šunky, který
* se bude ve hře zobrazovat a rodiči se nastaví typ pes.
* @author Pavel Pilař
*/
public class DogItem extends Item {
/** model věci. */
Spatial itemModel;
/** Konstruktor věci na odstranění překážky typu pes. */
public DogItem(Room to, AssetManager am){
super(to, ObstacleType.DOG, am);
itemModel = am.loadModel("Models/Ham/ham.j3o");
this.attachChild(itemModel);
}
}
| true
|
1d72a3ab5d409c53c4775557e1ef5c274f563bfa
|
Java
|
Vishwa07dev/PracticeAlgo
|
/Graphs/src/DynamicProgramming/MaximumContiguousSum.java
|
UTF-8
| 1,521
| 3.75
| 4
|
[] |
no_license
|
package DynamicProgramming;
/**
* Awsome algorithm I have written :)
* @author vmohan
*
*/
public class MaximumContiguousSum {
public static int maxSum(int[] arr){
int[] m = new int[arr.length];
m[0]= arr[0];
for(int i=1;i<arr.length ;i++){
if(m[i-1]+arr[i] <arr[i]){
m[i] = arr[i] ;
}else{
m[i] = m[i-1]+arr[i];
}
}
int maxSum =Integer.MIN_VALUE;
for(int i=0 ;i<m.length ;i++){
if(maxSum < m[i]){
maxSum = m[i];
}
}
return maxSum ;
}
public static int maxSumNoThreeContiguous(int[] arr ){
int[] m = new int[arr.length];
m[0]=arr[0];
m[1] = m[0]+arr[1]>arr[1]? m[0]+arr[1] : arr[1] ;
m[2] = m[1] > arr[0]+arr[2]? m[1] : arr[0]+arr[2];
if(m[2]<arr[1]+arr[2]){
m[2] = arr[1]+arr[2];
}
if(m[2] < arr[2]){
m[2] = arr[2];
}
for(int i=3;i<arr.length;i++){
m[i] = m[i-2] + arr[i] >arr[i] ? m[i-2] + arr[i] : arr[i];
if(m[i] < m[i-1]){
m[i] = m[i-1];
}
if(m[i] < m[i-3]+arr[i-1]+arr[i]){
m[i] = m[i-3]+arr[i-1]+arr[i] ;
}
}
int maxValue = Integer.MIN_VALUE;
for(int i=0;i<m.length;i++){
System.out.print(m[i]+" ");
if(maxValue < m[i]){
maxValue = m[i];
}
}
System.out.println();
System.out.println(m[m.length-1]);
return maxValue;
}
public static void main(String[] args){
int[] arr1 = {22,11,4,13,5,12};
//System.out.println(maxSum(arr1));
int[] arr2 ={1, 2, 3, 4, 5, 6, 7, 8} ;
System.out.println(maxSumNoThreeContiguous(arr2));
}
}
| true
|
14d589328e9e23f96b00b6758ed4ead86cc6f4be
|
Java
|
MarlonOurives/restful-spring-boot-mongodb
|
/src/main/java/com/marlon/coursemongo/repository/UserRepository.java
|
UTF-8
| 295
| 1.703125
| 2
|
[] |
no_license
|
package com.marlon.coursemongo.repository;
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.stereotype.Repository;
import com.marlon.coursemongo.domain.User;
@Repository
public interface UserRepository extends MongoRepository<User, String> {
}
| true
|
da66933c78fd5ffa7caa09fb6e19ebf35d23b134
|
Java
|
jie758/xiesange
|
/entity/src/main/java/com/xiesange/gen/dbentity/trip/TripComment.java
|
UTF-8
| 4,193
| 2.515625
| 3
|
[] |
no_license
|
package com.xiesange.gen.dbentity.trip;
import com.xiesange.orm.DBEntity;
import com.xiesange.orm.statement.field.BaseJField;
import com.xiesange.orm.annotation.DBTableAnno;
@DBTableAnno(name = "TRIP_COMMENT",primaryKey="",indexes="")
public class TripComment extends DBEntity implements net.sf.cglib.proxy.Factory{
private Long id;
private Long orderId;
private Long tripId;
private String pic;
private String name;
private String comment;
private Integer grade;
private java.util.Date createTime;
private Long sn;
public void setId(Long id){
this.id = id;
super._setFieldValue(TripComment.JField.id, id);
}
public Long getId(){
return this.id;
}
public void setOrderId(Long orderId){
this.orderId = orderId;
super._setFieldValue(TripComment.JField.orderId, orderId);
}
public Long getOrderId(){
return this.orderId;
}
public void setTripId(Long tripId){
this.tripId = tripId;
super._setFieldValue(TripComment.JField.tripId, tripId);
}
public Long getTripId(){
return this.tripId;
}
public void setPic(String pic){
this.pic = pic;
super._setFieldValue(TripComment.JField.pic, pic);
}
public String getPic(){
return this.pic;
}
public void setName(String name){
this.name = name;
super._setFieldValue(TripComment.JField.name, name);
}
public String getName(){
return this.name;
}
public void setComment(String comment){
this.comment = comment;
super._setFieldValue(TripComment.JField.comment, comment);
}
public String getComment(){
return this.comment;
}
public void setGrade(Integer grade){
this.grade = grade;
super._setFieldValue(TripComment.JField.grade, grade);
}
public Integer getGrade(){
return this.grade;
}
public void setCreateTime(java.util.Date createTime){
this.createTime = createTime;
super._setFieldValue(TripComment.JField.createTime, createTime);
}
public java.util.Date getCreateTime(){
return this.createTime;
}
public void setSn(Long sn){
this.sn = sn;
super._setFieldValue(TripComment.JField.sn, sn);
}
public Long getSn(){
return this.sn;
}
public enum JField implements BaseJField{
id("ID","BIGINT",19,Long.class,true),
orderId("ORDER_ID","BIGINT",19,Long.class,true),
tripId("TRIP_ID","BIGINT",19,Long.class,true),
pic("PIC","VARCHAR",256,String.class,true),
name("NAME","VARCHAR",50,String.class,true),
comment("COMMENT","VARCHAR",500,String.class,true),
grade("GRADE","INT",10,Integer.class,true),
createTime("CREATE_TIME","DATETIME",19,java.util.Date.class,true),
sn("SN","BIGINT",19,Long.class,true);
private String colName;
private String colTypeName;
private Integer length;
private Class<?> javaType;
private boolean nullable;
private JField(String colName,String colTypeName,Integer length,Class<?> javaType,boolean nullable){
this.colName = colName;
this.colTypeName = colTypeName;
this.length = length;
this.javaType = javaType;
this.nullable = nullable;
}
@Override
public String getName()
{
return this.name();
}
@Override
public String getColName()
{
return this.colName;
}
@Override
public String getColTypeName()
{
return this.colTypeName;
}
@Override
public Integer getLength()
{
return length;
}
@Override
public boolean getNullable()
{
return this.nullable;
}
@Override
public String getTableName()
{
return "TRIP_COMMENT";
}
@Override
public Class<?> getJavaType()
{
return this.javaType;
}
@Override
public Class<? extends DBEntity> getEntityClass()
{
return com.xiesange.gen.dbentity.trip.TripComment.class;
}
}
}
| true
|
a537d5cc9a96edb863b0c87ee9d3eb4ff93bb7e1
|
Java
|
wellpires/goku-enderecos-app
|
/src/main/java/com/goku/enderecos/controller/EnderecoController.java
|
UTF-8
| 2,706
| 2.1875
| 2
|
[] |
no_license
|
package com.goku.enderecos.controller;
import java.util.List;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.goku.enderecos.controller.resource.EnderecoResource;
import com.goku.enderecos.dto.EditarEnderecoDTO;
import com.goku.enderecos.dto.EnderecoCEPDetalheDTO;
import com.goku.enderecos.dto.EnderecoDTO;
import com.goku.enderecos.dto.NovoEnderecoDTO;
import com.goku.enderecos.response.EnderecoCEPDetalheResponse;
import com.goku.enderecos.response.EnderecosResponse;
import com.goku.enderecos.service.EnderecoService;
@RestController
@RequestMapping("/api/v1/enderecos")
public class EnderecoController implements EnderecoResource {
@Autowired
private EnderecoService enderecoService;
@Override
@PostMapping(consumes = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<Void> criarEndereco(@Valid @RequestBody NovoEnderecoDTO novoEndereco) {
enderecoService.criarEndereco(novoEndereco);
return ResponseEntity.noContent().build();
}
@Override
@GetMapping(produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<EnderecosResponse> listarEnderecos() {
List<EnderecoDTO> enderecos = enderecoService.listarEnderecos();
return ResponseEntity.ok(new EnderecosResponse(enderecos));
}
@Override
@PutMapping(path = "/{cep}", consumes = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<Void> editarEndereco(@PathVariable("cep") Long cep,
@Valid @RequestBody EditarEnderecoDTO editarEnderecoDTO) {
enderecoService.editarEndereco(cep, editarEnderecoDTO);
return ResponseEntity.noContent().build();
}
@Override
@GetMapping(path = "/{cep}")
public ResponseEntity<EnderecoCEPDetalheResponse> buscarPorCEP(@PathVariable("cep") Long cep) {
EnderecoCEPDetalheDTO enderecoCEPDetalhe = enderecoService.buscarPorCEP(cep);
return ResponseEntity.ok(new EnderecoCEPDetalheResponse(enderecoCEPDetalhe));
}
@Override
@DeleteMapping(path = "/{cep}")
public ResponseEntity<Void> deletarEndereco(@PathVariable("cep") Long cep) {
enderecoService.deletarEndereco(cep);
return ResponseEntity.noContent().build();
}
}
| true
|
db56eb35716ba50b814c9be344ae4a414f70f4c9
|
Java
|
bdleons/IngeSoft-Proyecto-Taller-Mecanico
|
/src/Entidad/Factura.java
|
UTF-8
| 3,450
| 2.34375
| 2
|
[] |
no_license
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package Entidad;
import java.io.Serializable;
import java.util.ArrayList;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
/**
*
* @author NICOLAS
*/
@Entity
@Table(name="factura")
public class Factura implements Serializable {
private long cedulacliente;
private int idempleado; //tomar el id del empleado por medio de la contraseña buscando en la tabla empleados
private String autoCliente;
private String servicioTomado;
private String productoComprado;
//private ArrayList<Producto> productos;
//private ArrayList<Servicio> servicios;
private float precio;
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int id;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
/*@Override
public int hashCode() {
int hash = 0;
hash += (id != null ? id.hashCode() : 0);
return hash;
}
@Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Factura)) {
return false;
}
Factura other = (Factura) object;
if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
return false;
}
return true;
}
@Override
public String toString() {
return "Entidad.Factura[ id=" + id + " ]";
}*/
public Factura() {
}
public long getCedulacliente() {
return cedulacliente;
}
public void setCedulacliente(long cedulacliente) {
this.cedulacliente = cedulacliente;
}
public int getIdempleado() {
return idempleado;
}
public void setIdempleado(int idempleado) {
this.idempleado = idempleado;
}
/*public ArrayList<Producto> getProductos() {
return productos;
}
public void setProductos(ArrayList<Producto> productos) {
this.productos = productos;
}
public ArrayList<Servicio> getServicios() {
return servicios;
}
public void setServicios(ArrayList<Servicio> servicios) {
this.servicios = servicios;
}*/
public float getPrecio() {
return precio;
}
public void setPrecio(float precio) {
this.precio = precio;
}
public String getAutoCliente() {
return autoCliente;
}
public void setAutoCliente(String autoCliente) {
this.autoCliente = autoCliente;
}
public String getServicioTomado() {
return servicioTomado;
}
public void setServicioTomado(String servicioTomado) {
this.servicioTomado = servicioTomado;
}
public String getProductoComprado() {
return productoComprado;
}
public void setProductoComprado(String productoComprado) {
this.productoComprado = productoComprado;
}
}
| true
|
339cab711e88ed7ff3c43300203e86664d64077c
|
Java
|
umeshbsa/android-project-architecture-diagram
|
/app/src/main/java/com/app/architecture/fragment/BaseFragment.java
|
UTF-8
| 400
| 2.125
| 2
|
[
"Apache-2.0"
] |
permissive
|
package com.app.architecture.fragment;
import android.content.Context;
import android.support.v4.app.Fragment;
import com.app.architecture.activity.BaseActivity;
public abstract class BaseFragment extends Fragment {
protected BaseActivity activity;
@Override
public void onAttach(Context context) {
super.onAttach(context);
activity = (BaseActivity) context;
}
}
| true
|
42885eef539af5f37766a6c2a077517dbab53a5c
|
Java
|
swagnhen/LeetCode-Top-Interview-Questions
|
/src/pers/swegnhan/leetcode/hard/backtracking/WordSearchII/Solution.java
|
UTF-8
| 1,926
| 3.34375
| 3
|
[] |
no_license
|
package pers.swegnhan.leetcode.hard.backtracking.WordSearchII;
import java.util.*;
public class Solution {
public boolean step(char[][]board, int x, int y, boolean[][] hasVisited, String word, int pos){
if(pos == word.length())
return true;
if(x < 0 || x >= board.length || y < 0 || y >= board[0].length || word.charAt(pos) != board[x][y] || hasVisited[x][y])
return false;
hasVisited[x][y] = true;
if(step(board, x + 1, y, hasVisited, word, pos + 1) ||
step(board, x - 1, y, hasVisited, word, pos + 1) ||
step(board, x, y + 1, hasVisited, word, pos + 1) ||
step(board, x, y - 1, hasVisited, word, pos + 1))
return true;
hasVisited[x][y] = false;
return false;
}
public List<String> findWords(char[][] board, String[] words) {
List<String> result = new LinkedList<>();
if(board.length == 0)
return result;
boolean[][] hasVisited = new boolean[board.length][board[0].length];
for(String word : words){
for(int i = 0; i < board.length; i++)
for(int j = 0; j < board[i].length; j++)
hasVisited[i][j] = false;
boolean loop = true;
for(int i = 0; i < board.length && loop; i++) {
for (int j = 0; j < board[i].length && loop; j++) {
if (step(board, i, j, hasVisited, word, 0)) {
result.add(word);
loop = false;
}
}
}
}
return result;
}
public static void main(String[] args) {
Solution solution = new Solution();
char[][] board = new char[][]{
{'a','a'}
};
String[] words = new String[]{"aa"};
System.out.println(solution.findWords(board, words));
}
}
| true
|
e3e6d7915b1614b217a6af2e7a508e0bf26b0f2a
|
Java
|
rahulkundu01/AutomobileProject
|
/src/Bill.java
|
UTF-8
| 2,738
| 2.875
| 3
|
[] |
no_license
|
import java.lang.*;
import java.io.*;
import java.awt.*;
import java.awt.event.*;
import java.sql.*;
import javax.swing.*;
class Bill extends JFrame
{
Bill()
{
resize(800,500);
setTitle("Bill");
setBackground(Color.pink);
setLayout(new GridLayout(25,7));
JButton C[][]=new JButton[1][7];
JLabel L[][]=new JLabel[25][7];
for(int i=0;i<25;i++)
{
for(int j=0;j<7;j++)
{
if(i==0)
{
C[i][j]=new JButton();
add(C[i][j]);
C[i][j].addActionListener(new BT());
}
else
{
L[i][j]=new JLabel();
add(L[i][j]);
}
}
}
C[0][0].setLabel("Name");
C[0][1].setLabel("Address");
C[0][2].setLabel("PhoneNo");
C[0][3].setLabel("BokDate");
C[0][4].setLabel("DelDate");
C[0][5].setLabel("ModelName");
C[0][6].setLabel("Color");
int i=1;
String msAccessDBName = "F:\\Work Environment\\MyProject\\AutomobileProject\\bin\\HONDA.MDB";
/*String data="jdbc:odbc:Driver="
+ "{Microsoft Access Driver (*.mdb, *.accdb)};"
+ "DBQ="
+ msAccessDBName
+ ";DriverID=22;READONLY=true";*/
String data = "jdbc:ucanaccess://F:\\Work Environment\\MyProject\\AutomobileProject\\HONDA.accdb";
try
{
//Class.forName("jdbc:ucanaccess:HONDA");
Connection conn = DriverManager.getConnection(data);
Statement st = conn.createStatement();
ResultSet rec = st.executeQuery("SELECT * FROM Billing");
while(rec.next())
{
L[i][0].setText(rec.getString("Name"));
L[i][1].setText(rec.getString("Address"));
L[i][2].setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
L[i][2].setText(rec.getString("Phone"));
L[i][3].setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
L[i][3].setText(rec.getString("BokDate"));
L[i][4].setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
L[i][4].setText(rec.getString("DelDate"));
L[i][5].setText(rec.getString("ModelName"));
L[i][6].setText(rec.getString("ModelColour"));
i=i+1;
}
st.close();
}
catch(Exception e)
{
//System.out.println("ERROR");
}
show();
MyWindow adapter = new MyWindow(this);
addWindowListener(adapter);
}
public static void main(String args[])
{
Bill B=new Bill();
B.show();
B.setBounds(1,1,800,600);
}
class MyWindow extends WindowAdapter
{
Bill menuFrame;
public MyWindow(Bill menuFrame)
{
this.menuFrame=menuFrame;
}
public void windowClosing(WindowEvent we)
{
menuFrame.setVisible(false);
}
}
class BT implements ActionListener
{
public void actionPerformed(ActionEvent ae)
{
setVisible(false);
repaint();
}
}
}
| true
|
0d30fb3b31d0b6daa70eb2a3e39e221b14b5f185
|
Java
|
Nolan1324/FTC-Threaded-OpMode
|
/threadopmode/ThreadOpMode.java
|
UTF-8
| 1,860
| 3.28125
| 3
|
[] |
no_license
|
package org.firstinspires.ftc.teamcode.threadopmode;
import com.qualcomm.robotcore.eventloop.opmode.OpMode;
import java.util.ArrayList;
import java.util.List;
/**
* A type of {@link OpMode} that contains threads to be ran in parallel periodically.
* Register threads with {@link ThreadOpMode#registerThread(TaskThread)}
*/
public abstract class ThreadOpMode extends OpMode {
private List<TaskThread> threads = new ArrayList<>();
/**
* Registers a new {@link TaskThread} to be ran periodically.
* Registered threads will automatically be started during {@link OpMode#start()} and stopped during {@link OpMode#stop()}.
*
* @param taskThread A {@link TaskThread} object to be ran periodically.
*/
public final void registerThread(TaskThread taskThread) {
threads.add(taskThread);
}
/**
* Contains code to be ran before the OpMode is started. Similar to {@link OpMode#init()}.
*/
public abstract void mainInit();
/**
* Contains code to be ran periodically in the MAIN thread. Similar to {@link OpMode#loop()}.
*/
public abstract void mainLoop();
/**
* Should not be called by subclass.
*/
@Override
public final void init() {
mainInit();
}
/**
* Should not be called by subclass.
*/
@Override
public final void start() {
for(TaskThread taskThread : threads) {
taskThread.start();
}
}
/**
* Should not be called by subclass.
*/
@Override
public final void loop() {
mainLoop();
}
/**
* Should not be called by subclass.
*/
@Override
public final void stop() {
for(TaskThread taskThread : threads) {
taskThread.stop();
}
}
}
| true
|
658a578c342ccae5cccafdb654654016ab6c23cd
|
Java
|
Sendrikz/AdmissionCampaign
|
/src/main/java/model/enteties/Faculty.java
|
UTF-8
| 1,407
| 2.9375
| 3
|
[] |
no_license
|
package model.enteties;
import java.util.Objects;
/**
* @author Olha Yuryeva
* @version 1.0
*/
public class Faculty {
private int id;
private String name;
private int universityId;
public Faculty (String name, int universityId) {
this.name = name;
this.universityId = universityId;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getUniversityId() {
return universityId;
}
public void setUniversityId(int universityId) {
this.universityId = universityId;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Faculty faculty = (Faculty) o;
return id == faculty.id &&
universityId == faculty.universityId &&
Objects.equals(name, faculty.name);
}
@Override
public int hashCode() {
return Objects.hash(id, name, universityId);
}
@Override
public String toString() {
return "Faculty{" +
"id=" + id +
", name='" + name + '\'' +
", university=" + universityId +
'}';
}
}
| true
|
a1165870edc34f152c063778eeda515c91131371
|
Java
|
jhany/ejercicio-advlatam
|
/src/main/java/ec/desarollo/no_circula/repository/RestriccionRepository.java
|
UTF-8
| 374
| 1.726563
| 2
|
[] |
no_license
|
package ec.desarollo.no_circula.repository;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
import ec.desarollo.no_circula.jpa.Restriccion;
@Repository
public interface RestriccionRepository extends CrudRepository<Restriccion, Long> {
// consulta de último digito
Restriccion findByDigito(int digito);
}
| true
|
1e70671c37fb918519070b4e4620fae43a2d6b1d
|
Java
|
AndreiJitaru/Projects
|
/Online management platform for sport facilities/platforma-mvc/src/main/java/com/myprojecy/platformamvc/models/data/RezervareDao.java
|
UTF-8
| 356
| 1.65625
| 2
|
[] |
no_license
|
package com.myprojecy.platformamvc.models.data;
import com.myprojecy.platformamvc.models.Rezervare;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
import javax.transaction.Transactional;
@Repository
@Transactional
public interface RezervareDao extends CrudRepository<Rezervare, Integer>{
}
| true
|
d0d2230f5499685166369229d07bc442b5ce7cc7
|
Java
|
QinshuXiao/Leetcode
|
/src/ScrambleString.java
|
UTF-8
| 931
| 3.265625
| 3
|
[] |
no_license
|
class Solution {
public boolean isScramble(String s1, String s2) {
if(s1.length() != s2.length())
return false;
if(s1.equals(s2))
return true;
int len = s1.length();
int[] alphabets = new int[26];
for(int i = 0; i < len; ++i){
alphabets[s1.charAt(i)-'a']++;
alphabets[s2.charAt(i)-'a']--;
}
for(int i = 0; i < 26; ++i)
if(alphabets[i] != 0)
return false;
for(int i = 1; i < len; ++i){
if(isScramble(s1.substring(0,i), s2.substring(0,i)) &&
isScramble(s1.substring(i),s2.substring(i)))
return true;
else if(isScramble(s1.substring(0,i),s2.substring(len-i)) &&
isScramble(s1.substring(i),s2.substring(0,len-i)))
return true;
}
return false;
}
}
| true
|
44ce9d1306a6fddaa5d616919315c45c0a90e91f
|
Java
|
manosbatsis/SAVEFILECOMPANY
|
/api1/src/main/java/com/heb/pm/repository/FactoryRepository.java
|
UTF-8
| 474
| 1.78125
| 2
|
[] |
no_license
|
/*
* FactoryRepository
*
* Copyright (c) 2016 HEB
* All rights reserved.
*
* This software is the confidential and proprietary information
* of HEB.
*/
package com.heb.pm.repository;
import com.heb.pm.entity.Factory;
import org.springframework.data.jpa.repository.JpaRepository;
/**
* Repository to retrieve information about factories.
*
* @author s573181
* @since 2.6.0
*/
public interface FactoryRepository extends JpaRepository<Factory, Integer> {
}
| true
|
520fbbc9d7db4d88f727ed0ac4579542f439b68e
|
Java
|
VenugopalBhatia/NucleusJava
|
/Assignment 10/src/SpanOfStock.java
|
UTF-8
| 1,730
| 3.703125
| 4
|
[] |
no_license
|
public class SpanOfStock {
// Done without stack in o(n^2) time complexity
public static int[] span(int[] arr){
int si[]= new int[arr.length];
for(int i=0;i<arr.length;i++){
int count=i+1;
for(int j=0;j<i;j++){
if(arr[j]>arr[i]){
count=i-j;
}
}
si[i]=count;
}
return si;
}
//Done without Stack in o(n)
public static int[] span_2(int arr[]){
int[] span=new int[arr.length];
int index=0;
for(int i=0;i<arr.length;i++){
index=i-1;
span[i]=1;
while(index>=0&&arr[index]<=arr[i]){
span[i]=span[i]+span[index];
index=index-span[index];// We skip the span of the element at index to go to the element greater than index element as that element may be smaller than the ith element
}
}
return span;
}
//Done with Stack in o(n)
public static int[] span_3(int[] stock)throws Exception{
MinStack stack=new MinStack();
int[] span=new int[stock.length];
for (int i = 0; i < stock.length; i++) {
int index = 0;
span[i] = 1;
while (!stack.IsEmpty() && stock[stack.outhead()] <= stock[i]) {
index = stack.pop();
span[i] = i - index + span[index];
}
stack.push(i);
}
return span;
}
public static void main(String[] args)throws Exception {
int[] arr={6,10,4,2,8,9};
int[] si=span(arr);
for(int i=0;i<si.length;i++){
System.out.print(si[i]+" ");
}
System.out.println();
si=span_2(arr);
for(int j=0;j<si.length;j++){
System.out.print(si[j]+" ");
}
System.out.println();
si=span_3(arr);
for(int j=0;j<si.length;j++){
System.out.print(si[j]+" ");
}
}
}
| true
|
c15479f7fef18dec8c5a92a1bb33c92d47723d2f
|
Java
|
SDET67/googleAuto
|
/src/main/java/com/google/qa/pages/SignInPage.java
|
UTF-8
| 1,434
| 2
| 2
|
[] |
no_license
|
package com.google.qa.pages;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;
import com.google.qa.base.TestBase;
public class SignInPage extends TestBase{
//Page factory
@FindBy(xpath="/html/body/div[1]/div[1]/div[2]/div[2]/div/div/div[2]/div/div/div/form/span/section/div/div/div/div/ul/li[2]/div/div/div[2]")
WebElement anotherAcc;
@FindBy(id="identifierId")
WebElement username;
@FindBy(xpath="/html/body/div[1]/div[1]/div[2]/div[2]/div/div/div[2]/div/div[2]/div/div[1]/div/span/span")
WebElement nextBtn1;
@FindBy(xpath="//input[@type='password']")
WebElement password;
@FindBy(xpath="/html/body/div[1]/div[1]/div[2]/div[2]/div/div/div[2]/div/div[2]/div/div[1]/div/span")
WebElement nextBtn2;
//define constuctor
public SignInPage() {
PageFactory.initElements(driver, this);
}
public String verifySignInPageTitle() {
return driver.getTitle();
}
/* public void verifySignInAccount(String un) throws InterruptedException {
anotherAcc.click();
username.sendKeys(un);
Thread.sleep(2000);
password.sendKeys(pwd);
Thread.sleep(2000);
nextBtn.click();
Thread.sleep(2000);
return new LoginPage();
} */
public void verifySignInAccount(String un) throws InterruptedException {
// TODO Auto-generated method stub
anotherAcc.click();
username.sendKeys(un);
Thread.sleep(2000);
}
}
| true
|
8632058f82384a4e83cc9e7fa0d0bd30cafd52cb
|
Java
|
Solaning/cloud-football
|
/app/src/main/java/com/kinth/football/ui/match/TournamentActivity.java
|
UTF-8
| 6,360
| 1.773438
| 2
|
[] |
no_license
|
package com.kinth.football.ui.match;
import java.util.List;
import org.json.JSONArray;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import com.android.volley.VolleyError;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.google.gson.reflect.TypeToken;
import com.kinth.football.R;
import com.kinth.football.adapter.TournamentListAdapter;
import com.kinth.football.manager.UserManager;
import com.kinth.football.network.NetWorkManager;
import com.kinth.football.singleton.SingletonBitmapClass;
import com.kinth.football.singleton.ViewCompat;
import com.kinth.football.ui.BaseActivity;
import com.kinth.football.util.ErrorCodeUtil;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;
/**
* 锦标赛(联赛)列表
* @author zyq
* 传link_in_where(在哪里点进来)
*/
public class TournamentActivity extends BaseActivity{
public static final String LINK_IN_WHERE = "LINK_IN_WHERE";
public static final String LINK_IN_HOMEPAGE = "LINK_IN_HOMEPAGE";
public static final String LINK_IN_PERSONINFO = "LINK_IN_PERSONINFO";
public static final String LINK_IN_MATCH = "LINK_IN_MATCH";
public static final String INTENT_PLAYER_UUID = "INTENT_PLAYER_UUID";
private String playerId;
@ViewInject(R.id.entire_layout)
private View entireLayout;
@ViewInject(R.id.nav_left)
private ImageButton back;
@ViewInject(R.id.nav_title)
private TextView title;
@ViewInject(R.id.loaddata)
private ProgressBar loaddataBar;
@ViewInject(R.id.list_tournament)
private ListView list_tournament;
@ViewInject(R.id.txt_nocount) //没有数据时显示的text
private TextView txt_nocount;
@OnClick(R.id.nav_left)
public void fun_1(View v) {
finish();
}
private TournamentListAdapter adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tournament);
ViewUtils.inject(this);
Bitmap background = SingletonBitmapClass.getInstance()
.getBackgroundBitmap();
ViewCompat.setBackground(entireLayout, new BitmapDrawable(
getResources(), background));
title.setText("锦标赛");
String link_in_where = getIntent().getStringExtra(LINK_IN_WHERE); // 得到从哪里点击进来的
// 传进Adapter
playerId = getIntent().getStringExtra(INTENT_PLAYER_UUID);
adapter = new TournamentListAdapter(mContext, null, link_in_where, playerId);
list_tournament.setAdapter(adapter);
if(LINK_IN_PERSONINFO.equals(link_in_where)){
getPersonalTournamentList(playerId);// mod @2015-07-28
}else{
getTournamentList(); // 获得联赛列表,传当前user的id
}
}
/**
* 获取锦标赛个人比赛数据
*/
private void getPersonalTournamentList(String playerUuid) {
NetWorkManager.getInstance(mContext).getPersonalTournamentList(playerUuid, UserManager.getInstance(mContext).getCurrentUser().getToken(),
new Listener<JSONArray>() {
@Override
public void onResponse(JSONArray response) {
List<com.kinth.football.bean.match.Tournament> tournamentList=null;
Gson gson = new Gson();
try{
tournamentList = gson.fromJson(response.toString(),
new TypeToken<List<com.kinth.football.bean.match.Tournament>>() {
}.getType());
}catch (JsonSyntaxException e) {
tournamentList = null;
e.printStackTrace();
}
if (tournamentList ==null || tournamentList.size()==0) {
txt_nocount.setVisibility(View.VISIBLE);
return;
}
adapter.setTournamentList(tournamentList);
}
}, new ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
txt_nocount.setVisibility(View.VISIBLE);
txt_nocount.setText("加载失败");
if (!NetWorkManager.getInstance(mContext)
.isNetConnected()) {
ShowToast("当前网络不可用");
} else if (error.networkResponse == null) {
// ShowToast("TeamInfoActivity-getFriendlyMatchResultOfTeam-服务器连接错误");
} else if (error.networkResponse.statusCode == 401) {
ErrorCodeUtil.ErrorCode401(mContext);
} else if (error.networkResponse.statusCode == 404) {
ShowToast("错误:球员找不到");
}
}
});
loaddataBar.setVisibility(View.GONE);
}
// 获得联赛列表
private void getTournamentList(){
NetWorkManager.getInstance(mContext).getTournamentList(UserManager.getInstance(mContext).getCurrentUser().getPlayer().getUuid(), UserManager.getInstance(mContext).getCurrentUser().getToken(),
new Listener<JSONArray>() {
@Override
public void onResponse(JSONArray response) {
List<com.kinth.football.bean.match.Tournament> tournamentList=null;
Gson gson = new Gson();
try{
tournamentList = gson.fromJson(response.toString(),
new TypeToken<List<com.kinth.football.bean.match.Tournament>>() {
}.getType());
}catch (JsonSyntaxException e) {
tournamentList = null;
e.printStackTrace();
}
if (tournamentList ==null || tournamentList.size()==0) {
txt_nocount.setVisibility(View.VISIBLE);
return;
}
adapter.setTournamentList(tournamentList);
}
}, new ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
txt_nocount.setVisibility(View.VISIBLE);
txt_nocount.setText("加载失败");
if (!NetWorkManager.getInstance(mContext)
.isNetConnected()) {
ShowToast("当前网络不可用");
} else if (error.networkResponse == null) {
// ShowToast("TeamInfoActivity-getFriendlyMatchResultOfTeam-服务器连接错误");
} else if (error.networkResponse.statusCode == 401) {
ErrorCodeUtil.ErrorCode401(mContext);
} else if (error.networkResponse.statusCode == 404) {
ShowToast("错误:球员找不到");
}
}
});
loaddataBar.setVisibility(View.GONE);
}
}
| true
|
a022e9846ec715bf1cc478822e7c43b0c65731e0
|
Java
|
shiyijun0/microonfig
|
/yifu_system/src/main/java/com/jwk/project/system/wordcolor/controller/WordColorController.java
|
UTF-8
| 3,645
| 2.03125
| 2
|
[] |
no_license
|
package com.jwk.project.system.wordcolor.controller;
import com.jwk.framework.aspectj.lang.annotation.Log;
import com.jwk.framework.web.controller.BaseController;
import com.jwk.framework.web.domain.JSON;
import com.jwk.framework.web.page.TableDataInfo;
import com.jwk.project.system.wordcolor.domain.WordColor;
import com.jwk.project.system.wordcolor.service.IWordColorService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
/**
* 文字颜色 控制层
*
* @author 陈志辉
*
*/
@Controller
@RequestMapping("/system/wordcolor")
public class WordColorController extends BaseController
{
private String prefix = "system/wordcolor";
@Autowired
private IWordColorService wordColorService;
/**
*查询文字颜色
*/
@RequiresPermissions("system:word:color:view")
@GetMapping()
public String color()
{
return prefix + "/color";
}
/**
*显示文字颜色
*/
@RequiresPermissions("system:word:color:list")
@GetMapping("/list")
@ResponseBody
public TableDataInfo list()
{
TableDataInfo rows = wordColorService.pageInfoQuery(getPageUtilEntity());
return rows;
}
/**
* 新增文字颜色
*/
@RequiresPermissions("system:word:color:add")
@Log(title = "文字定制", action = "文字颜色-新增颜色")
@GetMapping("/add")
public String add(Model model)
{
return prefix + "/add";
}
/**
* 修改文字颜色
*/
@RequiresPermissions("system:word:color:edit")
@Log(title = "文字定制", action = "文字颜色-修改颜色")
@GetMapping("/edit/{colorId}")
public String edit(@PathVariable("colorId") Long colorId, Model model)
{
WordColor wordColor = wordColorService.selectWordColorById(colorId);
model.addAttribute("wordColor", wordColor);
return prefix + "/edit";
}
/**
* 保存文字颜色
*/
@RequiresPermissions("system:word:color:save")
@Log(title = "文字定制", action = "文字颜色-保存颜色")
@PostMapping("/save")
@ResponseBody
public JSON save(WordColor wordColor)
{
if (wordColorService.saveWordColor(wordColor) > 0)
{
return JSON.ok();
}
return JSON.error();
}
/**
* 通过文字颜色ID删除文字颜色
*/
@RequiresPermissions("system:word:color:remove")
@Log(title = "文字定制", action = "文字颜色-删除颜色")
@RequestMapping("/remove/{colorId}")
@ResponseBody
public JSON remove(@PathVariable("colorId") Long colorId)
{
WordColor wordColor = wordColorService.selectWordColorById(colorId);
if (wordColor == null)
{
return JSON.error("文字颜色不存在");
}
if (wordColorService.deleteWordColorById(colorId) > 0)
{
return JSON.ok();
}
return JSON.error();
}
/**
* 批量删除文字颜色信息
*/
@RequiresPermissions("system:word:color:batchRemove")
@Log(title = "文字定制", action = "文字颜色-批量删除")
@PostMapping("/batchRemove")
@ResponseBody
public JSON batchRemove(@RequestParam("ids[]") Long[] ids)
{
int rows = wordColorService.batchDeleteWordColor(ids);
if (rows > 0)
{
return JSON.ok();
}
return JSON.error();
}
}
| true
|
2ead436e8aaf7b3b68026e64f1e406ccf20d5a7f
|
Java
|
aduyphm/QuanLyCapPhanThuong
|
/Nhom17_SoftwareEngineer_118586_QuanLyCapPhanThuong/src/controller/guicontroller/TableThongKeKhuyenHocTheoNha.java
|
UTF-8
| 4,395
| 2.296875
| 2
|
[] |
no_license
|
package controller.guicontroller;
import java.sql.Date;
import java.util.ArrayList;
import app.QuanLyNhanKhau;
import controller.entitycontroller.KhuyenHocTheoNhaController;
import entity.KhuyenHocTheoNha;
import javafx.scene.Node;
import javafx.scene.control.Alert;
import javafx.scene.control.ComboBox;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.control.Alert.AlertType;
public class TableThongKeKhuyenHocTheoNha extends TableController<KhuyenHocTheoNha> {
public TableThongKeKhuyenHocTheoNha(InsideMainFrameTab tab, int index, TextField sTextField) {
super(tab, index, sTextField, new KhuyenHocTheoNhaController(),
new String[]{"hocSinhList", "diaChi", "moTaSuatQuaDuocNhan", "moTaPhanQuaDuocNhan", "sumValue"},
new String[]{"Học sinh", "Địa chỉ", "Các loại quà", "Chi tiết", "Tổng giá trị"},
50);
setAddForm("/fxml/ThongKeTheoNhaDialog.fxml");
textField.textProperty().addListener((observable, oldValue, newValue) -> {
controller.getFilterList().setPredicate(thongke -> {
if (newValue == null || newValue.isEmpty()) {
return true;
}
String lowerCaseFilter = newValue.toLowerCase();
if (thongke.getHocSinhList().toLowerCase().indexOf(lowerCaseFilter) != -1) {
return true;
}
if (thongke.getDiaChi().toLowerCase().indexOf(lowerCaseFilter) != -1) {
return true;
}
if (thongke.getMoTaSuatQuaDuocNhan().toLowerCase().indexOf(lowerCaseFilter) != -1) {
return true;
}
if (thongke.getMoTaPhanQuaDuocNhan().toLowerCase().indexOf(lowerCaseFilter) != -1) {
return true;
}
if (String.valueOf(thongke.getSumValue()).toLowerCase().indexOf(lowerCaseFilter) != -1) {
return true;
}
return false;
});
});
}
@Override
public void firstClickOnTable() {
if(toolBar.getItems().size() > 4) toolBar.getItems().get(4).setDisable(true);
if(toolBar.getItems().size() > 5) toolBar.getItems().get(5).setDisable(true);
}
@Override
public void prepareAddRecord() {
ComboBox<String> comboBox = (ComboBox<String>)addFormRoot.lookup(".combo-box");
ArrayList<String> ngayPhatQua = ((KhuyenHocTheoNhaController)controller).getNgayPhatQua();
comboBox.getItems().addAll(ngayPhatQua);
if(((KhuyenHocTheoNhaController)controller).getDate() != null){
comboBox.getSelectionModel().select(((KhuyenHocTheoNhaController)controller).getDate().toString());
}
comboBox.setStyle("-fx-font: 18px \"System\";");
}
@Override
public boolean addRecord() {
ComboBox<String> comboBox = (ComboBox<String>)addFormRoot.lookup(".combo-box");
String date = comboBox.getSelectionModel().getSelectedItem();
if(date == null || date.isBlank()){
Alert alert = new Alert(AlertType.ERROR);
alert.setTitle("Error!!!");
alert.setContentText("Chưa chọn ngày !!!");
alert.showAndWait();
return false;
}
((KhuyenHocTheoNhaController)controller).setDate(Date.valueOf(date));
reloadPage();
Node node = QuanLyNhanKhau.primaryStage.getScene().lookup("#phanThuongCuoiNamLabel");
Label label = (Label)node;
label.setText(" Ngày phát: " + date);
label.setStyle("-fx-background-color: #ccebfa;");
return true;
}
@Override
public void onShowing(int index) {
Node node = QuanLyNhanKhau.primaryStage.getScene().lookup("#phanThuongCuoiNamLabel");
Label label = (Label)node;
if(((KhuyenHocTheoNhaController)controller).getDate() != null){
label.setText(" Ngày phát: " + ((KhuyenHocTheoNhaController)controller).getDate());
label.setStyle("-fx-background-color: #ccebfa;");
}
}
@Override
public boolean updateRecord() {
// TODO Auto-generated method stub
return false;
}
@Override
public boolean deleteRecord() {
// TODO Auto-generated method stub
return false;
}
}
| true
|
c1f26d42411f15327faaba625bf1b2a23375cfea
|
Java
|
EwyBoy/EwysWorkshop
|
/src/main/java/com/ewyboy/ewysworkshop/loaders/TileEntityLoader.java
|
UTF-8
| 918
| 2.28125
| 2
|
[
"MIT"
] |
permissive
|
package com.ewyboy.ewysworkshop.loaders;
import com.ewyboy.ewysworkshop.tileentity.TileEntityTable;
import com.ewyboy.ewysworkshop.util.Logger;
import com.ewyboy.ewysworkshop.util.StringMap;
import com.google.common.base.Stopwatch;
import cpw.mods.fml.common.registry.GameRegistry;
import java.util.concurrent.TimeUnit;
@GameRegistry.ObjectHolder(StringMap.ID)
public class TileEntityLoader {
public static void log(Class tileEntity) {Logger.info(" " + tileEntity + " successfully loaded");}
public static void loadTileEntities() {
Stopwatch watch = Stopwatch.createStarted();
Logger.info("Loading tile entities started");
GameRegistry.registerTileEntity(TileEntityTable.class, StringMap.WorkshopTable);
log(TileEntityTable.class);
Logger.info("Loading tile entities finished after " + watch.elapsed(TimeUnit.MILLISECONDS) + "ms");
}
}
| true
|
dca5fefb542fdcf009fb8f006a4010e2d90d1b2c
|
Java
|
cha63506/CompSecurity
|
/weather-widget-source/src/com/vladium/emma/report/ItemComparator$Factory$ReverseComparator.java
|
UTF-8
| 620
| 1.710938
| 2
|
[] |
no_license
|
// Decompiled by Jad v1.5.8e. Copyright 2001 Pavel Kouznetsov.
// Jad home page: http://www.geocities.com/kpdus/jad.html
// Decompiler options: braces fieldsfirst space lnc
package com.vladium.emma.report;
import java.util.Comparator;
// Referenced classes of package com.vladium.emma.report:
// ItemComparator
private static final class m_comparator
implements ItemComparator
{
private final Comparator m_comparator;
public int compare(Object obj, Object obj1)
{
return m_comparator.compare(obj1, obj);
}
(Comparator comparator)
{
m_comparator = comparator;
}
}
| true
|
6552f01b3d84adb069d5da2d5a69d4038cfa2127
|
Java
|
hzfzsoft-dev/shoppingMall_soa
|
/shoppingMall/shoppingmall-util/src/main/java/org/fzsoft/shoppingmall/utils/http/WeiXinToken.java
|
UTF-8
| 5,696
| 2.3125
| 2
|
[] |
no_license
|
package org.fzsoft.shoppingmall.utils.http;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import java.math.BigDecimal;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.concurrent.TimeUnit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.fzsoft.shoppingmall.utils.math.Arith;
import org.fzsoft.shoppingmall.utils.prop.SpringProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
public class WeiXinToken {
private Logger logger = LoggerFactory.getLogger(WeiXinToken.class);
public static final String WX_TOKEN = "wx_token";
public static final String WX_TICKET = "wx_ticket";
public static String TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=SECRET";
public static String TICKET_URL = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=ACCESS_TOKEN&type=jsapi";
@Autowired
private RedisTemplate<String, String> redisTemplate;
@Autowired
private SpringProperties properties;
public String getWinxinSign(String url, String timestamp, String nonceStr) {
String accessToken = getAccessToken(true);
String ticket = getTicket(accessToken);
//第一次获取ticket失败,则重新获取token
if ("0".equals(ticket)) {
accessToken = getAccessToken(false);
}
logger.info("==获取accessToken:"+accessToken);
//再获取下ticket
ticket = getTicket(accessToken);
//如果还错,直接退出
if ("0".equals(ticket)) {
throw new RuntimeException("签名获取异常");
}
return getSignForUrl(url, timestamp, ticket, nonceStr);
}
private String getSignForUrl(String url, String timestamp, String tikect, String nonceStr) {
String[] paramArr = new String[]{"jsapi_ticket=" + tikect, "timestamp=" + timestamp, "noncestr=" + nonceStr,
"url=" + url};
Arrays.sort(paramArr);
// 将排序后的结果拼接成一个字符串
String content = paramArr[0].concat("&" + paramArr[1]).concat("&" + paramArr[2]).concat("&" + paramArr[3]);
logger.info("sign for {}", content);
String gensignature = null;
try {
MessageDigest md = MessageDigest.getInstance("SHA-1");
// 对拼接后的字符串进行 sha1 加密
byte[] digest = md.digest(content.getBytes());
gensignature = byteToStr(digest);
} catch (NoSuchAlgorithmException e) {
logger.error(e.getMessage(), e);
}
return gensignature.toLowerCase();
}
public String getAccessToken(boolean cache) {
String appId = properties.getProperty("user.login.weixin.appid");
String secret = properties.getProperty("user.login.weixin.secret");
String accessToken = redisTemplate.opsForValue().get(WX_TOKEN);
if (!cache || accessToken == null) {
String tokenUrl = TOKEN_URL.replace("APPID", appId).replace("SECRET", secret);
JSONObject tokenObj = JSON.parseObject(HttpTools.doGet(tokenUrl, null, null));
logger.info("get accessToken : {} ", tokenObj);
if (tokenObj.getInteger("errcode") != null && tokenObj.getInteger("errcode") != 0) {
throw new RuntimeException("获取token异常");
}
accessToken = tokenObj.getString("access_token");
Integer expiresIn = new BigDecimal(Arith.multiplys(0, tokenObj.getIntValue("expires_in"), 0.9)).intValue();
redisTemplate.opsForValue().set(WX_TOKEN, accessToken, expiresIn, TimeUnit.SECONDS);
}
return accessToken;
}
public String getTicket(String accessToken) {
String ticket = redisTemplate.opsForValue().get(WX_TICKET);
if (ticket != null) {
return ticket;
}
String ticketUrl = TICKET_URL.replace("ACCESS_TOKEN", accessToken);
JSONObject tikectObj = JSON.parseObject(HttpTools.doGet(ticketUrl, null, null));
logger.info("get ticket : {} ", tikectObj);
//获取ticket失败,则return
if (tikectObj.getInteger("errcode") != null && tikectObj.getInteger("errcode") != 0) {
return "0";
}
ticket = tikectObj.getString("ticket");
Integer expiresIn = new BigDecimal(Arith.divides(0, tikectObj.getIntValue("expires_in"), 10)).intValue();
redisTemplate.opsForValue().set(WX_TICKET, ticket, expiresIn, TimeUnit.SECONDS);
return ticket;
}
/**
* 将字节数组转换为十六进制字符串
*
* @param byteArray
* @return
*/
private static String byteToStr(byte[] byteArray) {
String strDigest = "";
for (int i = 0; i < byteArray.length; i++) {
strDigest += byteToHexStr(byteArray[i]);
}
return strDigest;
}
/**
* 将字节转换为十六进制字符串
*
* @param mByte
* @return
*/
private static String byteToHexStr(byte mByte) {
char[] Digit = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
char[] tempArr = new char[2];
tempArr[0] = Digit[(mByte >>> 4) & 0X0F];
tempArr[1] = Digit[mByte & 0X0F];
String s = new String(tempArr);
return s;
}
}
| true
|
00f9c899e02d80b90c820477db7f50d89508c693
|
Java
|
iloveruning/mly
|
/src/main/java/com/hfutonline/mly/modules/sys/shiro/tool/ShiroKit.java
|
UTF-8
| 6,294
| 2.5625
| 3
|
[] |
no_license
|
package com.hfutonline.mly.modules.sys.shiro.tool;
import com.hfutonline.mly.common.utils.RandomUtil;
import com.hfutonline.mly.modules.sys.shiro.ShiroUser;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.ByteSource;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
/**
* Shiro工具类
*
* @author chenliangliang
* @date 2018/1/9
*/
public class ShiroKit {
/**
* 加密算法
*/
public static final String HASH_ALGORITHM_NAME = "MD5";
/**
* 循环次数
*/
public static final int HASH_ITERATIONS = 32;
/**
* shiro密码加密工具类
*
* @param password 密码
* @param salt 密码盐
* @return 返回加密后的密码
*/
public static String md5(String password, String salt) {
ByteSource s = new Md5Hash(salt);
return new SimpleHash(HASH_ALGORITHM_NAME, password, s, HASH_ITERATIONS).toString();
}
/**
* 获取随机盐值
*
* @param length
* @return
*/
public static String getRandomSalt(int length) {
return RandomUtil.randomString(length);
}
/**
* 获取当前 Subject
*
* @return Subject
*/
public static Subject getSubject() {
return SecurityUtils.getSubject();
}
/**
* 从shiro中获取session
*
* @return session
*/
public static Session getSession() {
return getSubject().getSession();
}
/**
* 通过key获取shiro指定的session属性
*
* @param key 键
* @return 值
*/
public static Object getSessionAttr(String key) {
Session session = getSession();
return session != null ? session.getAttribute(key) : null;
}
/**
* 设置shiro指定的session属性
*
* @param key
* @param value
*/
public static void setSessionAttr(String key, Object value) {
Session session = getSession();
session.setAttribute(key, value);
}
/**
* 移除shiro指定的session属性
*/
public static Object removeSessionAttr(String key) {
Session session = getSession();
return session != null ? session.removeAttribute(key) : null;
}
/**
* 验证当前用户是否属于该角色?,使用时与lacksRole 搭配使用
*
* @param roleName 角色名
* @return 属于该角色:true,否则false
*/
public static boolean hasRole(String roleName) {
Subject subject = getSubject();
return subject != null && roleName != null && subject.hasRole(roleName);
}
/**
* 验证当前用户是否拥有所有角色
*
* @param roles 角色集
* @return
*/
public static boolean hasAllRoles(String... roles) {
if (roles.length == 0) {
return false;
}
List<String> list = Arrays.asList(roles);
Subject subject = getSubject();
return subject != null && subject.hasAllRoles(list);
}
/**
* 验证当前用户是否拥有所有角色
*
* @param roles 角色集
* @return
*/
public static boolean hasAllRoles(Collection<String> roles) {
if (roles.size() == 0) {
return false;
}
Subject subject = getSubject();
return subject != null && subject.hasAllRoles(roles);
}
/**
* 验证当前用户是否拥有指定权限
*
* @param permission 权限名
* @return 拥有权限:true,否则false
*/
public static boolean hasPermission(String permission) {
Subject subject = getSubject();
return subject != null && permission != null && subject.isPermitted(permission);
}
/**
* 验证当前用户是否拥有指定权限集
*
* @param permissions 权限集
* @return 拥有权限:true,否则false
*/
public static boolean hasAllPermissions(String... permissions) {
if (permissions.length == 0) {
return false;
}
Subject subject = getSubject();
return subject != null && subject.isPermittedAll(permissions);
}
/**
* 已认证通过的用户。不包含已记住的用户,这是与user标签的区别所在。
*
* @return 通过身份验证:true,否则false
*/
public static boolean isAuthenticated() {
Subject subject = getSubject();
return subject != null && subject.isAuthenticated();
}
/**
* 认证通过或已记住的用户。与guset搭配使用。
*
* @return 用户:true,否则 false
*/
public static boolean isUser() {
Subject subject = getSubject();
return subject != null && subject.getPrincipal() != null;
}
/**
* 是否记住密码
*/
public static boolean isRemembered() {
Subject subject = getSubject();
return subject != null && subject.isRemembered();
}
/**
* 验证当前用户是否为“访客”,即未认证(包含未记住)的用户。用user搭配使用
*
* @return 访客:true,否则false
*/
public static boolean isGuest() {
return !isUser();
}
/**
* 退出登录
*/
public static void logout() {
Subject subject = getSubject();
if (subject != null) {
subject.logout();
}
}
/**
* 获取shiro用户
*
* @return shiro用户
*/
public static ShiroUser getPrincipal() {
Subject subject = getSubject();
if (subject != null) {
return (ShiroUser) subject.getPrincipal();
}
return null;
}
/**
* 获取登录用户名
*/
public static String getUserName() {
ShiroUser shiroUser = getPrincipal();
return shiroUser == null ? null : shiroUser.getName();
}
/**
* 获取登录用户名
*/
public static Integer getUserId() {
ShiroUser shiroUser = getPrincipal();
return shiroUser == null ? null : shiroUser.getId();
}
}
| true
|
9ad0a0a51a081805c2754bb7172d3d4393b850ad
|
Java
|
bculo/MyGroceryPal
|
/app/src/main/java/hr/foi/air/mygrocerypal/myapplication/PaymentHelper/PaymentActivity.java
|
UTF-8
| 8,294
| 2.078125
| 2
|
[] |
no_license
|
package hr.foi.air.mygrocerypal.myapplication.PaymentHelper;
import android.content.Intent;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.braintreepayments.api.dropin.DropInActivity;
import com.braintreepayments.api.dropin.DropInRequest;
import com.braintreepayments.api.dropin.DropInResult;
import com.braintreepayments.api.models.PaymentMethodNonce;
import com.google.android.gms.common.util.IOUtils;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import java.util.ArrayList;
import java.util.List;
import cz.msebera.android.httpclient.Header;
import hr.foi.air.mygrocerypal.myapplication.Controller.MainActivity;
import hr.foi.air.mygrocerypal.myapplication.FirebaseHelper.CreateNewGroceryListHelper;
import hr.foi.air.mygrocerypal.myapplication.FirebaseHelper.GroceryChangeStatusHelper;
import hr.foi.air.mygrocerypal.myapplication.FirebaseHelper.Listeners.AddGroceryListListener;
import hr.foi.air.mygrocerypal.myapplication.Model.GroceryListProductsModel;
import hr.foi.air.mygrocerypal.myapplication.Model.GroceryListsModel;
import hr.foi.air.mygrocerypal.myapplication.Model.StoresModel;
import hr.foi.air.mygrocerypal.myapplication.Model.UserModel;
import hr.foi.air.mygrocerypal.myapplication.R;
public class PaymentActivity extends AppCompatActivity implements PaymentListener{
private static final int PAYMENT_REQUEST = 1111;
private static final int REQUEST_CODE = 1234;
private static final String CHECKOUT = "http://cortex.foi.hr/grocerypal/checkout.php";
private Payment mPayment;
private String mToken;
private Double mTotalPayment = 0.0;
private GroceryListsModel mModel;
private UserModel mUserModel;
private TextView mPrice;
private Button mPay;
private LinearLayout mWaiting;
/**
* Inicijalizacija
* @param savedInstanceState
*/
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_payment);
mPrice = findViewById(R.id.totalPrice);
mPay = findViewById(R.id.startPayment);
mWaiting = findViewById(R.id.waiting);
Bundle extras = getIntent().getExtras();
if (extras != null) {
//mTotalPayment = extras.getDouble("TOTAL_PAYMENT");
mModel = (GroceryListsModel) extras.getSerializable("MODEL_GL");
mUserModel = (UserModel) extras.getSerializable("USER_MODEL");
for(GroceryListProductsModel product: mModel.getProductsModels())
mTotalPayment += product.getPrice() * product.getBought();
mTotalPayment += Double.parseDouble(mModel.getCommision());
mPrice.setText(mPrice.getText() + " " + String.format("%.2f", mTotalPayment) + " KN");
new Token(this).execute();
}
mPay.setEnabled(false);
mPay.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startPayment();
}
});
}
/**
* Prikaz Braintree Activitya za placanje
*/
private void startPayment(){
this.mWaiting.setVisibility(View.VISIBLE);
DropInRequest dropInRequest = new DropInRequest()
.clientToken(mToken.trim());
startActivityForResult(dropInRequest.getIntent(this), REQUEST_CODE);
}
/**
* Rad s Braintreeom
* @param requestCode
* @param resultCode
* @param data
*/
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
if (requestCode == REQUEST_CODE) {
if (resultCode == PaymentActivity.RESULT_OK) {
DropInResult result = data.getParcelableExtra(DropInResult.EXTRA_DROP_IN_RESULT);
PaymentMethodNonce nonce = result.getPaymentMethodNonce();
String stringNonce = nonce.getNonce();
if(mTotalPayment != null) {
mPayment = new Payment(stringNonce, String.format("%.2f", mTotalPayment));
sendPayments();
}
else {
Toast.makeText(this, getResources().getString(R.string.paymentFailed), Toast.LENGTH_LONG).show();
this.mWaiting.setVisibility(View.GONE);
}
} else if (resultCode == PaymentActivity.RESULT_CANCELED) {
Toast.makeText(this, getResources().getString(R.string.postponed), Toast.LENGTH_LONG).show();
this.mWaiting.setVisibility(View.GONE);
} else {
Exception error = (Exception) data.getSerializableExtra(DropInActivity.EXTRA_ERROR);
Log.d("ERROR ONACTIVITYSRESULT", error.getMessage());
Toast.makeText(this, getResources().getString(R.string.paymentFailed), Toast.LENGTH_LONG).show();
this.mWaiting.setVisibility(View.GONE);
}
}
}
/**
* Pokreni proces placanja
* Slanje upita PHP serveru (checkout.php)
*/
private void sendPayments() {
AsyncHttpClient client = new AsyncHttpClient();
RequestParams params = new RequestParams();
params.put("payment_method_nonce", mPayment.getmNonce());
params.put("order_id", mModel.getGrocerylist_key());
params.put("amount", mPayment.getmAmount());
params.put("deliverer_name", mUserModel.getFirst_name() + " " + mUserModel.getLast_name());
params.put("deliverer_uid", mUserModel.getUserUID());
params.put("deliverer_phone", mUserModel.getPhone_number());
client.post(CHECKOUT, params,
new AsyncHttpResponseHandler() {
@Override
public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
try {
String str = new String(responseBody, "UTF-8");
Log.d("RESULT POST-a", str);
if(str.contains("Successful"))
showFinalMessage(getResources().getString(R.string.paymentSuccess), true);
else
showFinalMessage(getResources().getString(R.string.paymentFailed), false);
}
catch (Exception e){
Log.d("CONVERT_EXCEPTION", e.getMessage());
showFinalMessage(getResources().getString(R.string.paymentFailed), false);
}
}
@Override
public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
Log.d("ONFAILURE POST", error.getMessage());
showFinalMessage(getResources().getString(R.string.paymentFailed), false);
}
}
);
}
/**
* Prikazi konacni status placanja
* @param message
*/
private void showFinalMessage(String message, boolean passed){
if(passed) {
mPay.setEnabled(false);
GroceryChangeStatusHelper helper = new GroceryChangeStatusHelper(this);
boolean mSuccess = helper.setStatusToFinished(mModel);
if(mSuccess) {
setResult(RESULT_OK);
this.finish();
}
}
Toast.makeText(this, message, Toast.LENGTH_LONG).show();
mWaiting.setVisibility(View.GONE);
}
/**
* Token dohvaćen s PHP servera
* Implementacija sučelja PaymentListener
* @param token
*/
@Override
public void tokenReceived(String token) {
if(token != null) {
Log.d("TOKEN", token);
this.mToken = token;
this.mWaiting.setVisibility(View.GONE);
this.mPay.setEnabled(true);
}
}
}
| true
|
edab73f40122c8a0ab3447c62735d6742e627500
|
Java
|
boncGit/ssm
|
/ssm-service/src/main/java/com/watchme/common/utils/DateUtils.java
|
UTF-8
| 9,491
| 2.765625
| 3
|
[
"Apache-2.0"
] |
permissive
|
/**
* Copyright © 2012-2014 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
*/
package com.watchme.common.utils;
import org.apache.commons.lang.time.DateFormatUtils;
import java.text.ParseException;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
/**
* 日期工具类, 继承org.apache.commons.lang.time.DateUtils类
* @author ThinkGem
* @version 2014-4-15
*/
public class DateUtils extends org.apache.commons.lang3.time.DateUtils {
private static String[] parsePatterns = {
"yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm", "yyyy-MM",
"yyyy/MM/dd", "yyyy/MM/dd HH:mm:ss", "yyyy/MM/dd HH:mm", "yyyy/MM",
"yyyy.MM.dd", "yyyy.MM.dd HH:mm:ss", "yyyy.MM.dd HH:mm", "yyyy.MM"};
/**
* 得到当前日期字符串 格式(yyyy-MM-dd)
*/
public static String getDate() {
return getDate("yyyy-MM-dd");
}
/**
* 得到当前日期字符串 格式(yyyy-MM-dd) pattern可以为:"yyyy-MM-dd" "HH:mm:ss" "E"
*/
public static String getDate(String pattern) {
return DateFormatUtils.format(new Date(), pattern);
}
/**
* 得到日期字符串 默认格式(yyyy-MM-dd) pattern可以为:"yyyy-MM-dd" "HH:mm:ss" "E"
*/
public static String formatDate(Date date, Object... pattern) {
String formatDate = null;
if (pattern != null && pattern.length > 0) {
formatDate = DateFormatUtils.format(date, pattern[0].toString());
} else {
formatDate = DateFormatUtils.format(date, "yyyy-MM-dd");
}
return formatDate;
}
/**
* 得到日期时间字符串,转换格式(yyyy-MM-dd HH:mm:ss)
*/
public static String formatDateTime(Date date) {
return formatDate(date, "yyyy-MM-dd HH:mm:ss");
}
/**
* 得到当前时间字符串 格式(HH:mm:ss)
*/
public static String getTime() {
return formatDate(new Date(), "HH:mm:ss");
}
/**
* 得到当前日期和时间字符串 格式(yyyy-MM-dd HH:mm:ss)
*/
public static String getDateTime() {
return formatDate(new Date(), "yyyy-MM-dd HH:mm:ss");
}
/**
* 得到当前年份字符串 格式(yyyy)
*/
public static String getYear() {
return formatDate(new Date(), "yyyy");
}
/**
* 得到当前月份字符串 格式(MM)
*/
public static String getMonth() {
return formatDate(new Date(), "MM");
}
/**
* 得到当天字符串 格式(dd)
*/
public static String getDay() {
return formatDate(new Date(), "dd");
}
/**
* 得到当前星期字符串 格式(E)星期几
*/
public static String getWeek() {
return formatDate(new Date(), "E");
}
/**
* 日期型字符串转化为日期 格式
* { "yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm",
* "yyyy/MM/dd", "yyyy/MM/dd HH:mm:ss", "yyyy/MM/dd HH:mm",
* "yyyy.MM.dd", "yyyy.MM.dd HH:mm:ss", "yyyy.MM.dd HH:mm" }
*/
public static Date parseDate(Object str) {
if (str == null){
return null;
}
try {
return parseDate(str.toString(), parsePatterns);
} catch (ParseException e) {
return null;
}
}
/**
* 获取过去的天数
* @param date
* @return
*/
public static long pastDays(Date date) {
long t = new Date().getTime()-date.getTime();
return t/(24*60*60*1000);
}
/**
* 获取过去的小时
* @param date
* @return
*/
public static long pastHour(Date date) {
long t = new Date().getTime()-date.getTime();
return t/(60*60*1000);
}
/**
* 获取过去的分钟
* @param date
* @return
*/
public static long pastMinutes(Date date) {
long t = new Date().getTime()-date.getTime();
return t/(60*1000);
}
/**
* 转换为时间(天,时:分:秒.毫秒)
* @param timeMillis
* @return
*/
public static String formatDateTime(long timeMillis){
long day = timeMillis/(24*60*60*1000);
long hour = (timeMillis/(60*60*1000)-day*24);
long min = ((timeMillis/(60*1000))-day*24*60-hour*60);
long s = (timeMillis/1000-day*24*60*60-hour*60*60-min*60);
long sss = (timeMillis-day*24*60*60*1000-hour*60*60*1000-min*60*1000-s*1000);
return (day>0?day+",":"")+hour+":"+min+":"+s+"."+sss;
}
/**
* 获取两个日期之间的天数
*
* @param before
* @param after
* @return
*/
public static double getDistanceOfTwoDate(Date before, Date after) {
long beforeTime = before.getTime();
long afterTime = after.getTime();
return (afterTime - beforeTime) / (1000 * 60 * 60 * 24);
}
public static Date getDateAfter(Date date){
Calendar c = Calendar.getInstance();
c.setTime(date);
int day=c.get(Calendar.DATE);
c.set(Calendar.DATE,day+1);
return c.getTime();
}
public static Date getDateBefore(Date date){
Calendar c = Calendar.getInstance();
c.setTime(date);
int day=c.get(Calendar.DATE);
c.set(Calendar.DATE,day-1);
return c.getTime();
}
/**
* 取得当前日期所在周的第一天
*
* @param date
* @return
*/
public static Date getFirstDayOfWeek(Date date) {
Calendar c = new GregorianCalendar();
c.setFirstDayOfWeek(Calendar.MONDAY);
c.setTime(date);
c.set(Calendar.DAY_OF_WEEK, c.getFirstDayOfWeek()); // Monday
return c.getTime ();
}
/**
* 取得当前日期所在周的最后一天
*
* @param date
* @return
*/
public static Date getLastDayOfWeek(Date date) {
Calendar c = new GregorianCalendar();
c.setFirstDayOfWeek(Calendar.MONDAY);
c.setTime(date);
c.set(Calendar.DAY_OF_WEEK, c.getFirstDayOfWeek() + 6); // Sunday
return c.getTime();
}
/**
* 取得当前日期所在月的第一天
*
* @param date
* @return
*/
public static Date getFirstDayOfMonth(Date date) {
Calendar c = new GregorianCalendar();
c.setTime(date);
c.set(Calendar.DAY_OF_MONTH,1); // Sunday
return c.getTime ();
}
/**
* 取得当前日期所在月的最后一天
*
* @param date
* @return
*/
public static Date getLastDayOfMonth(Date date) {
Calendar c = new GregorianCalendar();
c.setTime(date);
c.add(Calendar.MONTH,1);//月增加1天
c.set(Calendar.DAY_OF_MONTH,-1);//日期倒数一日,既得到本月最后一天
return c.getTime();
}
/**
* 获取当月的前几月
* num -1 位前一月 不支持大约13个月
* flag: true 返回月份 ,false 返回年月
* @param num
* @param flag
* @return
*/
public static String getYearMonth(int num,boolean flag){
Date date = new Date();
String cuDate = DateFormatUtils.format(date, "yyyyMM");
Calendar cal = Calendar.getInstance();
int cuM = cal.get(Calendar.MONTH) + 1;
if(num >= 0){
if(flag){
return String.valueOf(cuM);
}else{
return cuDate;
}
}
int numABS = Math.abs(num);
if(numABS > 12){
if(flag){
return String.valueOf(cuM);
}else{
return cuDate;
}
}
int month = cal.get(Calendar.MONTH) + 1;
int year = cal.get(Calendar.YEAR);
int rm = month-numABS;
if(rm <= 0){
year--;
}
int m = rm == 0?12:(rm>0?rm:(12-Math.abs(rm)));
String mon = m<10?"0"+String.valueOf(m):String.valueOf(m);
if(flag){
return String.valueOf(m);
}else{
return String.valueOf(year)+mon;
}
}
/**
* 数字月份转换成汉字月份
* @return
*/
public static String getChineseMonth(int month){
String [] cMonth = new String[]{"零","一月","二月","三月","四月","五月","六月","七月","八月","九月","十月","十一月","十二月"};
return cMonth[month];
}
/**
* 日期添加几天(负值就是减少)
* @param beforeDate
* @param n
* @return
*/
public static Date addDay(Date beforeDate, int n) {
Calendar calendar = new GregorianCalendar();
calendar.setTime(beforeDate);
calendar.add(Calendar.DATE, n);
Date afterDate = calendar.getTime();
return afterDate;
}
/**
* @param args
* @throws ParseException
*/
public static void main(String[] args) throws ParseException {
// System.out.println(formatDate(parseDate("2010/3/6")));
// System.out.println(getDate("yyyy年MM月dd日 E"));
// long time = new Date().getTime()-parseDate("2012-11-19").getTime();
// System.out.println(time/(24*60*60*1000));
System.out.println("DateUtils.getDateBefore(new Date())=="+ DateFormatUtils.format(DateUtils.getDateBefore(new Date()), parsePatterns[1]));
System.out.println("DateUtils.getDateAfter(new Date())=="+ DateFormatUtils.format(DateUtils.getDateAfter(new Date()), parsePatterns[1]));
System.out.println("DateUtils.getFirstDayOfWeek(new Date())=="+ DateFormatUtils.format(DateUtils.getFirstDayOfWeek(new Date()), parsePatterns[1]));
System.out.println("DateUtils.getLastDayOfWeek(new Date())=="+ DateFormatUtils.format(DateUtils.getLastDayOfWeek(new Date()), parsePatterns[1]));
System.out.println("DateUtils.getFirstDayOfMonth(new Date())=="+ DateFormatUtils.format(DateUtils.getFirstDayOfMonth(new Date()), parsePatterns[1]));
System.out.println("DateUtils.getLastDayOfMonth(new Date())=="+ DateFormatUtils.format(DateUtils.getLastDayOfMonth(new Date()), parsePatterns[1]));
}
}
| true
|
a637ac38ad622cbc5333efb88c784618efa6ed10
|
Java
|
Yann-Tricot/S5_POO_TP_Compteur
|
/src/code/Classes/ChaineDeCompteurs.java
|
UTF-8
| 1,823
| 3.96875
| 4
|
[] |
no_license
|
package code.Classes;
import java.util.Arrays;
public class ChaineDeCompteurs {
private Compteur[] compteurs;
boolean termine;
public ChaineDeCompteurs(int nombreCompteurs, int[] mins, int[] maxs, int[] pas) {
this.compteurs = new Compteur[nombreCompteurs];
for (int i = 0; i < nombreCompteurs; i++) {
this.compteurs[i] = new Compteur(mins[i], maxs[i], pas[i]);
}
}
/**
* Methode permettant d'incrementer la chaine de compteur
*/
public void incrementer() {
boolean termine = false;
for (int i = compteurs.length - 1; i >= 0 && !termine; i--) {
termine = !compteurs[i].incrementer();
}
}
/**
* Methode permettant de remettre à zero la chaine de compteur
*/
public void raz() {
for (Compteur compteur : compteurs) {
compteur.raz();
}
}
/**
* Methode permettant d'afficher la valeur en string de la chaine de caractère
*/
public void afficher() {
System.out.println(toString());
}
/**
* Methode permettant de convertir la chaine de compteur en string
*
* @return Valeur convertie en string
*/
public String toString() {
String valeur = "";
for (int i = 0; i < compteurs.length; i++) {
valeur += compteurs[i].toString();
if (i != compteurs.length - 1) {
valeur += ':';
}
}
return valeur;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
ChaineDeCompteurs that = (ChaineDeCompteurs) o;
return termine == that.termine &&
Arrays.equals(compteurs, that.compteurs);
}
}
| true
|
e67c06876c7da3ce846546b516d58c9c23dbab53
|
Java
|
BasisTI/madre
|
/internacao/src/main/java/br/com/basis/madre/web/rest/LeitoResource.java
|
UTF-8
| 7,891
| 2.09375
| 2
|
[] |
no_license
|
package br.com.basis.madre.web.rest;
import br.com.basis.madre.service.LeitoService;
import br.com.basis.madre.service.dto.LeitoDTO;
import br.gov.nuvem.comum.microsservico.web.rest.errors.BadRequestAlertException;
import io.github.jhipster.web.util.HeaderUtil;
import io.github.jhipster.web.util.PaginationUtil;
import io.github.jhipster.web.util.ResponseUtil;
import lombok.RequiredArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
import javax.validation.Valid;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.List;
import java.util.Optional;
@RequiredArgsConstructor
@RestController
@RequestMapping("/api")
public class LeitoResource {
private final Logger log = LoggerFactory.getLogger(LeitoResource.class);
private static final String ENTITY_NAME = "internacaoLeito";
@Value("${jhipster.clientApp.name}")
private String applicationName;
private final LeitoService leitoService;
public static String getEntityName() {
return ENTITY_NAME;
}
/**
* {@code POST /leitos} : Create a new leito.
*
* @param leitoDTO the leitoDTO to create.
* @return the {@link ResponseEntity} with status {@code 201 (Created)} and with body the new
* leitoDTO, or with status {@code 400 (Bad Request)} if the leito has already an ID.
* @throws URISyntaxException if the Location URI syntax is incorrect.
*/
@PostMapping("/leitos")
public ResponseEntity<LeitoDTO> createLeito(@Valid @RequestBody LeitoDTO leitoDTO)
throws URISyntaxException {
log.debug("REST request to save Leito : {}", leitoDTO);
if (leitoDTO.getId() != null) {
throw new BadRequestAlertException("A new leito cannot already have an ID", ENTITY_NAME,
"idexists");
}
LeitoDTO result = leitoService.save(leitoDTO);
return ResponseEntity.created(new URI("/api/leitos/" + result.getId()))
.headers(HeaderUtil.createEntityCreationAlert(applicationName, false, ENTITY_NAME,
result.getId().toString()))
.body(result);
}
/**
* {@code PUT /leitos} : Updates an existing leito.
*
* @param leitoDTO the leitoDTO to update.
* @return the {@link ResponseEntity} with status {@code 200 (OK)} and with body the updated
* leitoDTO, or with status {@code 400 (Bad Request)} if the leitoDTO is not valid, or with
* status {@code 500 (Internal Server Error)} if the leitoDTO couldn't be updated.
* @throws URISyntaxException if the Location URI syntax is incorrect.
*/
@PutMapping("/leitos")
public ResponseEntity<LeitoDTO> updateLeito(@Valid @RequestBody LeitoDTO leitoDTO)
throws URISyntaxException {
log.debug("REST request to update Leito : {}", leitoDTO);
if (leitoDTO.getId() == null) {
throw new BadRequestAlertException("Invalid id", ENTITY_NAME, "idnull");
}
LeitoDTO result = leitoService.save(leitoDTO);
return ResponseEntity.ok()
.headers(HeaderUtil.createEntityUpdateAlert(applicationName, false, ENTITY_NAME,
leitoDTO.getId().toString()))
.body(result);
}
/**
* {@code GET /leitos} : get all the leitos.
*
* @param pageable the pagination information.
* @return the {@link ResponseEntity} with status {@code 200 (OK)} and the list of leitos in
* body.
*/
@GetMapping("/leitos")
public ResponseEntity<List<LeitoDTO>> getAllLeitos(LeitoDTO leitoDTO, Pageable pageable) {
log.debug("REST request to get a page of Leitos");
Page<LeitoDTO> page = leitoService.findAll(leitoDTO, pageable);
HttpHeaders headers = PaginationUtil
.generatePaginationHttpHeaders(ServletUriComponentsBuilder.fromCurrentRequest(), page);
return ResponseEntity.ok().headers(headers).body(page.getContent());
}
@GetMapping("/leitos/situacao/{situacao}")
public ResponseEntity<List<LeitoDTO>> obterTodosOsLeitosPorSituacao(@PathVariable(name = "situacao") String situacao, Pageable pageable) {
Page<LeitoDTO> page = Page.empty();
if (situacao.equals("reservados")) {
page = leitoService.obterTodosOsLeitosLiberados(pageable);
} else if (situacao.equals("bloqueados")) {
page = leitoService.obterTodosOsLeitosBloqueados(pageable);
} else if (situacao.equals("ocupados")) {
page = leitoService.obterTodosOsLeitosOcupados(pageable);
} else if (situacao.equals("naoliberados")) {
page = leitoService.obterTodosOsLeitosNaoLiberados(pageable);
} else if (situacao.equals("liberados")) {
page = leitoService.obterTodosOsLeitosLiberados(pageable);
}
HttpHeaders headers = PaginationUtil
.generatePaginationHttpHeaders(ServletUriComponentsBuilder.fromCurrentRequest(), page);
return ResponseEntity.ok().headers(headers).body(page.getContent());
}
/**
* {@code GET /leitos/:id} : get the "id" leito.
*
* @param id the id of the leitoDTO to retrieve.
* @return the {@link ResponseEntity} with status {@code 200 (OK)} and with body the leitoDTO,
* or with status {@code 404 (Not Found)}.
*/
@GetMapping("/leitos/{id}")
public ResponseEntity<LeitoDTO> getLeito(@PathVariable Long id) {
log.debug("REST request to get Leito : {}", id);
Optional<LeitoDTO> leitoDTO = leitoService.findOne(id);
return ResponseUtil.wrapOrNotFound(leitoDTO);
}
/**
* {@code DELETE /leitos/:id} : delete the "id" leito.
*
* @param id the id of the leitoDTO to delete.
* @return the {@link ResponseEntity} with status {@code 204 (NO_CONTENT)}.
*/
@DeleteMapping("/leitos/{id}")
public ResponseEntity<Void> deleteLeito(@PathVariable Long id) {
log.debug("REST request to delete Leito : {}", id);
leitoService.delete(id);
return ResponseEntity.noContent().headers(HeaderUtil
.createEntityDeletionAlert(applicationName, false, ENTITY_NAME, id.toString())).build();
}
/**
* {@code SEARCH /_search/leitos?query=:query} : search for the leito corresponding to the
* query.
*
* @param query the query of the leito search.
* @param pageable the pagination information.
* @return the result of the search.
*/
@GetMapping("/_search/leitos")
public ResponseEntity<List<LeitoDTO>> searchLeitos(@RequestParam String query,
Pageable pageable) {
log.debug("REST request to search for a page of Leitos for query {}", query);
Page<LeitoDTO> page = leitoService.search(query, pageable);
HttpHeaders headers = PaginationUtil
.generatePaginationHttpHeaders(ServletUriComponentsBuilder.fromCurrentRequest(), page);
return ResponseEntity.ok().headers(headers).body(page.getContent());
}
}
| true
|
625f1bbca6b99315bf6f277aceaaf47a382dab22
|
Java
|
Jesssin/Tul09
|
/app/src/main/java/ylsin5/scm/tul09/Character.java
|
UTF-8
| 1,259
| 2.78125
| 3
|
[] |
no_license
|
package ylsin5.scm.tul09;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.util.Log;
import java.util.Random;
/**
* Created by JessSin on 7/11/16.
*/
enum State{
Idle,
ReadyForAttack,
Die,
}
class Character{
int Hp;
int ATP;
int Speed;//probability of miss
State CurrentState; //ready for click or not
Rect Position;
boolean BeingTouch;
Paint paint;
public Character(){}
int Distance(Character target){
return Math.abs(target.Position.top-this.Position.top);
}
void Attack(Character target){
Random rand = new Random();
int M=rand.nextInt(100)+1;
//Check miss
if(target.Speed+Distance(target)/20<=M){
paint.setColor(Color.RED);
if(target.CurrentState==State.Idle){target.Hp-=this.ATP;}
if(target.CurrentState==State.ReadyForAttack){target.Hp-=this.ATP/2;}
// do damage to Target
}else {
paint.setColor(Color.BLUE);
Log.d("ADebugTag", this+"Attack_Miss");
}
}
void CheckTouch(float x,float y){
BeingTouch=x>Position.left&&x<Position.right
&&y>Position.top&&y<Position.bottom;}
}
| true
|
17c457c8a0613bb3446b31e41b90eaabb06703ee
|
Java
|
BaeBae33/as_x_modlestudy
|
/View/Animate/TweenAnimation/src/main/java/com/view/animate/helper/AnimationSetHelper.java
|
UTF-8
| 1,874
| 2.3125
| 2
|
[] |
no_license
|
package com.view.animate.helper;
import android.content.Context;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.view.animation.AnimationUtils;
import android.view.animation.RotateAnimation;
import android.view.animation.ScaleAnimation;
import android.view.animation.TranslateAnimation;
import com.view.animate.R;
/**
* Created by yline on 2016/10/2.
*/
public class AnimationSetHelper
{
/**
* 获取Animation组合
* 通过java代码的方式
* @return
*/
public AnimationSet getAnimationSet()
{
AnimationSet animationSet = new AnimationSet(true);
Animation fAlpha = new AlphaAnimation(1.0f, 0.1f);
Animation fRotate = new RotateAnimation(0f, 360f);
Animation fScale = new ScaleAnimation(1.0f, 1.0f, 2.0f, 2.0f);
Animation fTranslate = new TranslateAnimation(0.0f, 100.0f, 0.0f, 100.0f);
animationSet.addAnimation(fAlpha);
animationSet.addAnimation(fRotate);
animationSet.addAnimation(fScale);
animationSet.addAnimation(fTranslate);
animationSet.setDuration(1000);
return animationSet;
}
/**
* 获取Animation组合
* 通过xml代码的方式
* @return
*/
public AnimationSet getAnimationSet(Context context)
{
AnimationSet animationSet = new AnimationSet(true);
Animation fAlpha = AnimationUtils.loadAnimation(context, R.anim.animator_alpha);
Animation fRotate = AnimationUtils.loadAnimation(context, R.anim.animator_rotate);
Animation fScale = AnimationUtils.loadAnimation(context, R.anim.animator_scale);
Animation fTranslate = AnimationUtils.loadAnimation(context, R.anim.animator_translate);
animationSet.addAnimation(fAlpha);
animationSet.addAnimation(fRotate);
animationSet.addAnimation(fScale);
animationSet.addAnimation(fTranslate);
animationSet.setDuration(1000);
return animationSet;
}
}
| true
|
75a9bdf4960e7fe4266a9b77ed679ee9b8316441
|
Java
|
wang-shun/erp_xiajun
|
/globalshop-biz1-app/src/main/java/com/wangqin/globalshop/biz1/app/dal/dataObject/LogisticCategoryMappingDO.java
|
UTF-8
| 2,156
| 2.15625
| 2
|
[] |
no_license
|
package com.wangqin.globalshop.biz1.app.dal.dataObject;
public class LogisticCategoryMappingDO extends BaseModel {
private Long id;
private String categoryCode;
private String categoryName;
private Long logisticsCompanyCode;
private String logisticsCompanyName;
private String logisticsCompanyCategoryCode;
private String creator;
private String modifier;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getCategoryCode() {
return categoryCode;
}
public void setCategoryCode(String categoryCode) {
this.categoryCode = categoryCode == null ? null : categoryCode.trim();
}
public String getCategoryName() {
return categoryName;
}
public void setCategoryName(String categoryName) {
this.categoryName = categoryName == null ? null : categoryName.trim();
}
public Long getLogisticsCompanyCode() {
return logisticsCompanyCode;
}
public void setLogisticsCompanyCode(Long logisticsCompanyCode) {
this.logisticsCompanyCode = logisticsCompanyCode;
}
public String getLogisticsCompanyName() {
return logisticsCompanyName;
}
public void setLogisticsCompanyName(String logisticsCompanyName) {
this.logisticsCompanyName = logisticsCompanyName == null ? null : logisticsCompanyName.trim();
}
public String getLogisticsCompanyCategoryCode() {
return logisticsCompanyCategoryCode;
}
public void setLogisticsCompanyCategoryCode(String logisticsCompanyCategoryCode) {
this.logisticsCompanyCategoryCode = logisticsCompanyCategoryCode == null ? null : logisticsCompanyCategoryCode.trim();
}
public String getCreator() {
return creator;
}
@Override
public void setCreator(String creator) {
this.creator = creator == null ? null : creator.trim();
}
public String getModifier() {
return modifier;
}
@Override
public void setModifier(String modifier) {
this.modifier = modifier == null ? null : modifier.trim();
}
}
| true
|
48e052080ee69abcf38a470435762bb8da528254
|
Java
|
codeqqby/kylin
|
/src/main/java/org/kylin/util/WyfCollectionUtils.java
|
UTF-8
| 4,644
| 2.5625
| 3
|
[
"MIT"
] |
permissive
|
package org.kylin.util;
import com.google.common.collect.Lists;
import org.apache.commons.collections4.CollectionUtils;
import org.kylin.algorithm.RandomKill;
import org.kylin.bean.W3DCode;
import org.kylin.bean.p5.WCode;
import org.kylin.constant.CodeTypeEnum;
import java.util.*;
/**
* @author huangyawu
* @date 2017/7/16 下午3:56.
*/
public class WyfCollectionUtils {
public static List<W3DCode> minus(List<W3DCode> w3DCodes, List<W3DCode> codes, CodeTypeEnum codeTypeEnum){
if(CollectionUtils.isEmpty(codes) || CollectionUtils.isEmpty(w3DCodes) || codeTypeEnum == null){
return w3DCodes;
}
List<W3DCode> ret = new ArrayList<>();
if(CodeTypeEnum.DIRECT.equals(codeTypeEnum)) {
codes.forEach(w3DCode -> {
int index = TransferUtil.findInDirectW3DCodes(w3DCodes, w3DCode);
if ( index < 0){
ret.add(w3DCode);
}
});
}else if(CodeTypeEnum.GROUP.equals(codeTypeEnum)){
codes.forEach(w3DCode -> {
int index = TransferUtil.findInGroupW3DCodes(w3DCodes, w3DCode);
if ( index < 0){
ret.add(w3DCode);
}
});
}
return ret;
}
public static List<W3DCode> union(List<W3DCode> w3DCodes, List<W3DCode> codes, CodeTypeEnum codeTypeEnum){
if(CollectionUtils.isEmpty(codes) || CollectionUtils.isEmpty(w3DCodes) || codeTypeEnum == null){
return w3DCodes;
}
List<W3DCode> ret = new ArrayList<>();
if(CodeTypeEnum.DIRECT.equals(codeTypeEnum)) {
codes.forEach(w3DCode -> {
int index = TransferUtil.findInDirectW3DCodes(w3DCodes, w3DCode);
if ( index >= 0){
ret.add(w3DCode);
}
});
}else if(CodeTypeEnum.GROUP.equals(codeTypeEnum)){
codes.forEach(w3DCode -> {
int index = TransferUtil.findInGroupW3DCodes(w3DCodes, w3DCode);
if ( index >= 0){
ret.add(w3DCode);
}
});
}
return ret;
}
public static<T> List<T> getSubList(List<T> wCodes, int pageSize, int startPosInPage){
if(CollectionUtils.isEmpty(wCodes)){
return Collections.emptyList();
}
List<T> ret = new ArrayList<>();
List<List<T>> codesArray = Lists.partition(wCodes, pageSize);
for(List<T> codes: codesArray){
if(CollectionUtils.isEmpty(codes)){
continue;
}
if(CollectionUtils.size(codes) < pageSize){
ret.addAll(codes.subList(codes.size()/2,codes.size()));
}else{
ret.addAll(codes.subList(startPosInPage, codes.size()));
}
}
return ret;
}
public static<T> List<T> getRandomList(List<T> wCodes, Integer count){
if(CollectionUtils.isEmpty(wCodes) || CollectionUtils.size(wCodes) < count){
return wCodes;
}
List<T> ret = new ArrayList<>();
Set<Integer> isSelected = new HashSet<>();
Integer size = wCodes.size();
for(int i=0; i<count && i<size; i++){
int index = new Random().nextInt(size);
if(isSelected.contains(i)){
continue;
}
ret.add(wCodes.get(index));
isSelected.add(i);
}
return ret;
}
public static<T> List<List<T>> getRandomLists(List<T> wCodes, int randomCount, int randomSize){
if(randomCount < 1){
return Collections.emptyList();
}
if(CollectionUtils.isEmpty(wCodes) || randomSize > wCodes.size()){
return Arrays.asList(wCodes);
}
List<List<T>> ret = new ArrayList<>();
for(int i=0; i< randomCount; i++){
List<T> randomList = getRandomList(wCodes, randomSize);
if(!CollectionUtils.isEmpty(randomList)){
ret.add(randomList);
}
}
return ret;
}
public static<T extends RandomKill> void markRandomDeletedByCount(List<T> wCodes, int randomCount){
int count = 0;
while(randomCount > 0 && CollectionUtils.size(wCodes) > count){
int randomSize = wCodes.size();
int index = new Random().nextInt(randomSize);
if(wCodes.get(index).isBeDeleted()){
count ++;
continue;
}
wCodes.get(index).setBeDeleted(true);
randomCount -= 1;
}
}
}
| true
|
d81ab6c25d77d31081913aa7ff35e8eb84ccfb30
|
Java
|
V1489Cygni/spec2fb
|
/src/ru/ifmo/optimization/instance/multimaskefsm/MultiMaskEfsmSkeleton.java
|
UTF-8
| 9,139
| 2.15625
| 2
|
[] |
no_license
|
package ru.ifmo.optimization.instance.multimaskefsm;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import ru.ifmo.optimization.instance.Constructable;
import ru.ifmo.optimization.instance.multimaskefsm.task.VarsActionsScenario;
import ru.ifmo.optimization.instance.mutation.InstanceMutation;
import ru.ifmo.util.Digest;
public class MultiMaskEfsmSkeleton implements Constructable<MultiMaskEfsmSkeleton>, Serializable {
public static int STATE_COUNT;
public static int PREDICATE_COUNT;
public static int INPUT_EVENT_COUNT;
public static int MEANINGFUL_PREDICATES_COUNT;
public static int TRANSITION_GROUPS_COUNT;
public static int MAX_OUTPUT_ACTION_COUNT;
public static Map<String, Integer> INPUT_EVENTS;
public static List<String> PREDICATE_NAMES;
private final List<VarsActionsScenario> counterExamples = new ArrayList<>();
private int initialState;
private State[] states;
private double fitness;
public MultiMaskEfsmSkeleton() {
states = new State[STATE_COUNT];
}
public int getNumberOfStates() {
return states.length;
}
public MultiMaskEfsmSkeleton(State[] states) {
this.states = states;
}
public MultiMaskEfsmSkeleton(MultiMaskEfsmSkeleton other) {
states = new State[other.states.length];
this.initialState = other.initialState;
counterExamples.addAll(other.counterExamples);
fitness = other.fitness;
for (int i = 0; i < states.length; i++) {
states[i] = new State(other.states[i]);
}
}
public static String tranIdToLabel(int tranId, List<Integer> meaningfulPredicates) {
String f = Integer.toBinaryString(tranId);
while (f.length() < meaningfulPredicates.size()) {
f = "0" + f;
}
StringBuilder formula = new StringBuilder();
for (int i = 0; i < f.length(); i++) {
if (f.charAt(i) == '0') {
formula.append("!");
}
formula.append(MultiMaskEfsmSkeleton.PREDICATE_NAMES.get(meaningfulPredicates.get(i)));
if (i < f.length() - 1) {
formula.append(" & ");
}
}
return formula.toString();
}
public void setFixedActionId(int state, int actionNumber, int actionId) {
states[state].setFixedActionId(actionNumber, actionId);
}
public int getFixedActionId(int state, int actionNumber) {
return states[state].getFixedActionId(actionNumber);
}
public double getFitness() {
return fitness;
}
public void setFitness(double fitness) {
this.fitness = fitness;
}
public List<VarsActionsScenario> getCounterExamples() {
return counterExamples;
}
public int getCounterExamplesLength() {
int result = 0;
for (VarsActionsScenario s : counterExamples) {
result += s.size();
}
return result;
}
public void clearCounterExamples() {
counterExamples.clear();
}
public void addCounterExample(VarsActionsScenario scenario) {
counterExamples.add(scenario);
}
public void markTransitionsUnused() {
for (int i = 0; i < states.length; i++) {
states[i].markTransitionsUnused();
}
}
public int getInitialState() {
return initialState;
}
public void setInitialState(int initialState) {
this.initialState = initialState;
}
public int getNewState(int state, String inputEvent, String variableValues) {
return states[state].getNewState(inputEvent, variableValues);
}
public TransitionGroup getNewStateTransitionGroup(int state, String inputEvent, String variableValues) {
return states[state].getNewStateTransitionGroup(inputEvent, variableValues);
}
public State getState(int state) {
return states[state];
}
public boolean hasTransitions(int state) {
return states[state].getUsedTransitionsCount() > 0;
}
public boolean stateUsedInTransitions(int state) {
if (states[state].getUsedTransitionsCount() > 0) {
return true;
}
for (int otherState = 0; otherState < MultiMaskEfsmSkeleton.STATE_COUNT; otherState++) {
if (otherState == state) {
continue;
}
for (int eventId = 0; eventId < MultiMaskEfsmSkeleton.INPUT_EVENT_COUNT; eventId++) {
for (int tgId = 0; tgId < MultiMaskEfsmSkeleton.TRANSITION_GROUPS_COUNT; tgId++) {
TransitionGroup tg = states[otherState].getTransitionGroup(eventId, tgId);
for (int tranId = 0; tranId < tg.getTransitionsCount(); tranId++) {
if (tg.isTransitionUsed(tranId) && tg.getNewState(tranId) == state) {
return true;
}
}
}
}
}
return false;
}
private String stringForHashing() {
StringBuilder sb = new StringBuilder();
for (State state : states) {
sb.append(state);
}
return sb.toString();
}
@Override
public Long computeStringHash() {
return Digest.RSHash(stringForHashing());
}
@Override
public void applyMutations(List<InstanceMutation<MultiMaskEfsmSkeleton>> mutations) {
for (InstanceMutation<MultiMaskEfsmSkeleton> m : mutations) {
m.apply(this);
}
}
@Override
public MultiMaskEfsmSkeleton copyInstance(MultiMaskEfsmSkeleton other) {
return new MultiMaskEfsmSkeleton(other);
}
@Override
public Object getFitnessDependentData() {
// TODO Auto-generated method stub
return null;
}
@Override
public void setFitnessDependentData(Object fitnessDependentData) {
// TODO Auto-generated method stub
}
@Override
public int getMaxNumberOfMutations() {
return Integer.MAX_VALUE;
}
public String toGraphvizString(Map<Integer, Integer> stateIdMap) {
StringBuilder sb = new StringBuilder();
for (int stateId = 0; stateId < states.length; stateId++) {
State state = states[stateId];
for (int eventId = 0; eventId < MultiMaskEfsmSkeleton.INPUT_EVENT_COUNT; eventId++) {
for (int tgId = 0; tgId < states[stateId].getTransitionGroupCount(eventId); tgId++) {
TransitionGroup tg = state.getTransitionGroup(eventId, tgId);
for (int tranId = 0; tranId < tg.getTransitionsCount(); tranId++) {
if (!tg.isTransitionDefined(tranId)) {
continue;
}
// if (!tg.isTransitionUsed(tranId)) {
// continue;
// }
if (stateIdMap.get(stateId) == null || stateIdMap.get(tg.getNewState(tranId)) == null) {
continue;
}
sb.append(stateIdMap.get(stateId) + " -> " + stateIdMap.get(tg.getNewState(tranId))
+ " [label = \"REQ [" + tranIdToLabel(tranId, tg.getMeaningfulPredicateIds()) + "] ()\"];\n");
}
}
}
}
return sb.toString();
}
public int getUsedTransitionsCount() {
int result = 0;
for (int i = 0; i < states.length; i++) {
result += states[i].getUsedTransitionsCount();
}
return result;
}
public int getDefinedTransitionsCount() {
int result = 0;
for (int i = 0; i < states.length; i++) {
result += states[i].getDefinedTransitionsCount();
}
return result;
}
public int getTransitionsCount() {
int result = 0;
for (int i = 0; i < states.length; i++) {
result += states[i].getTransitionsCount();
}
return result;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
Map<Integer, Integer> stateIdMap = new HashMap<Integer, Integer>();
int stateCounter = 0;
sb.append("digraph efsm{\n");
for (int state = 0; state < MultiMaskEfsmSkeleton.STATE_COUNT; state++) {
if (stateUsedInTransitions(state)) {
String label = "" + state;
sb.append(stateCounter + " [label=\"s_" + label + "\"];\n");
stateIdMap.put(state, stateCounter);
stateCounter++;
}
}
sb.append(toGraphvizString(stateIdMap));
sb.append("}");
return sb.toString();
}
public void clearUsedTransitions() {
for (State state : states) {
state.clearUsedTransitions();
}
}
public void removeNullTransitionGroups() {
for (State state : states) {
state.removeNullTransitionGroups();
}
}
}
| true
|
8c059caee11ae5f60e4eedff281f2903ca26f4e2
|
Java
|
nosebrain/simple-pipes
|
/src/main/java/de/nosebrain/pipes/filter/AuthorFilter.java
|
UTF-8
| 371
| 2.25
| 2
|
[] |
no_license
|
package de.nosebrain.pipes.filter;
import com.rometools.rome.feed.synd.SyndEntry;
public class AuthorFilter implements FeedEntryFilter {
private final String author;
public AuthorFilter(final String author) {
this.author = author;
}
@Override
public boolean filter(final SyndEntry entry) {
return entry.getAuthor().contains(this.author);
}
}
| true
|
52ebe578a7bdb485135851bd103ac07fbc4845db
|
Java
|
fchidzikwe/COP
|
/src/main/java/com/fortune/batch/Processor.java
|
UTF-8
| 999
| 2.421875
| 2
|
[] |
no_license
|
package com.fortune.batch;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.batch.item.ItemProcessor;
import com.fortune.model.User;
public class Processor implements ItemProcessor<User, User> {
private static final Logger log = LoggerFactory.getLogger(Processor.class);
@Override
public User process(User user) throws Exception {
final int active = user.getActive();
final int id = user.getId();
final String email = user.getEmail();
final String lastName = user.getLastName();
final String name = user.getName();
final String phoneNumber = user.getPhoneNumber();
final String password = user.getPassword();
final String role =user.getRoles();
final User fixedUser = new User(id,active , email,lastName, name,phoneNumber, password,role);
log.info("Converting (" + user + ") into (" + fixedUser + ")");
return fixedUser;
}
}
| true
|
21ecf9a52923847724d58f23c0fa78401939a891
|
Java
|
varunvenkitachalam/Therapist_Chat_Bot
|
/Java_Chat_App2/app/src/main/java/com/example/java_chat_app/MessageResponse.java
|
UTF-8
| 795
| 3.15625
| 3
|
[] |
no_license
|
package com.example.java_chat_app;
public class MessageResponse {
String messageText;
Boolean checkMe;
// constructor for our message holding the text
public MessageResponse(String messageText, Boolean checkMe) {
this.messageText = messageText;
this.checkMe = checkMe;
}
// retrieve message text
public String getMessageText() {
return messageText;
}
// set message text
public void setMessageText(String messageText) {
this.messageText = messageText;
}
// check whether it is a user message or a bot message
public Boolean getCheckMe() {
return checkMe;
}
// set message as user message or bot message
public void setCheckMe(Boolean checkMe) {
this.checkMe = checkMe;
}
}
| true
|
818f487dd7e87f7dc0b89d714d00d47518c337a4
|
Java
|
P-ss-R-ss-PLay-ss-D-ss/java1
|
/java1/Chuong9/Bai3/MyThread2.java
|
UTF-8
| 1,267
| 3.140625
| 3
|
[] |
no_license
|
package Chuong9.Bai3;
import java.util.logging.Level;
import java.util.logging.Logger;
public class MyThread2 {
public static void main(String args[]) throws InterruptedException {
int n = 5;
Thread thread = new Thread() {
@Override
public void run() {
for (int i = 1; i <= n; i++) {
System.out.printf("[%d]", i);
try {
Thread.sleep(490);
} catch (InterruptedException ex) {
}
}
}
};
Thread threadTwo = new Thread() {
@Override
public void run() {
for (int i = 1; i <= n; i++) {
System.out.printf("->(%d)", i * i);
System.out.println("");
try {
thread.join(500);
} catch (InterruptedException ex) {
Logger.getLogger(MyThread2.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
};
thread.setPriority(10);
threadTwo.setPriority(1);
thread.start();
threadTwo.start();
}
}
| true
|
ec1035111e04b91cb89d84ef2a4efa87d755dbad
|
Java
|
greenday12138/myQQ
|
/src/com/vince/view/chatFrame/ChatFrame.java
|
UTF-8
| 20,225
| 1.835938
| 2
|
[] |
no_license
|
/**
* @author 流浪大法师
* @time 2016-4-22 上午10:08:18
* @email liuliangsir@gmail.com
* @descript
* @warning 注意将字符集设置成UTF-8
*/
package com.vince.view.chatFrame;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Container;
import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.Image;
import java.awt.Rectangle;
import java.awt.Toolkit;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Iterator;
import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JRootPane;
import javax.swing.JScrollBar;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.JTextPane;
import javax.swing.JTree;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.text.SimpleAttributeSet;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyledDocument;
import org.apache.commons.lang3.StringUtils;
import com.vince.controller.listener.ChatFrameListener;
import com.vince.controller.util.GBC;
import com.vince.controller.util.Util;
import com.vince.view.config.MyChatFrameScrollBarUI;
import com.vince.view.config.MyScrollBarUI;
import com.vince.view.relationerdetail.RelationerDetail;
import com.vince.view.util.JSplitPaneWithZeroSizeDivider;
import com.vince.view.util.MenuButtonsComponent;
import com.vince.view.util.MyBasicSplitPaneUI;
import com.vince.view.util.ScrollPaneWatermark;
public class ChatFrame {
private JFrame jframe = null;
private Container container = null;//获取内容窗格
private JPanel content = null;
private JPanel topPanel = null;
private JPanel topLeftPanel = null;
private JPanel leftPanel = null;
private JPanel rightPanel = null;
private JPanel chatRecordPanel = null;
private JPanel chatOperatePanel = null;
private JPanel buttonPanel = null;
private JTextPane textPane = null;
private final static int CHAT_FRAME_WIDTH = 585;
private final static int CHAT_FRAME_HEIGHT = 509;
private final static int TOP_PANEL_MIN_HEIGHT = 84;
private final static int TOP_PANEL_MIN_WIDTH = CHAT_FRAME_WIDTH;
private final static int LEFT_PANEL_MIN_WIDTH = 434;
private final static int TOP_LEFT_PANEL_MIN_WIDTH = 321;
private final static int MENU_BUTTONS_COMPONENT_MIN_WIDTH_PADDING = 1;
private final static int MENU_BUTTONS_COMPONENT_MIN_HEIGHT_PADDING = 0;
private final static int LEFT_PANEL_MIN_HEIGHT = CHAT_FRAME_HEIGHT - TOP_PANEL_MIN_HEIGHT;
private final static int RIGHT_PANEL_MIN_WIDTH = CHAT_FRAME_WIDTH - LEFT_PANEL_MIN_WIDTH;
private final static int RIGHT_PANEL_MIN_HEIGHT = LEFT_PANEL_MIN_HEIGHT;
private final static int LEFT_TOP_PANEL_MIN_HEIGHT = 56;
private final static String QQ_SHOW_DEFAULT_PATH = "src\\images\\default_qq_show.png";
private ChatFrameListener chatFrameListener = null;
private MenuButtonsComponent menuButtonsComponent = null;
private JSplitPaneWithZeroSizeDivider splitPane = null;
private JScrollPane top = null;
private JScrollPane bottom = null;
private JScrollPane textPaneScrollPane = null;
private RelationerDetail relationerDetail = null;
private ImageIcon avatarFile = null;
private String nowNameContent = null;
private String dynamicMessageContent = null;
private String account = null;
private String ownerAccount = null;
private int dynamicMessageContentType = -1;
private int onlineType = -1;
private ArrayList<JButton> buttonList = null;
private ArrayList<String[]> buttonPathList = null;
private ArrayList<JButton> bottomButtonList = null;
private ArrayList<String[]> bottomButtonPathList = null;
private JButton closeButton = null;
private JButton submitButton = null;
private JButton caretButton = null;
private StyledDocument styledDocument = null;
private SimpleAttributeSet attributeSet = null;
private String avatarPath = null;
private boolean isDisposed = false;
public ChatFrame(String ownerAccount,String account,String avatarPath,ImageIcon avatarFile,String nowNameContent,String dynamicMessageContent,int dynamicMessageContentType,int onlineType){
this.ownerAccount = ownerAccount;
this.account = account;
this.avatarPath = avatarPath;
this.avatarFile = avatarFile;
this.nowNameContent = nowNameContent;
this.dynamicMessageContent = dynamicMessageContent;
this.dynamicMessageContentType = dynamicMessageContentType;
this.onlineType = onlineType;
init();
}
public void init(){
initData();
initView();
}
private void initView(){
content.setOpaque(false);
content.setLayout(new GridBagLayout());
jframe.setContentPane(content);
try {
jframe.setIconImage(Toolkit.getDefaultToolkit().createImage(new URL(avatarPath)).getScaledInstance(16, 16, Image.SCALE_SMOOTH));
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
container = jframe.getContentPane();
/*顶部布局*/
menuButtonsComponent = new MenuButtonsComponent(true,true,true,true);
menuButtonsComponent.setChatFrame(this);
/*topLeftPanel布局详情*/
topLeftPanel.add(relationerDetail);
initButtonListPosition(topLeftPanel,buttonPathList,relationerDetail,buttonList,4,3,false,0);
topPanel.add(topLeftPanel, new GBC(0,0,4,1).setFill(GBC.BOTH).setWeight(4.0, 1.0));
topPanel.add(menuButtonsComponent, new GBC(4,0,1,1).setFill(GBC.BOTH).setWeight(1.0, 1.0).setIpad(MENU_BUTTONS_COMPONENT_MIN_WIDTH_PADDING,MENU_BUTTONS_COMPONENT_MIN_HEIGHT_PADDING));
topPanel.setBorder(BorderFactory.createMatteBorder(0, 0, 1, 0, new Color(219,217,210)));
container.add(topPanel, new GBC(0,0,4,1).setFill(GBC.BOTH).setIpad(TOP_PANEL_MIN_WIDTH, TOP_PANEL_MIN_HEIGHT));
leftPanel.setLayout(new BorderLayout());
chatRecordPanel.setPreferredSize(new Dimension(LEFT_PANEL_MIN_WIDTH,300));
top = new JScrollPane(chatRecordPanel,JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER){
private static final long serialVersionUID = -1618957743603910647L;
@Override
public JScrollBar createVerticalScrollBar() {
// TODO Auto-generated method stub
final ScrollBar scrollBar = new ScrollBar(JScrollBar.VERTICAL);
SwingUtilities.invokeLater(new Runnable() {
public void run() {
scrollBar.setUI(new MyChatFrameScrollBarUI());
scrollBar.validate();
}
});
return scrollBar;
}
};top.setBorder(BorderFactory.createEmptyBorder());top.setOpaque(false);top.getViewport().setOpaque(false);top.setMinimumSize(new Dimension(LEFT_PANEL_MIN_WIDTH,56));
/*top滚动窗格的scrollbar绑定事件*/
top.getVerticalScrollBar().addMouseListener(chatFrameListener);
int maxHeight = initButtonListPosition(chatOperatePanel,bottomButtonPathList,null,bottomButtonList,6,3,true,90) + 7;
setPlainStyle("微软雅黑", 20, true, false, null, true,false,false,null,0,0,0,0);
textPane.setOpaque(false);textPane.setPreferredSize(new Dimension(CHAT_FRAME_WIDTH, 60));
textPaneScrollPane = new JScrollPane(textPane,JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER){
@Override
public JScrollBar createVerticalScrollBar() {
// TODO Auto-generated method stub
final ScrollBar scrollBar = new ScrollBar(JScrollBar.VERTICAL);
SwingUtilities.invokeLater(new Runnable() {
public void run() {
scrollBar.setUI(new MyChatFrameScrollBarUI());
scrollBar.validate();
}
});
return scrollBar;
}
};textPaneScrollPane.setBorder(null);textPaneScrollPane.setOpaque(false);textPaneScrollPane.getViewport().setOpaque(false);textPaneScrollPane.setSize(CHAT_FRAME_WIDTH, 65);textPaneScrollPane.setLocation(0, maxHeight);
textPaneScrollPane.getVerticalScrollBar().setPreferredSize(new Dimension(0,0));textPaneScrollPane.setWheelScrollingEnabled(true);
chatOperatePanel.add(textPaneScrollPane);
chatOperatePanel.setPreferredSize(new Dimension(LEFT_PANEL_MIN_WIDTH,100));
bottom = new JScrollPane(chatOperatePanel,JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER){
private static final long serialVersionUID = -1618957743603910647L;
@Override
public JScrollBar createVerticalScrollBar() {
// TODO Auto-generated method stub
final ScrollBar scrollBar = new ScrollBar(JScrollBar.VERTICAL);
SwingUtilities.invokeLater(new Runnable() {
public void run() {
scrollBar.setUI(new MyChatFrameScrollBarUI());
scrollBar.validate();
}
});
return scrollBar;
}
};bottom.setBorder(null);bottom.setMinimumSize(new Dimension(LEFT_PANEL_MIN_WIDTH,72));bottom.setWheelScrollingEnabled(false);
splitPane.setBorder(null);splitPane.setDividerLocation(200);
splitPane.setTopComponent(top);splitPane.setBottomComponent(bottom);
leftPanel.add(splitPane,BorderLayout.CENTER);
buttonPanel.add(caretButton);
buttonPanel.add(submitButton);
buttonPanel.add(closeButton);
buttonPanel.setPreferredSize(new Dimension(CHAT_FRAME_WIDTH,36));
leftPanel.add(buttonPanel,BorderLayout.SOUTH);
container.add(leftPanel, new GBC(0,1,2,3).setFill(GBC.BOTH).setWeight(2.0, 1.0));
rightPanel.setToolTipText("QQ秀商城");
rightPanel.setCursor(new Cursor(Cursor.HAND_CURSOR));
container.add(rightPanel, new GBC(2,1,1,3).setFill(GBC.BOTH).setIpad(120, 0).setWeight(1.0, 1.0));
jframe.getRootPane().setWindowDecorationStyle(JRootPane.NONE);
jframe.setUndecorated(true);
JFrame.setDefaultLookAndFeelDecorated(false);
jframe.setVisible(true);
jframe.setResizable(true);
jframe.setSize(CHAT_FRAME_WIDTH,CHAT_FRAME_HEIGHT);
Util.setHorizontalAndVerticalAlignCenter(jframe, Util.getScreenSize().width, Util.getScreenSize().height, CHAT_FRAME_WIDTH, CHAT_FRAME_HEIGHT);
chatFrameListener = new ChatFrameListener(this);
menuButtonsComponent.setChatFrameListener(chatFrameListener);
jframe.addMouseListener(chatFrameListener);
//jframe.setIconImage(avatarFile.getImage());
textPane.getDocument().addDocumentListener(chatFrameListener);
submitButton.addMouseListener(chatFrameListener);
closeButton.addMouseListener(chatFrameListener);
jframe.addMouseMotionListener(chatFrameListener);
}
private void initData(){
jframe = new JFrame();
content = new JPanel();
topPanel = new JPanel(new GridBagLayout());
leftPanel = new JPanel();
topLeftPanel = new JPanel(null);
rightPanel = new JPanel(){
@Override
public void paintComponent(Graphics g) {
// TODO Auto-generated method stub
super.paintComponent(g);
g.setColor(new Color(210,207,203));
g.drawRect(0, 0, RIGHT_PANEL_MIN_WIDTH, RIGHT_PANEL_MIN_HEIGHT);
g.fillRect(0, 0, RIGHT_PANEL_MIN_WIDTH, RIGHT_PANEL_MIN_HEIGHT);
g.drawImage(Toolkit.getDefaultToolkit().getImage(QQ_SHOW_DEFAULT_PATH),0,0,this);
}
};
chatRecordPanel = new JPanel(null);
chatOperatePanel = new JPanel(null);
splitPane = new JSplitPaneWithZeroSizeDivider(JSplitPane.VERTICAL_SPLIT);
buttonPanel = new JPanel(null);
textPane = new JTextPane();
styledDocument = textPane.getStyledDocument();
relationerDetail = new RelationerDetail(null,avatarFile, null, nowNameContent, dynamicMessageContent, account, dynamicMessageContentType, onlineType , false, false, false,false);
buttonPathList = initButtonPathList();
buttonList = new ArrayList<JButton>();
bottomButtonPathList = initBottomButtonPathList();
bottomButtonList = new ArrayList<JButton>();
ImageIcon iconRollover = new ImageIcon("src\\images\\close.png");ImageIcon iconDefault = new ImageIcon("src\\images\\close_no_border.png");ImageIcon iconPressed = new ImageIcon("src\\images\\close.png");
int width = iconRollover.getIconWidth(),height = iconRollover.getIconHeight(),x = 282,y = 4;
closeButton = Util.setButtonThreeStatus(iconRollover, iconDefault, iconPressed, null, null, width, height);closeButton.setBounds(x, y, width, height);
iconRollover = new ImageIcon("src\\images\\send.png");iconDefault = new ImageIcon("src\\images\\send_no_border.png");iconPressed = new ImageIcon("src\\images\\send.png");
x = x + width + 6;width = iconRollover.getIconWidth();height = iconRollover.getIconHeight();
submitButton = Util.setButtonThreeStatus(iconRollover, iconDefault, iconPressed, "按Enter键发送信息,按Ctrl + Enter键换行", null, width, height);submitButton.setBounds(x,y,width,height);
iconRollover = new ImageIcon("src\\images\\caret.png");iconDefault = new ImageIcon("src\\images\\caret_no_border.png");iconPressed = new ImageIcon("src\\images\\caret.png");
x = x + width - 1;width = iconRollover.getIconWidth();height = iconRollover.getIconHeight();
caretButton = Util.setButtonThreeStatus(iconRollover, iconDefault, iconPressed, null, null, width, height);caretButton.setBounds(x,y,width,height);
}
public void setPlainStyle(String fontFamily,int size,boolean isBold,boolean isItalic,Color fontColor,boolean isUnderLine,boolean hasBackground,boolean hasIcon,String imagePath,int x,int y,int width,int height){
attributeSet = new SimpleAttributeSet();
if(hasIcon){
StyleConstants.setIcon(attributeSet, new ImageIcon(Util.resizePNG(imagePath, x, y, width, height, false)));
}else{
StyleConstants.setBold(attributeSet, isBold);
StyleConstants.setFontFamily(attributeSet, fontFamily);
if(fontColor != null) StyleConstants.setForeground(attributeSet, fontColor);
StyleConstants.setFontSize(attributeSet, size);
StyleConstants.setUnderline(attributeSet, isUnderLine);
StyleConstants.setBidiLevel(attributeSet, 10);
if(hasBackground){
StyleConstants.setBackground(attributeSet, Color.WHITE);
}
}
}
private int initButtonListPosition(JPanel topLeftPanel,ArrayList<String[]> myButtonPathList,JComponent sibling,ArrayList<JButton> myButtonList,int x,int offset,boolean isSetLastItem,int otherOffset){
Iterator<String[]> iterator = myButtonPathList.iterator();
JButton button = null;
String[] strArray = null,arr = myButtonPathList.get(myButtonPathList.size()-1);
ImageIcon imageIcon = null;
Rectangle rect = sibling == null ? new Rectangle(0, 0) : sibling.getBounds();
int y = rect.y+rect.height,width = 0,height = 0,maxHeight = -10000;
while(iterator.hasNext()){
strArray = iterator.next();
imageIcon = new ImageIcon(strArray[1]);
width = imageIcon.getIconWidth();
height = imageIcon.getIconHeight();
button = Util.setButtonThreeStatus(imageIcon, new ImageIcon(strArray[0]), imageIcon, strArray[3], null, width, height);
if(strArray[3].equals(arr[3]) && isSetLastItem){
x = x + otherOffset - offset;
}
button.setBounds(x, y, width, height);
if(y+height > maxHeight) maxHeight = y + height;
x = x + width + offset;
topLeftPanel.add(button);
myButtonList.add(button);
}
return maxHeight;
}
private ArrayList<String[]> initButtonPathList(){
ArrayList<String[]> pathList = new ArrayList<String[]>();
pathList.add(new String[]{"src\\images\\record.png","src\\images\\record_border.png","src\\images\\record_border.png","发起语音通话"});
pathList.add(new String[]{"src\\images\\video.png","src\\images\\video_border.png","src\\images\\video_border.png","发起视频通话"});
pathList.add(new String[]{"src\\images\\chart.png","src\\images\\chart_border.png","src\\images\\chart_border.png","远程演示"});
pathList.add(new String[]{"src\\images\\file.png","src\\images\\file_border.png","src\\images\\file_border.png","传送文件"});
pathList.add(new String[]{"src\\images\\computer.png","src\\images\\computer_border.png","src\\images\\computer_border.png","远程桌面"});
pathList.add(new String[]{"src\\images\\message.png","src\\images\\message_border.png","src\\images\\message_border.png","创建讨论组"});
pathList.add(new String[]{"src\\images\\application.png","src\\images\\application_border.png","src\\images\\application_border.png","应用"});
return pathList;
}
private ArrayList<String[]> initBottomButtonPathList(){
ArrayList<String[]> pathList = new ArrayList<String[]>();
pathList.add(new String[]{"src\\images\\font_no_border.png","src\\images\\font.png","src\\images\\font.png","字体选择工具栏"});
pathList.add(new String[]{"src\\images\\face_no_border.png","src\\images\\face.png","src\\images\\face.png","选择表情"});
pathList.add(new String[]{"src\\images\\magic_no_border.png","src\\images\\magic.png","src\\images\\magic.png","VIP魔法表情/超级表情/涂鸦表情/宠物炫"});
pathList.add(new String[]{"src\\images\\shock_no_border.png","src\\images\\shock.png","src\\images\\shock.png","向好友发送窗口震动"});
pathList.add(new String[]{"src\\images\\voiceMessage_no_border.png","src\\images\\voiceMessage.png","src\\images\\voiceMessage.png","语音消息"});
pathList.add(new String[]{"src\\images\\multi-input_no_border.png","src\\images\\multi-input.png","src\\images\\multi-input.png","多功能辅助输入"});
pathList.add(new String[]{"src\\images\\picture_no_border.png","src\\images\\picture.png","src\\images\\picture.png","发送图片"});
pathList.add(new String[]{"src\\images\\music_no_border.png","src\\images\\music.png","src\\images\\music.png","点歌"});
pathList.add(new String[]{"src\\images\\knife_no_border.png","src\\images\\knife.png","src\\images\\knife.png","屏幕截图 CTRL + ALT + A"});
pathList.add(new String[]{"src\\images\\history_no_border.png","src\\images\\history.png","src\\images\\history.png","显示消息记录"});
return pathList;
}
/**
* @return the jframe
*/
public JFrame getJframe() {
return jframe;
}
/**
* @param jframe the jframe to set
*/
public void setJframe(JFrame jframe) {
this.jframe = jframe;
}
/**
* @return the top
*/
public JScrollPane getTop() {
return top;
}
/**
* @param top the top to set
*/
public void setTop(JScrollPane top) {
this.top = top;
}
/**
* @return the textPane
*/
public JTextPane getTextPane() {
return textPane;
}
/**
* @param textPane the textPane to set
*/
public void setTextPane(JTextPane textPane) {
this.textPane = textPane;
}
/**
* @return the ownerAccount
*/
public String getOwnerAccount() {
return ownerAccount;
}
/**
* @param ownerAccount the ownerAccount to set
*/
public void setOwnerAccount(String ownerAccount) {
this.ownerAccount = ownerAccount;
}
/**
* @return the attributeSet
*/
public SimpleAttributeSet getAttributeSet() {
return attributeSet;
}
/**
* @return the account
*/
public String getAccount() {
return account;
}
/**
* @param account the account to set
*/
public void setAccount(String account) {
this.account = account;
}
/**
* @param attributeSet the attributeSet to set
*/
public void setAttributeSet(SimpleAttributeSet attributeSet) {
this.attributeSet = attributeSet;
}
/**
* @return the submitButton
*/
public JButton getSubmitButton() {
return submitButton;
}
/**
* @param submitButton the submitButton to set
*/
public void setSubmitButton(JButton submitButton) {
this.submitButton = submitButton;
}
/**
* @return the closeButton
*/
public JButton getCloseButton() {
return closeButton;
}
/**
* @param closeButton the closeButton to set
*/
public void setCloseButton(JButton closeButton) {
this.closeButton = closeButton;
}
/**
* @return the chatRecordPanel
*/
public JPanel getChatRecordPanel() {
return chatRecordPanel;
}
/**
* @param chatRecordPanel the chatRecordPanel to set
*/
public void setChatRecordPanel(JPanel chatRecordPanel) {
this.chatRecordPanel = chatRecordPanel;
}
/**
* @return the isDisposed
*/
public boolean isDisposed() {
return isDisposed;
}
/**
* @param isDisposed the isDisposed to set
*/
public void setDisposed(boolean isDisposed) {
this.isDisposed = isDisposed;
}
}
| true
|
63ee43fd0e6932476685164a044e9823b8178471
|
Java
|
xiaohui249/flysky
|
/flysky-kafka/src/test/java/com/sean/flysky/kafka/TransProducer.java
|
UTF-8
| 5,166
| 2.625
| 3
|
[] |
no_license
|
package com.sean.flysky.kafka;
import com.alibaba.fastjson.JSON;
import org.apache.kafka.clients.producer.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.Future;
/**
* Kafka生产者程序示例
*
* @author xiaoh
* @create 2018-06-19 17:16
**/
public class TransProducer {
private final static Logger logger = LoggerFactory.getLogger(TransProducer.class);
private final static String PRODUCER_CONFIG_FILE = "producer.properties";
public static void main(String[] args) throws Exception {
Properties props = new Properties();
try {
props.load(TransProducer.class.getClassLoader().getResourceAsStream(PRODUCER_CONFIG_FILE));
} catch (IOException e) {
logger.error("Failed to load the config file of kafka producer!");
}
String topic = props.getProperty("topic", "");
if(topic.trim().length() == 0) {
logger.error("Please set topic!");
System.exit(0);
}
// alwaysProduce(props, topic);
// notAlwaysProduce(props, topic);
produceFromFile(props, topic, "E:\\tranInfo.txt");
}
/**
* 定量生产数据,以便性能测试
* @param props
* @param topic
*/
public static void notAlwaysProduce(Properties props, String topic) {
Producer<String, String> producer = new KafkaProducer<>(props);
long s = System.currentTimeMillis();
int x = 0, y = 1000000;
for(int i=x; i<y; i++) {
final String value = ItmTranDeltFactory.createJson().toJSONString();
Future<RecordMetadata> future = producer.send(new ProducerRecord<>(topic, value), new Callback() {
@Override
public void onCompletion(RecordMetadata metadata, Exception exception) {
if(null != exception) {
exception.printStackTrace();
} else {
logger.info(value + ", offset: " + metadata.offset());
}
}
});
// RecordMetadata metadata = future.get(); // 同步生产
// logger.info("log" + i + ", offset: " + metadata.offset());
}
logger.info("produce {} messages, cost {}ms", y-x, System.currentTimeMillis() - s);
producer.close();
}
/**
* 持续一直生产数据
* @param props
* @param topic
*/
public static void alwaysProduce(Properties props, String topic) {
Producer<String, String> producer = new KafkaProducer<>(props);
int i = 1;
while(true) {
final String value = ItmTranDeltFactory.createJson().toJSONString();
producer.send(new ProducerRecord<>(topic, value), new Callback() {
@Override
public void onCompletion(RecordMetadata metadata, Exception exception) {
if(null != exception) {
exception.printStackTrace();
} else {
logger.info(value + ", offset: " + metadata.offset());
}
}
});
i++;
try {
Thread.sleep(1);
} catch (Exception e) {
e.printStackTrace();
}
}
}
public static void produceFromFile(Properties props, String topic, String file) {
Producer<String, Map> producer = new KafkaProducer<>(props);
try(BufferedReader reader = new BufferedReader(new FileReader((file)), 5*1024*1024)) {
String content;
long s = System.currentTimeMillis();
int count = 0;
while((content = reader.readLine()) != null) {
count++;
Map<String, String> value = JSON.parseObject(content, Map.class);
producer.send(new ProducerRecord<>(topic, value), new Callback() {
@Override
public void onCompletion(RecordMetadata metadata, Exception exception) {
if(null != exception) {
exception.printStackTrace();
} else {
logger.info("offset: " + metadata.offset());
}
}
});
// Future<RecordMetadata> future = producer.send(new ProducerRecord<>(topic, value));
// RecordMetadata metadata = future.get(); // 同步生产
// logger.info("log" + count + ", offset: " + metadata.offset());
}
producer.close();
System.out.println("buffer reader size: " + count + ", cost: " + (System.currentTimeMillis() - s));
} catch (Exception e) {
logger.error("读取文件信息发送至kafka失败!", e);
}
}
}
| true
|
07aba8d860a0c41b4a17c1568d76fe7fe608b6c5
|
Java
|
iDC-NEU/PowerLog_ae
|
/src/java/socialite/dist/worker/WorkerNode.java
|
UTF-8
| 7,214
| 2.140625
| 2
|
[
"Apache-2.0"
] |
permissive
|
package socialite.dist.worker;
import java.net.*;
import java.util.*;
import java.io.*;
import java.nio.channels.*;
import java.util.concurrent.atomic.AtomicBoolean;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.ipc.RPC;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.apache.hadoop.net.NetUtils;
import socialite.dist.PortMap;
import socialite.dist.master.WorkerRequest;
import socialite.eval.Manager;
import socialite.resource.SRuntime;
import socialite.resource.SRuntimeWorker;
import socialite.util.ByteBufferPool;
import socialite.util.FastQueue;
import socialite.util.UnresolvedSocketAddr;
import socialite.yarn.ClusterConf;
public class WorkerNode extends Thread {
public static final Log L = LogFactory.getLog(WorkerNode.class);
private AtomicBoolean isReady = new AtomicBoolean(false);
private WorkerConnPool connPool;
private CmdListener cmdListener;
private WorkerRequest request;
private Manager manager;
private FastQueue<RecvTask> recvQ;
public WorkerNode() {
//super("WorkerNode Thread");
connPool = new WorkerConnPool();
}
public void serve() {
initManagerAndWorkers();
initCmdListener();
initNetworkResources();
initRecvThread();
startListen();
register();
// try {
// join();
// } catch (InterruptedException e) {
// L.info("Terminating WorkerNode:" + e);
// }
}
void initNetworkResources() {
ByteBufferPool.get();
}
void initCmdListener() {
cmdListener = new CmdListener(this);
cmdListener.start();
}
public void initManagerAndWorkers() {
manager = Manager.create();
}
void initRecvThread() {
recvQ = Receiver.recvq();
int recvNum = (ClusterConf.get().getNumWorkerThreads() + 1) / 2;
if (recvNum < 4) recvNum = 4;
if (recvNum > 64) recvNum = 64;
Thread[] recvThreads = new Thread[recvNum];
for (int i = 0; i < recvThreads.length; i++) {
Receiver recv = new Receiver(recvQ, connPool, manager, cmdListener);
recvThreads[i] = new Thread(recv, "Receiver #" + i);
recvThreads[i].start();
}
}
public boolean isReady() {
return isReady.get();
}
public FastQueue recvQ() {
return recvQ;
}
void startListen() {
start();
}
public WorkerConnPool getConnPool() {
return connPool;
}
public void run() {
try {
while (true) {
Set<SelectionKey> selectedKeys = connPool.select(5);
Iterator<SelectionKey> iter = selectedKeys.iterator();
while (iter.hasNext()) {
SelectionKey key = iter.next();
iter.remove();
if (!key.isValid()) {
L.warn("Invalid key:" + key);
continue;
}
if (key.isAcceptable()) {
connPool.acceptConn(key);
} else if (key.isReadable()) {
SocketChannel selectedChannel = (SocketChannel) (key.channel());
InetAddress nodeAddr = (selectedChannel.socket()).getInetAddress();
connPool.cancelKey(selectedChannel);
try {
selectedChannel.configureBlocking(true);
} catch (IOException e) {
L.error("Error while configure blocking:" + e);
L.fatal(ExceptionUtils.getStackTrace(e));
continue;
}
RecvTask recv = new RecvTask(nodeAddr, selectedChannel);
recvQ.add(recv);
} else {
L.error("Unexpected key operation(!acceptable, !readable):" + key);
}
} // while selectedKeys
connPool.registerCanceledConn();
}
} catch (Exception e) {
L.fatal("Error while select() operation:" + e);
L.fatal(ExceptionUtils.getStackTrace(e));
} finally {
L.info("WorkerNode terminating");
}
}
void register() {
isReady.set(true);
Configuration hConf = new Configuration();
String masterAddr = PortMap.worker().masterAddr();
int reqPort = PortMap.worker().getPort("workerReq");
InetSocketAddress addr = new InetSocketAddress(masterAddr, reqPort);
try {
request = RPC.waitForProxy(WorkerRequest.class,
WorkerRequest.versionID,
addr, hConf);
} catch (IOException e) {
L.fatal("Cannot connect to master:" + e);
L.fatal(ExceptionUtils.getStackTrace(e));
}
String host = NetUtils.getHostname().split("/")[1];
int cmdPort = PortMap.worker().getPort("workerCmd");
int dataPort = PortMap.worker().getPort("data");
System.out.println(host);
request.register(host, cmdPort, dataPort);
}
public void reportError(int ruleid, Throwable t) {
L.warn("Worker node error:" + ExceptionUtils.getStackTrace(t));
SRuntime runtime = SRuntimeWorker.getInst();
if (runtime == null) {
L.error("reportError(): Worker runtime is null.");
return;
}
String msg = "";
if (t != null) msg += t.getClass().getSimpleName() + " ";
if (t != null && t.getMessage() != null) msg = t.getMessage();
IntWritable workerid = new IntWritable(runtime.getWorkerAddrMap().myIndex());
request.handleError(workerid, new IntWritable(ruleid), new Text(msg));
}
public void reportIdle(int epochId, int ts) {
SRuntime runtime = SRuntimeWorker.getInst();
int id = runtime.getWorkerAddrMap().myIndex();
request.reportIdle(new IntWritable(epochId), new IntWritable(id), new IntWritable(ts));
}
public boolean connect(String[] workerAddrs) {
UnresolvedSocketAddr[] addrs = new UnresolvedSocketAddr[workerAddrs.length];
for (int i = 0; i < workerAddrs.length; i++) {
String host = workerAddrs[i].split(":")[0];
int port = Integer.parseInt(workerAddrs[i].split(":")[1]);
addrs[i] = new UnresolvedSocketAddr(host, port);
}
connPool.connect(addrs);
return true;
}
static WorkerNode theWorkerNode;
public static WorkerNode getInst() {
return theWorkerNode;
}
public static void startWorkerNode() {
theWorkerNode = new WorkerNode();
try {
theWorkerNode.serve();
} catch (Exception e) {
L.error("Exception while runining worker node:" + ExceptionUtils.getStackTrace(e));
}
}
public static void main(String[] args) {
startWorkerNode();
}
}
| true
|
5d7adf133ad965f02d93d11d73b7c157f16e72d8
|
Java
|
NishantSambyal/UGSHDD
|
/app/src/main/java/technician/inteq/com/ugshdd/util/UGSApplication.java
|
UTF-8
| 1,040
| 2.09375
| 2
|
[] |
no_license
|
package technician.inteq.com.ugshdd.util;
import android.app.Application;
import android.database.sqlite.SQLiteDatabase;
import technician.inteq.com.ugshdd.Database.DatabaseHelper;
/**
* Created by Nishant Sambyal on 12-Jul-17.
*/
public class UGSApplication extends Application {
public static String outletID;
public static String accountNumber;
public static String street;
public static String building;
public static String unit_country;
public static String stall_no;
public static String food_type;
public static String outlet_reference;
private static SQLiteDatabase db;
public static SQLiteDatabase getDb() {
return db;
}
public static void setDb(SQLiteDatabase db) {
UGSApplication.db = db;
}
@Override
public void onCreate() {
super.onCreate();
setDb(new DatabaseHelper(getApplicationContext(), null).getWritableDatabase());
}
@Override
public void onTerminate() {
super.onTerminate();
db.close();
}
}
| true
|
384e826620ea52013cd4fab9a70ae1244b1ec169
|
Java
|
anaghagaikar123/bms
|
/src/main/java/com/bms/service/MultiplexServiceImpl.java
|
UTF-8
| 1,529
| 2.21875
| 2
|
[] |
no_license
|
package com.bms.service;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.bms.controller.MultiplexController;
import com.bms.database.MovieDAO;
import com.bms.database.MultiplexDAO;
import com.bms.dto.MultiplexDTO;
import com.bms.module.Movie;
import com.bms.module.Multiplex;
@Service
@Transactional
public class MultiplexServiceImpl implements MultiplexService {
@Autowired
private MultiplexDAO multiplexDAO;
@Autowired
MovieDAO movieDAO;
private static Logger logger = LoggerFactory.getLogger(MultiplexServiceImpl.class);
@Override
public List<MultiplexDTO> searchMultiplex(Long mid) {
List<MultiplexDTO> dtos = new ArrayList<MultiplexDTO>();
Movie movie = movieDAO.findOne(mid);
if(movie != null)
{
Set<Multiplex> multiplexes = movie.getMultiplex();
if(!multiplexes.isEmpty())
{
multiplexes.forEach(m->{
MultiplexDTO dto = new MultiplexDTO();
dto.setName((Optional.ofNullable(m.getName())).orElse(""));
dto.setId((Optional.ofNullable(m.getId())).orElse(null));
dtos.add(dto);
});
return dtos;
}
}
//List<Multiplex> multiplexes = multiplexDAO.searchMultiplex(mid);
return null;
}
}
| true
|
05eb328d327169eacfb37f9c94cc403127b48b72
|
Java
|
vpeurala/islands
|
/test/JavaClass.java
|
UTF-8
| 468
| 2.84375
| 3
|
[] |
no_license
|
package test;
public class JavaClass extends Super implements Comparable<JavaClass> {
private long a = 5;
public int compareTo(JavaClass o) {
return Math.min(hashCode(), o.hashCode());
}
public Inner foo() {
Inner i = new Inner();
System.out.println(i.bar());
return i;
}
@Override
void foobar() {
}
class Inner {
public String bar() {
return "hello";
}
}
}
abstract class Super {
abstract void foobar();
}
| true
|
80bf2160a922d1a455d3f5cc9aacab12b430371c
|
Java
|
schwips/VisEditor
|
/Editor/src/com/kotcrab/vis/editor/Icons.java
|
UTF-8
| 2,070
| 1.867188
| 2
|
[
"Apache-2.0"
] |
permissive
|
/*
* Copyright 2014-2015 See AUTHORS file.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.kotcrab.vis.editor;
public enum Icons implements IconAsset {
NEW {
public String getIconName () {
return "new";
}
},
UNDO {
public String getIconName () {
return "undo";
}
},
REDO {
public String getIconName () {
return "redo";
}
},
SETTINGS {
public String getIconName () {
return "settings";
}
},
SETTINGS_VIEW {
public String getIconName () {
return "settings-view";
}
},
EXPORT {
public String getIconName () {
return "export";
}
},
IMPORT {
public String getIconName () {
return "import";
}
},
LOAD {
public String getIconName () {
return "load";
}
},
SAVE {
public String getIconName () {
return "save";
}
},
GLOBE {
public String getIconName () {
return "globe";
}
},
INFO {
public String getIconName () {
return "info";
}
},
EXIT {
public String getIconName () {
return "exit";
}
},
FOLDER_OPEN {
public String getIconName () {
return "folder-open";
}
},
SEARCH {
public String getIconName () {
return "search";
}
},
QUESTION {
public String getIconName () {
return "question";
}
},
MORE {
public String getIconName () {
return "more";
}
},
SOUND {
public String getIconName () {
return "sound";
}
},
MUSIC {
public String getIconName () {
return "music";
}
},
WARNING {
public String getIconName () {
return "warning";
}
}
}
interface IconAsset {
String getIconName ();
}
| true
|
969a78e64668c2af920b3f76beb5c2abf76ae742
|
Java
|
r0n9/spring-cloud
|
/cloud-eureka-consumer/src/main/java/vip/fanrong/mapper/UserMapper.java
|
UTF-8
| 555
| 2.125
| 2
|
[] |
no_license
|
package vip.fanrong.mapper;
import org.apache.ibatis.annotations.*;
import org.springframework.stereotype.Repository;
import vip.fanrong.model.User;
/*
* 用户的增删改查
*/
@Mapper
@Repository
public interface UserMapper {
//通过id或邮箱找到用户
public User getUser(@Param("id") Long id, @Param("email") String email);
//更新用户信息
public void updateUser(User user);
//创建一个用户
public void createUser(User user);
//删除一个用户
public void deleteUser(@Param("id") long id);
}
| true
|
48e3c5f4f431c94d4fe01fdd748d55065e826008
|
Java
|
karunmatharu/Android-4.4-Pay-by-Data
|
/sdk/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/AndroidXmlCharacterMatcherTest.java
|
UTF-8
| 5,098
| 1.695313
| 2
|
[
"EPL-1.0",
"MIT"
] |
permissive
|
/*
* Copyright (C) 2011 The Android Open Source Project
*
* Licensed under the Eclipse Public License, Version 1.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.eclipse.org/org/documents/epl-v10.php
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.ide.eclipse.adt.internal.editors;
import com.android.ide.eclipse.adt.internal.editors.layout.refactoring.AdtProjectTest;
import org.eclipse.core.resources.IFile;
import org.eclipse.jface.text.IRegion;
import org.eclipse.jface.text.source.ISourceViewer;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.ide.IDE;
import org.eclipse.wst.sse.core.internal.provisional.text.IStructuredDocument;
@SuppressWarnings("restriction")
public class AndroidXmlCharacterMatcherTest extends AdtProjectTest {
public void testGotoMatchingFwd1() throws Exception {
checkGotoMatching(
"<app^lication android:icon",
"^</application>");
}
public void testGotoMatchingFwd2() throws Exception {
checkGotoMatching(
"^<application android:icon",
"^</application>");
}
public void testGotoMatchingFwd3() throws Exception {
checkGotoMatching(
"<application^ android:icon",
"^</application>");
}
public void testGotoMatchingBwd1() throws Exception {
checkGotoMatching(
"^</application>",
"^<application android:icon");
}
public void testGotoMatchingBwd2() throws Exception {
checkGotoMatching(
"<^/application>",
"^<application android:icon");
}
public void testGotoMatchingBwd3() throws Exception {
checkGotoMatching(
"</^application>",
"^<application android:icon");
}
public void testGotoMatchingBwd4() throws Exception {
checkGotoMatching(
"</app^lication>",
"^<application android:icon");
}
public void testGotoMatchingBwd5() throws Exception {
checkGotoMatching(
"</^application>",
"^<application android:icon");
}
public void testGotoMatchingBwd6() throws Exception {
checkGotoMatching(
"</^application>",
"^<application android:icon");
}
public void testGotoMatchingFwd4() throws Exception {
checkGotoMatching(
"<intent-filter^>",
"^</intent-filter>");
}
public void testGotoMatchingFwd5() throws Exception {
checkGotoMatching(
"<intent-filter>^",
"^</intent-filter>");
}
public void testGotoMatchingFallback() throws Exception {
// Character matching is done by the superclass; ensure that fallback to the
// other XML matchers is working
checkGotoMatching(
"android:icon=^\"@drawable/icon\"",
"android:icon=\"@drawable/icon^\"");
}
private void checkGotoMatching(IFile file, String caretBefore,
String caretAfter) throws Exception {
IWorkbenchPage page = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();
assertNotNull(page);
IEditorPart editor = IDE.openEditor(page, file);
assertTrue(editor instanceof AndroidXmlEditor);
AndroidXmlEditor layoutEditor = (AndroidXmlEditor) editor;
ISourceViewer viewer = layoutEditor.getStructuredSourceViewer();
int caretPosBefore = updateCaret(viewer, caretBefore);
AndroidXmlCharacterMatcher matcher = new AndroidXmlCharacterMatcher();
IStructuredDocument document = layoutEditor.getStructuredDocument();
IRegion match = matcher.match(document, caretPosBefore);
assertNotNull(match);
String text = document.get();
final String after = stripCaret(caretAfter);
int index = text.indexOf(after);
int caretPosAfter = match.getOffset() - index;
String textWithCaret = after.substring(0, caretPosAfter)
+ "^" + after.substring(caretPosAfter);
assertEquals(caretAfter, textWithCaret);
}
private static String stripCaret(String s) {
int index = s.indexOf('^');
assertTrue(index != -1);
return s.substring(0, index) + s.substring(index + 1);
}
private void checkGotoMatching(String caretBefore,
String caretAfter) throws Exception {
checkGotoMatching(
getTestDataFile(getProject(), "manifest.xml", "AndroidManifest.xml", true),
caretBefore, caretAfter);
}
}
| true
|
2470114fe8cb904bf58ad6ba10018402bd320ef2
|
Java
|
talemache/MyJavaGames
|
/EvilGalaxy/src/main/java/entities/PlayerShip.java
|
UTF-8
| 4,193
| 2.328125
| 2
|
[] |
no_license
|
// MyShip.java
//
// Creator: Konstantin
//
package entities;
// import java libraries:
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.event.KeyEvent;
import java.util.ArrayList;
import java.util.List;
// import game packages:
import enums.Images;
import enums.SoundEffects;
import game_engine.SpritePattern;
import items.ShipMissile;
import items.ShipRocket;
import main.Main;
import menu_engine.CanvasMenu;
import menu_engine.ImageColorizer;
import sound_engine.PlayWave1st;
import util.Constants;
import util.LoadSounds;
public class PlayerShip extends SpritePattern {
public static PlayerShip playerOne;
double speedX, speedY;
private static final long serialVersionUID = 1L;
private List<ShipMissile> missiles;
private List<ShipRocket> rockets;
private String imageName, soundName;
public PlayerShip(int x, int y) {
super(x, y);
drawShip();
initAmmo();
}
public Image drawShip() {
imageName = Images.MYSHIPINIT.getImg();
loadImage(imageName);
getImageDimensions();
return loadImage(imageName);
}
public Image shipOnFire() {
imageName = Images.MYSHIPONFIRE.getImg();
loadImage(imageName);
getImageDimensions();
return loadImage(imageName);
}
public Image upsideDown() {
imageName = Images.MYSHIPLIFEBAR.getImg();
loadImage(imageName);
getImageDimensions();
return loadImage(imageName);
}
public Image godMode() {
imageName = Images.MYSHIPGOD.getImg();
loadImage(imageName);
getImageDimensions();
return loadImage(imageName);
}
public void shipShaked() {
x += speedX;
y += speedY;
if (x < 1) {
x = 1;
}
if (y < 1) {
y = 1;
}
x -= 1;
if (x < 100) {
speedX += 0.3;
}
y -= 1;
if (y == 0) {
x += 0.3;
}
if (x > 200) {
speedX -= 0.3;
speedY += 0.3;
}
if (y > 50) {
speedY -= 0.3;
}
}
public void move() {
Main.dim = Toolkit.getDefaultToolkit().getScreenSize();
x += speedX;
y += speedY;
if (x < 1) {
x = 1;
// escapeForbidden();
}
if (x > Main.dim.getWidth() - 340) {
x = (int) Main.dim.getWidth() - 340;
}
if (y < 0) {
y = 0;
// escapeForbidden();
} else if (y > Main.dim.getHeight() - 260) {
y = (int) (Main.dim.getHeight() - 260);
// escapeForbidden();
}
}
private void initAmmo() {
missiles = new ArrayList<>();
rockets = new ArrayList<>();
}
public List<ShipMissile> getMissiles() {
return missiles;
}
public List<ShipRocket> getRockets() {
return rockets;
}
public List<ShipMissile> loadMissiles() {
soundName = SoundEffects.LASER.getSound();
missiles.add(new ShipMissile(x + width, y-15 + height / 2));
new PlayWave1st(soundName).start();
return missiles;
}
public List<ShipRocket> loadRockets() {
soundName = SoundEffects.ROCKET.getSound();
rockets.add(new ShipRocket(x + width, y + height / 2));
new PlayWave1st(soundName).start();
return rockets;
}
public String gunLocked(KeyEvent e) {
soundName = SoundEffects.DENIED.getSound();
LoadSounds.DENIED.play();
if(e.isConsumed()) {
LoadSounds.DENIED.stop();
}
return soundName;
}
public void keyPressed(KeyEvent e) {
final int key = e.getKeyCode();
if (key == KeyEvent.VK_LEFT) {
speedX = -7.5;
// shipOnFire();
}
if (key == KeyEvent.VK_RIGHT) {
speedX = 7.5;
// shipOnFire();
}
if (key == KeyEvent.VK_UP) {
speedY = -7.5;
// shipOnFire();
}
if (key == KeyEvent.VK_DOWN) {
speedY = 7.5;
// shipOnFire();
}
}
public void keyReleased(KeyEvent e) {
final int key = e.getKeyCode();
if (key == KeyEvent.VK_LEFT || key == KeyEvent.VK_RIGHT) {
speedX = 0;
drawShip();
}
if (key == KeyEvent.VK_UP || key == KeyEvent.VK_DOWN) {
speedY = 0;
drawShip();
}
}
public void renderShip(Graphics g) {
g.drawImage(ImageColorizer.dye(Constants.LOAD_ASSETS.myShip, CanvasMenu.color.getColor()), Math.round(this.getX()), Math.round(this.getY()), null);
}
}
| true
|
d4fc9a19461360782495a24b109341d60585cfbc
|
Java
|
Xaoilin/help-me-translate-api
|
/src/main/java/com/xaoilin/translate/database/model/AuthUser.java
|
UTF-8
| 1,858
| 1.984375
| 2
|
[] |
no_license
|
package com.xaoilin.translate.database.model;
import javax.persistence.*;
import javax.validation.constraints.NotNull;
import java.util.List;
@Entity
@Table(name = "auth_user")
public class AuthUser {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column
private Long id;
@NotNull
@Column
private String email;
@NotNull
@Column
private String password;
@Column
private String status;
// @ManyToMany(cascade = CascadeType.ALL)
// @JoinTable(name = "auth_user_role")
// private Set<Role> roles;
@OneToMany(mappedBy = "authUser", cascade = CascadeType.ALL, fetch = FetchType.EAGER)
private List<SavedTranslations> savedTranslations;
public AuthUser(String email, String password, String status) {
this.email = email;
this.password = password;
this.status = status;
}
public AuthUser() {
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getEmail() {
return email;
}
public void setEmail(String name) {
this.email = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
// public Set<Role> getRoles() {
// return roles;
// }
//
// public void setRoles(Set<Role> roles) {
// this.roles = roles;
// }
public List<SavedTranslations> getSavedTranslations() {
return savedTranslations;
}
public void setSavedTranslations(List<SavedTranslations> savedTranslations) {
this.savedTranslations = savedTranslations;
}
}
| true
|
75e1f5fc3944772fa5d4ac969451a45b3407ffeb
|
Java
|
liweiheng/design
|
/prototype/src/com/lwh/prototype/deep/Client.java
|
UTF-8
| 452
| 2.90625
| 3
|
[] |
no_license
|
package com.lwh.prototype.deep;
public class Client {
public void show(ConcretePrototype prototypeA, ConcretePrototype prototypeB) {
prototypeA.show();
prototypeB.show();
System.out.println("PrototypeA==PrototypeB? " + (prototypeA == prototypeB ? "true" : "false"));
System.out.println("PrototypeA.WeelLog==PrototypeB.WeelLog? " + (prototypeA.getWeelLog() == prototypeB.getWeelLog() ? "true" : "false"));
}
}
| true
|
ca0077279c1e8d051514f0d9dbe6107b7900d68a
|
Java
|
freeuni-sdp/arkanoid-16
|
/src/main/java/ge/edu/freeuni/sdp/arkanoid/model/LevelBossBuilder.java
|
UTF-8
| 4,763
| 2.359375
| 2
|
[
"MIT"
] |
permissive
|
package ge.edu.freeuni.sdp.arkanoid.model;
import ge.edu.freeuni.sdp.arkanoid.model.geometry.Point;
import ge.edu.freeuni.sdp.arkanoid.model.geometry.Size;
import java.util.List;
import java.util.ArrayList;
import java.util.Random;
public class LevelBossBuilder extends FrameBuilder {
// will be changed when new bricks are introduces in issue #8
private BrickColor[][] monsterAppearance = new BrickColor[][] {
{ null, null, BrickColor.Red, null, null, null, null, null, BrickColor.Red, null, null },
{ null, null, BrickColor.Red, null, null, null, null, null, BrickColor.Red, null, null },
{ null, null, null, BrickColor.Red, null, null, null, BrickColor.Red, null, null, null },
{ null, null, null, BrickColor.Red, null, null, null, BrickColor.Red, null, null, null },
{ null, null, BrickColor.Red, BrickColor.Red, BrickColor.Red, BrickColor.Red, BrickColor.Red, BrickColor.Red,
BrickColor.Red, null, null },
{ null, null, BrickColor.Red, BrickColor.Red, BrickColor.Red, BrickColor.Red, BrickColor.Red, BrickColor.Red,
BrickColor.Red, null, null },
{ null, BrickColor.Red, BrickColor.Red, null, BrickColor.Red, BrickColor.Red, BrickColor.Red, null,
BrickColor.Red, BrickColor.Red, null },
{ null, BrickColor.Red, BrickColor.Red, null, BrickColor.Red, BrickColor.Red, BrickColor.Red, null,
BrickColor.Red, BrickColor.Red, null },
{ BrickColor.Red, BrickColor.Red, BrickColor.Red, BrickColor.Red, BrickColor.Red, BrickColor.Red,
BrickColor.Red, BrickColor.Red, BrickColor.Red, BrickColor.Red, BrickColor.Red },
{ BrickColor.Red, BrickColor.Red, BrickColor.Red, BrickColor.Red, BrickColor.Red, BrickColor.Red,
BrickColor.Red, BrickColor.Red, BrickColor.Red, BrickColor.Red, BrickColor.Red },
{ BrickColor.Red, BrickColor.Red, BrickColor.Red, BrickColor.Red, BrickColor.Red, BrickColor.Red,
BrickColor.Red, BrickColor.Red, BrickColor.Red, BrickColor.Red, BrickColor.Red },
{ BrickColor.Red, null, BrickColor.Red, BrickColor.Red, BrickColor.Red, BrickColor.Red, BrickColor.Red,
BrickColor.Red, BrickColor.Red, BrickColor.Red, BrickColor.Red },
{ BrickColor.Red, null, BrickColor.Red, null, null, null, null, null, BrickColor.Red, null, BrickColor.Red },
{ BrickColor.Red, null, BrickColor.Red, null, null, null, null, null, BrickColor.Red, null, BrickColor.Red }
};
private CapsuleFactory capsuleFactory;
private List<CapsuleType> capsuleTypes;
private Random random;
public LevelBossBuilder(Size size) {
super(size);
random = new Random();
capsuleFactory = CapsuleFactory.getInstance();
capsuleTypes = new ArrayList<>(CapsuleFactory.getInstance().getCapsuleTypes());
prepareCapsuleTypeList();
}
private void prepareCapsuleTypeList() {
int listLength = capsuleTypes.size();
// 70% of list should be null capsules
int addNullCapsules = (int)((listLength-1) * 0.7);
for (int i = 0; i < addNullCapsules; ++i) {
capsuleTypes.add(CapsuleType.Null);
}
}
public void build(Room room, ScoreCounter scoreCounter) {
super.build(room, scoreCounter);
int brickWidth = getNormalBrickWidth();
int brickHeight = getNormalBrickHeight();
int roomWidth = Configuration.getInstance().getSize().getWidth();
createMonster(room, brickWidth, brickHeight, roomWidth);
}
private void createMonster(Room room, int brickWidth, int brickHeight, int roomWidth) {
int monsterHeight = monsterAppearance.length;
int monsterWidth = monsterAppearance[0].length;
int upperLeftX = (roomWidth - monsterWidth * brickWidth) / 2;
int upperLeftY = 2;
for (int i = 0; i < monsterHeight; ++i) {
for (int j = 0; j < monsterWidth; ++j) {
if (monsterAppearance[i][j] != null) {
Point position = new Point(upperLeftX + j * brickWidth, upperLeftY + i * brickHeight);
Brick current = new NormalBrick(position, monsterAppearance[i][j],
capsuleFactory.createCapsule(capsuleTypes.get
(random.nextInt(capsuleTypes.size())), position, room));
room.add(current);
}
}
}
}
private int getNormalBrickWidth() {
return new NormalBrick(null, BrickColor.Red, null).getShape().getSize().getWidth();
}
private int getNormalBrickHeight() {
return new NormalBrick(null, BrickColor.Red, null).getShape().getSize().getHeight();
}
}
| true
|
4aed3aedb886a112093ef33e8c4993ec93524428
|
Java
|
ewjmulder/program-your-home
|
/voice-control/src/main/java/com/programyourhome/voice/config/VoiceControlConfigLoader.java
|
UTF-8
| 1,687
| 2.15625
| 2
|
[] |
no_license
|
package com.programyourhome.voice.config;
import javax.inject.Inject;
import org.springframework.stereotype.Component;
import com.programyourhome.common.config.ConfigLoader;
import com.programyourhome.common.config.ConfigurationException;
import com.programyourhome.voice.VoiceControl;
@Component
public class VoiceControlConfigLoader extends ConfigLoader<VoiceControlConfig> {
private static final String CONFIG_BASE_PATH = "/com/programyourhome/config/voice-control/";
private static final String XSD_BASE_PATH = CONFIG_BASE_PATH + "xsd/";
private static final String XML_BASE_PATH = CONFIG_BASE_PATH + "xml/";
private static final String XSD_FILENAME = "voice-control.xsd";
private static final String XML_FILENAME = "voice-control.xml";
@Inject
private VoiceControl voiceControl;
@Override
protected Class<VoiceControlConfig> getConfigType() {
return VoiceControlConfig.class;
}
@Override
protected String getPathToXsd() {
return XSD_BASE_PATH + XSD_FILENAME;
}
@Override
protected String getPathToXml() {
return XML_BASE_PATH + XML_FILENAME;
}
@Override
protected void validateConfig(final VoiceControlConfig voiceControlConfig) throws ConfigurationException {
// TODO: List of validations:
/**
* <pre>
* - Internal XML:
* - Unique id's
* - Unique language names (PYH common utils thingy, since has overlap with server stuff (is ok, see as apache commons alternative))
* - Existing Java locales
* - confirmations/negations can contain only 1 word (per entry)!
* </pre>
*/
}
}
| true
|
4d3d9089809d4b9d92d3f0763852c5ee26fc33b2
|
Java
|
JoHwanhee/horse
|
/JejuHorse.java
|
UTF-8
| 202
| 2.4375
| 2
|
[] |
no_license
|
public class JejuHorse implements HorseRunnable{
private final int speed = 3;
@Override
public HorseScore run() {
return new HorseScore((int)((Math.random()*10000)%speed));
}
}
| true
|
6f2e39b44b7c8b8c0d89cd391072bf93d141762c
|
Java
|
deanflood/WeatherApp
|
/app/src/main/java/com/example/adminibm/weatherapp/MainActivity.java
|
UTF-8
| 2,764
| 2.703125
| 3
|
[] |
no_license
|
package com.example.adminibm.weatherapp;
import android.app.Activity;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
import models.Weather;
import models.WeatherCondition;
import static android.R.attr.data;
public class MainActivity extends Activity implements AdapterView.OnItemSelectedListener {
ArrayList<Weather> weatherList = new ArrayList<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
weatherList.add(new Weather("Dublin", 10, WeatherCondition.CLOUDY));
weatherList.add(new Weather("London", 5, WeatherCondition.RAIN));
weatherList.add(new Weather("Madrid", 30, WeatherCondition.SUNNY));
// initialise spinner with cities from data
Spinner spinner = (Spinner) findViewById(R.id.cityspinner);
List<String> cities = new ArrayList<> ();
for (int i = 0; i < weatherList.size(); i++)
{
cities.add(weatherList.get(i).getCity());
}
ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, cities);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
// hook in handler for selections on spinner
spinner.setOnItemSelectedListener(this);
}
// item on picker selected
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
String city = parent.getItemAtPosition(pos).toString();
TextView temperaturetv = (TextView) findViewById(R.id.temperatureTextView);
ImageView conditionsiv = (ImageView) findViewById(R.id.conditionsImageView);
// update UI i.e. temperature and conditions
for (Weather w : weatherList) {
if (w.getCity().equalsIgnoreCase(city)) {
temperaturetv.setText(w.getDegrees() + " Celsius");
if (w.getCondition() == WeatherCondition.SUNNY) {
conditionsiv.setImageResource(R.drawable.sunny);
} else if (w.getCondition() == WeatherCondition.CLOUDY) {
conditionsiv.setImageResource(R.drawable.cloudy);
} else {
conditionsiv.setImageResource(R.drawable.rain);
}
}
}
}
public void onNothingSelected(AdapterView<?> parent)
{
// Another interface callback
}
}
| true
|
728c8222e8ccffe9fe54f0a864aa3e19abe7285f
|
Java
|
sergiotaborda/lense-lang
|
/src/main/java/lense/compiler/typesystem/PackageResolver.java
|
UTF-8
| 271
| 1.773438
| 2
|
[] |
no_license
|
/**
*
*/
package lense.compiler.typesystem;
import compiler.CompilationUnit;
/**
*
*/
public interface PackageResolver {
/**
* @param compilationUnit
* @return
*/
public String resolveUnitPackageName(CompilationUnit compilationUnit);
}
| true
|
36996127e5e68da4ae05eb697147c7edf1e53fa4
|
Java
|
MayankAtulkar/MovieDB
|
/Witworks/app/src/main/java/main/java/com/witworks/witworks/HomeActivity.java
|
UTF-8
| 16,659
| 1.789063
| 2
|
[] |
no_license
|
package main.java.com.witworks.witworks;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothClass;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothServerSocket;
import android.bluetooth.BluetoothSocket;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Camera;
import android.media.MediaRecorder;
import android.net.Uri;
import android.os.Handler;
import android.os.Message;
import android.os.ParcelFileDescriptor;
import android.os.ParcelUuid;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Set;
public class HomeActivity extends AppCompatActivity {
ListView listViewPaired;
ListView listViewDetected;
ArrayList<String> arrayListpaired;
Button buttonSearch,buttonOn,buttonDesc,buttonOff;
ArrayAdapter<String> adapter,detectedAdapter;
static HandleSeacrh handleSeacrh;
BluetoothDevice bdDevice;
BluetoothClass bdClass;
ArrayList<BluetoothDevice> arrayListPairedBluetoothDevices;
private ButtonClicked clicked;
ListItemClickedonPaired listItemClickedonPaired;
BluetoothAdapter bluetoothAdapter = null;
ArrayList<BluetoothDevice> arrayListBluetoothDevices = null;
ListItemClicked listItemClicked;
private BluetoothDevice mmDevice;
private BluetoothSocket mmSocket;
private InputStream mmInStream;
private OutputStream mmOutStream;
private static final int REQUEST_BLU = 1;
private static final int DISCOVER_DURATION = 300;
private BluetoothServerSocket mmServerSocket;
private OutputStream outputStream;
private InputStream inStream;
private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100;
private Uri fileUri;
final int MESSAGE_READ = 9999;
private Handler mHandler;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
listViewDetected = (ListView) findViewById(R.id.listViewDetected);
listViewPaired = (ListView) findViewById(R.id.listViewPaired);
buttonSearch = (Button) findViewById(R.id.buttonSearch);
buttonOn = (Button) findViewById(R.id.buttonOn);
buttonDesc = (Button) findViewById(R.id.buttonDesc);
buttonOff = (Button) findViewById(R.id.buttonOff);
arrayListpaired = new ArrayList<String>();
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
clicked = new ButtonClicked();
handleSeacrh = new HandleSeacrh();
arrayListPairedBluetoothDevices = new ArrayList<BluetoothDevice>();
/*
* the above declaration is just for getting the paired bluetooth devices;
* this helps in the removing the bond between paired devices.
*/
listItemClickedonPaired = new ListItemClickedonPaired();
arrayListBluetoothDevices = new ArrayList<BluetoothDevice>();
adapter= new ArrayAdapter<String>(HomeActivity.this, android.R.layout.simple_list_item_1, arrayListpaired);
detectedAdapter = new ArrayAdapter<String>(HomeActivity.this, android.R.layout.simple_list_item_single_choice);
listViewDetected.setAdapter(detectedAdapter);
listItemClicked = new ListItemClicked();
detectedAdapter.notifyDataSetChanged();
listViewPaired.setAdapter(adapter);
}
@Override
protected void onStart() {
// TODO Auto-generated method stub
super.onStart();
getPairedDevices();
buttonOn.setOnClickListener(clicked);
buttonSearch.setOnClickListener(clicked);
buttonDesc.setOnClickListener(clicked);
buttonOff.setOnClickListener(clicked);
listViewDetected.setOnItemClickListener(listItemClicked);
listViewPaired.setOnItemClickListener(listItemClickedonPaired);
}
private void getPairedDevices() {
Set<BluetoothDevice> pairedDevice = bluetoothAdapter.getBondedDevices();
if(pairedDevice.size()>0)
{
for(BluetoothDevice device : pairedDevice)
{
arrayListpaired.add(device.getName()+"\n"+device.getAddress());
arrayListPairedBluetoothDevices.add(device);
}
}
adapter.notifyDataSetChanged();
}
class ListItemClicked implements AdapterView.OnItemClickListener
{
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// TODO Auto-generated method stub
bdDevice = arrayListBluetoothDevices.get(position);
//bdClass = arrayListBluetoothDevices.get(position);
Log.i("Log", "The device : "+bdDevice.toString());
/*
* here below we can do pairing without calling the callthread(), we can directly call the
* connect(). but for the safer side we must usethe threading object.
*/
//callThread();
//connect(bdDevice);
Boolean isBonded = false;
try {
isBonded = createBond(bdDevice);
if(isBonded)
{
//arrayListpaired.add(bdDevice.getName()+"\n"+bdDevice.getAddress());
//adapter.notifyDataSetChanged();
getPairedDevices();
adapter.notifyDataSetChanged();
}
} catch (Exception e) {
e.printStackTrace();
}//connect(bdDevice);
Log.i("Log", "The socket is created: "+isBonded);
}
}
class ListItemClickedonPaired implements AdapterView.OnItemClickListener
{
@Override
public void onItemClick(AdapterView<?> parent, View view, int position,long id) {
bdDevice = arrayListPairedBluetoothDevices.get(position);
Toast.makeText(HomeActivity.this, " Clicked Here" , Toast.LENGTH_LONG).show();
BluetoothAdapter blueAdapter = BluetoothAdapter.getDefaultAdapter();
Set<BluetoothDevice> bondedDevices = blueAdapter.getBondedDevices();
if(bondedDevices.size() > 0) {
Log.i("Log", "The bond devices size: ");
Object[] devices = (Object []) bondedDevices.toArray();
BluetoothDevice device = (BluetoothDevice) devices[position];
ParcelUuid[] uuids = device.getUuids();
BluetoothSocket socket = null;
try {
socket = device.createRfcommSocketToServiceRecord(uuids[0].getUuid());
Log.i("Log", "The bond is created socket: ");
socket.connect();
Log.i("Log", "The socket is connected: ");
outputStream = socket.getOutputStream();
inStream = socket.getInputStream();
} catch (IOException e) {
e.printStackTrace();
}
}else {
Log.e("error", "No appropriate paired devices.");
}
/********* To remove paired device *********/
/*try {
Boolean removeBonding = removeBond(bdDevice);
if(removeBonding)
{
arrayListpaired.remove(position);
adapter.notifyDataSetChanged();
}
Log.i("Log", "Removed"+removeBonding);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}*/
}
}
public void write(String s) throws IOException {
outputStream.write(s.getBytes());
}
public void run() {
final int BUFFER_SIZE = 1024;
byte[] buffer = new byte[BUFFER_SIZE];
int bytes = 0;
int b = BUFFER_SIZE;
while (true) {
try {
bytes = inStream.read(buffer, bytes, BUFFER_SIZE - bytes);
} catch (IOException e) {
e.printStackTrace();
}
}
}
/*private void callThread() {
new Thread(){
public void run() {
Boolean isBonded = false;
try {
isBonded = createBond(bdDevice);
if(isBonded)
{
arrayListpaired.add(bdDevice.getName()+"\n"+bdDevice.getAddress());
adapter.notifyDataSetChanged();
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}//connect(bdDevice);
Log.i("Log", "The bond is created: "+isBonded);
}
}.start();
}*/
private Boolean connect(BluetoothDevice bdDevice) {
Boolean bool = false;
try {
Log.i("Log", "service method is called ");
Class cl = Class.forName("android.bluetooth.BluetoothDevice");
Class[] par = {};
Method method = cl.getMethod("createBond", par);
Object[] args = {};
bool = (Boolean) method.invoke(bdDevice);//, args);// this invoke creates the detected devices paired.
//Log.i("Log", "This is: "+bool.booleanValue());
//Log.i("Log", "devicesss: "+bdDevice.getName());
} catch (Exception e) {
Log.i("Log", "Inside catch of serviceFromDevice Method");
e.printStackTrace();
}
return bool.booleanValue();
};
public boolean removeBond(BluetoothDevice btDevice)
throws Exception
{
Class btClass = Class.forName("android.bluetooth.BluetoothDevice");
Method removeBondMethod = btClass.getMethod("removeBond");
Boolean returnValue = (Boolean) removeBondMethod.invoke(btDevice);
return returnValue.booleanValue();
}
public boolean createBond(BluetoothDevice btDevice)
throws Exception
{
Class class1 = Class.forName("android.bluetooth.BluetoothDevice");
Method createBondMethod = class1.getMethod("createBond");
Boolean returnValue = (Boolean) createBondMethod.invoke(btDevice);
return returnValue.booleanValue();
}
class ButtonClicked implements View.OnClickListener
{
@Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.buttonOn:
onBluetooth();
break;
case R.id.buttonSearch:
arrayListBluetoothDevices.clear();
startSearching();
break;
case R.id.buttonDesc:
makeDiscoverable();
break;
case R.id.buttonOff:
offBluetooth();
break;
default:
break;
}
}
}
private BroadcastReceiver myReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
Message msg = Message.obtain();
String action = intent.getAction();
if(BluetoothDevice.ACTION_FOUND.equals(action)){
Toast.makeText(context, "ACTION_FOUND", Toast.LENGTH_SHORT).show();
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
try
{
//device.getClass().getMethod("setPairingConfirmation", boolean.class).invoke(device, true);
//device.getClass().getMethod("cancelPairingUserInput", boolean.class).invoke(device);
}
catch (Exception e) {
Log.i("Log", "Inside the exception: ");
e.printStackTrace();
}
if(arrayListBluetoothDevices.size()<1) // this checks if the size of bluetooth device is 0,then add the
{ // device to the arraylist.
detectedAdapter.add(device.getName()+"\n"+device.getAddress());
arrayListBluetoothDevices.add(device);
detectedAdapter.notifyDataSetChanged();
}
else
{
boolean flag = true; // flag to indicate that particular device is already in the arlist or not
for(int i = 0; i<arrayListBluetoothDevices.size();i++)
{
if(device.getAddress().equals(arrayListBluetoothDevices.get(i).getAddress()))
{
flag = false;
}
}
if(flag == true)
{
detectedAdapter.add(device.getName()+"\n"+device.getAddress());
arrayListBluetoothDevices.add(device);
detectedAdapter.notifyDataSetChanged();
}
}
}
}
};
private void startSearching() {
Log.i("Log", "in the start searching method");
IntentFilter intentFilter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
HomeActivity.this.registerReceiver(myReceiver, intentFilter);
bluetoothAdapter.startDiscovery();
}
private void onBluetooth() {
if(!bluetoothAdapter.isEnabled())
{
bluetoothAdapter.enable();
Log.i("Log", "Bluetooth is Enabled");
}
}
private void offBluetooth() {
if(bluetoothAdapter.isEnabled())
{
bluetoothAdapter.disable();
}
}
private void makeDiscoverable() {
Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, DISCOVER_DURATION);
startActivityForResult(discoverableIntent, REQUEST_BLU);
Log.i("Log", "Discoverable ");
}
protected void onActivityResult (int requestCode, int resultCode, Intent data){
if(resultCode == DISCOVER_DURATION && requestCode == REQUEST_BLU){
}
else {
Toast.makeText(this, "Canceled",Toast.LENGTH_SHORT).show();
}
}
class HandleSeacrh extends Handler
{
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case 111:
break;
default:
break;
}
}
}
public void ConnectedThread(BluetoothSocket socket) {
mmSocket = socket;
InputStream tmpIn = null;
OutputStream tmpOut = null;
// Get the input and output streams, using temp objects because
// member streams are final
try {
tmpIn = socket.getInputStream();
tmpOut = socket.getOutputStream();
} catch (IOException e) { }
mmInStream = tmpIn;
mmOutStream = tmpOut;
}
/*public void run() {
byte[] buffer = new byte[1024]; // buffer store for the stream
int bytes; // bytes returned from read()
// Keep listening to the InputStream until an exception occurs
while (true) {
try {
// Read from the InputStream
bytes = mmInStream.read(buffer);
// Send the obtained bytes to the UI activity
mHandler.obtainMessage(MESSAGE_READ, bytes, -1, buffer)
.sendToTarget();
} catch (IOException e) {
break;
}
}
}*/
/* Call this from the main activity to send data to the remote device */
/* public void write(byte[] bytes) {
try {
mmOutStream.write(bytes);
} catch (IOException e) { }
}*/
/* Call this from the main activity to shutdown the connection */
public void cancel() {
try {
mmSocket.close();
} catch (IOException e) { }
}
}
| true
|
337ac970b7ff3f35f90f82c394537eb0fc0b792a
|
Java
|
jzft/framework-code
|
/framework-auth-base/src/main/java/com/framework/auth/api/SysUserController.java
|
UTF-8
| 5,445
| 2.21875
| 2
|
[] |
no_license
|
package com.framework.auth.api;
import com.framework.auth.enums.ResultCodeEnum;
import com.framework.auth.pojo.dto.role.RoleInfoDTO;
import com.framework.auth.pojo.dto.user.RegisterUserDTO;
import com.framework.auth.pojo.dto.user.UserInfoDTO;
import com.framework.auth.pojo.dto.user.UserInfoListDTO;
import com.framework.auth.pojo.dto.user.UserRoleInfoDTO;
import com.framework.auth.pojo.entity.RoleEntity;
import com.framework.auth.pojo.entity.UserEntity;
import com.framework.auth.pojo.vo.PageVo;
import com.framework.auth.pojo.vo.ResultVo;
import com.framework.auth.pojo.vo.ResultVo;
import com.framework.auth.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.validation.Errors;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;
import java.util.LinkedList;
import java.util.List;
/**
* 系统用户接口
*
* @author casper
*/
@RestController
@RequestMapping("/user")
@Api(description = "系统用户接口")
public class SysUserController {
private static final Logger log = LoggerFactory.getLogger(SysUserController.class);
@Autowired
private UserService userService;
/**
* 添加用户
*
* @param userInfoDTO 用户信息
* @return 用户id
*/
@PostMapping("add")
@ApiOperation(value = "添加用户")
public ResultVo<Integer> add(@Valid @RequestBody UserInfoDTO userInfoDTO, Errors errors) {
if (StringUtils.isEmpty(userInfoDTO.getPassword())) {
return ResultVo.build(ResultCodeEnum.PARAMETER_ERROR.getCode(), "密码不能为空");
}
return ResultVo.build(ResultCodeEnum.SUCCESS.getCode(),ResultCodeEnum.SUCCESS.getMsg(),userService.saveOrUpdate(userInfoDTO));
}
@PostMapping("register")
@ApiOperation(value = "添加用户")
public ResultVo<RegisterUserDTO> register(@Valid @RequestBody UserInfoDTO userInfoDTO, Errors errors) {
if (StringUtils.isEmpty(userInfoDTO.getPassword())) {
return ResultVo.build(ResultCodeEnum.PARAMETER_ERROR.getCode(), "密码不能为空");
}
RegisterUserDTO dto = new RegisterUserDTO();
dto.setUserInfo(userInfoDTO);
return ResultVo.build(ResultCodeEnum.SUCCESS.getCode(),ResultCodeEnum.SUCCESS.getMsg(),userService.register(dto ));
}
/**
* 更新用户信息
*
* @param userInfoDTO 用户信息
* @return 用户id
*/
@PutMapping("")
@ApiOperation(value = "更新用户信息")
public ResultVo<Integer> update(@RequestBody UserInfoDTO userInfoDTO, Errors errors) {
/*校验参数*/
if (userInfoDTO.getId() == null || userInfoDTO.getId() == 0) {
return ResultVo.build(ResultCodeEnum.PARAMETER_ERROR.getCode(), "用户id不能为空或者0");
}
return ResultVo.build(ResultCodeEnum.SUCCESS.getCode(),ResultCodeEnum.SUCCESS.getMsg(),userService.saveOrUpdate(userInfoDTO));
}
/**
* 列表查询
*
* @return 列表数据
*/
@GetMapping("/list")
@ApiOperation(value = "列表查询")
public PageVo<UserInfoListDTO> list() {
return PageVo.build(ResultCodeEnum.SUCCESS.getCode(),ResultCodeEnum.SUCCESS.getMsg(),0, 0, null);
}
/**
* 查询用户详细信息
*
* @param id 用户id
* @return 用户详情
*/
@GetMapping()
@ApiOperation(value = "查询用户详细信息")
public ResultVo<UserInfoDTO> detail(@RequestParam Integer id) {
UserEntity user = userService.getById(id);
if (user == null) {
return ResultVo.build(ResultCodeEnum.NOT_FOUND.getCode(), "用户不存在");
}
return ResultVo.build(ResultCodeEnum.SUCCESS.getCode(),ResultCodeEnum.SUCCESS.getMsg(),UserInfoDTO.build(user));
}
/**
* 重新绑定角色,旧的角色会清除
*
* @param userRoleInfoDTO 用户和角色信息
* @return
*/
@PostMapping("/role")
@ApiOperation(value = "重新绑定角色,旧的角色会清除")
public ResultVo<String> rebindingRoles(@RequestBody UserRoleInfoDTO userRoleInfoDTO, Errors errors) {
userService.rebindingRoles(userRoleInfoDTO);
return ResultVo.build(ResultCodeEnum.SUCCESS.getCode(),ResultCodeEnum.SUCCESS.getMsg(),"success");
}
/**
* 获取success用户的角色信息
*
* @param id 用户id
* @return 角色列表
*/
@GetMapping("/role")
@ApiOperation(value = "获取用户的角色信息")
public ResultVo<List<RoleInfoDTO>> roleInfo(@RequestParam Integer id) {
UserEntity user = userService.getById(id);
if (user == null) {
return ResultVo.build(ResultCodeEnum.NOT_FOUND.getCode(), "用户不存在");
}
List<RoleEntity> roleEntities = userService.getUserRoles(id);
List<RoleInfoDTO> result = new LinkedList<>();
if (!CollectionUtils.isEmpty(roleEntities)) {
for (RoleEntity roleEntity : roleEntities) {
result.add(RoleInfoDTO.build(roleEntity));
}
}
return ResultVo.build(ResultCodeEnum.SUCCESS.getCode(),ResultCodeEnum.SUCCESS.getMsg(),result);
}
}
| true
|
5ca298ad271736fe26910f778826b1fd91731524
|
Java
|
youngzil/quickstart-spring-boot
|
/quickstart-spring-boot-web/src/main/java/org/quickstart/spring/boot/web/aspect/LoggingAspect.java
|
UTF-8
| 5,190
| 2.1875
| 2
|
[
"Apache-2.0"
] |
permissive
|
/**
* 项目名称:msgtest-console
* 文件名:LoggingAspect.java
* 版本信息:
* 日期:2018年4月11日
* Copyright yangzl Corporation 2018
* 版权所有 *
*/
package org.quickstart.spring.boot.web.aspect;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Date;
import javax.servlet.http.HttpServletRequest;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
/**
* LoggingAspect
*
* @author:youngzil@163.com
* @2018年4月11日 下午5:11:16
* @since 1.0
*/
@Aspect
@Component
public class LoggingAspect {
// 日志记录
private static final Logger logger = LoggerFactory.getLogger(LoggingAspect.class);
// @Autowired
// private OperationLogService operationLogService;
@Pointcut("@annotation(com.ai.quickstart.aspect.annotation.Logger)")
public void loggerMethodPointcut() {}
/**
* 统计Service中方法调用的时间 logServiceMethodAccess
*
* @Description:
* @param joinPoint
* @return
* @throws Throwable Object
* @Exception
* @author:youngzil@163.com
* @2018年4月11日 下午5:32:23
* @since 1.0
*/
// @Around("execution(* com.ai.quickstart.service..*.*(..))")
// @Around("execution(* com.ai.quickstart..*.*(..)) && @annotation(org.springframework.web.bind.annotation.RequestMapping) ")
@Around("loggerMethodPointcut()")
public Object logServiceMethodAccess(ProceedingJoinPoint joinPoint) throws Throwable {
long start = System.currentTimeMillis();
Object result = null;
try {
result = joinPoint.proceed();
} catch (Throwable e) {
try {
long costTime = System.currentTimeMillis() - start;
String className = joinPoint.getSignature().toString();
Object[] args = joinPoint.getArgs();
ServletRequestAttributes sra = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = sra.getRequest();
OperationLog operLog = new OperationLog();
operLog.setRemoteHost(request.getRemoteHost() + ":" + request.getRemotePort());
operLog.setServerInfo(request.getServerName() + ":" + request.getServerPort());
operLog.setClassName(className);
operLog.setParam(String.valueOf(args));
operLog.setOperTime(new Date());
operLog.setCostTime((int) costTime);
String exceptionInfo = String.valueOf(e);
if (exceptionInfo.length() > 4000) {
exceptionInfo = exceptionInfo.substring(0, 4000);
}
operLog.setExceptionInfo(exceptionInfo);
// operationLogService.insert(operLog);
} catch (Exception ex) {
logger.error("record operation log exception: ", ex);
}
logger.error("exception: ", e);
throw e;
}
try {
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
Method method1 = signature.getMethod(); // 获取被拦截的方法
logger.debug("请求方法名称:" + method1);
// String methodName = method.getName(); // 获取被拦截的方法名
String description1 = method1.getAnnotation(org.quickstart.spring.boot.web.aspect.Logger.class).description();
Object object = joinPoint.getTarget();
System.out.println("请求方法:" + (joinPoint.getTarget().getClass().getName() + "." + joinPoint.getSignature().getName() + "()"));
String targetName = joinPoint.getTarget().getClass().getName();
String methodName = joinPoint.getSignature().getName();
long costTime = System.currentTimeMillis() - start;
String className = joinPoint.getSignature().toString();
Object[] args = joinPoint.getArgs();
ServletRequestAttributes sra = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = sra.getRequest();
OperationLog operLog = new OperationLog();
operLog.setRemoteHost(request.getRemoteHost() + ":" + request.getRemotePort());
operLog.setServerInfo(request.getServerName() + ":" + request.getServerPort());
operLog.setClassName(className);
operLog.setParam(Arrays.toString(args));
operLog.setOperTime(new Date());
operLog.setCostTime((int) costTime);
// operationLogService.insert(operLog);
} catch (Exception e) {
logger.error("record operation log exception: ", e);
}
return result;
}
}
| true
|
4a683be4326405f19ade15508cf9568c9060e1b0
|
Java
|
kuptservol/sphinx-management-console
|
/development/sphinx-console-dao-hibernate-spring/src/main/java/ru/skuptsov/sphinx/console/spring/service/impl/ServerServiceImpl.java
|
UTF-8
| 4,791
| 2.125
| 2
|
[] |
no_license
|
package ru.skuptsov.sphinx.console.spring.service.impl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import ru.skuptsov.sphinx.console.coordinator.model.AdminProcess;
import ru.skuptsov.sphinx.console.coordinator.model.ProcessType;
import ru.skuptsov.sphinx.console.coordinator.model.Server;
import ru.skuptsov.sphinx.console.coordinator.model.SphinxProcessType;
import ru.skuptsov.sphinx.console.dao.api.ServerDao;
import ru.skuptsov.sphinx.console.spring.service.api.AdminProcessService;
import ru.skuptsov.sphinx.console.spring.service.api.ServerService;
import java.util.List;
@Service
public class ServerServiceImpl extends AbstractSpringService<ServerDao, Server> implements ServerService {
@Autowired
private AdminProcessService adminProcessService;
private String coordinatorCallbackHost = "127.0.0.1";
@Value("${jmx.coordinator.callback.port}")
private String coordinatorCallbackPort;
@Override
@Transactional(readOnly = true)
public List<ru.skuptsov.sphinx.console.coordinator.model.Server> getServers() {
return getDao().getServers();
}
@Override
@Transactional(readOnly = true)
public List<ru.skuptsov.sphinx.console.coordinator.model.Server> getServers(SphinxProcessType sphinxProcessType) {
return getDao().getServers(sphinxProcessType);
}
@Override
@Transactional(readOnly = true)
public Server getServer(String name) {
return getDao().getServer(name);
}
@Override
@Transactional
public Server addServer(Server server) throws Throwable {
return save(server);
}
@Override
@Transactional
public void deleteServer(Long serverId) {
deleteById(serverId);
}
@Override
@Transactional
public void deleteServer(String serverName) {
delete(getDao().getServer(serverName));
}
@Override
@Transactional
public AdminProcess getAdminProcess(ProcessType type, String serverName) {
return adminProcessService.getAdminProcess(type, serverName);
}
@Override
@Transactional(readOnly = true)
public Server getServer(ProcessType type, String serverName) {
AdminProcess adminProcess = adminProcessService.getAdminProcess(type, serverName);
if (adminProcess != null) {
return adminProcess.getServer();
}
return null;
}
@Override
@Transactional(readOnly = true)
public String getCoordinatorCallbackHost() {
AdminProcess adminProcess = adminProcessService.getAdminProcess(ProcessType.COORDINATOR, null);
Server server = null;
if (adminProcess != null) {
server = adminProcess.getServer();
}
if (server != null) {
return server.getIp();
}
return coordinatorCallbackHost;
}
@Override
@Transactional(readOnly = true)
public String getCoordinatorCallbackPort() {
AdminProcess adminProcess = adminProcessService.getAdminProcess(ProcessType.COORDINATOR, null); // коордиратор всегда один. - поэтому null
if (adminProcess != null) {
return adminProcess.getPort() + "";
}
return coordinatorCallbackPort;
}
@Override
@Transactional(readOnly = true)
public Server getServer(SphinxProcessType type, String serverName) {
ProcessType processType = null;
if (type == null) {
processType = ProcessType.COORDINATOR;
} else if (type == SphinxProcessType.SEARCHING) {
processType = ProcessType.SEARCH_AGENT;
} else if (type == SphinxProcessType.INDEXING) {
processType = ProcessType.INDEX_AGENT;
}
AdminProcess adminProcess = adminProcessService.getAdminProcess(processType, serverName);
if (adminProcess != null) {
return adminProcess.getServer();
}
return null;
}
@Override
@Transactional(readOnly = true)
public AdminProcess getAdminProcess(ProcessType type, Server server) {
return adminProcessService.getAdminProcess(type, server.getName());
}
@Override
@Transactional(readOnly = true)
public Server getServer(Long id) {
return getDao().findById(id);
}
@Override
@Transactional(readOnly = true)
public Server getCoordinator() {
ProcessType processType = ProcessType.COORDINATOR;
AdminProcess adminProcess = adminProcessService.getAdminProcess(processType, null);
if (adminProcess != null) {
return adminProcess.getServer();
}
return null;
}
}
| true
|
170ba56a1161636287d127fcb56a93dceeef0fad
|
Java
|
GitHubDJ6/spring-ssm
|
/src/main/java/top/dj/web/UserController.java
|
UTF-8
| 707
| 2.015625
| 2
|
[] |
no_license
|
package top.dj.web;
import org.springframework.web.bind.annotation.*;
//声明这个处理器所有的返回信息都以流写在前台界面
@RestController
//窄化搜索
@RequestMapping("/User")
public class UserController {
@GetMapping("/queryAllUser")
public String queryAllUser(){
return null;
}
@GetMapping("/queryUserById")
public String queryUserById(){
return null;
}
@DeleteMapping("/deleteUserById")
public String deleteUserById(){
return null;
}
@PutMapping("/updateUserById")
public String updateUserById(){
return null;
}
@PostMapping("/addUser")
public String addUser(){
return null;
}
}
| true
|
95670839424145c24d2a6a60a7c6d98a91a2a07b
|
Java
|
mikeb01/jax2012
|
/src/counters/Factory.java
|
UTF-8
| 72
| 1.929688
| 2
|
[] |
no_license
|
package counters;
public interface Factory<T>
{
T newInstance();
}
| true
|
01f54e2a36e7ea43b3f00c7d027690525e997aaa
|
Java
|
veosett/test
|
/src/main/java/com/example/quote/service/EnergyLevelService.java
|
UTF-8
| 685
| 2.203125
| 2
|
[] |
no_license
|
package com.example.quote.service;
import com.example.quote.enitity.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;
import java.util.*;
@Service
@Validated
public class EnergyLevelService {
final EnergyLevelRepository repository;
@Autowired
public EnergyLevelService(EnergyLevelRepository repository) {
this.repository = repository;
}
public Optional<EnergyLevel> findById(String isin) {
return repository.findById(isin);
}
public Iterable<EnergyLevel> findAll() {
return repository.findAll();
}
}
| true
|
741b2da9b33470e471258003d4eb302e3f67a8de
|
Java
|
martinth/uzl-sem01
|
/vs_uebung02/src/main/java/de/uniluebeck/itm/vs1112/uebung2/aufgabe221/LengthFieldEncoder.java
|
UTF-8
| 1,480
| 3
| 3
|
[] |
no_license
|
package de.uniluebeck.itm.vs1112.uebung2.aufgabe221;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import de.uniluebeck.itm.vs1112.uebung2.Encoder;
import de.uniluebeck.itm.vs1112.uebung2.EncodingException;
/**
* The LengthFieldEncoder encodes a set of plain old Java objects (POJOs) into a byte array. Therefore, it
* serializes the individual elements using the {@link LengthFieldEncoder#elementEncoder} and writes them into the
* resulting byte array, split by length fields prepending each individual serialized element.
*
* @param <T>
* the type of the deserialized objects
*/
public class LengthFieldEncoder<T> implements Encoder<T[]> {
private final Encoder<T> elementEncoder;
private static int HEADER_LENGTH = 4;
public LengthFieldEncoder(final Encoder<T> elementEncoder) {
this.elementEncoder = elementEncoder;
}
public byte[] encode(final T[] object) throws EncodingException {
ByteArrayOutputStream output = new ByteArrayOutputStream();
try {
for (T t : object) {
byte[] encoded = this.elementEncoder.encode(t);
ByteBuffer buf = ByteBuffer.allocate(HEADER_LENGTH + encoded.length);
buf.putInt(encoded.length);
buf.put(encoded);
output.write(buf.array());
}
} catch (IOException e) {
throw new EncodingException(e);
}
return output.toByteArray();
}
}
| true
|