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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
20b8e8aac2b3476de973f4fb3db60baa7fecc292
|
Java
|
jgroups-extras/manet
|
/src/main/java/urv/emulator/tasks/stats/CommunicationStatsTask.java
|
UTF-8
| 9,183
| 2.640625
| 3
|
[
"Apache-2.0"
] |
permissive
|
package urv.emulator.tasks.stats;
import java.net.InetAddress;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.Iterator;
import org.jgroups.Message;
import org.jgroups.View;
import urv.emulator.core.EmulationController;
import urv.emulator.tasks.EmulationGroupMembershipListener;
import urv.emulator.tasks.EmulationMessageListener;
import urv.emulator.tasks.EmulatorTask;
import urv.emulator.tasks.GroupMembershipNotifier;
import urv.emulator.tasks.MessageNotifier;
import urv.machannel.MChannel;
import urv.util.graph.HashMapSet;
/**
* This task gathers information about all messages sent and received
* in the network by all applications
* It verifies that all nodes that were in the view of the source node
* received the multicast message
*
* @author Marcel Arrufat Arias
*/
public class CommunicationStatsTask extends EmulatorTask implements EmulationMessageListener, EmulationGroupMembershipListener{
// CLASS FIELDS --
public Hashtable<MessageIdentifier,View> sentMessages = new Hashtable <MessageIdentifier,View>();
public HashSet<MessageIdentifier> receivedMessages = new HashSet<MessageIdentifier>();
private HashMapSet<InetAddress,InetAddress> registeredMembership = new HashMapSet<InetAddress,InetAddress>();
private Object lock = new Object();
private HashSet<MessageIdentifier> removeIfMcastReceived = new HashSet<MessageIdentifier>();
//Stats info
private int ucastReceived=0;
private int ucastNotReceived=0;
private int mcastReceived=0;
private int mcastNotReceived=0;
private int partialsNotFound=0;
private int partialsFound=0;
private float resultUcast=0;
private float resultMcast=0;
private float resultMcastPartials=0;
private int numSentMessages=0;
private int numReceivedMessages=0;
// CONSTRUCTORS --
/**
* @param emulationController
*/
public CommunicationStatsTask() {
super();
}
// OVERRIDDEN METHODS --
/**
* Add the code that should be launched in the run method
*/
public void doSomething() {
//In first place, register the class as listener in order to intercept
//network messages
EmulationController controller = super.getEmulationController();
MessageNotifier messageNotifier = controller.getMessageNotifier();
messageNotifier.addMessageListener(this);
//Improved: now we will check if multicast messages are received by all
//nodes that started the channel
GroupMembershipNotifier membershipNotifier = controller.getGroupMembershipNotifier();
membershipNotifier.addGroupMembershipListener(this);
while (true){
//Rest for a little while
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
//Check all send messages have been received correctly
checkMessages();
}
}
public void onGroupCreated(InetAddress multicastAddress, InetAddress localAddress, MChannel mChannel) {
synchronized (lock) {
//Store info
registeredMembership.addToSet(multicastAddress,localAddress);
}
}
public void onMessageReceived(Message msg, InetAddress src, InetAddress mainDst, InetAddress realDst, int seqNumber){
//Maybe this lock could be removed since we are just retrieving information with
synchronized (lock) {
MessageIdentifier mid = new MessageIdentifier(src,mainDst,realDst,seqNumber);
numReceivedMessages++;
receivedMessages.add(mid);
}
}
public void onMessageSent(Message msg, InetAddress src, InetAddress dst, int seqNumber, View view) {
synchronized (lock) {
sentMessages.put(new MessageIdentifier(src,dst,dst,seqNumber),view);
numSentMessages++;
}
}
// PRIVATE METHODS --
/**
* For each sent message, checks that a received message exists
* in the receivedMessages structure
*
*/
private void checkMessages() {
synchronized (lock) {
//for (MessageIdentifier mid:){
Iterator<MessageIdentifier> it = sentMessages.keySet().iterator();
while (it.hasNext()){
MessageIdentifier mid = it.next();
//MULTICAST messages
InetAddress mainDst = mid.getMainDst();
if (mainDst.isMulticastAddress()){
//View is not used now!
View view = sentMessages.get(mid);
//For each node that the multicast was sent to
//Check if they really received the multicast message
InetAddress src = mid.getSrc();
//InetAddress realDst = mid.getRealDst();
int seqNum = mid.getSeqNumber();
boolean hasReceivedMulticast=true;
//Now we won't ask the channel view, but all the nodes that started
//a channel instead
//Clear the tmp list of message to delete
removeIfMcastReceived.clear();
for(InetAddress dstInView:registeredMembership.getSet(mainDst)){
MessageIdentifier dstMid = new MessageIdentifier(src,mainDst,dstInView,seqNum);
if (!receivedMessages.contains(dstMid)){
hasReceivedMulticast=false;
partialsNotFound++;
}else{
removeIfMcastReceived.add(dstMid);
partialsFound++;
}
}
if (hasReceivedMulticast){
mcastReceived++;
//The message was received ok, so remove the messages
//If the message was processed and we have receive it
//just substract 1 from the number of not received
if (mid.isProcessed()){
mcastNotReceived--;
}
//Remove the current sent message
it.remove();
//Remove all the messages kept in removeIfMcastReceived
for (MessageIdentifier midToRemove:removeIfMcastReceived){
receivedMessages.remove(midToRemove);
}
} else {
//if the message was not received, mark it as processed
//Just add the first time is processed as not received
if (!mid.isProcessed()){
mcastNotReceived++;
mid.setProcessed(true);
}
}
}else{
//UNICAST messages
if (receivedMessages.contains(mid)){
if (mid.isProcessed()){
ucastNotReceived--;
}
ucastReceived++;
//Remove from sent messages
it.remove();
//Remove from received
receivedMessages.remove(mid);
}else{
System.out.println("++ NO ++ Cannot find the message:"+mid);
if (!mid.isProcessed()){
ucastNotReceived++;
mid.setProcessed(true);
}
}
}
}
System.out.println("Messages received but not removed ("+receivedMessages.size()+")");
for (MessageIdentifier rcvdMsg:receivedMessages){
System.out.println("\t"+rcvdMsg);
}
System.out.println("Messages sent but not removed ("+sentMessages.size()+")");
for (MessageIdentifier sentMsg:sentMessages.keySet()){
System.out.println("\t"+sentMsg);
}
String output = "";
if ((ucastReceived+ucastNotReceived)>0)
resultUcast = 100*(float)ucastReceived/(ucastReceived+ucastNotReceived);
if ((mcastReceived+mcastNotReceived)>0)
resultMcast = 100*(float)mcastReceived/(mcastReceived+mcastNotReceived);
if ((partialsFound+partialsNotFound)>0)
resultMcastPartials = 100*(float)partialsFound/(partialsFound+partialsNotFound);
output += "#sentMgs="+numSentMessages+"\\rcvdMsgs="+numReceivedMessages+"\n";
output += "UCAST: "+ucastReceived+ " ok;"+ucastNotReceived+" ko ("+resultUcast+"%)\n";
output += "MCAST: "+mcastReceived+ " ok;"+mcastNotReceived+" ko ("+resultMcast+"%)\n";
output += "MCAST: "+partialsFound+ " partials ok;"+partialsNotFound+" partials ko ("+resultMcastPartials+"%)\n";
print(output,true);
}
}
// PRIVATE CLASSES --
private class MessageIdentifier{
// CLASS FIELDS --
private InetAddress src;
private InetAddress mainDst;
private int seqNumber;
private InetAddress realDst;
private boolean processed=false;
// CONSTRUCTORS --
/**
* @param src
* @param mainDst
* @param realDst
* @param seqNumber
*/
public MessageIdentifier(InetAddress src, InetAddress mainDst, InetAddress realDst, int seqNumber) {
this.src = src;
this.mainDst = mainDst;
this.realDst = realDst;
this.seqNumber = seqNumber;
}
// OVERRIDDEN METHODS --
public boolean equals(Object obj){
MessageIdentifier mid = (MessageIdentifier)obj;
return mid.getMainDst().equals(this.mainDst) && mid.getSrc().equals(this.src) && mid.getRealDst().equals(this.realDst)&& mid.getSeqNumber()==this.seqNumber;
}
public int hashCode(){
return src.hashCode()+mainDst.hashCode()+realDst.hashCode()+seqNumber;
}
public String toString(){
return "src:"+src+";mainDst:"+mainDst+";realDst:"+realDst+";seqNo:"+seqNumber;
}
// ACCESS METHODS --
/**
* @return Returns the mainDst.
*/
public InetAddress getMainDst() {
return mainDst;
}
/**
* @return Returns the realDst.
*/
public InetAddress getRealDst() {
return realDst;
}
/**
* @return Returns the seqNumber.
*/
public int getSeqNumber() {
return seqNumber;
}
/**
* @return Returns the src.
*/
public InetAddress getSrc() {
return src;
}
/**
* @return Returns the processed.
*/
public boolean isProcessed() {
return processed;
}
/**
* @param processed The processed to set.
*/
public void setProcessed(boolean processed) {
this.processed = processed;
}
}
}
| true
|
f728b1219dae1e0c9ca9a2b7ffb82feb3166ec04
|
Java
|
mayurtailor009/Dineplan
|
/app/src/main/java/com/dineplan/model/TicketOrderTax.java
|
UTF-8
| 834
| 2.203125
| 2
|
[] |
no_license
|
package com.dineplan.model;
import java.io.Serializable;
/**
* Created by Mayur on 24-09-2016.
*/
public class TicketOrderTax implements Serializable{
private int AT;
private int RN;
private String TN;
private float TR;
private int TT;
public int getAT() {
return AT;
}
public void setAT(int AT) {
this.AT = AT;
}
public int getRN() {
return RN;
}
public void setRN(int RN) {
this.RN = RN;
}
public String getTN() {
return TN;
}
public void setTN(String TN) {
this.TN = TN;
}
public float getTR() {
return TR;
}
public void setTR(float TR) {
this.TR = TR;
}
public int getTT() {
return TT;
}
public void setTT(int TT) {
this.TT = TT;
}
}
| true
|
864470f76c00d0ea3f96b8baca79a9caf88bfc3e
|
Java
|
uguney/Java_Assignments
|
/assignments_8_Methods/Question14_threeLocks.java
|
UTF-8
| 650
| 3.859375
| 4
|
[] |
no_license
|
package java_assignments.assignments_8_Methods;
public class Question14_threeLocks {
public static void main(String[] args) {
threeLocks(true, false, true);
}
public static void threeLocks(boolean a, boolean b, boolean c) {
if ((a == true && b == true) || (c == true)) {
System.out.println(true);
} else {
System.out.println(false);
}
}
}
/*
* Question-14
*
* This one is about truth table logic, threeLocks gets 3 booleans and returns a
* boolean.
*
* It returns true only if both a and b are true or c is true.
*
* https://en.wikipedia.org/wiki/Truth_table
*
*
*
*/
| true
|
38bf26c2a6cefdd10b4ab991ab79d5af3030a298
|
Java
|
aguther/dds-examples
|
/src/main/java/com/github/aguther/dds/routing/dynamic/command/remote/CommandBuilder.java
|
UTF-8
| 5,625
| 1.679688
| 2
|
[
"MIT"
] |
permissive
|
/*
* MIT License
*
* Copyright (c) 2018 Andreas Guther
*
* 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.
*/
package com.github.aguther.dds.routing.dynamic.command.remote;
import com.github.aguther.dds.routing.dynamic.command.DynamicPartitionCommandProvider;
import com.github.aguther.dds.routing.dynamic.observer.Session;
import com.github.aguther.dds.routing.dynamic.observer.TopicRoute;
import com.github.aguther.dds.routing.util.RoutingServiceCommandInterface;
import idl.RTI.RoutingService.Administration.CommandKind;
import idl.RTI.RoutingService.Administration.CommandRequest;
class CommandBuilder {
private final RoutingServiceCommandInterface routingServiceCommandInterface;
private final String targetRoutingService;
private final DynamicPartitionCommandProvider provider;
CommandBuilder(
RoutingServiceCommandInterface routingServiceCommandInterface,
String targetRoutingService,
DynamicPartitionCommandProvider dynamicPartitionCommandProvider
) {
this.routingServiceCommandInterface = routingServiceCommandInterface;
this.targetRoutingService = targetRoutingService;
this.provider = dynamicPartitionCommandProvider;
}
Command buildCreateSessionCommand(
Session session
) {
// create request
CommandRequest commandRequest = routingServiceCommandInterface.createCommandRequest();
commandRequest.target_router = targetRoutingService;
commandRequest.command._d = CommandKind.RTI_ROUTING_SERVICE_COMMAND_CREATE;
commandRequest.command.entity_desc.name = provider.getSessionParent(session);
commandRequest.command.entity_desc.xml_url.is_final = true;
commandRequest.command.entity_desc.xml_url.content = provider.getSessionConfiguration(session);
// create and return command
return new Command(
CommandType.COMMAND_TYPE_CREATE,
session,
null,
commandRequest,
String.format(
"entity='Session', topic='%s', partition='%s'",
session.getTopic(),
session.getPartition()
)
);
}
Command buildDeleteSessionCommand(
Session session
) {
// create request
CommandRequest commandRequest = routingServiceCommandInterface.createCommandRequest();
commandRequest.target_router = targetRoutingService;
commandRequest.command._d = CommandKind.RTI_ROUTING_SERVICE_COMMAND_DELETE;
commandRequest.command.entity_name = provider.getSessionEntityName(session);
// create and return command
return new Command(
CommandType.COMMAND_TYPE_DELETE,
session,
null,
commandRequest,
String.format(
"entity='Session', topic='%s', partition='%s'",
session.getTopic(),
session.getPartition()
)
);
}
Command buildCreateTopicRouteCommand(
Session session,
TopicRoute topicRoute
) {
// create request
CommandRequest commandRequest = routingServiceCommandInterface.createCommandRequest();
commandRequest.target_router = targetRoutingService;
commandRequest.command._d = CommandKind.RTI_ROUTING_SERVICE_COMMAND_CREATE;
commandRequest.command.entity_desc.name = provider.getSessionEntityName(session);
commandRequest.command.entity_desc.xml_url.is_final = true;
commandRequest.command.entity_desc.xml_url.content = provider.getTopicRouteConfiguration(session, topicRoute);
// create and return command
return new Command(
CommandType.COMMAND_TYPE_CREATE,
session,
topicRoute,
commandRequest,
String.format(
"entity='TopicRoute', topic='%s', type='%s', partition='%s', direction='%s'",
session.getTopic(),
topicRoute.getType(),
session.getPartition(),
topicRoute.getDirection().toString()
)
);
}
Command buildDeleteTopicRouteCommand(
Session session,
TopicRoute topicRoute
) {
// create request
CommandRequest commandRequest = routingServiceCommandInterface.createCommandRequest();
commandRequest.target_router = targetRoutingService;
commandRequest.command._d = CommandKind.RTI_ROUTING_SERVICE_COMMAND_DELETE;
commandRequest.command.entity_name = provider.getTopicRouteEntityName(session, topicRoute);
// create and return command
return new Command(
CommandType.COMMAND_TYPE_DELETE,
session,
topicRoute,
commandRequest,
String.format(
"entity='TopicRoute', topic='%s', type='%s', partition='%s', direction='%s'",
session.getTopic(),
topicRoute.getType(),
session.getPartition(),
topicRoute.getDirection().toString()
)
);
}
}
| true
|
b7716b4a8168f9bd4cadf35078629e33f1b9edd1
|
Java
|
mizech/udacity-android-basics-nanodegree
|
/InventoryApp/app/src/main/java/michael/example/com/inventoryapp/data/ProductInventoryContract.java
|
UTF-8
| 918
| 2.140625
| 2
|
[] |
no_license
|
package michael.example.com.inventoryapp.data;
import android.net.Uri;
import android.provider.BaseColumns;
public class ProductInventoryContract {
public static final String PATH_PREFIX = "michael.example.com.inventoryapp";
public static final Uri URI_PREFIX = Uri.parse("content://" + PATH_PREFIX);
public static final String RESOURCE = "products";
public static final class ProductItem implements BaseColumns {
public static final Uri FULL_URI = Uri.withAppendedPath(URI_PREFIX, RESOURCE);
public final static String TABLE_NAME = "products";
public final static String PRODUCT_NAME = "product_name";
public final static String PRICE = "price";
public final static String QUANTITY = "quantity";
public final static String SUPPLIER_NAME = "supplier_name";
public final static String SUPPLIER_PHONE_NUMBER = "supplier_phone_number";
}
}
| true
|
20f37ad3f5290e30df791dfa8bbdc677b7cae20e
|
Java
|
TaoLeeyu/java-file-sync
|
/starwifi-common/src/main/java/com/treebear/starwifi/common/ErrorCode.java
|
UTF-8
| 298
| 1.945313
| 2
|
[] |
no_license
|
package com.treebear.starwifi.common;
/**
* 错误码接口.<br>
*
*
*/
public interface ErrorCode {
/**
* 获取错误码
*
* @return
*/
public String getCode();
/**
* 获取错误描述
*
* @return
*/
public String getDescription();
}
| true
|
5b32c85f9cf5b6c860f20506aafc9e9520f1f267
|
Java
|
winstone/repository
|
/src/cn/org/act/sdp/bpmnRepository/portal/util/LoginCheck.java
|
UTF-8
| 777
| 2.25
| 2
|
[] |
no_license
|
package cn.org.act.sdp.bpmnRepository.portal.util;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import cn.org.act.sdp.bpmnRepository.entity.UserBean;
import cn.org.act.sdp.bpmnRepository.portal.constants.Message;
public class LoginCheck {
static public boolean isLogin(HttpServletRequest request,
HttpServletResponse response) throws IOException, ServletException {
UserBean user = (UserBean) request.getSession().getAttribute("user");
if (user == null) {
request.setAttribute("msg", Message.MSG_NO_LOGIN);
request.getRequestDispatcher("login_register.jsp").forward(request,
response);
return false;
} else {
return true;
}
}
}
| true
|
54691e106721841d49255c444f78fac1a9d66e57
|
Java
|
gustavotsuji/shortener-challenge
|
/src/test/java/com/neueda/challenge/shortenerUrl/util/Base62ConverterTest.java
|
UTF-8
| 2,026
| 2.28125
| 2
|
[] |
no_license
|
package com.neueda.challenge.shortenerUrl.util;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import org.springframework.boot.test.context.SpringBootTest;
import org.powermock.reflect.Whitebox;
import static org.junit.Assert.assertEquals;
@SpringBootTest
@RunWith(PowerMockRunner.class)
@PrepareForTest(Base62Converter.class)
public class Base62ConverterTest {
@Mock
Base62Converter encoder;
@Before
public void setUp() {
encoder = new Base62Converter();
}
@Test
public void testEncode0() throws Exception {
String result = Whitebox.invokeMethod(encoder,
"mapNumberToCharacter", 0l);
assertEquals("0", result);
}
@Test
public void testEncode10() throws Exception {
String result = Whitebox.invokeMethod(encoder,
"mapNumberToCharacter", 10l);
assertEquals("A", result);
}
@Test
public void testEncode37() throws Exception {
String result = Whitebox.invokeMethod(encoder,
"mapNumberToCharacter",36l);
assertEquals("a", result);
}
@Test
public void testEncode62() throws Exception {
String result = encoder.encode(62l);
assertEquals("10", result);
}
@Test
public void testEncode3846() throws Exception {
String result = encoder.encode(3846l);
assertEquals("102", result);
}
@Test
public void testDecode0() throws Exception {
long result = encoder.decode("0");
assertEquals(0l, result);
}
@Test
public void testDecode62() throws Exception {
long result = encoder.decode("10");
assertEquals(62l, result);
}
@Test
public void testDecode10a() throws Exception {
long result = encoder.decode("10a");
assertEquals(3880l, result);
}
}
| true
|
be8941239e107011de14d2a42401c8e754278bb1
|
Java
|
jishankai/pet
|
/native/android/Pet/src/com/aidigame/hisun/imengstar/widget/fragment/DialogNote.java
|
UTF-8
| 6,006
| 2.03125
| 2
|
[] |
no_license
|
package com.aidigame.hisun.imengstar.widget.fragment;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.MeasureSpec;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.PopupWindow;
import android.widget.Toast;
import android.widget.PopupWindow.OnDismissListener;
import android.widget.TextView;
import com.aidigame.hisun.imengstar.PetApplication;
import com.aidigame.hisun.imengstar.bean.Animal;
import com.aidigame.hisun.imengstar.constant.Constants;
import com.aidigame.hisun.imengstar.http.HttpUtil;
import com.aidigame.hisun.imengstar.ui.ChoseAcountTypeActivity;
import com.aidigame.hisun.imengstar.R;
/**
* 用户是否注册弹窗
* @author admin
*
*/
public class DialogNote {
View parent,view;
Activity context;
PopupWindow popupWindow;
View blackView;
int mode=0;//0,注册提示;1,加入王国超过10个提示,金币不足;2,取消关注提示;3,使用邀请码超过十个,4加入王国超过10个提示,消耗金币
TextView tv1,tv2,tv3,tv4,noteTv;
Animal animal;//取消关注的宠物
ResultListener listener;
public DialogNote(View parent,Activity context,View blackView,int mode){
this.parent=parent;
this.context=context;
this.blackView=blackView;
this.mode=mode;
initView();
}
private void initView() {
// TODO Auto-generated method stub
view=LayoutInflater.from(context).inflate(R.layout.popup_dialog_go_register, null);
popupWindow=new PopupWindow(view, ViewGroup.LayoutParams.WRAP_CONTENT,ViewGroup.LayoutParams.WRAP_CONTENT);
popupWindow.setFocusable(true);
popupWindow.setBackgroundDrawable(new BitmapDrawable());
popupWindow.setOutsideTouchable(true);
view.measure(MeasureSpec.UNSPECIFIED, MeasureSpec.UNSPECIFIED);
int[] location=new int[2];
parent.getLocationInWindow(location);
blackView.setBackgroundResource(R.color.window_black_bagd);
popupWindow.showAsDropDown(parent, location[0]+parent.getWidth()/2-view.getMeasuredWidth()/2, -view.getMeasuredHeight()/2);
view.findViewById(R.id.imageView1).setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
popupWindow.dismiss();
blackView.setBackgroundDrawable(null);
}
});
tv1=(TextView)view.findViewById(R.id.textView1);
tv2=(TextView)view.findViewById(R.id.textView2);
tv3=(TextView)view.findViewById(R.id.textView3);
noteTv=(TextView)view.findViewById(R.id.note_tv);
tv4=(TextView)view.findViewById(R.id.textView4);
tv4.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(mode==0||mode==4){
Intent intent=new Intent(context,ChoseAcountTypeActivity.class);
if(mode==4){
intent.putExtra("from", 1);
}
context.startActivity(intent);
}
//取消关注
if(mode==2){
deleteFocus();
}
popupWindow.dismiss();
}
});
popupWindow.setOnDismissListener(new OnDismissListener() {
@Override
public void onDismiss() {
// TODO Auto-generated method stub
blackView.setBackgroundDrawable(null);
}
});
switch (mode) {
case 1:
joinKingdomNote();
break;
case 2:
cancelFocus();
break;
case 3:
joinKingdomNote2();
break;
case 4:
joinKingdomNote3();
break;
}
}
/**
* 需要被取消关注的宠物
* @param animal
*/
public void setAnimal(Animal animal){
this.animal=animal;
}
/**
* 加入王国超过10个弹窗提示
*/
private void joinKingdomNote(){
tv1.setText("本次成功捧星或创建萌星");
int num=0;
if(PetApplication.myUser.aniList.size()>=10&&PetApplication.myUser.aniList.size()<=20){
num=(PetApplication.myUser.aniList.size()+1)*5;
}else{
num=100;
}
tv2.setText("需要消耗"+num+"金币哦~");
tv3.setText("您的余额不足~");
tv4.setText("哎~好吧");
}
private void joinKingdomNote3(){
tv1.setText("本次成功捧星或创建萌星");
int num=0;
if(PetApplication.myUser.aniList.size()>=10&&PetApplication.myUser.aniList.size()<=20){
num=(PetApplication.myUser.aniList.size()+1)*5;
}else{
num=100;
}
tv2.setText("需要消耗"+num+"金币哦~");
tv3.setText("您的余额不足~");
tv3.setVisibility(View.GONE);
tv4.setText("没问题");
}
/**
* 使用邀请码 超过十个
*/
private void joinKingdomNote2(){
tv1.setText("暂不能使用邀请码~");
tv2.setText("星球法则是最多捧10个萌星~");
tv3.setText("专一点嘛~");
tv4.setText("哎~好吧");
}
/**
* 取消关注弹窗提示
*/
private void cancelFocus(){
tv1.setText("亲爱的真的忍心取消关注我么?");
tv2.setText("这是真的么~");
tv3.setText("是么~");
tv4.setText("额~是的");
}
/**
* 取消关注
*/
private void deleteFocus(){
if(animal!=null){
new Thread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
final boolean flag=HttpUtil.userDeleteFollow(animal, null,context);
context.runOnUiThread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
if(flag){
animal.is_follow=false;
Toast.makeText(context, "取消关注成功", Toast.LENGTH_SHORT).show();
animal.is_follow=false;
animal.followers--;
if(listener!=null){
listener.getResult(true);
}
}else{
// * 取消关注失败
Toast.makeText(context, "取消关注失败", Toast.LENGTH_SHORT).show();
}
}
});
}
}).start();
}
}
public void setListener(ResultListener listener){
this.listener=listener;
}
public static interface ResultListener{
void getResult(boolean isSuccess);
}
}
| true
|
39b78db125f412ac8fca9d2eed0ccd777a19a039
|
Java
|
zongzhibin1107/rabbitmq_demo
|
/tuling-rabbitmq/rabbitmq-elegant/src/main/java/com/zxkj/ack_nack/AckNackRabbitmqConsumer.java
|
UTF-8
| 1,253
| 2.34375
| 2
|
[] |
no_license
|
package com.zxkj.ack_nack;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import java.io.IOException;
import java.util.concurrent.TimeoutException;
public class AckNackRabbitmqConsumer {
public static void main(String[] args) throws IOException, TimeoutException {
ConnectionFactory connectionFactory = new ConnectionFactory();
connectionFactory.setHost("112.35.144.201");
connectionFactory.setPort(5672);
connectionFactory.setVirtualHost("/");
connectionFactory.setUsername("smlz");
connectionFactory.setPassword("smlz");
Connection connection = connectionFactory.newConnection();
Channel channel = connection.createChannel();
String exchangeName = "tuling.ack.direct";
String exchangeType = "direct";
String queueName = "tuling.ack.queue";
String routingKey = "tuling.ack.key";
channel.exchangeDeclare(exchangeName,exchangeType,true,true,null);
channel.queueDeclare(queueName,true,false,true,null);
channel.queueBind(queueName,exchangeName,routingKey);
channel.basicConsume(queueName,false,new TulingAckConsumer(channel));
}
}
| true
|
80b5a5c3326435d39db480235be383a5588ab794
|
Java
|
JNM-2T17/SystemScape_CODE
|
/src/view/Button.java
|
UTF-8
| 1,562
| 2.828125
| 3
|
[] |
no_license
|
package view;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Image;
import javax.swing.ImageIcon;
import javax.swing.JButton;
public class Button extends JButton {
private Button(ButtonBuilder specs) {
super();
this.setText(specs.text);
this.setIcon(specs.img);
if (specs.clr != null)
this.setBackground(specs.clr);
this.setContentAreaFilled(false);
this.setBorderPainted(false);
if(specs.text.equals("")&&specs.img!=null){
this.setPreferredSize(new Dimension(this.getIcon().getIconWidth()+10, this.getIcon().getIconHeight()));
}
}
public static class ButtonBuilder {
private ImageIcon img;
private String text;
private Color clr;
public ButtonBuilder() {
text="";
clr = null;
img = null;
}
public ButtonBuilder img(String path, int height, int width) {
img = new ImageIcon(getClass().getResource(path));
Image image = img.getImage();
Image newimg = image.getScaledInstance(width, height,
java.awt.Image.SCALE_SMOOTH);
img = new ImageIcon(newimg);
return this;
}
public ButtonBuilder img(String path, double d) {
img = new ImageIcon(getClass().getResource(path));
Image image = img.getImage();
Image newimg = image.getScaledInstance(
(int) (img.getIconWidth() * d),
(int) (img.getIconHeight() * d),
java.awt.Image.SCALE_SMOOTH);
img = new ImageIcon(newimg);
return this;
}
public ButtonBuilder text(String text) {
this.text = text;
return this;
}
public Button build() {
return new Button(this);
}
}
}
//
| true
|
700256605ee48fe275bf6fc3fa51602efafb14bd
|
Java
|
SaqibSayed/Vehicle-Loan
|
/SpringMVC/src/main/java/com/aditi/dao/AdminDao.java
|
UTF-8
| 232
| 1.671875
| 2
|
[] |
no_license
|
package com.aditi.dao;
import java.util.List;
import com.aditi.model.Admin;
import com.aditi.model.UserDetails;
public interface AdminDao {
Admin checkPassword(int adminLoginId);
List<UserDetails> fetchUser(String status);
}
| true
|
9c557e65071c6ce3f05df582fad0abcc45803167
|
Java
|
jiangzhonghui/android-radio-t
|
/Radio-T-Test/src/org/dandelion/radiot/accepttest/testables/FakeStatusDisplayer.java
|
UTF-8
| 579
| 2.109375
| 2
|
[] |
no_license
|
package org.dandelion.radiot.accepttest.testables;
import org.dandelion.radiot.live.core.LiveShowState;
import org.dandelion.radiot.live.core.LiveShowStateListener;
import static junit.framework.Assert.assertEquals;
public class FakeStatusDisplayer implements LiveShowStateListener {
private LiveShowState currentState;
public void showsStatusFor(LiveShowState expected) {
assertEquals("Notified status", expected, currentState);
}
@Override
public void onStateChanged(LiveShowState state, long timestamp) {
currentState = state;
}
}
| true
|
ab239edde27d770736d2c585a4da7e4d47705e49
|
Java
|
edinhogomes/CaelumFJ16
|
/src/test/java/br/com/caelum/argentum/reader/CandlestickFactoryTest.java
|
UTF-8
| 3,791
| 3.171875
| 3
|
[] |
no_license
|
package br.com.caelum.argentum.reader;
import java.util.ArrayList;
import java.util.Calendar;
import org.junit.Test;
import junit.framework.Assert;
import br.com.caelum.argentum.*;
public class CandlestickFactoryTest {
@Test
public void sequenciaSimplesDeNegocios() {
Calendar hoje = Calendar.getInstance();
Negocio negocio1 = new Negocio(40.5,100, hoje);
Negocio negocio2 = new Negocio(45.0,100, hoje);
Negocio negocio3 = new Negocio(39.8,100, hoje);
Negocio negocio4 = new Negocio(42.3,100, hoje);
ArrayList<Negocio> negocios = new ArrayList<Negocio>();
negocios.add(negocio1);
negocios.add(negocio2);
negocios.add(negocio3);
negocios.add(negocio4);
CandlestickFactory fabrica = new CandlestickFactory();
Candlestick candle = fabrica.constroiCandleParaData(hoje, negocios);
Assert.assertEquals(40.5, candle.getAbertura(), 0.00001);
Assert.assertEquals(42.3, candle.getFechamento(), 0.00001);
Assert.assertEquals(39.8, candle.getMinimo(), 0.00001);
Assert.assertEquals(45.0, candle.getMaximo(), 0.00001);
Assert.assertEquals(16760.0, candle.getVolume(), 0.00001);
}
@Test(expected = IndexOutOfBoundsException.class)
public void semNegociosGeraCandleComZeros(){
Calendar hoje = Calendar.getInstance();
ArrayList<Negocio> negocios = new ArrayList<Negocio>();
CandlestickFactory fabrica = new CandlestickFactory();
Candlestick candle = fabrica.constroiCandleParaData(hoje, negocios);
Assert.assertEquals(0.0, candle.getVolume(), 0.00001);
Assert.assertEquals(0.0, candle.getAbertura(), 0.00001);
Assert.assertEquals(0.0, candle.getFechamento(), 0.00001);
Assert.assertEquals(0.0, candle.getMinimo(), 0.00001);
Assert.assertEquals(0.0, candle.getMaximo(), 0.00001);
}
@Test
public void apenasUmNegocioGeraCandleComValoresIguais() {
Calendar hoje = Calendar.getInstance();
Negocio negocio1 = new Negocio(40.5, 100, hoje);
ArrayList<Negocio> negocios = new ArrayList<Negocio>();
negocios.add(negocio1);
CandlestickFactory fabrica = new CandlestickFactory();
Candlestick candle = fabrica.constroiCandleParaData(hoje, negocios);
Assert.assertEquals(40.5, candle.getAbertura(), 0.00001);
Assert.assertEquals(40.5, candle.getFechamento(), 0.00001);
Assert.assertEquals(40.5, candle.getMinimo(), 0.00001);
Assert.assertEquals(40.5, candle.getMaximo(), 0.00001);
Assert.assertEquals(4050.0, candle.getVolume(), 0.00001);
}
@Test
public void CandlestickTest(){
}
@Test
public void testaOrdemCrescenteDeNegocios(){
Calendar hoje = Calendar.getInstance();
Negocio negocio1 = new Negocio(10, 100, hoje);
Negocio negocio2 = new Negocio(20, 100, hoje);
Negocio negocio3 = new Negocio(20.5, 100, hoje);
ArrayList<Negocio> negocios1 = new ArrayList<Negocio>();
negocios1.add(negocio1);
negocios1.add(negocio2);
negocios1.add(negocio3);
ArrayList<Negocio> negocios2 = new ArrayList<Negocio>();
negocios2.add(negocio2);
negocios2.add(negocio3);
negocios2.add(negocio1);
CandlestickFactory.negociosEmOrdemCrescenteDeValor(negocios2);
Assert.assertEquals(negocios1, negocios2);
}
@Test
public void testaOrdemDecrescenteDeNegocios(){
Calendar hoje = Calendar.getInstance();
Negocio negocio1 = new Negocio(20.5, 100, hoje);
Negocio negocio2 = new Negocio(20, 100, hoje);
Negocio negocio3 = new Negocio(10, 100, hoje);
ArrayList<Negocio> negocios1 = new ArrayList<Negocio>();
negocios1.add(negocio1);
negocios1.add(negocio2);
negocios1.add(negocio3);
ArrayList<Negocio> negocios2 = new ArrayList<Negocio>();
negocios2.add(negocio2);
negocios2.add(negocio3);
negocios2.add(negocio1);
CandlestickFactory.negociosEmOrdemDecrescenteDeValor(negocios2);
Assert.assertEquals(negocios1, negocios2);
}
}
| true
|
e93efeaf6dbffc3ad5d541b0b139ad58380f8783
|
Java
|
izaopan/VehicleAll
|
/vehicle-monitor-system/data-generator/src/main/java/com/data/generator/VehicleInfoRequest.java
|
UTF-8
| 224
| 2.078125
| 2
|
[] |
no_license
|
package com.data.generator;
public class VehicleInfoRequest {
private String vehicleId;
public VehicleInfoRequest(){}
public VehicleInfoRequest(String vehicleId) {
this.vehicleId = vehicleId;
}
}
| true
|
916bd657e5c7e02d421002c3d78f8837fc40fcc0
|
Java
|
belaidseif/java
|
/src/classe/Couple.java
|
UTF-8
| 2,184
| 2.890625
| 3
|
[] |
no_license
|
package classe;
import enseignant.Enseignant;
import matiere.Matiere;
public class Couple {
private Matiere matiere1;
private Matiere matiere2;
private Enseignant enseignant1;
private Enseignant enseignant2;
public boolean isDifferent = false;
private int heureustique;
public int getHeureustique() {
if(!isDifferent)
return matiere1.getHeureustique();
else
return 0;
}
public int getHeureustique2() {
if(!isDifferent)
return matiere1.getHeureustique2();
else
return 0;
}
public Enseignant getEnseignant1() {
return enseignant1;
}
public void setEnseignant1(Enseignant enseignant1) {
this.enseignant1 = enseignant1;
}
public Enseignant getEnseignant2() {
return enseignant2;
}
public void setEnseignant2(Enseignant enseignant2) {
this.enseignant2 = enseignant2;
}
public Couple() {
super();
}
public Matiere getMatiere1() {
return matiere1;
}
public void setMatiere1(Matiere matiere1) {
this.matiere1 = matiere1;
}
public Matiere getMatiere2() {
return matiere2;
}
public void setMatiere2(Matiere matiere2) {
this.matiere2 = matiere2;
}
public static Couple twice(Matiere m) {
return new Couple(m, m);
}
public boolean setOne(Matiere m) {
if(matiere1 == null) {
matiere1 = m;
isDifferent = true;
return true;
}else if(matiere2 == null) {
matiere2 = m;
isDifferent = true;
return true;
}else
return false;
}
private Couple(Matiere matiere1, Matiere matiere2) {
super();
this.matiere1 = matiere1;
this.matiere2 = matiere2;
}
@Override
public String toString() {
return ""+matiere1+" "+enseignant1+" "+matiere2+" "+enseignant2;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((matiere1 == null) ? 0 : matiere1.hashCode());
result = prime * result + ((matiere2 == null) ? 0 : matiere2.hashCode());
return result;
}
@Override//matiere 1 et matiere 2
public boolean equals(Object obj) {
Couple other = (Couple)obj;
if(other.getMatiere1().getName().equals(this.getMatiere1().getName())&&other.getMatiere2().equals(this.getMatiere2()))
return true;
return false;
}
}
| true
|
fe6178e5b807683dda9d19d05fff48933648d95a
|
Java
|
dadsf456/MyAndroidSDK
|
/app/src/main/java/com/example/myandroidsdk/ui/activity/PopupActivity.java
|
UTF-8
| 4,361
| 2.3125
| 2
|
[] |
no_license
|
package com.example.myandroidsdk.ui.activity;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import com.example.myandroidsdk.R;
import com.tool.cs.common.popup.CommonPopupWindow;
import com.tool.cs.common.utils.ScreenUtils;
import butterknife.OnClick;
public class PopupActivity extends BaseSecondActivity implements CommonPopupWindow.ViewInterface {
private CommonPopupWindow popup;
@Override
protected String getBarTitleText() {
return "popupDemo";
}
@Override
protected int createContent() {
return R.layout.activity_popup;
}
@Override
protected void initView() {
super.initView();
showPopup();
}
private void showPopup() {
if (popup != null && popup.isShowing())
return;
popup = new CommonPopupWindow.Builder(this)
.setView(R.layout.popup_address_select)
.setWidthAndHeight(ViewGroup.LayoutParams.MATCH_PARENT,
(int) (ScreenUtils.getScreenHeight(this) * 0.3f))
.setOutsideTouchable(true)
.setViewOnclickListener(this)
.create();
// popup.showAtLocation(findViewById(android.R.id.content), Gravity.TOP, 0, 0);
}
/**
* 小一点的布局
*/
private void showMixPopup() {
if (popup != null && popup.isShowing())
return;
popup = new CommonPopupWindow.Builder(this)
.setView(R.layout.popup_address_select)
.setWidthAndHeight(180,
90)
.setOutsideTouchable(true)
.setViewOnclickListener(this)
.create();
// popup.showAtLocation(findViewById(android.R.id.content), Gravity.TOP, 0, 0);
}
@Override
public void getChildView(View view, int layoutResId) {
view.findViewById(R.id.btn_close).setOnClickListener(v -> popup.dismiss());
}
@OnClick({R.id.bt_top, R.id.bt_left, R.id.bt_down, R.id.bt_right, R.id.bt_center,R.id.bt_top1,R.id.bt_top2})
public void onViewClicked(View view) {
switch (view.getId()) {
case R.id.bt_top:
popup.setAnimationStyle(R.style.top_down_anim);
popup.showAtLocation(findViewById(android.R.id.content), Gravity.TOP, 0, 0);
break;
case R.id.bt_left:
popup.setAnimationStyle(R.style.left_right_anim);
popup.showAtLocation(findViewById(android.R.id.content), Gravity.LEFT, 0, 0);
break;
case R.id.bt_down:
popup.setAnimationStyle(R.style.down_top_anim);
popup.showAtLocation(findViewById(android.R.id.content), Gravity.BOTTOM, 0, 0);
break;
case R.id.bt_right:
popup.setAnimationStyle(R.style.right_left_anim);
popup.showAtLocation(findViewById(android.R.id.content), Gravity.RIGHT, 0, 0);
break;
case R.id.bt_center:
popup.setAnimationStyle(R.style.scale_center_anim);
// popup.showAtLocation(findViewById(android.R.id.content), Gravity.CENTER, ScreenUtils.getScreenWidth(this)/2, ScreenUtils.getScreenHeight(this)/2);
// popup.showAsDropDown(view);
popup.showAtLocation(findViewById(android.R.id.content),Gravity.CENTER,0,0);
break;
case R.id.bt_top1:
// popup测量 布局中match warp无效的
int[] position = new int[2];
view.getLocationOnScreen(position);
popup.setAnimationStyle(R.style.scale_down_up_anim);
popup.showAtLocation(view, Gravity.NO_GRAVITY, 0,position[1]+view.getMeasuredHeight());
break;
case R.id.bt_top2:
//PopupWindow小坑:无论偏移多大,不会跑出屏幕
// popup测量 布局中match warp无效的
int[] position1 = new int[2];
view.getLocationOnScreen(position1);
showMixPopup();
popup.setAnimationStyle(R.style.scale_lefr_right_anim);
popup.showAtLocation(view, Gravity.NO_GRAVITY, position1[0]+view.getMeasuredWidth(),position1[1]);
break;
}
}
}
| true
|
3d7b0943b6c3c8c3a61cec9fa95f213b48ee8499
|
Java
|
kenny2892/Harmony
|
/Harmony/src/server_application/Room.java
|
UTF-8
| 3,580
| 2.96875
| 3
|
[] |
no_license
|
package server_application;
import java.nio.channels.SocketChannel;
import java.util.ArrayList;
public class Room
{
private ArrayList<ClientData> clients;
public Room()
{
clients = new ArrayList<ClientData>();
}
public ClientData findClientByUsername(String usernameToFind)
{
for(int i = 0; i < clients.size(); i++)
{
ClientData client = clients.get(i);
if(usernameToFind.compareTo(client.getUsername()) == 0)
return client;
}
return null;
}
public ClientData findClientBySocket(SocketChannel socketChannel)
{
for(int i = 0; i < clients.size(); i++)
{
ClientData client = clients.get(i);
if(socketChannel.equals(client.getSocketChannel()))
return client;
}
return null;
}
public boolean addClient(ClientData client)
{
if(client == null)
throw new IllegalArgumentException("Client is null.");
boolean canAdd = true;
for(ClientData toCheck : clients)
{
if(toCheck.getIp().compareTo(client.getIp()) == 0)
canAdd = false;
if(toCheck.getUsername().compareTo(client.getUsername()) == 0)
canAdd = false;
if(toCheck.getSocketChannel().equals(client.getSocketChannel()))
canAdd = false;
if(!canAdd)
break;
}
if(canAdd)
clients.add(client);
return canAdd;
}
public boolean removeClient(String username)
{
if(username == null)
throw new IllegalArgumentException("Username is null.");
int index = -1;
for(int i = 0; i < clients.size(); i++)
{
ClientData client = clients.get(i);
if(username.compareTo(client.getUsername()) == 0)
{
index = i;
break;
}
}
if(index > -1)
{
clients.remove(index);
return true;
}
return false;
}
public boolean removeClient(SocketChannel socketChannel)
{
if(socketChannel == null)
throw new IllegalArgumentException("Socket Channel is null.");
int index = -1;
for(int i = 0; i < clients.size(); i++)
{
ClientData client = clients.get(i);
if(socketChannel.equals(client.getSocketChannel()))
{
index = i;
break;
}
}
if(index > -1)
{
clients.remove(index);
return true;
}
return false;
}
public boolean containsClientBySocketChannel(SocketChannel socketChannel)
{
return findClientBySocket(socketChannel) != null;
}
public ArrayList<ClientData> getClientList()
{
return clients;
}
public void updateColor(SocketChannel socketChannel, String color)
{
if(socketChannel == null)
throw new IllegalArgumentException("Socket Channel is null.");
else if(color == null)
throw new IllegalArgumentException("Color is null.");
for(ClientData client : clients)
{
if(client.getSocketChannel().equals(socketChannel))
{
client.setColor(color);
break;
}
}
}
public void updateIconID(SocketChannel socketChannel, String iconID)
{
if(socketChannel == null)
throw new IllegalArgumentException("Socket Channel is null.");
else if(iconID == null)
throw new IllegalArgumentException("iconID is null.");
for(ClientData client : clients)
{
if(client.getSocketChannel().equals(socketChannel))
{
client.setIconID(iconID);
break;
}
}
}
@Override
public boolean equals(Object obj)
{
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Room other = (Room) obj;
if (clients == null)
{
if (other.clients != null)
return false;
}
else if (!clients.equals(other.clients))
return false;
return true;
}
}
| true
|
15d55a1f5d0f0dee8fe8142f2f42e70b94c47b78
|
Java
|
diss12/MLMCPlugins
|
/NeoProfessions/src/me/Neoblade298/NeoProfessions/Utilities/CulinarianUtils.java
|
UTF-8
| 12,053
| 2.75
| 3
|
[] |
no_license
|
package me.Neoblade298.NeoProfessions.Utilities;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Random;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.PlayerInventory;
import org.bukkit.potion.PotionEffect;
import org.bukkit.potion.PotionEffectType;
import net.milkbowl.vault.economy.Economy;
public class CulinarianUtils {
static final int CRAFT_COST = 5;
static Random gen = new Random();
Util util;
public CulinarianUtils() {
util = new Util();
}
public void checkAlcoholUp(Player p, int amount, HashMap<Player, Integer> drunkness) {
if(amount >= 30 && amount < 50) {
p.addPotionEffect(new PotionEffect(PotionEffectType.CONFUSION, 30*20, 0), true);
util.sendMessage(p, "&7You are now &esomewhat drunk&7 (" + amount + "/100).");
}
else if(amount >= 50 && amount < 70) {
p.addPotionEffect(new PotionEffect(PotionEffectType.BLINDNESS, 10*20, 0), true);
p.addPotionEffect(new PotionEffect(PotionEffectType.CONFUSION, 60*20, 0), true);
util.sendMessage(p, "&7You are now &6very drunk&7 (" + amount + "/100).");
}
else if(amount >= 70 && amount < 100) {
p.addPotionEffect(new PotionEffect(PotionEffectType.WITHER, 10*20, 0), true);
p.addPotionEffect(new PotionEffect(PotionEffectType.BLINDNESS, 20*20, 0), true);
p.addPotionEffect(new PotionEffect(PotionEffectType.CONFUSION, 60*20, 0), true);
util.sendMessage(p, "&7You are now &4dangerously drunk&7. (" + amount + "/100).");
}
else if(amount > 100) {
double chance = gen.nextDouble();
if(chance >= 0.5) {
util.sendMessage(p, "&7You throw up from being too drunk. Your drunkness is reduced to &6very drunk&7 (50/100).");
drunkness.put(p, 50);
}
else {
util.sendMessage(p, "&7You become too drunk and lose 80% of your current health.");
p.damage(1);
p.setHealth(p.getHealth() * 0.2);
drunkness.put(p, 100);
}
}
else {
util.sendMessage(p, "&7You drink&7 (" + amount + "/100).");
}
}
public void checkAlcoholDown(Player p, int amount) {
if(amount == 0) {
util.sendMessage(p, "&7You are completely sober&7 (0/100).");
}
else if(amount == 29) {
util.sendMessage(p, "&7Your drunkness is reduced to &fsober&7 (29/100).");
}
else if(amount == 49) {
p.addPotionEffect(new PotionEffect(PotionEffectType.CONFUSION, 30*20, 0), true);
util.sendMessage(p, "&7Your drunkness is reduced to &esomewhat drunk&7 (49/100).");
}
else if(amount == 69) {
p.addPotionEffect(new PotionEffect(PotionEffectType.BLINDNESS, 10*20, 0), true);
p.addPotionEffect(new PotionEffect(PotionEffectType.CONFUSION, 60*20, 0), true);
util.sendMessage(p, "&7Your drunkness is reduced to &6very drunk&7 (69/100).");
}
}
public int getRecipeLevel(ItemStack item) {
if(item.hasItemMeta() && item.getItemMeta().hasLore()) {
String line = item.getItemMeta().getLore().get(0);
if(line.contains("Tier 1") || line.contains("Ingredient")) {
return 1;
}
else if(line.contains("Tier 2")) {
return 2;
}
else if(line.contains("Tier 3") || line.contains("Drink")) {
return 3;
}
else if(line.contains("Limited Edition") || line.contains("Legendary")) {
return 4;
}
}
return -1;
}
public int getTotalLeaves(ItemStack[] contents) {
int total = 0;
for(ItemStack content : contents) {
if(content != null) {
if(content.isSimilar(new ItemStack(Material.LEAVES)) ||
content.isSimilar(util.setData(new ItemStack(Material.LEAVES), 1)) ||
content.isSimilar(util.setData(new ItemStack(Material.LEAVES), 2)) ||
content.isSimilar(util.setData(new ItemStack(Material.LEAVES), 3)) ||
content.isSimilar(new ItemStack(Material.LEAVES_2)) ||
content.isSimilar(util.setData(new ItemStack(Material.LEAVES_2), 1))) {
total += content.getAmount();
}
}
}
return total;
}
public void removeLeaves(PlayerInventory inv, int amount) {
ItemStack[] contents = inv.getStorageContents();
int slotNum = 0;
for(ItemStack content : contents) {
if(amount <= 0) {
return;
}
if(content != null) {
if(content.isSimilar(new ItemStack(Material.LEAVES)) ||
content.isSimilar(util.setData(new ItemStack(Material.LEAVES), 1)) ||
content.isSimilar(util.setData(new ItemStack(Material.LEAVES), 2)) ||
content.isSimilar(util.setData(new ItemStack(Material.LEAVES), 3)) ||
content.isSimilar(new ItemStack(Material.LEAVES_2)) ||
content.isSimilar(util.setData(new ItemStack(Material.LEAVES_2), 1))) {
if(content.getAmount() > amount) {
content.setAmount(content.getAmount() - amount);
inv.setItem(slotNum, content);
amount = 0;
}
else {
amount -= content.getAmount();
inv.setItem(slotNum, null);
}
}
}
slotNum++;
}
}
public void removeMushrooms(PlayerInventory inv, int amount) {
ItemStack[] contents = inv.getStorageContents();
int slotNum = 0;
for(ItemStack content : contents) {
if(amount <= 0) {
return;
}
if(content != null) {
if(content.isSimilar(new ItemStack(Material.RED_MUSHROOM)) ||
content.isSimilar(new ItemStack(Material.BROWN_MUSHROOM))) {
if(content.getAmount() > amount) {
amount = 0;
content.setAmount(content.getAmount() - amount);
}
else {
amount -= content.getAmount();
inv.setItem(slotNum, null);
}
}
}
slotNum++;
}
}
public int getTotalMushrooms(ItemStack[] contents) {
int total = 0;
for(ItemStack content : contents) {
if(content != null) {
if(content.isSimilar(new ItemStack(Material.RED_MUSHROOM)) ||
content.isSimilar(new ItemStack(Material.BROWN_MUSHROOM))) {
total += content.getAmount();
}
}
}
return total;
}
public int getMaxCraftable(Player p, ArrayList<ItemStack> items, boolean isSmelted) {
int count = -1;
PlayerInventory inv = p.getInventory();
ItemStack[] contents = inv.getStorageContents();
for(ItemStack item : items) {
int total = 0;
if(item.isSimilar(new ItemStack(Material.LEAVES))) {
total = getTotalLeaves(contents);
}
else if(item.isSimilar(new ItemStack(Material.RED_MUSHROOM))) {
total = getTotalMushrooms(contents);
}
else {
for(ItemStack content : contents) {
if(content != null && content.isSimilar(item)) {
total += content.getAmount();
}
}
}
int canCraft = total / item.getAmount();
if(canCraft < count || count == -1) {
count = canCraft;
}
}
if(isSmelted) {
int total = 0;
HashMap<Integer, ? extends ItemStack> all = inv.all(Material.COAL);
for(Integer i : all.keySet()) {
total += all.get(i).getAmount();
}
int canCraft = total * 8;
if(canCraft < count || count == -1) {
count = canCraft;
}
}
return count;
}
public boolean canCraft(Player p, ArrayList<ItemStack> items, boolean isSmelted, int amount) {
PlayerInventory inv = p.getInventory();
for(ItemStack item : items) {
if(item.isSimilar(new ItemStack(Material.LEAVES))) {
if(getTotalLeaves(inv.getStorageContents()) < item.getAmount() * amount) {
return false;
}
}
else if(item.isSimilar(new ItemStack(Material.RED_MUSHROOM))) {
if(getTotalMushrooms(inv.getStorageContents()) < item.getAmount() * amount) {
return false;
}
}
else {
if(!(inv.containsAtLeast(item, item.getAmount() * amount))) {
return false;
}
}
}
if(isSmelted) {
if(!(inv.containsAtLeast(new ItemStack(Material.COAL), (int) Math.ceil(amount / 8)))) {
return false;
}
}
return true;
}
public void craftRecipeMax(Player p, Economy econ, ArrayList<ItemStack> recipe, ItemStack result, boolean isSmelted, String name) {
String[] id = result.getItemMeta().getLore().get(0).split(" ");
String perm = "";
if(id[0].contains("Ingredient")) {
perm = "recipes.Ingr" + id[1];
}
else if(id[0].contains("Tier")) {
perm = "recipes.t" + id[1] + "r" + id[3];
}
else if(id[0].contains("Limited")) {
perm = "recipes.tler" + id[3];
}
else if(id[0].contains("Legendary")) {
perm = "recipes.tlegend" + id[2];
}
if(p.hasPermission(perm)) {
PlayerInventory inv = p.getInventory();
int amount = getMaxCraftable(p, recipe, isSmelted);
if(econ.has(p, CRAFT_COST * amount)) {
if(amount > 0) {
for(ItemStack item : recipe) {
// Edge case for leaves
if(item.isSimilar(new ItemStack(Material.LEAVES))) {
removeLeaves(inv, item.getAmount() * amount);
}
// Edge case for mushrooms
else if(item.isSimilar(new ItemStack(Material.RED_MUSHROOM))) {
removeMushrooms(inv, item.getAmount() * amount);
}
// Normal case
else {
inv.removeItem(util.setAmount(item, item.getAmount() * amount));
}
// Return buckets
if(item.isSimilar(new ItemStack(Material.WATER_BUCKET))) {
inv.addItem(new ItemStack(Material.BUCKET, amount));
}
if(item.isSimilar(new ItemStack(Material.MILK_BUCKET))) {
inv.addItem(new ItemStack(Material.BUCKET, amount));
}
if(item.isSimilar(new ItemStack(Material.LAVA_BUCKET))) {
inv.addItem(new ItemStack(Material.BUCKET, amount));
}
}
if(isSmelted) {
inv.removeItem(util.setAmount(new ItemStack(Material.COAL), (int) Math.ceil((double)(amount / 8))));
}
econ.withdrawPlayer(p, CRAFT_COST * amount);
inv.addItem(util.setAmount(result, amount));
util.sendMessage(p, "&7Successfully crafted &e" + amount + " " + name);
}
else {
util.sendMessage(p, "&cYou lack the ingredients to craft any of this recipe!");
}
}
else {
util.sendMessage(p, "&cYou lack the gold to craft " + amount + " of this recipe!");
}
}
else {
util.sendMessage(p, "&cYou have not yet unlocked this recipe!");
}
}
public void craftRecipe(Player p, Economy econ, int amount, ArrayList<ItemStack> recipe, ItemStack result, boolean isSmelted, String name) {
String[] id = result.getItemMeta().getLore().get(0).split(" ");
String perm = "";
if(id[0].contains("Ingredient")) {
perm = "recipes.Ingr" + id[1];
}
else if(id[0].contains("Tier")) {
perm = "recipes.t" + id[1] + "r" + id[3];
}
else if(id[0].contains("Limited")) {
perm = "recipes.tler" + id[3];
}
else if(id[0].contains("Drink")) {
perm = "recipes.drink" + id[3];
}
else if(id[0].contains("Legendary")) {
perm = "recipes.tlegend" + id[2];
}
if(p.hasPermission(perm)) {
PlayerInventory inv = p.getInventory();
if(canCraft(p, recipe, isSmelted, amount)) {
if(econ.has(p, CRAFT_COST * amount)) {
for(ItemStack item : recipe) {
// Edge case for leaves
if(item.isSimilar(new ItemStack(Material.LEAVES))) {
removeLeaves(inv, item.getAmount() * amount);
}
// Edge case for mushrooms
else if(item.isSimilar(new ItemStack(Material.RED_MUSHROOM))) {
removeMushrooms(inv, item.getAmount() * amount);
}
// Normal case
else {
inv.removeItem(util.setAmount(item, item.getAmount() * amount));
}
// Return buckets
if(item.equals(new ItemStack(Material.WATER_BUCKET))) {
inv.addItem(new ItemStack(Material.BUCKET, amount));
}
if(item.equals(new ItemStack(Material.MILK_BUCKET))) {
inv.addItem(new ItemStack(Material.BUCKET, amount));
}
}
if(isSmelted) {
inv.removeItem(util.setAmount(new ItemStack(Material.COAL), (int) Math.ceil((double)(amount / 8))));
}
econ.withdrawPlayer(p, CRAFT_COST * amount);
inv.addItem(util.setAmount(result, amount));
util.sendMessage(p, "&7Successfully crafted &e" + amount + " " + name);
}
else {
util.sendMessage(p, "&cYou lack the gold to craft " + amount + " of this recipe!");
}
}
else {
util.sendMessage(p, "&cYou lack the materials to craft " + amount + " of this recipe!");
}
}
else {
util.sendMessage(p, "&cYou have not yet unlocked this recipe!");
}
}
}
| true
|
668457e8928ad910880b5582a16e6fffaca4d1df
|
Java
|
VladimirYushkevich/puzzles
|
/hacker-rank/src/test/java/algorithms/implementation/QueenAttackTwoTest.java
|
UTF-8
| 6,755
| 3.09375
| 3
|
[] |
no_license
|
package algorithms.implementation;
import org.junit.Before;
import org.junit.Test;
import static algorithms.implementation.QueenAttackTwo.*;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertThat;
public class QueenAttackTwoTest {
private QueenAttackTwo.Point pQueen;
private int boardSize;
@Before
public void setUp() throws Exception {
pQueen = new QueenAttackTwo.Point(3, 4);
boardSize = 5;
initBoard(pQueen, boardSize);
}
@Test
public void testInsertObstacles() throws Exception {
insertObstacle(pQueen, new QueenAttackTwo.Point(5, 5));
insertObstacle(pQueen, new QueenAttackTwo.Point(2, 4));
insertObstacle(pQueen, new QueenAttackTwo.Point(3, 2));
assertThat(getTotalAllowedPoints(), is(10));
allowedPointsToAngle.clear();
initBoard(new Point(4, 4), 4);
assertThat(getTotalAllowedPoints(), is(9));
allowedPointsToAngle.clear();
initBoard(new Point(1, 1), 8);
assertThat(getTotalAllowedPoints(), is(21));
}
@Test
public void testInitBoard() throws Exception {
assertThat(allowedPointsToAngle.get(0.0d), is(2));
assertThat(allowedPointsToAngle.get(45.0d), is(1));
assertThat(allowedPointsToAngle.get(90.0d), is(1));
assertThat(allowedPointsToAngle.get(135.0d), is(1));
assertThat(allowedPointsToAngle.get(180.0d), is(2));
assertThat(allowedPointsToAngle.get(225.0d), is(2));
assertThat(allowedPointsToAngle.get(270.0d), is(3));
assertThat(allowedPointsToAngle.get(315.0d), is(2));
assertNull(allowedPointsToAngle.get(314.0d));
}
@Test
public void testGetNumberOfPointsBeforeObstacle() throws Exception {
assertThat(getNumberOfPointsBeforeObstacle(pQueen, new QueenAttackTwo.Point(5, 4)), is(1));
assertThat(getNumberOfPointsBeforeObstacle(pQueen, new QueenAttackTwo.Point(2, 4)), is(0));
assertThat(getNumberOfPointsBeforeObstacle(pQueen, new QueenAttackTwo.Point(4, 5)), is(0));
assertThat(getNumberOfPointsBeforeObstacle(pQueen, new QueenAttackTwo.Point(2, 3)), is(0));
assertThat(getNumberOfPointsBeforeObstacle(pQueen, new QueenAttackTwo.Point(2, 5)), is(0));
assertThat(getNumberOfPointsBeforeObstacle(pQueen, new QueenAttackTwo.Point(4, 3)), is(0));
assertThat(getNumberOfPointsBeforeObstacle(pQueen, new QueenAttackTwo.Point(3, 5)), is(0));
assertThat(getNumberOfPointsBeforeObstacle(pQueen, new QueenAttackTwo.Point(3, 2)), is(1));
assertThat(getNumberOfPointsBeforeObstacle(pQueen, new QueenAttackTwo.Point(5, 5)), is(0));
}
@Test
public void testGetAngle() throws Exception {
assertThat(getAngle(pQueen, new QueenAttackTwo.Point(4, 4)), is(0.0d));
assertThat(getAngle(pQueen, new QueenAttackTwo.Point(5, 4)), is(0.0d));
assertThat(getAngle(pQueen, new QueenAttackTwo.Point(4, 5)), is(45.0d));
assertThat(getAngle(pQueen, new QueenAttackTwo.Point(3, 5)), is(90.0d));
assertThat(getAngle(pQueen, new QueenAttackTwo.Point(2, 5)), is(135.0d));
assertThat(getAngle(pQueen, new QueenAttackTwo.Point(2, 4)), is(180.0d));
assertThat(getAngle(pQueen, new QueenAttackTwo.Point(2, 3)), is(225.0d));
assertThat(getAngle(pQueen, new QueenAttackTwo.Point(3, 3)), is(270.0d));
assertThat(getAngle(pQueen, new QueenAttackTwo.Point(4, 3)), is(315.0d));
}
@Test
public void testGetNumberOfPoints() throws Exception {
assertThat(getNumberOfPoints(pQueen, boardSize, 0.0d), is(2));
assertThat(getNumberOfPoints(pQueen, boardSize, 45.0d), is(1));
assertThat(getNumberOfPoints(pQueen, boardSize, 90.0d), is(1));
assertThat(getNumberOfPoints(pQueen, boardSize, 135.0d), is(1));
assertThat(getNumberOfPoints(pQueen, boardSize, 180.0d), is(2));
assertThat(getNumberOfPoints(pQueen, boardSize, 225.0d), is(2));
assertThat(getNumberOfPoints(pQueen, boardSize, 270.0d), is(3));
assertThat(getNumberOfPoints(pQueen, boardSize, 315.0d), is(2));
final Point point1 = new Point(4, 5);
assertThat(getNumberOfPoints(point1, boardSize, 0.0d), is(1));
assertThat(getNumberOfPoints(point1, boardSize, 45.0d), is(0));
assertThat(getNumberOfPoints(point1, boardSize, 90.0d), is(0));
assertThat(getNumberOfPoints(point1, boardSize, 135.0d), is(0));
assertThat(getNumberOfPoints(point1, boardSize, 180.0d), is(3));
assertThat(getNumberOfPoints(point1, boardSize, 225.0d), is(3));
assertThat(getNumberOfPoints(point1, boardSize, 270.0d), is(4));
assertThat(getNumberOfPoints(point1, boardSize, 315.0d), is(1));
final Point point2 = new Point(5, 5);
assertThat(getNumberOfPoints(point2, boardSize, 0.0d), is(0));
assertThat(getNumberOfPoints(point2, boardSize, 45.0d), is(0));
assertThat(getNumberOfPoints(point2, boardSize, 90.0d), is(0));
assertThat(getNumberOfPoints(point2, boardSize, 135.0d), is(0));
assertThat(getNumberOfPoints(point2, boardSize, 180.0d), is(4));
assertThat(getNumberOfPoints(point2, boardSize, 225.0d), is(4));
assertThat(getNumberOfPoints(point2, boardSize, 270.0d), is(4));
assertThat(getNumberOfPoints(point2, boardSize, 315.0d), is(0));
final Point point3 = new Point(1, 1);
assertThat(getNumberOfPoints(point3, 1, 0.0d), is(0));
assertThat(getNumberOfPoints(point3, 1, 45.0d), is(0));
assertThat(getNumberOfPoints(point3, 1, 90.0d), is(0));
assertThat(getNumberOfPoints(point3, 1, 135.0d), is(0));
assertThat(getNumberOfPoints(point3, 1, 180.0d), is(0));
assertThat(getNumberOfPoints(point3, 1, 225.0d), is(0));
assertThat(getNumberOfPoints(point3, 1, 270.0d), is(0));
assertThat(getNumberOfPoints(point3, 1, 315.0d), is(0));
}
@Test
public void testInsertObstacle() throws Exception {
insertObstacle(pQueen, new QueenAttackTwo.Point(2, 4));
}
@Test
public void testMath() throws Exception {
assertThat(-0.0d * 1.0d, is(-0.0d));
assertThat(-0.0d * Double.POSITIVE_INFINITY, is(Double.NaN));
assertThat(-0.0d * Double.NEGATIVE_INFINITY, is(Double.NaN));
assertThat(Math.toDegrees(Math.atan2(4 - 4, 4 - 3)), is(0.0d));
assertThat(Math.toDegrees(Math.atan2(5 - 4, 4 - 3)), is(45.0d));
assertThat(Math.toDegrees(Math.atan2(5 - 4, 3 - 3)), is(90.0d));
assertThat(Math.toDegrees(Math.atan2(5 - 4, 2 - 3)), is(135.0d));
assertThat(Math.toDegrees(Math.atan2(4 - 4, 2 - 3)), is(180.0d));
}
}
| true
|
0e322dd9ab557ca2f4f3243d4ff949d20d79f8ac
|
Java
|
michacana/lexStorm
|
/src/java/com/Abogados/Lex/dto/DocumentosCitasPk.java
|
UTF-8
| 2,398
| 2.265625
| 2
|
[] |
no_license
|
/*
* This source file was generated by FireStorm/DAO.
*
* If you purchase a full license for FireStorm/DAO you can customize this header file.
*
* For more information please visit http://www.codefutures.com/products/firestorm
*/
package com.Abogados.Lex.dto;
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.Date;
/**
* This class represents the primary key of the DOCUMENTOS_CITAS table.
*/
public class DocumentosCitasPk implements Serializable
{
protected long idCita;
/**
* This attribute represents whether the primitive attribute idCita is null.
*/
protected boolean idCitaNull;
/**
* Sets the value of idCita
*/
public void setIdCita(long idCita)
{
this.idCita = idCita;
}
/**
* Gets the value of idCita
*/
public long getIdCita()
{
return idCita;
}
/**
* Method 'DocumentosCitasPk'
*
*/
public DocumentosCitasPk()
{
}
/**
* Method 'DocumentosCitasPk'
*
* @param idCita
*/
public DocumentosCitasPk(final long idCita)
{
this.idCita = idCita;
}
/**
* Sets the value of idCitaNull
*/
public void setIdCitaNull(boolean idCitaNull)
{
this.idCitaNull = idCitaNull;
}
/**
* Gets the value of idCitaNull
*/
public boolean isIdCitaNull()
{
return idCitaNull;
}
/**
* Method 'equals'
*
* @param _other
* @return boolean
*/
public boolean equals(Object _other)
{
if (_other == null) {
return false;
}
if (_other == this) {
return true;
}
if (!(_other instanceof DocumentosCitasPk)) {
return false;
}
final DocumentosCitasPk _cast = (DocumentosCitasPk) _other;
if (idCita != _cast.idCita) {
return false;
}
if (idCitaNull != _cast.idCitaNull) {
return false;
}
return true;
}
/**
* Method 'hashCode'
*
* @return int
*/
public int hashCode()
{
int _hashCode = 0;
_hashCode = 29 * _hashCode + (int) (idCita ^ (idCita >>> 32));
_hashCode = 29 * _hashCode + (idCitaNull ? 1 : 0);
return _hashCode;
}
/**
* Method 'toString'
*
* @return String
*/
public String toString()
{
StringBuffer ret = new StringBuffer();
ret.append( "com.Abogados.Lex.dto.DocumentosCitasPk: " );
ret.append( "idCita=" + idCita );
return ret.toString();
}
}
| true
|
c5174175dfaae11b616947356121c397faf50e8c
|
Java
|
wangkang09/design-patterns
|
/src/main/java/com/wangkang/design_patterns/工厂模式/SimplePizzaFactory.java
|
UTF-8
| 690
| 3.421875
| 3
|
[] |
no_license
|
package com.wangkang.design_patterns.工厂模式;
/**
* @Description: pizza 的简单工厂:客户端程序直接调用这个工厂的静态方法
* @Author: wangkang
* @Date: Created in 22:52 2019/5/24
* @Modified By:
*/
public class SimplePizzaFactory {
public static Pizza createPizza(String type) {
Pizza pizza = null;
switch (type) {
case "cheese":
pizza = new CheesePizza();
break;
case "greek":
pizza = new GreekPizza();
break;
default:
throw new IllegalArgumentException("无此类型的Pizza");
}
return pizza;
}
}
| true
|
3cb080b578698898de7a9637ed9cc5b5d7b43764
|
Java
|
sirinath/x10
|
/x10.compiler/src/x10cpp/visit/StringLiteralManager.java
|
UTF-8
| 2,836
| 2.21875
| 2
|
[] |
no_license
|
/*
* This file is part of the X10 project (http://x10-lang.org).
*
* This file is licensed to You under the Eclipse Public License (EPL);
* You may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.opensource.org/licenses/eclipse-1.0.php
*
* (C) Copyright IBM Corporation 2006-2014.
*/
package x10cpp.visit;
import java.util.HashMap;
import java.util.Map.Entry;
import polyglot.ast.Node;
import polyglot.ast.StringLit_c;
import polyglot.ast.Typed;
import polyglot.types.Name;
import polyglot.util.InternalCompilerError;
import polyglot.util.StringUtil;
import polyglot.visit.NodeVisitor;
import x10.ast.X10ClassDecl_c;
import x10.types.X10ClassType;
import x10.util.ClassifiedStream;
/**
* A class to manage generation of string literals.
* Objectives:
* (1) All string literals should be created as C++ statics
* to minimize dynamic allocation costs.
* (2) If the same string literal is used multiple times within
* a compilation unit, only create it once.
*/
public class StringLiteralManager {
HashMap<String,Name> map = new HashMap<String,Name>();
String cname;
String fqcname;
public Name get(String lit) {
return map.get(lit);
}
public String getCName(String lit) {
Name n = map.get(lit);
if (n == null) return null;
return "::"+fqcname+"::"+Emitter.mangled_non_method_name(n.toString());
}
public void populate(X10ClassDecl_c n) {
fqcname = Emitter.translate_mangled_FQN(Emitter.fullName(n.classDef().asType()).toString())+"_Strings";
cname = Emitter.mangled_non_method_name(n.name().id().toString())+"_Strings";
class FindStrings extends NodeVisitor {
public Node override(Node n) {
if (n instanceof StringLit_c) {
String str = ((StringLit_c) n).value();
if (!map.containsKey(str)) {
map.put(str, Name.makeFresh("sl"));
}
}
return null;
}
}
n.visit(new FindStrings());
}
public boolean hasStrings() {
return !map.isEmpty();
}
public void codeGen(ClassifiedStream h, ClassifiedStream d) {
h.writeln("class "+cname+" {");
h.writeln(" public:");
for (Entry<String,Name> e : map.entrySet()) {
String var = Emitter.mangled_non_method_name(e.getValue().toString());
h.writeln(" static ::x10::lang::String "+var+";");
d.write("::x10::lang::String "+fqcname+"::"+var+"(\"" );
d.write(StringUtil.escape(e.getKey()));
d.writeln("\");");
}
h.writeln("};");
h.forceNewline();
d.forceNewline();
}
}
| true
|
c3c6849a5e5013e71c5be3e1bf588ea22627ebd6
|
Java
|
medwinwang/landison
|
/src/main/java/com/medwin/landison/kms/informationservice/GetInformationResponse.java
|
GB18030
| 1,696
| 1.953125
| 2
|
[] |
no_license
|
package com.medwin.landison.kms.informationservice;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
/**
* <p>anonymous complex type Java ࡣ
*
* <p>ģʽƬָڴеԤݡ
*
* <pre>
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="GetInformationResult" type="{http://www.shijinet.com.cn/kunlun/kws/1.1/}ArrayOfCommonInfo" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"getInformationResult"
})
@XmlRootElement(name = "GetInformationResponse")
public class GetInformationResponse {
@XmlElement(name = "GetInformationResult")
protected ArrayOfCommonInfo getInformationResult;
/**
* ȡgetInformationResultԵֵ
*
* @return
* possible object is
* {@link ArrayOfCommonInfo }
*
*/
public ArrayOfCommonInfo getGetInformationResult() {
return getInformationResult;
}
/**
* getInformationResultԵֵ
*
* @param value
* allowed object is
* {@link ArrayOfCommonInfo }
*
*/
public void setGetInformationResult(ArrayOfCommonInfo value) {
this.getInformationResult = value;
}
}
| true
|
76f135becdcf737de68dd6fc49066bfd68730616
|
Java
|
janagrit/Website_BREdu
|
/IdeaProjects/SeleniumLectures/src/April_7/SeleniumDemo.java
|
UTF-8
| 3,187
| 2.671875
| 3
|
[] |
no_license
|
package April_7;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class SeleniumDemo {
public static void main(String[] args) {
// Setup
System.setProperty("webdriver.chrome.driver", "/Applications/1 selenium-java-3.141.59/chromedriver");
WebDriver driver1 = new ChromeDriver();
// WebDriver driver2 = new FirefoxDriver();
driver1.get("https://www.google.com/");
String actualTitle = driver1.getTitle();
String expectedTitle = "Google";
System.out.println();
if (actualTitle.equals(expectedTitle)){
System.out.println("Test case is passed. Actual title "+ actualTitle + " matches to expected title " + expectedTitle);
}else{
System.out.println("Test is failed. Actual title is "+ actualTitle + " expected title is " + expectedTitle);
}
//driver1.quit();
// driver1.close();
// 4. verify page url is google.com
String expectedUrl = "https://www.google.com/";
String actualUrl = driver1.getCurrentUrl();
if (actualUrl.equals(expectedUrl)){
System.out.println("Test case is passed. Actual URL "+ actualUrl + " matches to expected Url " + expectedUrl);
}else{
System.out.println("Test is failed. Actual URL is "+ actualUrl + " expected Url is " + expectedUrl);
}
// System.out.println("Page sourse");
// System.out.println("---------------");
// String source = driver1.getPageSource();
// System.out.println(source);
// 5. Verify that word About is part of this page
String str = "Selenium";
String source = driver1.getPageSource();
if(source.contains(str)){
System.out.println("Pass");
}else{
System.out.println("Fail. The pade does not contain the word " + str);
}
driver1.navigate().to("https://www.amazon.com");
driver1.navigate().back();
driver1.navigate().forward();
driver1.navigate().refresh();
driver1.quit();
}
}
/*
BASIC WEBDRIVER METHODS
get() -Load a new web page in the current browser window.
getCurentUrl() -Get a string representing the current URL that the browser is looking at.
getTitle() -The title of the current page
getPageSource() -Get the source of the last loaded page.
quit() -Quits this driver, closing every associated window.
close() -Close the current window, quitting the browser if it's the last window currently open.
navigate().to()
navigate().back()
navigate().forward()
*/
/*
WebElement inboxLink = driver.findElement(By.partialLinkText("Inbox"));
System.out.println(inboxLink.getText());
WebElement loginButton= driver.findElement(By.tagName("button"));
loginButton.click();
WebElement table = driver.findElement(By.id("summaryTable"));
List<WebElement> rows = table.findElements(By.tagName("tr"));
List<WebElement> links = driver.findElements(By.tagName("a"));
*/
| true
|
d03a2086105c010c22f877a7be30b0140cdeb48a
|
Java
|
tild09/EyeMod-Port
|
/src/main/java/me/fabric/eyephonemod/gui/handler/dummy/DummyClientScreenHandler.java
|
UTF-8
| 880
| 2.21875
| 2
|
[] |
no_license
|
package me.fabric.eyephonemod.gui.handler.dummy;
import me.fabric.eyephonemod.gui.ScreenRegistry;
import me.fabric.eyephonemod.gui.handler.ClientScreenHandler;
import me.fabric.eyephonemod.gui.handler.ScreenPacket;
import net.minecraft.network.PacketByteBuf;
public class DummyClientScreenHandler extends ClientScreenHandler {
public DummyClientScreenHandler(int syncId) {
super(ScreenRegistry.DUMMY_GUI.getScreenHandlerType(), syncId);
}
@Override
public void onPacket(PacketByteBuf packetByteBuf, int packetAction) {
}
public void onClick(double mouseX, double mouseY) {
final PacketByteBuf packetByteBuf = ScreenPacket.newPacket(syncId, DummyPacketAction.MOUSE_CLICK.getActionOrdinal());
packetByteBuf.writeDouble(mouseX);
packetByteBuf.writeDouble(mouseY);
ScreenPacket.sendToServer(packetByteBuf);
}
}
| true
|
57e927a820f48b0bc9bc1510705b6d340adf59c4
|
Java
|
ChengHsu/Leetcode
|
/src/Tree/SubtreeofAnotherTree.java
|
UTF-8
| 1,560
| 3.984375
| 4
|
[] |
no_license
|
package Tree;
/**
* @Number: #572. Subtree of another tree
* @Descpription: Given two non-empty binary trees s and t, check whether tree t has exactly the same structure and node
* values with a subtree of s.
* A subtree of s is a tree consists of a node in s and all of this node's descendants.
* The tree s could also be considered as a subtree of itself.
* @Author: Created by xucheng.
*/
public class SubtreeofAnotherTree {
// Preorder traversal of both s and t
// Get preorder traversal string of s and t
// Check whether string of t is a substring of s
public boolean isSubtree(TreeNode s, TreeNode t) {
if (s == null || t == null)
return false;
String preS = preorder(s, "");
String preT = preorder(t, "");
// Use substring will cause indexOutOfBound exception cuz the char of endIndex will not be included in the return string
return preS.indexOf(preT) >= 0;
}
private String preorder(TreeNode root, String traversalSequence) {
traversalSequence += "#" + root.val + " ";
if (root.left == null && root.right == null) {
traversalSequence += "null null ";
return traversalSequence;
}
if (root.left != null)
traversalSequence = preorder(root.left, traversalSequence);
else traversalSequence += "null ";
if (root.right != null)
traversalSequence = preorder(root.right, traversalSequence);
else traversalSequence += "null ";
return traversalSequence;
}
}
| true
|
017e7b03c7589476c1a84cf8402a78af2f344c65
|
Java
|
liusiyu95/Twilio_Interview
|
/listenup-takehome/java/listenup-solution-server/src/main/java/com/twilio/interview/listenup/Models/UserTrack.java
|
UTF-8
| 263
| 2.0625
| 2
|
[] |
no_license
|
package com.twilio.interview.listenup.Models;
public class UserTrack extends UserInfo {
public int tracks;
public int getTracks() {
return tracks;
}
public void setTracks(int tracks) {
this.tracks = tracks;
}
}
| true
|
4bea10252f20a8b9ce6610a7754dd37db340665a
|
Java
|
MicrophoneBen/Company
|
/src/cn/hengxin/service/ICaseService.java
|
UTF-8
| 282
| 1.789063
| 2
|
[] |
no_license
|
package cn.hengxin.service;
import java.util.List;
import cn.hengxin.entity.Client;
public interface ICaseService {
List<Client> listCase();
Client getCase(Integer id);
int caseRelease(Client acase);
int caseUpdate(Client aase);
int caseDelete(Integer id);
}
| true
|
32da3031c5b47b5f589b3a647525f119d34fb483
|
Java
|
TangLiTao2810020131/NB-WATER2.0
|
/nb-water-nbiot/src/main/java/com/ets/nb_iot/cmdinfo/command/concurrent/CmdAdapter.java
|
UTF-8
| 2,905
| 2.046875
| 2
|
[] |
no_license
|
package com.ets.nb_iot.cmdinfo.command.concurrent;
import com.ets.common.ObjectCode;
import com.ets.nb_iot.cmdinfo.command.send.CommandService;
import com.ets.nb_iot.model.ReportDataHAC;
import com.ets.nb_iot.model.ReportDataTLV;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;
/**
* @author 姚轶文
* @create 2018- 12-19 9:08
*/
@Service
@Scope(value = "singleton")
public class CmdAdapter implements Runnable {
CmdDelay cmdDelay;
@Autowired
protected CommandService commandService;
public CmdDelay getCmdDelay() {
return cmdDelay;
}
public void setCmdDelay(CmdDelay cmdDelay) {
this.cmdDelay = cmdDelay;
}
@Override
public void run() {
if(cmdDelay!=null)
{
String deviceId = cmdDelay.getDeviceId();
ReportDataHAC reportData = cmdDelay.getReportData();
ReportDataTLV reportDataTLV = cmdDelay.getReportDataTLV();
if(reportData != null){
if(reportData.getCmdType() == ObjectCode.NB_CHECK_TIME){
//logger.info("=========================================start时间校验==========================================");
commandService.CheckTime(deviceId, reportData);
//logger.info("==========================================end时间校验===========================================");
}
if(reportData.getCmdType() == ObjectCode.NB_REPORT_CYCLE){
//logger.info("=========================================start执行上报周期命令=======================================");
commandService.AssemblyDeliveryCommand(deviceId, reportData);
//logger.info("=========================================end执行上报周期命令=========================================");
}
if(reportData.getCmdType() == ObjectCode.NB_VALVE_CONTROL){
//logger.info("=========================================start执行设置读数命令==========================================");
commandService.AssemblyValveControlCommand(deviceId, reportData);
//logger.info("==========================================end执行设置读数命令===========================================");
}
if(reportData.getCmdType() == ObjectCode.NB_METER_READING){
//logger.info("=========================================start执行阀控命令==========================================");
commandService.AssemblyWaterMeterBasicCommand(deviceId, reportData);
//logger.info("==========================================end执行阀控命令===========================================");
}
}
if(reportDataTLV != null){
if(reportDataTLV.getCmdType() == ObjectCode.NB_CHECK_TIME){
//commandService.CheckTimeTLV(deviceId, reportDataTLV);
}
if(reportDataTLV.getCmdType() == ObjectCode.NB_RAW){
commandService.AssemblyTLVBasicCommand(deviceId, reportDataTLV);
}
}
}
}
}
| true
|
8c299f68b0dd8df820def7d6d19740a5d9dbf4f0
|
Java
|
mcflasco/Flight-Attendant-App
|
/Flasco_CallAttendant.java
|
UTF-8
| 2,243
| 3.703125
| 4
|
[] |
no_license
|
package week01;
//Name: Michael Flasco
//Date: 01/13/2019
//Program Name: Call Attendant
//Purpose: Simulation using call button for call attendant
import java.util.Scanner;
public class Flasco_CallAttendant {
static Scanner input;
static Flasco_Attendant attendant;
public static void main(String[] args) {
// TODO Auto-generated method stub
input = new Scanner(System.in);
boolean run = true;
attendant = new Flasco_Attendant();
while (run) {
System.out.println("1. Seat Buttons ");
System.out.println("2. Attendent Buttons ");
System.out.println("3. Show Seats ");
System.out.println("4. Exit");
String menu = input.nextLine();
switch (menu) {
case "1":
chooseSeat();
break;
case "2":
attendantCall();
break;
case "3":
showSeats();
break;
case "4":
run = false;
System.out.println("Goodbye...");
}
}
input.close();
}
public static void showSeats() {
for (Flasco_Seats seats : attendant.seats)
if (attendant.attendants.isEmpty()) {
System.out.println(seats);
}
for (int i = 0; i < attendant.attendants.size(); i++) {
System.out.println(attendant.attendants.get(i));
}
}
public static void chooseSeat() {
System.out.println("Enter a seat Number (1, 2, 3, 4, 5)");
String num = input.nextLine();
System.out.println("Would you like to call an Attendant (y/n)");
String button = input.nextLine();
System.out.println("Seat " + num + ": light has been turned on.");
for (int i = 0; i < attendant.seats.size(); i++) {
if (attendant.seats.get(i).seatNum.equals(num)) {
// System.out.println(attendant.seats.get(i));
if (button.equals("y")) {
attendant.attendants.add(new Flasco_Attendant(num, "On"));
}
}
}
}
public static void attendantCall() {
for (int i = 0; i < attendant.attendants.size(); i++) {
System.out.println(attendant.attendants.get(i));
}
System.out.println("Enter seat number to turn off.");
String seatNum = input.nextLine();
for (int i = 0; i < attendant.attendants.size(); i++) {
if (attendant.attendants.get(i).seatNum.equals(seatNum))
attendant.attendants.remove(i);
}
System.out.println("Seat " + seatNum + ": light has been turned off");
}
}
| true
|
20931c6ad3108fe3061c395d3157ac2afb2de661
|
Java
|
Bal-os/ChatMessenger
|
/src/main/java/com/gmail/sbal/stels/controllers/ChatController.java
|
UTF-8
| 2,127
| 2.453125
| 2
|
[] |
no_license
|
package com.gmail.sbal.stels.controllers;
import com.gmail.sbal.stels.models.Chat;
import com.gmail.sbal.stels.models.Message;
import com.gmail.sbal.stels.services.ChatService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
/**
* @author Alex Balashov
*/
@Controller
@RequestMapping("/chats")
public class ChatController {
@Autowired
private ChatService chatService;
@GetMapping("/{chat_name}")
public String show(@PathVariable("chat_name") String chatName, Model model) {
Chat chat = chatService.getChat(chatName);
model.addAttribute("chat", chat);
return "chat";
}
@PatchMapping("/{chat_name}")
public String edit(@PathVariable(value = "chat_name") String chatName,
@RequestParam(value = "chat_name") String newChatName,
@RequestParam String title,
Model model) {
Chat chat = chatService.getChat(chatName);
if(chat != null){
chat.setChatName(chatName);
chat.setTitle(title);
}
return "chat";
}
@PostMapping("/{chat_name}/add")
public String addMessage(@PathVariable(value = "chat_name") String chatName,
@RequestParam String text,
Model model) {
Chat chat = chatService.getChat(chatName);
if (chat != null) {
chatService.addMessage(new Message(text, chat));
return "chat";
}
return "chat";
}
@GetMapping("/new")
public String add() {
return "chat_form";
}
@PostMapping
public String add(@RequestParam(value = "chat_name") String chatName,
@RequestParam String title,
Model model) {
if (chatService.getChat(chatName) == null) {
Chat chat = new Chat(chatName, title);
model.addAttribute("chat", chat);
return "chat";
}
else return "chat_form";
}
}
| true
|
4e6016db9ca07a268e7a2fb82c51f60ec52190a7
|
Java
|
santiontanon/Parallel
|
/PCGMC4PP/src/game/UnitState.java
|
UTF-8
| 3,049
| 2.65625
| 3
|
[] |
no_license
|
/*
* The MIT License
*
* Copyright 2016 Josep Valls-Vargas <josep@valls.name>.
*
* 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.
*/
package game;
import game.component.ComponentUnit;
import java.util.ArrayList;
import java.util.List;
/**
*
* @author Josep Valls-Vargas <josep@valls.name>
*/
public class UnitState {
private List<ComponentUnit> units;
public void addUnit(ComponentUnit unit) {
units.add(unit);
}
public List<ComponentUnit> getUnits() {
return units;
}
public ComponentUnit getUnit(int index){
return units.get(index);
}
public ComponentUnit getUnitById(int id){
for(ComponentUnit component : this.units){
if(component.id==id){
return component;
}
}
return null;
}
public ComponentUnit getUnitByPosition(int x, int y){
// Only one component can be in each tile but multiple units can
for(ComponentUnit component : this.units){
if(component.x==x && component.y==y){
return component;
}
}
return null;
}
public List<ComponentUnit> getUnitsByPosition(int x, int y){
return this.getUnitsByPosition(x, y, null);
}
public List<ComponentUnit> getUnitsByPosition(int x, int y, ComponentUnit exclude){
List<ComponentUnit> l = new ArrayList();
for(ComponentUnit cu : this.units){
if(cu.x==x && cu.y==y && cu!=exclude){
l.add(cu);
}
}
return l;
}
public void setUnits(List<ComponentUnit> units) {
this.units = units;
}
public UnitState(){
units = new ArrayList<ComponentUnit>();
}
public UnitState(List<ComponentUnit> units){
this.units = units;
}
public UnitState clone(){
List<ComponentUnit> new_units = new ArrayList<ComponentUnit>();
for(ComponentUnit unit:units){
new_units.add(unit.clone());
}
return new UnitState(new_units);
}
}
| true
|
3974f35776ab88fff2a3d20a6e2920675ae49eb9
|
Java
|
suollon/parent-mask
|
/mask-service/service-oversea-pay/src/main/java/com/lingdong/service/oversea_pay/ServiceOverseaPayApplication.java
|
UTF-8
| 359
| 1.671875
| 2
|
[] |
no_license
|
package com.lingdong.service.oversea_pay;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class ServiceOverseaPayApplication {
public static void main(String[] args) {
SpringApplication.run(ServiceOverseaPayApplication.class, args);
}
}
| true
|
fa26c8f97e35a6fdb7f25df2a29d35aa0aae3e62
|
Java
|
Detail0805/Leetcode
|
/src/main/java/SimpleMaths/leetcode/LongestConsecutive.java
|
UTF-8
| 862
| 3.546875
| 4
|
[] |
no_license
|
package SimpleMaths.leetcode;
import java.util.HashSet;
/**
* leetcode 128. Longest Consecutive Sequence
* @author user
*
*/
// Longest Consecutive Sequence
// Time Complexity: O(n)Space Complexity: O(n)
public class LongestConsecutive {
public int longestConsecutive(int[] nums) {
final HashSet<Integer> mySet = new HashSet<Integer>();
for (int i : nums) mySet.add(i);
int longest = 0;
for (int i : nums) {
int length = 1;
for (int j = i - 1; mySet.contains(j); --j) {
mySet.remove(j);
++length;
}
for (int j = i + 1; mySet.contains(j); ++j) {
mySet.remove(j);
++length;
}
longest = Math.max(longest, length);
}
return longest;
}
}
| true
|
3f42131ccac3de73b3ba808ff0f03d1264645c14
|
Java
|
zhenjiekeji/xxx
|
/src/com/uk/sec/framework/extremeImpl/SecColumnTag.java
|
UTF-8
| 20,829
| 1.867188
| 2
|
[] |
no_license
|
/*
* Copyright 2001-2012 Software Engineering Center Chinese Academy of Sciences.
* All rights reserved. SEC PROPRIETARY/CONFIDENTIAL. Use is subject to license
* terms.
*/
package com.uk.sec.framework.extremeImpl;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.BodyTagSupport;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang3.StringEscapeUtils;
import org.apache.taglibs.standard.lang.support.ExpressionEvaluatorManager;
import org.extremecomponents.table.bean.Column;
import org.extremecomponents.table.core.TableModel;
import org.extremecomponents.table.core.TableModelUtils;
import org.extremecomponents.table.interceptor.ColumnInterceptor;
import org.extremecomponents.table.tag.TagUtils;
import org.extremecomponents.util.ExceptionUtils;
/**
* @author xzw.
* @since 1.0
* @version 1.0
*/
public class SecColumnTag extends BodyTagSupport implements ColumnInterceptor {
private String alias;
private String calc;
private String calcTitle;
private String cell;
private Object filterOptions;
private String filterable;
private String filterCell;
private String filterClass;
private String filterStyle;
private String format;
private String headerCell;
private String headerClass;
private String headerStyle;
private String interceptor;
private String parse;
private String property;
private String sortable;
private String style;
private String styleClass;
private String title;
private Object value;
private String viewsAllowed;
private String viewsDenied;
private String width;
private String escapeAutoFormat;
private boolean escapeHtml = true;
/**
* @jsp.attribute description="Used to uniquely identify the column when the
* same property is used for more than one column."
* required="false" rtexprvalue="true"
*/
public void setAlias(String alias) {
this.alias = alias;
}
/**
* @jsp.attribute description="A fully qualified class name to a custom Calc
* implementation. Could also be a named type in the
* preferences. Used to do math on a column."
* required="false" rtexprvalue="true"
*/
public void setCalc(String calc) {
this.calc = calc;
}
/**
* @jsp.attribute description="The title of the calc." required="false"
* rtexprvalue="true"
*/
public void setCalcTitle(String totalTitle) {
this.calcTitle = totalTitle;
}
/**
* @jsp.attribute description="Display for the column. The valid values are
* display, currency, rowCount, and date. The default value
* is display. The cell can also be a fully qualified class
* name to a custom Cell. Be sure to implement the Cell
* interface or extend AbstractCell if making a custom cell."
* required="false" rtexprvalue="true"
*/
public void setCell(String cell) {
this.cell = cell;
}
/**
* @jsp.attribute description="Specify whether auto format of value will be
* skipped. False by default, and is only effective if
* autoformatting is implement in the view." required="false"
* rtexprvalue="true"
*/
public void setEscapeAutoFormat(String escapeAutoFormat) {
this.escapeAutoFormat = escapeAutoFormat;
}
/**
* @jsp.attribute description="Specify whether escape HTML code from
* propertyValue. Default value is true." required="false"
* rtexprvalue="true"
*/
public void setEscapeHtml(boolean escapeHtml) {
this.escapeHtml = escapeHtml;
}
/**
* @jsp.attribute description="Specify whether or not the column should be
* filterable. Acceptable values are true or false. The
* default is to use the value for the table filterable
* attribute." required="false" rtexprvalue="true"
*/
public void setFilterable(String filterable) {
this.filterable = filterable;
}
/**
* @jsp.attribute description="Displays the filter column. The valid values
* are filter and droplist. The default is filter. The cell
* can also be a fully qualified class name to a custom
* cell." required="false" rtexprvalue="true"
*/
public void setFilterCell(String filterCell) {
this.filterCell = filterCell;
}
/**
* @jsp.attribute description="The css class style sheet used to define what
* the table filter column looks like." required="false"
* rtexprvalue="true"
*/
public void setFilterClass(String filterClass) {
this.filterClass = filterClass;
}
/**
* @jsp.attribute description="The object that contains the collection of
* elements that implement the Option interface."
* required="false" rtexprvalue="true"
*/
public void setFilterOptions(Object filterOptions) {
this.filterOptions = filterOptions;
}
/**
* @jsp.attribute description="The css class style sheet to use for the
* filter column." required="false" rtexprvalue="true"
*/
public void setFilterStyle(String filterStyle) {
this.filterStyle = filterStyle;
}
/**
* @jsp.attribute description="The format to use for the cell. For instance
* if used with a date cell then the format can be
* MM/dd/yyyy." required="false" rtexprvalue="true"
*/
public void setFormat(String format) {
this.format = format;
}
/**
* @jsp.attribute description="Display for the header column. The default is
* header. The cell can also be a fully qualified class name
* to a custom cell." required="false" rtexprvalue="true"
*/
public void setHeaderCell(String headerCell) {
this.headerCell = headerCell;
}
/**
* @jsp.attribute description="The css class style sheet used to define what
* the table header column looks like." required="false"
* rtexprvalue="true"
*/
public void setHeaderClass(String headerClass) {
this.headerClass = headerClass;
}
/**
* @jsp.attribute description="The css class style sheet to use for the
* header column." required="false" rtexprvalue="true"
*/
public void setHeaderStyle(String headerStyle) {
this.headerStyle = headerStyle;
}
/**
* @jsp.attribute description="A fully qualified class name to a custom
* InterceptColumn implementation. Could also be a named type
* in the preferences. Used to add or modify column
* attributes." required="false" rtexprvalue="true"
*/
public void setInterceptor(String interceptor) {
this.interceptor = interceptor;
}
/**
* @jsp.attribute description="Used if the format needs to be interpreted.
* For instance, a date needs to be parsed in the specific
* format, such as MM-dd-yyyy." required="false"
* rtexprvalue="true"
*/
public void setParse(String parse) {
this.parse = parse;
}
/**
* @jsp.attribute description="The bean attribute to use for the column."
* required="false" rtexprvalue="true"
*/
public void setProperty(String property) {
this.property = property;
}
/**
* @jsp.attribute description="Specify whether or not the column should be
* sortable. The acceptable values are true or false. The
* default is to use the value for the table sortable
* attribute." required="false" rtexprvalue="true"
*/
public void setSortable(String sortable) {
this.sortable = sortable;
}
/**
* @jsp.attribute description="The css inline style sheet." required="false"
* rtexprvalue="true"
*/
public void setStyle(String style) {
this.style = style;
}
/**
* @jsp.attribute description="The css class style sheet." required="false"
* rtexprvalue="true"
*/
public void setStyleClass(String styleClass) {
this.styleClass = styleClass;
}
/**
* @jsp.attribute description="The display for the table column header. If
* the title is not specified then it will default to the
* name of the property, changing the camelcase syntax to
* separate words." required="false" rtexprvalue="true"
*/
public void setTitle(String title) {
this.title = title;
}
/**
* @jsp.attribute description="The value for the column. If the value
* attribute is not specifed then it will be retrieved
* automatically using the property attribute. The value can
* also be defined within the column body." required="false"
* rtexprvalue="true"
*/
public void setValue(Object value) {
this.value = value;
}
/**
* @jsp.attribute description="The comma separated list of views that this
* column will be used in." required="false"
* rtexprvalue="true"
*/
public void setViewsAllowed(String viewsAllowed) {
this.viewsAllowed = viewsAllowed;
}
/**
* @jsp.attribute description="The comma separated list of views that this
* column will not be used in." required="false"
* rtexprvalue="true"
*/
public void setViewsDenied(String viewsDenied) {
this.viewsDenied = viewsDenied;
}
/**
* @jsp.attribute description="Specify the column width." required="false"
* rtexprvalue="true"
*/
public void setWidth(String width) {
this.width = width;
}
/**
* Get the value for the column. First look to see if it displayed in the
* body of the column. If it is not in the body, then use the value
* attribute. If the value attribute is not specified then use the property
* attribute to find the value in the bean. Note: Weblogic will always
* return a bodyContent so do additional checking.
*/
protected Object getColumnValue(Object propertyValue) throws JspException {
Object result = value;
if (result == null && bodyContent != null) {
result = getBodyContent().getString();
}
if (result != null) {
result = ExpressionEvaluatorManager.evaluate("result", result.toString(), Object.class, this, pageContext);
}
if (result == null || (result != null && result instanceof String && StringUtils.isBlank(result.toString()))) {
if (escapeHtml) {
result = propertyValue == null ? null : StringEscapeUtils.escapeHtml4(propertyValue.toString());
} else {
result = propertyValue;
}
}
return result;
}
@Override
public int doStartTag() throws JspException {
if (!TagUtils.isIteratingBody(this)) {
return SKIP_BODY;
}
return EVAL_BODY_BUFFERED;
}
/**
* Must make a copy of the column because this tag may be reused. Send the
* copy up to the Model.
*/
@Override
public int doEndTag() throws JspException {
try {
TableModel model = TagUtils.getModel(this);
if (TagUtils.isIteratingBody(this)) {
String alias = TagUtils.evaluateExpressionAsString("alias", this.alias, this, pageContext);
String property = TagUtils.evaluateExpressionAsString("property", this.property, this, pageContext);
Column column = model.getColumnHandler().getColumnByAlias(TableModelUtils.getAlias(alias, property));
if (column != null) { // null if view not allowed
Object bean = TagUtils.getModel(this).getCurrentRowBean();
Object propertyValue = TableModelUtils.getColumnPropertyValue(bean, property);
column.setValue(getColumnValue(propertyValue));
column.setPropertyValue(propertyValue);
modifyColumnAttributes(model, column);
model.getColumnHandler().modifyColumnAttributes(column);
model.getViewHandler().addColumnValueToView(column);
}
} else {
Column column = new Column(model);
column.setAlias(TagUtils.evaluateExpressionAsString("alias", this.alias, this, pageContext));
column.setCalc(TagUtils.evaluateExpressionAsString("calc", this.calc, this, pageContext));
column.setCalcTitle(TagUtils.evaluateExpressionAsString("calcTitle", calcTitle, this, pageContext));
column.setCell(TagUtils.evaluateExpressionAsString("cell", this.cell, this, pageContext));
column.setEscapeAutoFormat(TagUtils.evaluateExpressionAsBoolean("escapeAutoFormat",
this.escapeAutoFormat,
this,
pageContext));
column.setFilterable(TagUtils.evaluateExpressionAsBoolean("filterable",
this.filterable,
this,
pageContext));
column.setFilterCell(TagUtils.evaluateExpressionAsString("filterCell",
this.filterCell,
this,
pageContext));
column.setFilterClass(TagUtils.evaluateExpressionAsString("filterClass",
this.filterClass,
this,
pageContext));
column.setFilterOptions(TagUtils.evaluateExpressionAsObject("filterOptions",
this.filterOptions,
this,
pageContext));
column.setFilterStyle(TagUtils.evaluateExpressionAsString("filterStyle",
this.filterStyle,
this,
pageContext));
column.setFormat(TagUtils.evaluateExpressionAsString("format", this.format, this, pageContext));
column.setHeaderCell(TagUtils.evaluateExpressionAsString("headerCell",
this.headerCell,
this,
pageContext));
column.setHeaderClass(TagUtils.evaluateExpressionAsString("headerClass",
this.headerClass,
this,
pageContext));
column.setHeaderStyle(TagUtils.evaluateExpressionAsString("headerStyle",
this.headerStyle,
this,
pageContext));
column.setInterceptor(TagUtils.evaluateExpressionAsString("interceptor",
this.interceptor,
this,
pageContext));
column.setParse(TagUtils.evaluateExpressionAsString("parse", this.parse, this, pageContext));
column.setProperty(TagUtils.evaluateExpressionAsString("property", this.property, this, pageContext));
column.setSortable(TagUtils.evaluateExpressionAsBoolean("sortable", this.sortable, this, pageContext));
column.setStyle(TagUtils.evaluateExpressionAsString("style", this.style, this, pageContext));
column.setStyleClass(TagUtils.evaluateExpressionAsString("styleClass",
this.styleClass,
this,
pageContext));
column.setTitle(TagUtils.evaluateExpressionAsString("title", this.title, this, pageContext));
column.setViewsAllowed(TagUtils.evaluateExpressionAsString("viewsToAllow",
this.viewsAllowed,
this,
pageContext));
column.setViewsDenied(TagUtils.evaluateExpressionAsString("viewsToDeny",
this.viewsDenied,
this,
pageContext));
column.setWidth(TagUtils.evaluateExpressionAsString("width", this.width, this, pageContext));
addColumnAttributes(model, column);
model.getColumnHandler().addColumn(column);
}
if (bodyContent != null) {
bodyContent.clearBody();
}
} catch (Exception e) {
throw new JspException("ColumnTag.doEndTag() Problem: " + ExceptionUtils.formatStackTrace(e));
}
return EVAL_PAGE;
}
public void addColumnAttributes(TableModel model, Column column) {
}
public void modifyColumnAttributes(TableModel model, Column column) {
}
@Override
public void release() {
alias = null;
calc = null;
calcTitle = null;
cell = null;
escapeAutoFormat = null;
filterable = null;
filterCell = null;
filterClass = null;
filterStyle = null;
format = null;
headerCell = null;
headerClass = null;
headerStyle = null;
interceptor = null;
parse = null;
property = null;
sortable = null;
style = null;
styleClass = null;
title = null;
value = null;
viewsAllowed = null;
viewsDenied = null;
width = null;
super.release();
}
}
| true
|
26ebe89eec1675c743c8e9f447feaa9b2ec426df
|
Java
|
InsideZhou/southern-quiet
|
/event-spring-boot-starter-redis/src/main/java/me/insidezhou/southernquiet/event/driver/RedisEventPubSub.java
|
UTF-8
| 4,766
| 2.25
| 2
|
[
"BSD-3-Clause"
] |
permissive
|
package me.insidezhou.southernquiet.event.driver;
import com.fasterxml.jackson.databind.ObjectMapper;
import me.insidezhou.southernquiet.FrameworkAutoConfiguration;
import me.insidezhou.southernquiet.event.RedisTemplateProvider;
import me.insidezhou.southernquiet.logging.SouthernQuietLogger;
import me.insidezhou.southernquiet.logging.SouthernQuietLoggerFactory;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.context.ApplicationContext;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.listener.ChannelTopic;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.util.Assert;
import java.io.Serializable;
import java.util.Map;
import java.util.Objects;
@SuppressWarnings("rawtypes")
public class RedisEventPubSub<E extends Serializable> extends AbstractEventPubSub<E> implements DisposableBean {
private final static SouthernQuietLogger log = SouthernQuietLoggerFactory.getLogger(RedisEventPubSub.class);
public final static String EventTypeIdName = "TypeId";
private final RedisTemplate redisTemplate;
private final RedisSerializer<E> eventSerializer;
private final RedisSerializer channelSerializer;
private final ObjectMapper objectMapper;
private final RedisMessageListenerContainer container;
public RedisEventPubSub(RedisTemplateProvider<E> provider,
ObjectMapper objectMapper,
FrameworkAutoConfiguration.EventProperties properties,
ApplicationContext applicationContext) {
super(properties, applicationContext);
this.objectMapper = objectMapper;
this.redisTemplate = provider.getRedisTemplate();
this.eventSerializer = provider.getEventSerializer();
this.channelSerializer = provider.getChannelSerializer();
this.container = new RedisMessageListenerContainer();
container.setConnectionFactory(provider.getConnectionFactory());
}
@SuppressWarnings({"unchecked", "ConstantConditions"})
@Override
protected void broadcast(E event, String[] channels, String eventType) {
Assert.notNull(event, "null事件无法发布");
Map map = objectMapper.convertValue(event, Map.class);
map.put(EventTypeIdName, eventType);
byte[] message = eventSerializer.serialize((E) map);
redisTemplate.execute((RedisConnection connection) -> {
for (String channel : channels) {
connection.publish(channelSerializer.serialize(channel), message);
}
return null;
});
}
@Override
protected void initChannel(String channel) {
log.message("创建RedisMessageListener").context("channel", channel).debug();
container.addMessageListener(this::onMessage, new ChannelTopic(channel));
}
@Override
public void afterPropertiesSet() throws Exception {
super.afterPropertiesSet();
container.afterPropertiesSet();
container.start();
}
protected void onMessage(Message message, byte[] patternRaw) {
String channel = Objects.requireNonNull(channelSerializer.deserialize(message.getChannel())).toString();
String pattern = Objects.requireNonNull(redisTemplate.getStringSerializer().deserialize(patternRaw)).toString();
byte[] data = message.getBody();
onMessageReceived(channel, data, pattern);
E event = eventSerializer.deserialize(data);
if (null == event) {
log.message("收到空事件")
.context(context -> {
context.put("channel", channel);
context.put("pattern", pattern);
context.put("data", new String(data));
})
.trace();
return;
}
onEventDeserialized(channel, event, pattern);
}
protected void onMessageReceived(String channel, byte[] data, String pattern) {
log.message("收到事件")
.context(context -> {
context.put("channel", channel);
context.put("pattern", pattern);
context.put("data", new String(data));
})
.debug();
}
@SuppressWarnings("unused")
protected void onEventDeserialized(String channel, E event, String pattern) {
publishToLocalOnly(event);
}
@Override
public void destroy() throws Exception {
container.destroy();
}
}
| true
|
21c40f2967c4b9360ad25b4264af209a065049fa
|
Java
|
jorgeaperez/firstRepository
|
/Vigener.java
|
UTF-8
| 554
| 2.6875
| 3
|
[] |
no_license
|
public class Vigener {
/**
* @param args
*/
public static void main(String[] args) {
String word = "crypto";
String m = "whatanicedaytoday";
String result ="";
System.out.println((int)word.charAt(0));
System.out.println((m.toString().charAt(0)+word.toString().charAt(0))%26);
System.out.println(word.charAt(1)%26);
System.out.println((int)(m.charAt(1))-96);
System.out.println((int)(word.charAt(1))-96);
for(int i =0;i<m.length();i++){
for(int j=0;j<word.length();j++){
}
}
}
}
| true
|
15886523fe870957a19d7f68ef239fa77c04dfa7
|
Java
|
apache/sling-whiteboard
|
/graalvm/src/main/java/org/apache/sling/graalvm/sling/MockErrorHandler.java
|
UTF-8
| 831
| 2.21875
| 2
|
[
"Apache-2.0"
] |
permissive
|
package org.apache.sling.graalvm.sling;
import java.io.IOException;
import org.apache.sling.api.SlingHttpServletRequest;
import org.apache.sling.api.SlingHttpServletResponse;
import org.apache.sling.engine.servlets.ErrorHandler;
public class MockErrorHandler implements ErrorHandler {
@Override
public void handleError(int status, String message, SlingHttpServletRequest request,
SlingHttpServletResponse response) throws IOException {
response.getWriter().write(getClass().getSimpleName() + ':' + status + ':' + message);
}
@Override
public void handleError(Throwable throwable, SlingHttpServletRequest request, SlingHttpServletResponse response)
throws IOException {
response.getWriter().write(getClass().getSimpleName() + ':' + throwable.toString());
}
}
| true
|
7d70457d08dfcbae1242495f27236834db6fa7eb
|
Java
|
chenjiwawa/sansehua
|
/app/src/main/java/com/zl/dappore/photo/PhotoCutActivity.java
|
UTF-8
| 2,759
| 1.992188
| 2
|
[] |
no_license
|
package com.zl.dappore.photo;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import com.qsmaxmin.qsbase.common.log.L;
import com.qsmaxmin.qsbase.common.utils.QsHelper;
import com.qsmaxmin.qsbase.common.viewbind.annotation.Bind;
import com.qsmaxmin.qsbase.common.viewbind.annotation.OnClick;
import com.qsmaxmin.qsbase.mvp.QsABActivity;
import com.zl.dappore.R;
import com.zl.dappore.common.model.UserConfig;
import com.zl.dappore.common.widget.CutImageView;
import com.zl.dappore.photo.model.PhotoConstants;
import com.zl.dappore.photo.presenter.PhotoCutPresenter;
import java.io.ByteArrayOutputStream;
/**
* @CreateBy qsmaxmin
* @Date 16/9/18 下午4:53
* @Description 裁剪图片
*/
public class PhotoCutActivity extends QsABActivity<PhotoCutPresenter> {
@Bind(R.id.civ_photo)
CutImageView civ_photo;
@Bind(android.R.id.title)
TextView title;
@Bind(R.id.tv_right)
TextView tv_right;
@Bind(R.id.cut_cancel)
Button cut_cancel;
@Bind(R.id.cut_ok)
Button cut_ok;
/**
* 设置标题
*/
@Override
public int actionbarLayoutId() {
return R.layout.actionbar_right_text;
}
/**
* 设置布局
*/
@Override
public int layoutId() {
return R.layout.activity_cutphoto;
}
/**
* 初始化数据
*/
@Override
public void initData(Bundle savedInstanceState) {
tv_right.setVisibility(View.GONE);
String head_path = getIntent().getExtras().getString(PhotoConstants.BUNDLE_KEY_PHOTO_PATH);
civ_photo.setFilePath(head_path);
title.setText(QsHelper.getInstance().getString(R.string.move_zoom));
}
/**
* 返回按钮
*/
@OnClick({R.id.layout_title_back, R.id.cut_cancel, R.id.cut_ok})
public void onViewClick(View view) {
super.onViewClick(view);
switch (view.getId()) {
case R.id.layout_title_back:
onBackPressed();
break;
case R.id.cut_cancel:
onBackPressed();
break;
case R.id.cut_ok:
Bitmap bitmap = civ_photo.clip();
L.i(initTag(),"cut bitmap success width:" + bitmap.getWidth() + " charHeight:" + bitmap.getHeight() + " byte:" + bitmap.getByteCount());
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 50, baos);
getPresenter().requestChangeHead(UserConfig.getInstance().getId(),baos.toByteArray());
bitmap.recycle();
break;
default:
break;
}
}
}
| true
|
9659493a33333327e7c86074e7c8fda01550900a
|
Java
|
stevenay/App_Design
|
/app/src/main/java/net/naylinaung/appdesign/data/vos/LessonCardVO.java
|
UTF-8
| 1,518
| 2.4375
| 2
|
[] |
no_license
|
package net.naylinaung.appdesign.data.vos;
/**
* Created by Dell on 9/8/2016.
*/
public class LessonCardVO {
private int cardID;
private int courseID;
private Integer chapterID;
private String lessonImage;
private String lessonDescription;
private Integer cardOrderNumber;
private boolean bookmarked;
public int getCardID() {
return cardID;
}
public void setCardID(int cardID) {
this.cardID = cardID;
}
public int getCourseID() {
return courseID;
}
public void setCourseID(int courseID) {
this.courseID = courseID;
}
public Integer getChapterID() {
return chapterID;
}
public void setChapterID(Integer chapterID) {
this.chapterID = chapterID;
}
public String getLessonImage() {
return lessonImage;
}
public void setLessonImage(String lessonImage) {
this.lessonImage = lessonImage;
}
public String getLessonDescription() {
return lessonDescription;
}
public void setLessonDescription(String lessonDescription) {
this.lessonDescription = lessonDescription;
}
public int getCardOrderNumber() {
return cardOrderNumber;
}
public void setCardOrderNumber(int cardOrderNumber) {
this.cardOrderNumber = cardOrderNumber;
}
public boolean isBookmarked() {
return bookmarked;
}
public void setBookmarked(boolean bookmarked) {
this.bookmarked = bookmarked;
}
}
| true
|
94fc16aca6638f5e1463b18fa50e62d8b3f144dc
|
Java
|
yadavraju/encog-java-core
|
/src/main/java/org/encog/neural/error/CrossEntropyErrorFunction.java
|
UTF-8
| 549
| 2.921875
| 3
|
[
"BSD-3-Clause",
"Apache-2.0"
] |
permissive
|
package org.encog.neural.error;
/**
* Implements a cross entropy error function. This can be used with backpropagation to
* sometimes provide better performance than the standard linear error function.
* @author jheaton
*
*/
public class CrossEntropyErrorFunction implements ErrorFunction {
/**
* {@inheritDoc}
*/
@Override
public void calculateError(double[] ideal, double[] actual, double[] error) {
for(int i=0;i<actual.length;i++) {
error[i] = -ideal[i] * Math.log(actual[i]) + (1-ideal[i])*Math.log(1-actual[i]);
}
}
}
| true
|
e7529f95f63680a6d08930549273fde26c55ec5d
|
Java
|
mrjato/IO
|
/4.1/src/org/proteomecommons/io/CentroidedPeak.java
|
UTF-8
| 1,577
| 2.3125
| 2
|
[] |
no_license
|
/*
* Copyright 2005 The Regents of the University of Michigan
*
* 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.proteomecommons.io;
/**
* Abstraction of a peptide fragment, i.e. a "peak" in either MS/MS or MS
* spectra.
*
* @author Jayson Falkner - jfalkner@umich.edu
*
*/
public interface CentroidedPeak extends Peak {
/**
* Constant for flagging if this peak's mass was determined from averaging.
*/
public static int UNKNOWN_AVERAGED = Integer.MIN_VALUE;
/**
* Flags that symbolizes this peak was averaged and reduced to a
* monoisotopic peak, not resolved to a visible monoisotopic peak. Older
* instruments and current instruments dealing with high charge states often
* can't accurately resolve a monoisotopic peak.
*/
public static int AVERAGED = 0;
/**
* Flags that the monoisotopic peak was clearly resolved, not averaged.
*/
public static int RESOLVED = 1;
/**
* A read-only method of obtaining if the monoisotopic mass was clearly
* resolved or if it was averaged.
*
* @return
*/
public int getAveraged();
}
| true
|
9bf27f19a03817396049bac7ee233cb1a3153730
|
Java
|
jaycsa19/aconex-coding-challenge
|
/src/test/java/UtilsTest.java
|
UTF-8
| 3,528
| 2.921875
| 3
|
[] |
no_license
|
import com.aconex.util.Utils;
import org.junit.Assert;
import org.junit.Test;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class UtilsTest {
@Test
public void testReturnNullIfStringIsNullRemovePunctuationTest() {
String s = Utils.removePunctuation(null);
Assert.assertEquals(null, s);
}
@Test
public void testRemovePunctuationAndWhiteSpaceTest() {
String s = Utils.removePunctuation("flow er,pot^");
Assert.assertEquals("flowerpot", s);
}
@Test
public void testReturnNullIfStringIsEmptyRemovePunctuationTest() {
String s = Utils.removePunctuation("");
Assert.assertEquals(null, s);
}
@Test
public void testReturnNullIfStringHasAllPunctuationRemovePunctuationTest() {
String s = Utils.removePunctuation("$...,*");
Assert.assertEquals(null, s);
}
@Test
public void testReturnNullIfStringIsNullRemoveUnwantedCharsFromPhoneTest() {
String s = Utils.removeUnwantedCharsFromPhone(null);
Assert.assertEquals(null, s);
}
@Test
public void testRemoveUnwantedCharsFromPhoneTest() {
String s = Utils.removeUnwantedCharsFromPhone("123.:^45. 4");
Assert.assertEquals("123.45.4", s);
}
@Test
public void testReturnNullIfStringIsEmptyRemoveUnwantedCharsFromPhoneTest() {
String s = Utils.removeUnwantedCharsFromPhone("");
Assert.assertEquals(null, s);
}
@Test
public void testReturnNullIfStringHasAllPunctuationRemoveUnwantedCharsFromPhoneTest() {
String s = Utils.removeUnwantedCharsFromPhone("$--- ,*");
Assert.assertEquals(null, s);
}
@Test
public void testReturnHyphenSeparatedStringsCombinePhrasesTest() {
List<List<String>> input = new ArrayList<List<String>>();
List<String> phrase1 = new ArrayList<String>();
phrase1.add("mul");
phrase1.add("add");
phrase1.add("sub");
List<String> digit = new ArrayList<String>();
digit.add("1");
List<String> phrase2 = new ArrayList<String>();
phrase2.add("ab");
phrase2.add("cd");
input.add(phrase1);
input.add(digit);
input.add(phrase2);
Set<String> actual = Utils.combinePhrases(input);
Set<String> expected = new HashSet<String>();
expected.add("add-1-ab");
expected.add("mul-1-ab");
expected.add("sub-1-ab");
expected.add("mul-1-cd");
expected.add("add-1-cd");
expected.add("sub-1-cd");
Assert.assertEquals(expected, actual);
}
@Test
public void testReturnNULLIfNullListCombinePhrasesTest() {
Set<String> actual = Utils.combinePhrases(null);
Assert.assertEquals(null, actual);
}
@Test
public void testReturnSetIfListOfSizeOneCombinePhrasesTest() {
List<List<String>> input = new ArrayList<List<String>>();
List<String> phrase1 = new ArrayList<String>();
phrase1.add("abc");
input.add(phrase1);
Set<String> expected = new HashSet<String>();
expected.add("abc");
Set<String> actual = Utils.combinePhrases(input);
Assert.assertEquals(expected, actual);
}
@Test
public void testReturnNULLIfEmptyListCombinePhrasesTest() {
List<List<String>> input = new ArrayList<List<String>>();
Set<String> actual = Utils.combinePhrases(input);
Assert.assertEquals(null, actual);
}
}
| true
|
4866dbb37574567dda4cea63121e2a62dab947c9
|
Java
|
chnng/AchingMarket
|
/app/src/main/java/com/market/aching/model/AccountInfo.java
|
UTF-8
| 1,433
| 2.34375
| 2
|
[] |
no_license
|
package com.market.aching.model;
import android.os.Parcel;
import android.os.Parcelable;
/**
* Created by chnng on 2017/4/2.
*/
public class AccountInfo implements Parcelable
{
public String account;
public byte[] password;
public int loginState;
public String name;
public String address;
public String icon;
public AccountInfo()
{
}
@Override
public int describeContents()
{
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags)
{
dest.writeString(this.account);
dest.writeByteArray(this.password);
dest.writeInt(this.loginState);
dest.writeString(this.name);
dest.writeString(this.address);
dest.writeString(this.icon);
}
protected AccountInfo(Parcel in)
{
this.account = in.readString();
this.password = in.createByteArray();
this.loginState = in.readInt();
this.name = in.readString();
this.address = in.readString();
this.icon = in.readString();
}
public static final Creator<AccountInfo> CREATOR = new Creator<AccountInfo>()
{
@Override
public AccountInfo createFromParcel(Parcel source)
{
return new AccountInfo(source);
}
@Override
public AccountInfo[] newArray(int size)
{
return new AccountInfo[size];
}
};
}
| true
|
bc28ba748987aa6e60113b51470e3f07c54c4e64
|
Java
|
ehuang3/robotic_pulling
|
/matlab/experiments/ros_interface/ros_packages/matlab_gen/build/rosjava_build/robot_comm/build/generated-src/robot_comm/robot_SetSpeed.java
|
UTF-8
| 336
| 2.0625
| 2
|
[] |
no_license
|
package robot_comm;
public interface robot_SetSpeed extends org.ros.internal.message.Message {
static final java.lang.String _TYPE = "robot_comm/robot_SetSpeed";
static final java.lang.String _DEFINITION = "# Service to Set the max Speed of the robot.\n\nfloat64 tcp # mm/s\nfloat64 ori # deg/s\n---\nint64 ret\nstring msg\n";
}
| true
|
2b4a36f81fcd3a3f70f8539d8021f509f3cafe7c
|
Java
|
mkrtichi/VectorDisplay
|
/app/src/main/java/mobi/omegacentauri/vectordisplay/WifiService.java
|
UTF-8
| 7,257
| 1.984375
| 2
|
[
"MIT"
] |
permissive
|
package mobi.omegacentauri.vectordisplay;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbDeviceConnection;
import android.hardware.usb.UsbManager;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.util.Log;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;
public class WifiService extends ConnectionService {
public static final int PORT = 7788;
public static boolean SERVICE_CONNECTED = false;
public boolean stop = false;
public String ipAddress = "";
private WifiServer server;
private WifiInfo wifiInfo;
@Override
synchronized public void onDestroy() {
super.onDestroy();
if (server != null)
server.close();
stop = true;
WifiService.SERVICE_CONNECTED = false;
}
@Override
public void onCreate() {
super.onCreate();
Log.v("VectorDisplay", "on create WiFiService");
WifiService.SERVICE_CONNECTED = true;
new WifiService.ConnectionThread().start();
}
@Override
synchronized public void write(byte[] data) {
if (server != null) { // TODO: fix synchronization
server.write(data);
}
}
/*
* This function will be called from MainActivity to change baud rate
*/
@Override
public void disconnectDevice() {
if (server != null && server.mClient != null) {
try {
server.mClient.close();
server.mClient = null;
} catch (IOException e) {
}
}
}
@Override
synchronized public void close() {
if (server != null)
server.close();
stop = true;
stopSelf();
}
@Override
public void setRecord(RecordAndPlay r) {
super.setRecord(r);
if (wifiInfo != null && wifiInfo.getNetworkId() != -1) {
int ip = wifiInfo.getIpAddress();
if (record != null) {
record.setDisconnectedStatus(new String[]{"WiFi device not connected", "Connect to " + ipString(ip)});
record.forceUpdate();
}
}
}
private static String ipString(int ip) {
return "" + (0xFF & ip) + "." + (0xFF & (ip >> 8)) + "." + (0xFF & (ip >> 16)) + "." + (0xFF & (ip >> 24));
}
private class ConnectionThread extends Thread {
@Override
public void run() {
boolean done = false;
do {
server = null;
WifiManager wifiManager = (WifiManager) getApplicationContext().getSystemService(WIFI_SERVICE);
int net = -1;
int ip = 0;
if (wifiManager != null) {
wifiInfo = wifiManager.getConnectionInfo();
net = wifiInfo.getNetworkId();
if (net != -1)
ip = wifiInfo.getIpAddress();
}
else
wifiInfo = null;
if (ip != 0) {
if (record != null) {
record.setDisconnectedStatus(new String[]{"WiFi device not connected", "Connect to " + ipString(ip)});
MainActivity.log("ip "+ipString(ip));
record.forceUpdate();
}
try {
synchronized (WifiService.this) {
done = true;
server = new WifiServer(WifiService.this, PORT);
}
server.start();
} catch (Exception e) {
if (server != null) {
server.stop();
server = null;
}
}
if (!done) {
synchronized (WifiService.this) {
if (WifiService.this.stop)
break;
}
}
}
else {
if (record != null)
record.setDisconnectedStatus(new String[]{"WiFi not connected"});
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
}
} while(!done);
Intent intent = new Intent(ACTION_DEVICE_DISCONNECTED); // TODO: more informative
context.sendBroadcast(intent);
}
}
public class WifiServer extends Thread {
private ServerSocket listener;
WifiService wifiService;
Socket mClient = null;
InputStream in = null;
OutputStream out = null;
byte[] byteBuffer = new byte[256];
Boolean stop;
public WifiServer(WifiService service, int port) throws IOException {
listener = new ServerSocket(port);
wifiService = service;
}
@Override
public void run() {
stop = false;
while(! stop) {
synchronized(wifiService) {
if (wifiService.stop)
break;
}
try {
WifiServer.this.mClient = listener.accept();
Socket client = WifiServer.this.mClient; // local copy
Log.v("VectorDisplay", "Accepted");
in = client.getInputStream();
synchronized(WifiServer.this) {
out = client.getOutputStream();
}
wifiService.broadcast(ConnectionService.ACTION_DEVICE_CONNECTED);
while(client.isConnected()) {
int n = in.read(byteBuffer);
wifiService.record.feed(byteBuffer, n);
}
} catch (IOException e) {
Log.v("VectorDisplay", "disconnected client");
}
stopClient();
}
}
public void close() {
stopClient();
stop = true;
if (listener != null) {
try {
listener.close();
} catch (IOException e) {
listener = null;
}
}
}
public void stopClient() {
wifiService.broadcast(ACTION_DEVICE_DISCONNECTED);
if (mClient != null) {
try {
mClient.close();
} catch (IOException e1) {
}
mClient = null;
}
}
synchronized public void write(byte[] data) {
if (out != null) {
try {
out.write(data);
} catch (IOException e) {
}
}
}
}
}
| true
|
e09e43251c386a220c92b6889e3d669d35d080e5
|
Java
|
adamorzelski/product_RESTservice_app
|
/src/main/java/com/example/product_app/model/type/ProductTypeEnum.java
|
UTF-8
| 100
| 2.015625
| 2
|
[] |
no_license
|
package com.example.product_app.model.type;
public enum ProductTypeEnum {
MALE, FEMALE, KID
}
| true
|
7efb493d03bf73b2fe04393f2abeb42dc3d39ef1
|
Java
|
BaeJaeHyun7/Eclipse-Workspace-Test
|
/IT20200518/src/Truck.java
|
UHC
| 910
| 3.453125
| 3
|
[] |
no_license
|
public class Truck extends Vehicle {
double maxLoad; //ִ 緮
public Truck(int w, int s, double max) {
super(); // ڿ ִ ۱(θ ) -> Vehicle (Vehicle();)
//Ӱ ִ
//θŬ ã°Ŵ
//super θ super();
//ڴ ü ̴
System.out.println("Truck ȣ");
numberOfWheel = w;
numberOfSeat = s;
maxLoad = max;
}
//ȭ ĭ ƴ
public void load() {
}
//Vehicle(θ) startҵ带 Truck ̵ؼ
@Override
//̼(̴ annotation θ) : ̵ ̼
public void start() {
System.out.println("Ʈ ߱");
}
}
| true
|
c4df42591153aff09280de6b47c43ebafe90cafe
|
Java
|
Billy-Chung/CFA102G4
|
/src/com/generalMemberPetPhotos/model/GeneralMemberPetPhotosDAO.java
|
UTF-8
| 5,833
| 2.21875
| 2
|
[] |
no_license
|
package com.generalMemberPetPhotos.model;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import com.adoptMemberReport.model.AdoptMemberReportVO;
public class GeneralMemberPetPhotosDAO implements GeneralMemberPetPhotosDAO_Interface {
public static final String DRIVER = "com.mysql.cj.jdbc.Driver";
public static final String URL = "jdbc:mysql://localhost:3306/CFA_102_04?serverTimezone=Asia/Taipei";
public static final String USER = "David";
public static final String PASSWORD = "123456";
public static final String INSERT_SQL ="INSERT INTO GENERAL_MEMBER_PET_PHOTOS VALUES (?, ?, ?)";
public static final String UPDATE_SQL ="UPDATE GENERAL_MEMBER_PET_PHOTOS SET GEN_MEB_NO=?,GEN_MEB_PET_PHOTO=? WHERE GEN_MEB_PET_PHOTO_NO=?";
public static final String DELETE_SQL ="DELETE FROM GENERAL_MEMBER_PET_PHOTOS WHERE GEN_MEB_PET_PHOTO_NO=?";
public static final String FIND_BY_DEPTNO_SQL = "SELECT * FROM GENERAL_MEMBER_PET_PHOTOS WHERE GEN_MEB_PET_PHOTO_NO = ?";
public static final String GET_ALL_SQL = "SELECT * FROM GENERAL_MEMBER_PET_PHOTOS";
static {
try {
Class.forName(DRIVER);
} catch(ClassNotFoundException e) {
e.printStackTrace();
}
}
@Override
public void insert(GeneralMemberPetPhotosVO gmppVO) {
Connection conn = null;
PreparedStatement pst = null;
try {
conn = DriverManager.getConnection(URL,USER,PASSWORD);
pst = conn.prepareStatement(INSERT_SQL);
pst.setInt(1,gmppVO.getGen_meb_photo_no());
pst.setInt(2,gmppVO.getGen_meb_no());
pst.setBytes(3,gmppVO.getGen_meb_pet_photo());
pst.executeUpdate();
}catch(SQLException se) {
se.printStackTrace();
} finally {
if(pst!=null) {
try {
pst.close();
} catch(SQLException se) {
se.printStackTrace();
}
}
if(conn !=null) {
try {
conn.close();
} catch (SQLException se) {
se.printStackTrace();
}
}
}
}
@Override
public void update(GeneralMemberPetPhotosVO gmppVO) {
Connection conn = null;
PreparedStatement pst = null;
try {
conn = DriverManager.getConnection(URL,USER,PASSWORD);
pst = conn.prepareStatement(UPDATE_SQL);
pst.setInt(1,gmppVO.getGen_meb_no());
pst.setBytes(2,gmppVO.getGen_meb_pet_photo());
pst.setInt(3,gmppVO.getGen_meb_photo_no());
pst.executeUpdate();
}catch(SQLException se) {
se.printStackTrace();
} finally {
if(pst!=null) {
try {
pst.close();
} catch(SQLException se) {
se.printStackTrace();
}
}
if(conn !=null) {
try {
conn.close();
} catch (SQLException se) {
se.printStackTrace();
}
}
}
}
@Override
public void delete(Integer gmppno) {
Connection con = null;
PreparedStatement pstmt = null;
try {
con = DriverManager.getConnection(URL,USER,PASSWORD);
pstmt = con.prepareStatement(DELETE_SQL);
pstmt.setInt(1,gmppno);
pstmt.executeUpdate();
}catch(SQLException e) {
e.printStackTrace();
}finally {
if(pstmt!=null) {
try {
pstmt.close();
}catch(SQLException e) {
e.printStackTrace();
}
}
if(con!=null) {
try {
con.close();
}
catch(SQLException e) {
e.printStackTrace();
}
}
}
}
@Override
public GeneralMemberPetPhotosVO findByPrimaryKey(Integer gmpno) {
Connection con = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
GeneralMemberPetPhotosVO gmppVO = null;
try {
con = DriverManager.getConnection(URL,USER,PASSWORD);
pstmt = con.prepareStatement(FIND_BY_DEPTNO_SQL);
pstmt.setInt(1,gmpno);
rs = pstmt.executeQuery();
while(rs.next()) {
//進來代表有查到資料,就用一個Dept的Bean來包裝著查詢出來的部門資料
gmppVO = new GeneralMemberPetPhotosVO();
gmppVO.setGen_meb_photo_no(gmpno);
gmppVO.setGen_meb_no(rs.getInt("GEN_MEB_NO"));
gmppVO.setGen_meb_pet_photo(rs.getBytes("GEN_MEB_PET_PHOTO"));
}
} catch(SQLException se) {
se.printStackTrace();
} finally {
if (rs != null) {
try {
rs.close();
} catch (SQLException se) {
se.printStackTrace();
}
}
if (pstmt != null) {
try {
pstmt.close();
} catch (SQLException se) {
se.printStackTrace();
}
}
if (con != null) {
try {
con.close();
} catch (SQLException se) {
se.printStackTrace();
}
}
}
return gmppVO;
}
@Override
public List<GeneralMemberPetPhotosVO> getAll() {
Connection con = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
List <GeneralMemberPetPhotosVO> gmppList = new ArrayList<>();
try {
con = DriverManager.getConnection(URL,USER,PASSWORD);
pstmt = con.prepareStatement(GET_ALL_SQL);
rs = pstmt.executeQuery();
while(rs.next()) {
//進來代表有查到資料,就用一個Dept的Bean來包裝著查詢出來的部門資料
GeneralMemberPetPhotosVO gmppVO = new GeneralMemberPetPhotosVO();
gmppVO.setGen_meb_photo_no(rs.getInt("GEN_MEB_PET_PHOTO_NO"));
gmppVO.setGen_meb_no(rs.getInt("GEN_MEB_NO"));
gmppVO.setGen_meb_pet_photo(rs.getBytes("GEN_MEB_PET_PHOTO"));
gmppList.add(gmppVO);
}
} catch(SQLException se) {
se.printStackTrace();
} finally {
if (rs != null) {
try {
rs.close();
} catch (SQLException se) {
se.printStackTrace();
}
}
if (pstmt != null) {
try {
pstmt.close();
} catch (SQLException se) {
se.printStackTrace();
}
}
if (con != null) {
try {
con.close();
} catch (SQLException se) {
se.printStackTrace();
}
}
}
return gmppList;
}
}
| true
|
1dbfe8d6be898cc1137a2e25a866bdb00d26a40b
|
Java
|
Chyngyzkam/jdbcAndHibernate
|
/jdbc/jdbcAndHibernate/src/main/java/peaksoft/dao/UserDaoJdbcImpl.java
|
UTF-8
| 3,385
| 2.9375
| 3
|
[] |
no_license
|
package peaksoft.dao;
import peaksoft.model.User;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
import static peaksoft.util.Util.connect;
public class UserDaoJdbcImpl implements UserDao {
public UserDaoJdbcImpl() {
}
public void createUsersTable() {
String createTable = "create table if not exists users("+
"id serial primary key,name varchar (40) not null,"+
"lastName varchar (40) not null ,"+
"age integer not null)";
try (Connection conn =connect();
Statement stmt = conn.createStatement()){
stmt.executeUpdate(createTable);
System.out.println("added Table");
} catch (SQLException ex) {
System.out.println(ex.getMessage());
}
}
public void dropUsersTable() {
String dropTable = "drop table if exists users";
try (Connection conn = connect();
PreparedStatement stmt = conn.prepareStatement(dropTable)) {
stmt.executeUpdate();
System.out.println("deleted Table");
} catch (SQLException ex) {
System.out.println(ex.getMessage());
}
}
public void saveUser(String name, String lastName, byte age) {
String addUser = "insert into users(name, lastName,age )" +
"values (?,?,?)";
try (Connection conn =connect();
PreparedStatement stmt = conn.prepareStatement(addUser)) {
stmt.setString(1, name);
stmt.setString(2, lastName);
stmt.setByte(3, age);
stmt.executeUpdate();
System.out.println(name + " " + lastName + "added to users");
} catch (SQLException e) {
System.out.println(e.getMessage());
}
}
public void removeUserById(long id) {
String delete = "delete from users where id= ?";
try (Connection conn = connect();
PreparedStatement stmt = conn.prepareStatement(delete)) {
stmt.setLong(1, id);
stmt.executeUpdate();
System.out.println("removed users by id");
} catch (SQLException e) {
System.out.println(e.getMessage());
}
}
public List<User> getAllUsers() {
ArrayList<User> users = new ArrayList<>();
String getAll = "select * from users";
try (Connection conn =connect();
Statement stmt = conn.createStatement();
ResultSet resSet = stmt.executeQuery(getAll)){
while (resSet.next()) {
User user = new User();
user.setId((long) resSet.getInt("id"));
user.setName(resSet.getString("name"));
user.setLastName(resSet.getString("lastName"));
user.setAge(resSet.getByte("age"));
users.add(user);
}
} catch (SQLException e) {
System.out.println(e.getMessage());
}
return users;
}
public void cleanUsersTable() {
String clean ="delete from users";
try(Connection conn =connect();
PreparedStatement stmt = conn.prepareStatement(clean)){
stmt.executeUpdate();
System.out.println("Deleted all users");
}catch(SQLException e){
System.out.println(e.getMessage());
}
}
}
| true
|
2ae14afe3f3c96ea97442dbc7bb0289006825532
|
Java
|
WilleamZhao/codframe
|
/cod-admin/src/main/java/com/tlkj/cod/admin/model/core/SystemSetAllowDisable.java
|
UTF-8
| 1,067
| 1.992188
| 2
|
[] |
no_license
|
/*
* Copyright (c) 2019.
* Beijing sky blue technology co., LTD.
* All rights reserved
*
* author: sourcod
* github: https://github.com/WilleamZhao
* site:http://codframe.sourcod.com
*/
package com.tlkj.cod.admin.model.core;
import java.util.List;
/**
* Desc 黑白名单设置
*
* @author sourcod
* @version 1.0
* @className SystemSetAllowDisable
* @date 2018/12/26 8:41 PM
*/
public class SystemSetAllowDisable {
private String allowDisable;
private List<String> blackList;
private List<String> whiteList;
public String getAllowDisable() {
return allowDisable;
}
public void setAllowDisable(String allowDisable) {
this.allowDisable = allowDisable;
}
public List<String> getBlackList() {
return blackList;
}
public void setBlackList(List<String> blackList) {
this.blackList = blackList;
}
public List<String> getWhiteList() {
return whiteList;
}
public void setWhiteList(List<String> whiteList) {
this.whiteList = whiteList;
}
}
| true
|
9584aee58bb0135788b1c7e8c5909a426f1bfb67
|
Java
|
suzhonghe/zyfy_market
|
/src/com/zhongyang/java/controller/AccountController.java
|
UTF-8
| 4,702
| 2.125
| 2
|
[] |
no_license
|
package com.zhongyang.java.controller;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.zhongyang.java.biz.FundAccountBiz;
import com.zhongyang.java.biz.UserFundBiz;
import com.zhongyang.java.pojo.User;
import com.zhongyang.java.system.SystemEnum;
import com.zhongyang.java.system.Exception.UException;
import com.zhongyang.java.vo.BankInfoVo;
import com.zhongyang.java.vo.ParamsPojo;
import com.zhongyang.java.vo.UserFundVo;
import com.zhongyang.java.vo.loan.LoanRepaymentVo;
import com.zhongyang.java.vo.loan.LoanVo;
/**
* @author 作者:zhaofq
* @version 创建时间:2015年12月1日 下午4:17:46 类说明:用户账户信息
*/
@Controller
public class AccountController extends BaseController {
@Autowired
private UserFundBiz userFundBiz;
@Autowired
private FundAccountBiz fundAccountBiz;
/*
* @return Obiect 通过userId获得UserFund跳转到充值页面--pc
*/
@RequestMapping(value = "/userFundRecharge")
public @ResponseBody UserFundVo userFundRecharge(HttpServletRequest request) {
User userI = (User) request.getSession().getAttribute("zycfLoginUser");
UserFundVo userFundVo = new UserFundVo();
try {
if (userI != null) {
userFundVo.setUserid(userI.getId());
userFundVo = userFundBiz.byUserId(userFundVo);
}
return userFundVo;
} catch (Exception e) {
throw new UException(SystemEnum.USER_NOLOGIN, "没有登录");
}
}
/*
* @return Obiect 通过userId获得UserFund跳转到充值页面--app
*/
@RequestMapping(value = "/mobileUserFundRecharge")
public @ResponseBody UserFundVo mobileUserFundRecharge(HttpServletRequest request) {
User userI = (User) request.getSession().getAttribute("zycfLoginUser");
UserFundVo userFundVo = new UserFundVo();
try {
if (userI != null) {
userFundVo.setUserid(userI.getId());
userFundVo = userFundBiz.mobileUserFundRecharge(userFundVo);
}
return userFundVo;
} catch (Exception e) {
throw new UException(SystemEnum.USER_NOLOGIN, "没有登录");
}
}
/*
* @return Obiect 通过userId获得UserFund跳转到提现页面:app和pc
*/
@RequestMapping(value = "/userFundWithdraw")
public @ResponseBody UserFundVo ByUserIdWithdraw(HttpServletRequest request) {
User userI = (User) request.getSession().getAttribute("zycfLoginUser");
try {
UserFundVo userFundVo = new UserFundVo();
if (userI != null) {
userFundVo.setUserid(userI.getId());
return userFundBiz.byUserIdWithdraw(userFundVo);
}else{
throw new UException(SystemEnum.USER_NOLOGIN, "没有登录");
}
} catch (Exception e) {
throw new UException(SystemEnum.USER_NOLOGIN, "没有登录");
}
}
/*
* @return Obiect 通过userId查询用户借款记录
*/
@SuppressWarnings("unused")
@RequestMapping(value = "/loanManagement")
public @ResponseBody List<LoanVo> loanManagement(HttpServletRequest request,LoanVo loanVo) {
User userI = (User) request.getSession().getAttribute("zycfLoginUser");
try {
if (userI != null) {
loanVo.setLoanUserId(userI.getId());
return fundAccountBiz.byUserIdLoanVo(loanVo);
}else{
throw new UException(SystemEnum.USER_NOLOGIN, "没有登录");
}
} catch (Exception e) {
throw new UException(SystemEnum.USER_NOLOGIN, "没有登录");
}
}
/*
* @return Obiect 通过userId查询用户还款计划记录
*/
@SuppressWarnings("unused")
@RequestMapping(value = "/loanRepaymentPlan")
public @ResponseBody List<LoanRepaymentVo> loanRepaymentPlan(HttpServletRequest request,LoanVo loanVo) {
User userI = (User) request.getSession().getAttribute("zycfLoginUser");
try {
if (userI != null) {
loanVo.setLoanUserId(userI.getId());
return fundAccountBiz.loanRepaymentPlan(loanVo);
}else{
throw new UException(SystemEnum.USER_NOLOGIN, "没有登录");
}
} catch (Exception e) {
throw new UException(SystemEnum.USER_NOLOGIN, "没有登录");
}
}
/*
* 查询移动移动端用户绑卡银行列表信息
*/
@RequestMapping(value = "/getUserBankInfo")
public @ResponseBody List<BankInfoVo> getUserBankInfo(HttpServletRequest request) {
return fundAccountBiz.getUserBankInfo();
}
@RequestMapping(value = "/queryBankList")
public @ResponseBody List<BankInfoVo> queryBankList(@RequestBody ParamsPojo params) {
return fundAccountBiz.queryBankList(params.getNumber());
}
}
| true
|
231914a636a7d9e5b5d69dff596761f5f38bed7f
|
Java
|
suzhao1995/LineKing
|
/teach-project/teach-dao/src/main/java/com/rs/teach/mapper/section/dao/TrainSectionMapper.java
|
UTF-8
| 3,438
| 2.078125
| 2
|
[] |
no_license
|
package com.rs.teach.mapper.section.dao;
import com.rs.teach.mapper.backstage.entity.TotleSection;
import com.rs.teach.mapper.section.dto.SectionDto;
import com.rs.teach.mapper.section.dto.TotleSectionDto;
import com.rs.teach.mapper.section.entity.Section;
import com.rs.teach.mapper.section.entity.TrainSection;
import com.rs.teach.mapper.section.vo.TrainLitterSectionVo;
import com.rs.teach.mapper.section.vo.TrainSectionVo;
import org.apache.ibatis.annotations.Param;
import java.util.List;
/**
* @author 汪航
* @Description
* @create 2019-08-03 11:25
*/
public interface TrainSectionMapper {
/**
* 查询返回页面信息(1.当前小章节全部信息)
* @param sectionId
* @return
*/
TrainSection selectTrainSection(@Param("sectionId") String sectionId);
/**
* 查询小章节目录
* @param trainCourseId
* @param trainSectionSortid
* @return
*/
List<TrainSection> selectSectionList(@Param("trainCourseId") String trainCourseId, @Param("trainSectionSortid") String trainSectionSortid);
/**
* 根据id查询大章节信息
* @param courseId
* @return
*/
List<TrainSectionVo> selectTrainSectionById(@Param("courseId") String courseId);
/**
* 查询小章节信息
* @param courseId
* @param trainSectionSortid
* @return
*/
List<TrainLitterSectionVo> selectTrainLitterSection(@Param("courseId") String courseId, @Param("trainSectionSortid") String trainSectionSortid);
/**
* 根据课程ID获取当前课程的章节总数
* @param courseId
* @return
*/
Integer selectSectionNum(@Param("courseId") String courseId);
/**
* 添加培训章节
* @param sectionDto
*
*/
void addTrainSection(SectionDto sectionDto);
/**
* 修改培训章节
* @param sectionDto
*/
void updateTrainSection(SectionDto sectionDto);
/**
* 通过课程id查询所有章节信息
* @param courseId
* @return
*/
List<Section> getSectionByCourseId(@Param("courseId") String courseId);
/**
* 查询当前课程大章节序号最大的一条数据
* @param courseId
* @return
*/
TotleSection selectTotoleSectionSortMax(@Param("courseId") String courseId);
/**
* 批量插入大章节表
* @param list
*/
void addAllTotleSection(List<TotleSection> list);
/**
* 查询大章节
* @param totleSectionDto
* @return
*/
List<TotleSection> selectTotleSection(TotleSectionDto totleSectionDto);
/**
* 修改大章节名
* @param totleSectionDto
*/
void updateTotleSection(TotleSectionDto totleSectionDto);
/**
* 查询当前课程是否含有大章节
* @param courseId
* @return
*/
Integer IsEmpty(@Param("courseId") String courseId);
/**
* 查询当前课程大章节内有无小章节
* @param sectionDto
* @return
*/
Integer IsBlank(SectionDto sectionDto);
/**
* 查询当前课程大章节中小章节序号最大的一条数据
* @param sectionDto
* @return
*/
TrainLitterSectionVo selectTrainLitterSectionSortMax(SectionDto sectionDto);
SectionDto selectPidAndTid(@Param("sectionId") String sectionId);
void deleteTrainSection(@Param("sectionId") String sectionId);
void updateSort(TrainSection trainSection);
}
| true
|
2e15faca596d8d9487d8ab054da2265353ffafe5
|
Java
|
stephenmac7/AllenCS
|
/Game/Game.java
|
UTF-8
| 5,737
| 3.296875
| 3
|
[] |
no_license
|
import java.util.List;
import java.util.Arrays;
public class Game {
public static void main(String[] args) {
System.out.println("Welcome to Game! You must outlast your competitors in the hard world of business! Good luck.");
// Init
World world = new World();
ScanWrapper sc = new ScanWrapper();
// Setup
setUp(world, sc);
// Main loop
String opt = "";
int time = 1;
while (!opt.equals("q")) {
for (Company c : world.getCompanies()) {
showCompany(c);
String uopt = "";
while (!match("d", "done", uopt)) {
dispatch(world, c, uopt, sc);
uopt = sc.promptString("Option");
}
if (!c.cycle(time, world)) {
System.out.println("You went bankrupt. Bye bye.");
world.removeCompany(c);
}
}
opt = sc.promptString("q to quit or enter to continue");
if (world.getCompanies().size() == 1) {
break;
}
time++;
}
// Finish up
List<Company> companies = world.getCompanies();
Company most = companies.get(0);
for (int i = 1; i < companies.size(); i++) {
if (companies.get(i).getCash() > most.getCash()) {
most = companies.get(i);
}
}
// Announce winner
System.out.println("Winner:");
showCompany(most);
}
private static void setUp(World world, ScanWrapper sc) {
int players = sc.promptInt("Number of Players");
for (int i = 1; i <= players; i++) {
world.addCompany(new Company(sc.promptString("Player " + i + " company name")));
}
System.out.println("\n\nAll set up! Here are all the companies:");
for (Company c : world.getCompanies()) {
showCompany(c);
}
}
private static void showCompany(Company c) {
System.out.println(c);
c.showStock();
c.showActions();
c.showEquipment();
System.out.println("\n");
}
private static void showHelp() {
System.out.println("set price, setp: set price");
System.out.println("remove price, remp: removes item from market. Set price to put it back on the market");
System.out.println("set employees, sete: set employees");
System.out.println("buy equipment, buye: get new equipment");
System.out.println("sell equipment, selle: sell equipment for 4/5 of original price");
System.out.println("change number of runs, cnr: change the number of times a process action runs, from 0 for a new process");
System.out.println("add purchase action, apurce: add a purchase action");
System.out.println("remove action, rema: remove an action");
System.out.println("show, s: show company again");
System.out.println("help, h: show this help");
System.out.println("done, d: done");
}
private static boolean match(String sh, String lo, String arg) {
return arg.equalsIgnoreCase(sh) || arg.equalsIgnoreCase(lo);
}
private static void showEquipment(List<Equipment> elist, boolean sellPrice) {
System.out.println("Equipment:");
for (Equipment e : elist) {
double price;
if (sellPrice) {
price = e.getSellPrice();
}
else {
price = e.getBuyPrice();
}
System.out.println(String.format("- %20s %5f", e.toString(), price));
}
}
private static void showAvailableEquipment(Company c) {
System.out.print("Available ");
List<Equipment> elist = Arrays.asList(Equipment.values());
elist.removeAll(c.getEquipment());
showEquipment(elist, false);
}
private static void dispatch(World world, Company c, String opt, ScanWrapper sc) {
if (match("setp", "set price", opt)) {
Material item = sc.promptMaterial("Item");
System.out.println("Current price: " + c.getPrice(item));
double price = sc.promptDouble("New Price");
c.setPrice(item, price);
}
else if (match("remp", "remove price", opt)) {
Material item = sc.promptMaterial("Item");
c.removePrice(item);
}
else if (match("sete", "set employees", opt)) {
System.out.println("Current Number of Employees: " + c.getEmployees());
c.setEmployees(sc.promptInt("New Number of Employees"));
}
else if (match("buye", "buy equipment", opt)) {
showAvailableEquipment(c);
Equipment item = sc.promptEquipment("Equipment");
if (c.buyEquipment(item)) {
System.out.println("Bought.");
}
else {
System.out.println("You already have that!");
}
}
else if (match("selle", "sell equipment", opt)) {
showEquipment(c.getEquipment(), true); // show sell price
Equipment item = sc.promptEquipment("Equipment");
if (c.sellEquipment(item)) {
System.out.println("Sold.");
}
else {
System.out.println("You don't own that!");
}
}
else if (match("cnr", "change number of runs", opt)) {
Process p = sc.promptProcess("Process");
System.out.println("Current # of runs: " + c.getRuns(p));
int newNumber = sc.promptInt("New #");
c.setRuns(p, newNumber);
}
else if (match("apurce", "add purchase action", opt)) {
Material m = sc.promptMaterial("Material");
int amount = sc.promptInt("Amount");
Company tar = null;
while (tar == null) {
tar = world.dgetCompanyByName(sc.promptString("Company"));
}
c.addPurchase(m, amount, tar);
}
else if (match("rema", "remove action", opt)) {
Process p = sc.promptProcess("Process");
c.setRuns(p, 0);
}
else if (match("s", "show", opt)) {
showCompany(c);
}
else {
showHelp();
}
}
}
| true
|
da1e3066f3d110ecf1cfec06283373e4ee774908
|
Java
|
zhangtao0908/QuickAF
|
/library/src/cn/ieclipse/af/util/PopWindowUtils.java
|
UTF-8
| 5,943
| 2.53125
| 3
|
[] |
no_license
|
package cn.ieclipse.af.util;
import android.content.Context;
import android.graphics.drawable.BitmapDrawable;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.PopupWindow;
/**
* show popwindow
*
* @author wangjian
* @date 2015/11/11.
*/
public class PopWindowUtils {
/**
* show the popwindow on view's bottom
*
* @param context
* @param clickView the view click to show popwidow
* @param contentView the layout view be shown
*/
public static PopupWindow showPopWindowBottom(Context context, View clickView, View contentView) {
return showPopWindow(context, clickView, contentView, 0, 0);
}
/**
* show the popwindow on view's bottom
*
* @param context
* @param clickView the view click to show popwidow
* @param layoutId the layout resid be shown
*/
public static PopupWindow showPopWindowBottom(Context context, View clickView, int layoutId) {
return showPopWindow(context, clickView, null, layoutId, 0);
}
/**
* show the popwindow on view's top
*
* @param context
* @param clickView the view click to show popwidow
* @param contentView the layout view be shown
*/
public static PopupWindow showPopWindowTop(Context context, View clickView, View contentView) {
return showPopWindow(context, clickView, contentView, 0, 1);
}
/**
* show the popwindow on view's top
*
* @param context
* @param clickView the view click to show popwidow
* @param layoutId the layout resid be shown
*/
public static PopupWindow showPopWindowTop(Context context, View clickView, int layoutId) {
return showPopWindow(context, clickView, null, layoutId, 1);
}
/**
* show the popwindow on view's left
*
* @param context
* @param clickView the view click to show popwidow
* @param contentView the layout view be shown
*/
public static PopupWindow showPopWindowLeft(Context context, View clickView, View contentView) {
return showPopWindow(context, clickView, contentView, 0, 2);
}
/**
* show the popwindow on view's left
*
* @param context
* @param clickView the view click to show popwidow
* @param layoutId the layout resid be shown
*/
public static PopupWindow showPopWindowLeft(Context context, View clickView, int layoutId) {
return showPopWindow(context, clickView, null, layoutId, 2);
}
/**
* show the popwindow on view's right
*
* @param context
* @param clickView the view click to show popwidow
* @param contentView the layout view be shown
*/
public static PopupWindow showPopWindowRight(Context context, View clickView, View contentView) {
return showPopWindow(context, clickView, contentView, 0, 3);
}
/**
* show the popwindow on view's right
*
* @param context
* @param clickView the view click to show popwidow
* @param layoutId the layout resid be shown
*/
public static PopupWindow showPopWindowRight(Context context, View clickView, int layoutId) {
return showPopWindow(context, clickView, null, layoutId, 3);
}
/**
* show popwindow on clickview top, bottom ,right or left
*
* @param context
* @param clickView the view click to show popwidow
* @param contentView the layout view be shown
* @param layoutId the layout resid be shown
* @param location 0.bottom
* 1.top
* 2.left
* 3.right
* @return
*/
private static PopupWindow showPopWindow(Context context, View clickView, View contentView, int layoutId,
int location) {
PopupWindow mPopupWindows = new PopupWindow(context);
View layout = null;
if (contentView != null) {
layout = contentView;
}
else if (layoutId > 0) {
layout = LayoutInflater.from(context).inflate(layoutId, null);
}
else {
throw new RuntimeException("the contentView should not be null or the layoutId > 0 is request");
}
mPopupWindows.setContentView(layout);
// 在layout中如果view是设置为WRAP_CONTENT
// 在popview弹出时无法获取宽度(getWidth() =-2)
// 此时需要重新测量view
ViewUtils.measureView(layout);
mPopupWindows.setTouchable(true);
mPopupWindows.setFocusable(true);
mPopupWindows.setWidth(WindowManager.LayoutParams.WRAP_CONTENT);
mPopupWindows.setHeight(WindowManager.LayoutParams.WRAP_CONTENT);
mPopupWindows.setBackgroundDrawable(new BitmapDrawable());
if (location == 0) {
// bottom
mPopupWindows.showAsDropDown(clickView);
}
else if (location == 1) {
// top
int[] local = new int[2];
clickView.getLocationOnScreen(local);
mPopupWindows.showAtLocation(clickView, Gravity.NO_GRAVITY, local[0],
local[1] - mPopupWindows.getContentView().getMeasuredHeight());
}
else if (location == 2) {
// left
int[] local = new int[2];
clickView.getLocationOnScreen(local);
mPopupWindows.showAtLocation(clickView, Gravity.NO_GRAVITY,
local[0] - mPopupWindows.getContentView().getMeasuredWidth(), local[1]);
}
else if (location == 3) {
// right
int[] local = new int[2];
clickView.getLocationOnScreen(local);
mPopupWindows.showAtLocation(clickView, Gravity.NO_GRAVITY, local[0] + clickView.getMeasuredWidth(),
local[1]);
}
return mPopupWindows;
}
}
| true
|
6e025205299e8435b8ae3144db5c768d3130f3dd
|
Java
|
Khal-Shah/Java_And_Data_Structure_Exercises
|
/Ch03_Selections_Boolean_RandomNum/ch3exercises/Ch3_03_LinearEq_CramersRule.java
|
UTF-8
| 1,442
| 3.875
| 4
|
[] |
no_license
|
package ch3exercises;
import java.util.*;
/* Chapter 3 - Exercise 3
* (Algebra: solve 2 * 2 linear equations) A linear equation can be solved using Cramer’s rule given in Programming
* Exercise 1.13. Write a program that prompts the user to enter a, b, c, d, e, and f and displays the result.
* If ad - bc is 0, report that “The equation has no solution.”
*
* ax + by=e x= ed - bf /ad - bc
cx + dy = f y= af-ec / ad - bc
Enter a, b, c, d, e, f: 9.0 4.0 3.0 -5.0 -6.0 -21.0
x is -2.0 and y is 3.0
Enter a, b, c, d, e, f: 1.0 2.0 2.0 4.0 4.0 5.0
The equation has no solution
*/
//By Khaled Shah
public class Ch3_03_LinearEq_CramersRule
{
static Scanner kb = new Scanner(System.in);
public static void main(String[] args)
{
System.out.println("Enter the values for a, b, c, d, e and f respectively below.");
System.out.print("a = ");
double a = kb.nextDouble();
System.out.print("b = ");
double b = kb.nextDouble();
System.out.print("c = ");
double c = kb.nextDouble();
System.out.print("d = ");
double d = kb.nextDouble();
System.out.print("e = ");
double e = kb.nextDouble();
System.out.print("f = ");
double f = kb.nextDouble();
boolean invalid = (a* d - b* c == 0);
double x = (e * d - b * f) / (a * d - b * c);
double y = (a * f - e * c) / (a * d - b * c);
System.out.println((invalid)? "The system has no solution" : "x is " + x + "\ny is " + y);
}
}
| true
|
4f7f434572a1be03009fda8a337389f5841aae34
|
Java
|
mikkipastel/Actionsheet-android
|
/xample/src/main/java/android/actionsheet/demo/com/khoiron/demo/MainActivityJava.java
|
UTF-8
| 2,360
| 2.40625
| 2
|
[
"Apache-2.0"
] |
permissive
|
package android.actionsheet.demo.com.khoiron.demo;
import com.mikkipastel.actionsheet.ActionSheet;
import com.mikkipastel.actionsheet.callback.ActionSheetCallBack;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import org.jetbrains.annotations.NotNull;
import java.util.ArrayList;
public class MainActivityJava extends AppCompatActivity {
ArrayList<String> data = new ArrayList<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_java);
data.add("Delete it");
data.add("Copy");
data.add("Move");
data.add("Duplicate");
Button button = findViewById(R.id.testbtn);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
new ActionSheet(MainActivityJava.this,data)
.setTitle("What do you want to do with the file")
.setCancelTitle("Cancel")
.setColorTitle(getResources().getColor(R.color.title))
.setColorTitleCancel(getResources().getColor(R.color.action))
.setColorData(getResources().getColor(R.color.action))
.setColorSelected(getResources().getColor(R.color.colorAccent))
.create(new ActionSheetCallBack() {
@Override
public void data(@NotNull String data, int position) {
switch (position){
case 0:
// your action
setLog(data);
case 1:
// your action
case 2:
// your action
case 3:
// your action
}
}
});
}
});
}
private void setLog(String s) {
Log.e("Tag",s);
}
}
| true
|
e7d748337e8c4e9fd2f934f3e42947bc454095ba
|
Java
|
vartika1403/Project
|
/app/src/main/java/com/example/user/project/ApiService.java
|
UTF-8
| 641
| 1.820313
| 2
|
[] |
no_license
|
package com.example.user.project;
import com.example.user.project.webservice.response.Movie;
import retrofit.Call;
import retrofit.http.GET;
import retrofit.http.Headers;
import retrofit.http.Path;
public interface ApiService {
// @Headers({"Content-Type:application/json"})
@Headers("Content-Type: application/json")
/* @GET("/discover/movie/550?")
//Observable<String> getMovieList(Callback<List<Movie>> responseCallback);
Call<List<Movie>> getMovieList(@Query("api_key") String api_key, Callback<List<Movie>> callback);
*/
@GET("/movie/{id}")
Call<Movie> summary(
@Path("id") int tmdbId);
}
| true
|
583ff2d7da1b385650e650a5676598f8eb59103a
|
Java
|
kha0213/Today-I-Learn
|
/JPA/spring-data-jpa/src/main/java/com/example/springdatajpa/repository/CustomRepositoryImpl.java
|
UTF-8
| 821
| 2.5
| 2
|
[] |
no_license
|
package com.example.springdatajpa.repository;
import com.example.springdatajpa.entity.Teacher;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import javax.persistence.EntityManager;
import javax.transaction.Transactional;
@Repository
@Transactional
public class CustomRepositoryImpl implements CustomRepository {
@Autowired
EntityManager em;
@Override
public Teacher findCustomById(Long id) {
System.out.println("========================");
System.out.println("now CustomRepositoryImpl");
System.out.println("========================");
return em.createQuery("select t from Teacher as t where t.id = :id",Teacher.class)
.setParameter("id",id)
.getSingleResult();
}
}
| true
|
11cf156e1fb5a3e1e088b5dd0e1523d74d0f4ee1
|
Java
|
gobbisanches/ubisoldiers
|
/app/src/main/java/com/github/gobbisanches/ubisoldiers/app/ItemListFragment.java
|
UTF-8
| 5,315
| 2.46875
| 2
|
[
"MIT"
] |
permissive
|
package com.github.gobbisanches.ubisoldiers.app;
import android.app.ListFragment;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import com.github.gobbisanches.ubisoldiers.mechanics.Item;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Sanches on 12/07/2014.
*/
public class ItemListFragment extends ListFragment {
private static final String LIST_ID = "com.github.gobbisanches.ubisoldier.app.ItemListFragment.ListId";
private static final String ITEMS = "com.github.gobbisanches.ubisoldier.app.ItemListFragment.Items";
public interface ItemListFragmentListener {
public void onSelectItem(int id, Item item, int position, ArrayList<Item> allItems);
}
private class ItemArrayAdapter extends ArrayAdapter<Item> {
private ItemArrayAdapter(Context context, int resource, List<Item> objects) {
super(context, resource, objects);
Log.d("UBISOLDIERS", "Objects = " + objects.toString());
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if(convertView == null) {
convertView = getActivity().getLayoutInflater().inflate(R.layout.item_list_item_layout, null);
}
Item item = getItem(position);
ImageView itemIconView = (ImageView) convertView.findViewById(R.id.itemIconView);
TextView nameView = (TextView) convertView.findViewById(R.id.nameView);
TextView stat1TextView = (TextView) convertView.findViewById(R.id.stat1TextView);
ImageView stat1IconView = (ImageView) convertView.findViewById(R.id.stat1IconView);
TextView stat2TextView = (TextView) convertView.findViewById(R.id.stat2TextView);
ImageView stat2IconView = (ImageView) convertView.findViewById(R.id.stat2IconView);
Log.d("UBISOLDIERS", "Item = " + item.toString());
itemIconView.setImageResource(ResourceManager.getResourceForItem(item));
nameView.setText(item.getName());
if ((item.getAttack() > 0) && item.getDefense() > 0) {
setStat(item.getAttack(), ResourceManager.getResourceForAttack(), stat1TextView, stat1IconView);
setStat(item.getDefense(), ResourceManager.getResourceForDefense(), stat2TextView, stat2IconView);
} else if ((item.getAttack() > 0) && item.getDefense() == 0) {
setStat(item.getAttack(), ResourceManager.getResourceForAttack(), stat1TextView, stat1IconView);
hideStat(stat2TextView, stat2IconView);
} else if ((item.getAttack() == 0) && item.getDefense() > 0) {
setStat(item.getDefense(), ResourceManager.getResourceForDefense(), stat1TextView, stat1IconView);
hideStat(stat2TextView, stat2IconView);
} else {
throw new RuntimeException("Invalid item state");
}
return convertView;
}
private void setStat(double value, int iconResId, TextView textView, ImageView iconView) {
textView.setText(String.valueOf((int) Math.floor(value)));
iconView.setImageResource(iconResId);
textView.setVisibility(View.VISIBLE);
iconView.setVisibility(View.VISIBLE);
}
private void hideStat(TextView textView, ImageView iconView) {
textView.setVisibility(View.INVISIBLE);
iconView.setVisibility(View.INVISIBLE);
}
}
private ArrayList<Item> items;
private ItemArrayAdapter adapter;
private int listId;
private ItemListFragmentListener listener;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
listId = getArguments().getInt(LIST_ID);
items = (ArrayList<Item>) getArguments().getSerializable(ITEMS);
adapter = new ItemArrayAdapter(getActivity(), R.layout.item_list_item_layout, items);
setListAdapter(adapter);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return super.onCreateView(inflater, container, savedInstanceState);
}
@Override
public void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
listener.onSelectItem(listId, adapter.getItem(position), position, items);
}
private void setItemListListener(ItemListFragmentListener listener) {
this.listener = listener;
}
public static ItemListFragment newInstance(int listId, ArrayList<Item> items, ItemListFragmentListener listener) {
Log.d("UBISOLDIERS", "In newInstance: objects = " + items.toString());
Bundle args = new Bundle();
args.putInt(LIST_ID, listId);
args.putSerializable(ITEMS, items);
ItemListFragment fragment = new ItemListFragment();
fragment.setArguments(args);
fragment.setItemListListener(listener);
return fragment;
}
}
| true
|
b2379f306613fdc245c1d79adf841da6a2c466fc
|
Java
|
igor-sfdc/aura
|
/aura-impl/src/test/java/org/auraframework/impl/root/theme/VarDefHandlerTest.java
|
UTF-8
| 3,450
| 2.046875
| 2
|
[
"Apache-2.0"
] |
permissive
|
/*
* Copyright (C) 2013 salesforce.com, inc.
*
* 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.auraframework.impl.root.theme;
import org.auraframework.def.ThemeDef;
import org.auraframework.def.VarDef;
import org.auraframework.expression.PropertyReference;
import org.auraframework.impl.css.StyleTestCase;
import org.auraframework.impl.root.parser.handler.VarDefHandler;
import org.auraframework.throwable.quickfix.InvalidDefinitionException;
import org.auraframework.throwable.quickfix.QuickFixException;
import com.google.common.collect.Iterables;
/**
* Unit tests for {@link VarDefHandler}.
*/
public class VarDefHandlerTest extends StyleTestCase {
public VarDefHandlerTest(String name) {
super(name);
}
public void testName() throws Exception {
VarDef def = source("<aura:var name='color' value='red'/>");
assertEquals("didn't get expected aura:var name", "color", def.getName());
}
public void testValue() throws Exception {
VarDef def = source("<aura:var name='color' value='red'/>");
assertEquals("didn't get expected aura:var value", "red", def.getValue().toString());
}
public void testDescription() throws Exception {
VarDef def = source("<aura:var name='color' value='red' description='test'/>");
assertEquals("didn't get expected aura:var description", "test", def.getDescription());
}
public void testValueIsExpression() throws Exception {
VarDef def = source("<aura:var name='myColor' value='{!color}'/><aura:var name='color' value='red'/>");
assertTrue(def.getValue() instanceof PropertyReference);
}
public void testInvalidChild() throws Exception {
try {
source("<aura:var name='f' value='f'><ui:button/></aura:var>");
fail("Should have thrown AuraException");
} catch (Exception e) {
checkExceptionContains(e, InvalidDefinitionException.class, "No children");
}
}
public void testWithTextBetweenTag() throws Exception {
try {
source("<aura:var name='f' value='f'>text</aura:var>");
fail("Should have thrown AuraException");
} catch (Exception e) {
checkExceptionContains(e, InvalidDefinitionException.class, "No literal text");
}
}
public void testMissingName() throws Exception {
try {
source("<aura:var value='f'/>");
fail("Should have thrown AuraException");
} catch (Exception e) {
checkExceptionContains(e, InvalidDefinitionException.class, "Missing required attribute 'name'");
}
}
/** utility */
private VarDef source(CharSequence contents) throws QuickFixException {
ThemeDef def = addSeparateTheme(String.format("<aura:theme>%s</aura:theme>", contents)).getDef();
return Iterables.getFirst(def.getDeclaredVarDefs().values(), null);
}
}
| true
|
6938fc67b9e4bb2ff5cf5e66659057bd06a18556
|
Java
|
zhouns/easydp
|
/src/main/java/com/sgepm/easydp/system/manager/SysDictCodeManager.java
|
UTF-8
| 307
| 1.617188
| 2
|
[
"Apache-2.0"
] |
permissive
|
package com.sgepm.easydp.system.manager;
import java.util.List;
import com.sgepm.easydp.common.manager.IBaseManager;
import com.sgepm.easydp.system.entity.SysDictCode;
public interface SysDictCodeManager extends IBaseManager<SysDictCode> {
List<SysDictCode> findDictByGrp(String groupCode);
}
| true
|
9bdd91b499cb788f2e3d89e672931d1f5e9ff3d1
|
Java
|
codeandcoke/multimedia-ejercicios
|
/Marcianitos/core/src/com/centroafuera/holalibgdx/screens/PantallaJuego.java
|
UTF-8
| 3,990
| 2.515625
| 3
|
[] |
no_license
|
package com.centroafuera.holalibgdx.screens;
import com.badlogic.gdx.*;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.math.MathUtils;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.utils.Array;
import com.badlogic.gdx.utils.TimeUtils;
import com.centroafuera.holalibgdx.model.Marciano;
import com.centroafuera.holalibgdx.model.Nave;
import com.centroafuera.holalibgdx.model.Roca;
import com.centroafuera.holalibgdx.util.Constantes;
public class PantallaJuego implements Screen {
private SpriteBatch batch;
private Nave nave;
private Array<Marciano> marcianos;
private Array<Roca> rocas;
private long tiempoJuego;
@Override
public void show() {
batch = new SpriteBatch();
nave = new Nave(Vector2.Zero, new Texture("ship/f1.png"), 3, Constantes.VELOCIDAD_NAVE,
Nave.TipoDisparo.RAFAGA, false);
marcianos = new Array<>();
rocas = new Array<>();
tiempoJuego = TimeUtils.millis();
}
@Override
public void render(float delta) {
actualizar();
pintar();
}
private void actualizar() {
// Input de usuario (teclado)
comprobarTeclado();
// Generar enemigos
generarEnemigos();
// Mover enemigos
moverEnemigos();
// Comprobar colisiones
comprobarColisiones();
// Comprobaciones varias . . .
}
private void comprobarTeclado() {
if (Gdx.input.isKeyPressed(Input.Keys.UP))
nave.moverArriba();
if (Gdx.input.isKeyPressed(Input.Keys.DOWN))
nave.moverAbajo();
if (Gdx.input.isKeyPressed(Input.Keys.LEFT))
nave.moverIzquierda();
if (Gdx.input.isKeyPressed(Input.Keys.RIGHT))
nave.moverDerecha();
if (Gdx.input.isKeyPressed(Input.Keys.ESCAPE)) {
((Game) Gdx.app.getApplicationListener()).setScreen(new PantallaMenuPrincipal());
}
}
private void generarEnemigos() {
if (TimeUtils.millis() - tiempoJuego > Constantes.TIEMPO_ENTRE_MARCIANOS) {
Texture textura = new Texture("enemy/e_f1.png");
Vector2 posicion = new Vector2(Gdx.graphics.getWidth() - textura.getWidth(),
MathUtils.random(0, Gdx.graphics.getHeight()));
Marciano marciano = new Marciano(posicion, textura, 1, 2);
marcianos.add(marciano);
tiempoJuego = TimeUtils.millis();
}
}
private void moverEnemigos() {
for (Marciano marciano : marcianos) {
marciano.moverIzquierda();
if (marciano.getPosicion().x < 0) {
marcianos.removeValue(marciano, true);
}
}
}
private void comprobarColisiones() {
for (Marciano marciano : marcianos) {
if (marciano.rect.overlaps(nave.rect)) {
Preferences prefs = Gdx.app.getPreferences("marcianos");
if (prefs.getBoolean("sonido")) {
// Hacer sonar
}
marciano.quitarVida();
nave.quitarVida();
// Comprobar si deben seguir vivos . . .
}
}
}
private void pintar() {
Gdx.gl.glClearColor(0, 0, 0, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
batch.begin();
// Pintar la nave
nave.pintar(batch);
// Pintar los enemigos
for (Marciano marciano : marcianos)
marciano.pintar(batch);
for (Roca roca : rocas)
roca.pintar(batch);
batch.end();
}
@Override
public void resize(int width, int height) {
}
@Override
public void pause() {
}
@Override
public void resume() {
}
@Override
public void hide() {
}
@Override
public void dispose() {
batch.dispose();
}
}
| true
|
75ce9fabbdc37caf35040b1497d7d9670da0406b
|
Java
|
xin-liu521/springBoot-importOrExport
|
/src/main/java/com/velvol/salary/dao/SalaryUserInfoMapper.java
|
UTF-8
| 613
| 1.726563
| 2
|
[] |
no_license
|
package com.velvol.salary.dao;
import com.velvol.salary.domain.SalaryUserInfo;
import java.util.List;
import java.util.Map;
/**
* Created by Administrator on 2018/4/21.
*/
public interface SalaryUserInfoMapper {
int insertBatch(List<Map<String, Object>> params);
List<SalaryUserInfo> querySalaryUserInfoPage(SalaryUserInfo salaryUserInfo);
int deleteUserInfo(Integer recordId);
int selectUserInfo(Map<String, Object> params);
int insertUserInfo(Map<String, Object> params);
int updateUserInfo(Map<String, Object> params);
int editUserInfo(SalaryUserInfo salaryUserInfo);
}
| true
|
4757dd11bf90695784ea58a58942f38aaaf3261a
|
Java
|
GabrielSirtoriCorrea/Sexta-Feira-Mark_6
|
/Sexta-FeiraInterface/src/com/friday/SceneController.java
|
UTF-8
| 16,839
| 2.03125
| 2
|
[
"MIT"
] |
permissive
|
package com.friday;
import java.io.File;
import java.lang.reflect.Array;
import java.net.URL;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.Locale;
import java.util.List;
import java.util.ResourceBundle;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.omg.CORBA.portable.IDLEntity;
import javafx.event.ActionEvent;
import javafx.event.Event;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Label;
import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
import javafx.collections.ObservableList;
import javafx.util.Duration;
import javafx.event.EventHandler;
import javafx.scene.image.ImageView;
import javafx.scene.control.TableView;
import javafx.scene.control.TableColumn;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.collections.FXCollections;
import javafx.scene.image.Image;
import javafx.scene.control.TableColumn.CellDataFeatures;
import javafx.beans.value.ObservableValue;
import javafx.beans.property.ReadOnlyObjectWrapper;
import javafx.util.Callback;
public class SceneController implements Initializable {
@FXML
private Label lblTime;
@FXML
private Label lblDayMonth;
@FXML
private Label lblWeekDay;
@FXML
private ImageView imageView;
@FXML
private TableView<JSONArray> tableView;
private TableColumn idColumn = new TableColumn<JSONArray, Integer>("ID");
private TableColumn keyWord1Column = new TableColumn<JSONArray, String>("Palavra chave 1");
private TableColumn keyWord2Column = new TableColumn<JSONArray, String>("Palavra chave 2");
private TableColumn keyWord3Column = new TableColumn<JSONArray, String>("Palavra chave 3");
private TableColumn response1Column = new TableColumn<JSONArray, String>("Resposta 1");
private TableColumn response2Column = new TableColumn<JSONArray, String>("Resposta 2");
private TableColumn response3Column = new TableColumn<JSONArray, String>("Resposta 3");
private TableColumn commandColumn = new TableColumn<JSONArray, String>("Comando");
private TableColumn homeWorkTypeColumn = new TableColumn<JSONArray, String>("Tipo");
private TableColumn homeWorkSubjectColumn = new TableColumn<JSONArray, String>("Matéria");
private TableColumn homeWorkColumn = new TableColumn<JSONArray, String>("Tarefa");
private TableColumn homeWorkDeliveryColumn = new TableColumn<JSONArray, String>("Entrega");
private TableColumn homeWorkDescColumn = new TableColumn<JSONArray, String>("Descrição");
private TableColumn projectColumn = new TableColumn<JSONArray, String>("Projeto");
private TableColumn projectTypeColumn = new TableColumn<JSONArray, String>("Tipo");
private TableColumn DeviceColumn = new TableColumn<JSONArray, String>("Device");
private TableColumn DeviceDescColumn = new TableColumn<JSONArray, String>("Descrição");
private TableColumn DeviceActionsColumn = new TableColumn<JSONArray, String>("Número de ações");
JSONArray arrayResponse;
JSONObject response;
String imagePath;
int action;
File imageFile;
Image image;
ObservableList<JSONArray> tableViewData = FXCollections.observableArrayList();
Locale locale;
Calendar calendar;
GregorianCalendar gregCalendar;
SimpleDateFormat dateFormat;
SimpleDateFormat hourFormat;
String date;
String hour;
String weekDay;
@Override
public void initialize(URL url, ResourceBundle rb) {
EventHandler handler = new EventHandler() {
@Override
public void handle(Event event) {
setClock();
connectionLoop();
}
};
KeyFrame frame = new KeyFrame(Duration.millis(1000), handler);
Timeline timeline = new Timeline();
timeline.getKeyFrames().add(frame);
timeline.setCycleCount(Timeline.INDEFINITE);
timeline.play();
}
private void connectionLoop() {
response = FridayComunication.readJsonFile();
action = Integer.parseInt(response.get("action").toString());
switch (action) {
case 0:
tableView.setVisible(false);
imageView.setVisible(false);
break;
case 1:
if (!tableView.getColumns().contains(commandColumn)) {
imageView.setVisible(false);
setTableData();
addInteractionsColumns();
}
break;
case 2:
if (!tableView.getColumns().contains(homeWorkColumn)) {
imageView.setVisible(false);
setTableData();
addHomeWorksColumns();
}
break;
case 3:
if (!tableView.getColumns().contains(projectColumn)) {
imageView.setVisible(false);
setTableData();
addProjectsColumns();
}
break;
case 4:
if (!tableView.getColumns().contains(DeviceColumn)) {
imageView.setVisible(false);
setTableData();
addDevicesColumns();
}
break;
case 5:
tableView.setVisible(false);
imagePath = response.get("url").toString();
System.out.println(imagePath);
imageFile = new File(imagePath);
image = new Image(imageFile.toURI().toString());
imageView.setImage(image);
imageView.setVisible(true);
default:
break;
}
}
private void addInteractionsColumns() {
tableView.getColumns().clear();
idColumn.setCellValueFactory(new Callback<CellDataFeatures<JSONArray, Integer>, ObservableValue<Integer>>() {
@Override
public ObservableValue<Integer> call(CellDataFeatures<JSONArray, Integer> param) {
// TODO Auto-generated method stub
return new ReadOnlyObjectWrapper(param.getValue().get(0));
}
});
keyWord1Column.setCellValueFactory(new Callback<CellDataFeatures<JSONArray, String>, ObservableValue<String>>() {
@Override
public ObservableValue<String> call(CellDataFeatures<JSONArray, String> param) {
// TODO Auto-generated method stub
return new ReadOnlyObjectWrapper(param.getValue().get(1));
}
});
keyWord2Column.setCellValueFactory(new Callback<CellDataFeatures<JSONArray, String>, ObservableValue<String>>() {
@Override
public ObservableValue<String> call(CellDataFeatures<JSONArray, String> param) {
// TODO Auto-generated method stub
return new ReadOnlyObjectWrapper(param.getValue().get(2));
}
});
keyWord3Column.setCellValueFactory(new Callback<CellDataFeatures<JSONArray, String>, ObservableValue<String>>() {
@Override
public ObservableValue<String> call(CellDataFeatures<JSONArray, String> param) {
// TODO Auto-generated method stub
return new ReadOnlyObjectWrapper(param.getValue().get(3));
}
});
response1Column.setCellValueFactory(new Callback<CellDataFeatures<JSONArray, String>, ObservableValue<String>>() {
@Override
public ObservableValue<String> call(CellDataFeatures<JSONArray, String> param) {
// TODO Auto-generated method stub
return new ReadOnlyObjectWrapper(param.getValue().get(4));
}
});
response2Column.setCellValueFactory(new Callback<CellDataFeatures<JSONArray, String>, ObservableValue<String>>() {
@Override
public ObservableValue<String> call(CellDataFeatures<JSONArray, String> param) {
// TODO Auto-generated method stub
return new ReadOnlyObjectWrapper(param.getValue().get(5));
}
});
response3Column.setCellValueFactory(new Callback<CellDataFeatures<JSONArray, String>, ObservableValue<String>>() {
@Override
public ObservableValue<String> call(CellDataFeatures<JSONArray, String> param) {
// TODO Auto-generated method stub
return new ReadOnlyObjectWrapper(param.getValue().get(6));
}
});
commandColumn.setCellValueFactory(new Callback<CellDataFeatures<JSONArray, String>, ObservableValue<String>>() {
@Override
public ObservableValue<String> call(CellDataFeatures<JSONArray, String> param) {
// TODO Auto-generated method stub
return new ReadOnlyObjectWrapper(param.getValue().get(7));
}
});
tableView.getColumns().addAll(idColumn, keyWord1Column, keyWord2Column, keyWord3Column, response1Column,
response2Column, response3Column, commandColumn);
tableView.setVisible(true);
}
private void addHomeWorksColumns() {
tableView.getColumns().clear();
idColumn.setCellValueFactory(new Callback<CellDataFeatures<JSONArray, Integer>, ObservableValue<Integer>>() {
@Override
public ObservableValue<Integer> call(CellDataFeatures<JSONArray, Integer> param) {
// TODO Auto-generated method stub
return new ReadOnlyObjectWrapper(param.getValue().get(0));
}
});
homeWorkTypeColumn.setCellValueFactory(new Callback<CellDataFeatures<JSONArray, String>, ObservableValue<String>>() {
@Override
public ObservableValue<String> call(CellDataFeatures<JSONArray, String> param) {
// TODO Auto-generated method stub
return new ReadOnlyObjectWrapper(param.getValue().get(1));
}
});
homeWorkSubjectColumn.setCellValueFactory(new Callback<CellDataFeatures<JSONArray, String>, ObservableValue<String>>() {
@Override
public ObservableValue<String> call(CellDataFeatures<JSONArray, String> param) {
// TODO Auto-generated method stub
return new ReadOnlyObjectWrapper(param.getValue().get(2));
}
});
homeWorkColumn.setCellValueFactory(new Callback<CellDataFeatures<JSONArray, String>, ObservableValue<String>>() {
@Override
public ObservableValue<String> call(CellDataFeatures<JSONArray, String> param) {
// TODO Auto-generated method stub
return new ReadOnlyObjectWrapper(param.getValue().get(3));
}
});
homeWorkDeliveryColumn.setCellValueFactory(new Callback<CellDataFeatures<JSONArray, String>, ObservableValue<String>>() {
@Override
public ObservableValue<String> call(CellDataFeatures<JSONArray, String> param) {
// TODO Auto-generated method stub
return new ReadOnlyObjectWrapper(param.getValue().get(4));
}
});
homeWorkDescColumn.setCellValueFactory(new Callback<CellDataFeatures<JSONArray, String>, ObservableValue<String>>() {
@Override
public ObservableValue<String> call(CellDataFeatures<JSONArray, String> param) {
// TODO Auto-generated method stub
return new ReadOnlyObjectWrapper(param.getValue().get(5));
}
});
tableView.getColumns().addAll(idColumn, homeWorkTypeColumn, homeWorkSubjectColumn, homeWorkColumn,
homeWorkDeliveryColumn, homeWorkDescColumn);
tableView.setVisible(true);
}
private void addProjectsColumns() {
tableView.getColumns().clear();
projectTypeColumn.setCellValueFactory(new Callback<CellDataFeatures<JSONArray, String>, ObservableValue<String>>() {
@Override
public ObservableValue<String> call(CellDataFeatures<JSONArray, String> param) {
// TODO Auto-generated method stub
return new ReadOnlyObjectWrapper(param.getValue().get(1));
}
});
projectColumn.setCellValueFactory(new Callback<CellDataFeatures<JSONArray, String>, ObservableValue<String>>() {
@Override
public ObservableValue<String> call(CellDataFeatures<JSONArray, String> param) {
// TODO Auto-generated method stub
return new ReadOnlyObjectWrapper(param.getValue().get(2));
}
});
idColumn.setCellValueFactory(new Callback<CellDataFeatures<JSONArray, Integer>, ObservableValue<Integer>>() {
@Override
public ObservableValue<Integer> call(CellDataFeatures<JSONArray, Integer> param) {
// TODO Auto-generated method stub
return new ReadOnlyObjectWrapper(param.getValue().get(0));
}
});
tableView.getColumns().addAll(idColumn, projectTypeColumn, projectColumn);
tableView.setVisible(true);
}
private void addDevicesColumns() {
tableView.getColumns().clear();
idColumn.setCellValueFactory(new Callback<CellDataFeatures<JSONArray, Integer>, ObservableValue<Integer>>() {
@Override
public ObservableValue<Integer> call(CellDataFeatures<JSONArray, Integer> param) {
// TODO Auto-generated method stub
return new ReadOnlyObjectWrapper(param.getValue().get(0));
}
});
DeviceColumn.setCellValueFactory(new Callback<CellDataFeatures<JSONArray, String>, ObservableValue<String>>() {
@Override
public ObservableValue<String> call(CellDataFeatures<JSONArray, String> param) {
// TODO Auto-generated method stub
return new ReadOnlyObjectWrapper(param.getValue().get(1));
}
});
DeviceDescColumn.setCellValueFactory(new Callback<CellDataFeatures<JSONArray, String>, ObservableValue<String>>() {
@Override
public ObservableValue<String> call(CellDataFeatures<JSONArray, String> param) {
// TODO Auto-generated method stub
return new ReadOnlyObjectWrapper(param.getValue().get(2));
}
});
DeviceActionsColumn.setCellValueFactory(new Callback<CellDataFeatures<JSONArray, String>, ObservableValue<String>>() {
@Override
public ObservableValue<String> call(CellDataFeatures<JSONArray, String> param) {
// TODO Auto-generated method stub
return new ReadOnlyObjectWrapper(param.getValue().get(3));
}
});
tableView.getColumns().addAll(idColumn, DeviceColumn, DeviceDescColumn, DeviceActionsColumn);
tableView.setVisible(true);
}
private void setTableData(){
tableView.getItems().clear();
response = (JSONObject) FridayComunication.readJsonFile().get("content");
System.out.println(response);
for (int c = 0; c < response.size(); c++) {
arrayResponse = (JSONArray) response.get(Integer.toString(c));
tableViewData.add(arrayResponse);
System.out.println(arrayResponse);
}
tableView.setItems(tableViewData);
System.out.println("TableView dados >>> " + tableView.getItems());
}
private void setClock() {
try {
locale = new Locale("pt", "BR");
gregCalendar = new GregorianCalendar();
dateFormat = new SimpleDateFormat("dd'/'MM'/'yyyy", locale);
hourFormat = new SimpleDateFormat("HH':'mm", locale);
calendar = gregCalendar.getInstance();
date = dateFormat.format(calendar.getTime());
hour = hourFormat.format(calendar.getTime());
calendar.setTime(dateFormat.parse(date));
weekDay = Integer.toString(calendar.get(Calendar.DAY_OF_WEEK)) + "ª Feira";
if(weekDay.equals("7ª Feira")){
weekDay = "Sábado";
}else{
if(weekDay.equals("1ª Feira")){
weekDay = "Domingo";
}
}
lblWeekDay.setText(weekDay);
lblDayMonth.setText(date);
lblTime.setText(hour);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
| true
|
bdf51f1c184d35e8bdd0bbbcdb46c31a36ae4b81
|
Java
|
rectuspin/CZ2006_final
|
/app/src/main/java/com/example/athletica/ui/login/LoginRegisterActivity.java
|
UTF-8
| 2,231
| 2.265625
| 2
|
[] |
no_license
|
package com.example.athletica.ui.login;
import android.content.Intent;
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;
import androidx.viewpager.widget.ViewPager;
import com.example.athletica.R;
import com.example.athletica.data.account.LoginRegisterManager;
import com.example.athletica.ui.home.HomeActivity;
import java.util.ArrayList;
public class LoginRegisterActivity extends AppCompatActivity {
private LoginRegisterManager loginRegisterManager;
private ViewPager viewPager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login_register);
// Initialise a LoginRegisterManager
loginRegisterManager = new LoginRegisterManager(getApplicationContext());
// Start the HomeActivity if the user is already logged in
if (loginRegisterManager.isLoggedIn()) {
startActivity(new Intent(LoginRegisterActivity.this, HomeActivity.class));
finish();
} else {
// Setup the ViewPager
viewPager = findViewById(R.id.viewPager);
LoginRegisterPagerAdapter loginRegisterPagerAdapter = new LoginRegisterPagerAdapter(getSupportFragmentManager());
loginRegisterPagerAdapter.addFragment(new LoginFragment());
loginRegisterPagerAdapter.addFragment(new RegisterFragment());
viewPager.setAdapter(loginRegisterPagerAdapter);
}
}
// Adapter for the ViewPager
class LoginRegisterPagerAdapter extends FragmentPagerAdapter {
private ArrayList<Fragment> fragmentList = new ArrayList<>();
public LoginRegisterPagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int i) {
return fragmentList.get(i);
}
@Override
public int getCount() {
return fragmentList.size();
}
void addFragment(Fragment fragment) {
fragmentList.add(fragment);
}
}
}
| true
|
acfa0ae532714be647e3e5ea41403398a6012dbe
|
Java
|
misoyun/BitProject3
|
/MyPage2/src/main/java/com/bit/mypage/UserController.java
|
UTF-8
| 2,426
| 2.0625
| 2
|
[] |
no_license
|
package com.bit.mypage;
import java.util.HashMap;
import java.util.Map;
import javax.inject.Inject;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import com.bit.mypage.service.User_Service;
import com.bit.mypage.vo.User_VO;
@Controller
@RequestMapping("/user")
public class UserController {
@Inject
User_Service userServ;
//로그인페이지
@RequestMapping(value="/login", method = RequestMethod.GET)
public String login()
{
return "login";
}
//회원가입페이지
@RequestMapping(value="/joinform", method = RequestMethod.GET)
public String insertform()
{
return "joinform";
}
//회원가입 - DB에 회원정보 입력후 로그인 페이지로 넘어가기
@RequestMapping(value="/join", method=RequestMethod.GET)
public String insert(@ModelAttribute User_VO vo)
{
boolean temp = userServ.join(vo);
if(temp == true)
return "login";
else
return "joinfail";
}
//아이디와 비밀번호 확인
@RequestMapping(value = "/logincheck", method = RequestMethod.POST)
public String loginCheck(@ModelAttribute User_VO vo, HttpSession session, Model model) {
return "home";
}
//로그인 실패
@RequestMapping(value = "/loginfail")
public String loginfail()
{
return "loginfail";
}
@RequestMapping(value = "/profile")
public String profile()
{
return "profile";
}
//logout
@RequestMapping(value="/logout")
public String logout(HttpSession session)
{
return "redirect:login";
}
@RequestMapping(value="/gotoprofile")
public String goToProfile()
{
return "profileUpdate";
}
//profile photo upload
@RequestMapping(value="/updateprofile")
public ModelAndView updateProfile(HttpServletRequest request)
{
Map param = new HashMap();
param.put("id", request.getParameter("id"));
param.put("intro", request.getParameter("intro"));
// param.put("imgsrc", request.getParameter("imgsrc"));
userServ.updateProfile(param);
ModelAndView mv = new ModelAndView();
return mv;
}
}
| true
|
740f2da0250e5f9a231b2103481311c8311b8bc2
|
Java
|
loochao/nevernote-1
|
/src/cx/fbn/nevernote/sql/DatabaseConnection.java
|
UTF-8
| 5,895
| 2.125
| 2
|
[] |
no_license
|
/*
* This file is part of NeverNote
* Copyright 2009 Randy Baumgarte
*
* This file may be licensed under the terms of of the
* GNU General Public License Version 2 (the ``GPL'').
*
* Software distributed under the License is distributed
* on an ``AS IS'' basis, WITHOUT WARRANTY OF ANY KIND, either
* express or implied. See the GPL for the specific language
* governing rights and limitations.
*
* You should have received a copy of the GPL along with this
* program. If not, go to http://www.gnu.org/licenses/gpl.html
* or write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
*/
package cx.fbn.nevernote.sql;
import java.io.File;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import com.trolltech.qt.sql.QJdbc;
import cx.fbn.nevernote.Global;
import cx.fbn.nevernote.sql.driver.NSqlQuery;
import cx.fbn.nevernote.utilities.ApplicationLogger;
public class DatabaseConnection {
// Table helpers
private WordsTable wordsTable;
private TagTable tagTable;
private NotebookTable notebookTable;
private NoteTable noteTable;
private DeletedTable deletedTable;
private SavedSearchTable searchTable;
private WatchFolderTable watchFolderTable;
private InvalidXMLTable invalidXMLTable;
private SyncTable syncTable;
private final ApplicationLogger logger;
private Connection conn;
int id;
public DatabaseConnection(ApplicationLogger l, String url, String userid, String password, String cypherPassword) {
logger = l;
dbSetup(url, userid, password, cypherPassword);
}
private void setupTables() {
tagTable = new TagTable(logger, this);
notebookTable = new NotebookTable(logger, this);
noteTable = new NoteTable(logger, this);
deletedTable = new DeletedTable(logger, this);
searchTable = new SavedSearchTable(logger, this);
watchFolderTable = new WatchFolderTable(logger, this);
invalidXMLTable = new InvalidXMLTable(logger, this);
wordsTable = new WordsTable(logger, this);
syncTable = new SyncTable(logger, this);
}
// Compact the database
public void compactDatabase() {
}
// Initialize the database connection
public void dbSetup(String url,String userid, String userPassword, String cypherPassword) {
logger.log(logger.HIGH, "Entering DatabaseConnection.dbSetup " +id);
try {
Class.forName("org.h2.Driver");
} catch (ClassNotFoundException e1) {
e1.printStackTrace();
System.exit(16);
}
QJdbc.initialize();
File f = new File(Global.getDirectoryPath() +File.separator +"db" +File.separator +"NeverNote.h2.db");
boolean dbExists = f.exists();
setupTables();
logger.log(logger.HIGH, "Entering RDatabaseConnection.dbSetup");
try {
String passwordString = null;
if (cypherPassword==null || cypherPassword.trim().equals(""))
passwordString = userPassword;
else
passwordString = cypherPassword+" "+userPassword;
conn = DriverManager.getConnection(url,userid,passwordString);
// conn = DriverManager.getConnection(url+";AUTO_SERVER=TRUE",userid,passwordString);
} catch (SQLException e) {
e.printStackTrace();
return;
}
// If it doesn't exist and we are the main thread, then we need to create stuff.
if (!dbExists) {
createTables();
Global.setAutomaticLogin(false);
}
logger.log(logger.HIGH, "Leaving RDatabaseConnection.dbSetup");
logger.log(logger.HIGH, "Leaving DatabaseConnection.dbSetup" +id);
}
public void dbShutdown() {
logger.log(logger.HIGH, "Entering RDatabaseConnection.dbShutdown");
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
logger.log(logger.HIGH, "Leaving RDatabaseConnection.dbShutdown");
}
public void upgradeDb(String version) {
if (version.equals("0.85")) {
executeSql("alter table note add column titleColor integer");
executeSql("alter table note add column thumbnail blob");
executeSql("alter table note add column thumbnailneeded boolean");
executeSql("Update note set thumbnailneeded = true;");
executeSql("create index NOTE_NOTEBOOK_INDEX on note (notebookguid, guid);");
executeSql("create index NOTETAGS_TAG_INDEX on notetags (tagguid, noteguid);");
version = "0.86";
Global.setDatabaseVersion(version);
}
}
public void executeSql(String sql) {
NSqlQuery query = new NSqlQuery(conn);
query.exec(sql);
}
public void checkDatabaseVersion() {
if (!Global.getDatabaseVersion().equals("0.86")) {
upgradeDb(Global.getDatabaseVersion());
}
}
public void backupDatabase(int highSequence, long date) {
}
public void createTables() {
Global.setDatabaseVersion("0.85");
Global.setAutomaticLogin(false);
Global.saveCurrentNoteGuid("");
Global.saveUploadAmount(0);
getTagTable().createTable();
notebookTable.createTable();
noteTable.createTable();
deletedTable.createTable();
searchTable.createTable();
watchFolderTable.createTable();
invalidXMLTable.createTable();
wordsTable.createTable();
syncTable.createTable();
}
public Connection getConnection() {
return conn;
}
//***************************************************************
//* Table get methods
//***************************************************************
public DeletedTable getDeletedTable() {
return deletedTable;
}
public TagTable getTagTable() {
return tagTable;
}
public NoteTable getNoteTable() {
return noteTable;
}
public NotebookTable getNotebookTable() {
return notebookTable;
}
public SavedSearchTable getSavedSearchTable() {
return searchTable;
}
public WatchFolderTable getWatchFolderTable() {
return watchFolderTable;
}
public WordsTable getWordsTable() {
return wordsTable;
}
public InvalidXMLTable getInvalidXMLTable() {
return invalidXMLTable;
}
public SyncTable getSyncTable() {
return syncTable;
}
}
| true
|
5da727d486242cef383f0f2fc56456630f882130
|
Java
|
thevpc/upa
|
/upa-test-old/src/test/java/net/thevpc/upa/test/v1_0_2_29/SelectUC.java
|
UTF-8
| 4,909
| 2.265625
| 2
|
[] |
no_license
|
package net.thevpc.upa.test.v1_0_2_29;
import junit.framework.Assert;
import net.thevpc.upa.test.v1_0_2_29.model.SharedClient;
import net.thevpc.upa.test.v1_0_2_29.util.PUUtils;
import org.junit.BeforeClass;
import org.junit.Test;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* @author Taha BEN SALAH <taha.bensalah@gmail.com>
* @creationdate 9/16/12 10:02 PM
*/
public class SelectUC {
private static final java.util.logging.Logger log = java.util.logging.Logger.getLogger(SelectUC.class.getName());
private static Business bo;
@BeforeClass
public static void setup() {
PersistenceUnit pu = PUUtils.createTestPersistenceUnit(SelectUC.class);
pu.addEntity(SharedClient.class);
pu.start();
bo = UPA.makeSessionAware(new Business());
bo.init();
}
@Test
public void testQuery1() {
bo.testQuery1();
}
@Test
public void testQuery2() {
bo.testQuery2();
}
@Test
public void testQuery3() {
bo.testQuery3();
}
@Test
public void testQuery4() {
bo.testQuery4();
}
@Test
public void testQuery5() {
bo.testQuery5();
}
public static class Business {
public void init() {
PersistenceUnit pu = UPA.getPersistenceUnit();
pu.clear(null, null);
pu.persist(getRefClient1());
pu.persist(getRefClient2());
}
private SharedClient getRefClient1() {
SharedClient c = new SharedClient();
c.setId(1);
c.setFirstName("emma");
c.setLastName("community");
c.setRight("left");
return c;
}
private SharedClient getRefClient2() {
SharedClient c = new SharedClient();
c.setId(2);
c.setFirstName("thomson");
c.setLastName("community");
c.setRight("up");
return c;
}
public void testQuery1() {
PersistenceUnit pu = UPA.getPersistenceUnit();
Query q = pu.createQuery("Select a from SharedClient a order by a.firstName");
List<Record> r = q.getRecordList();
EntityBuilder b = pu.getEntity(SharedClient.class).getBuilder();
List<Record> expected = Arrays.asList(
b.objectToRecord(getRefClient1()),
b.objectToRecord(getRefClient2())
);
Assert.assertEquals(expected, r);
}
public void testQuery2() {
PersistenceUnit pu = UPA.getPersistenceUnit();
Query q = pu.createQuery("Select a from SharedClient a order by a.firstName");
List<SharedClient> r = q.getResultList();
List<SharedClient> expected = Arrays.asList(
(getRefClient1()),
(getRefClient2())
);
Assert.assertEquals(expected, r);
}
public void testQuery3() {
PersistenceUnit pu = UPA.getPersistenceUnit();
// Query q = pu.createQuery("Select a from Client a where a.firstName like :v").setParameter("v", "%mm%");
Query q = pu.createQuery("Select a. `right` from SharedClient a order by a. `right`");
List<Record> found = q.getRecordList();
EntityBuilder b = pu.getEntity(SharedClient.class).getBuilder();
List<Record> expected=new ArrayList<>();
Record d = b.createRecord();
d.setString("right", "left");
expected.add(d);
d = b.createRecord();
d.setString("right", "up");
expected.add(d);
Assert.assertEquals(expected, found);
}
public void testQuery4() {
PersistenceUnit pu = UPA.getPersistenceUnit();
// Query q = pu.createQuery("Select a from Client a where a.firstName like :v").setParameter("v", "%mm%");
Query q = pu.createQuery("Select a from SharedClient a where a.firstName like :v or a.firstName like :v or a.firstName like :v")
.setParameter("v", "%mm%");
List<Record> r = q.getRecordList();
List<Record> expected = Arrays.asList(pu.getEntity(SharedClient.class).getBuilder().objectToRecord(getRefClient1()));
Assert.assertEquals(expected, r);
}
public void testQuery5() {
PersistenceUnit pu = UPA.getPersistenceUnit();
// Query q = pu.createQuery("Select a from Client a where a.firstName like :v").setParameter("v", "%mm%");
Query q = pu.createQuery("Select a. `right` from SharedClient a order by a.id desc");
List<Object> r = q.getValueList(0);
List<String> expected = new ArrayList<>();
expected.add("up");
expected.add("left");
Assert.assertEquals(expected, r);
}
}
}
| true
|
3d6f909922940530f66ad3ef5cd87f3818b6f55a
|
Java
|
MiranBatti/AoDLab3
|
/src/se/hig/aod/lab3/BSTQueuePerformance.java
|
UTF-8
| 2,404
| 3.25
| 3
|
[] |
no_license
|
package se.hig.aod.lab3;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import se.hig.aod.lab3.BSTPriorityQueue;
import se.hig.aod.lab3.DuplicateItemException;
import se.hig.aod.lab3.EmptyQueueException;
/**
* This class measures the speed of inserting and removing elements from a BST based priority queue.
*
* @author Miran Batti
* @author Fredrik Lindorf
*
* @version 2015-12-08
*/
public class BSTQueuePerformance {
public static void main(String[] args) {
BSTPriorityQueue<Integer> pq = new BSTPriorityQueue<Integer>();
ArrayList<Integer> biggerL = null;
ArrayList<Integer> smallerL = null;
DataLoader r = new DataLoader();
try {
biggerL = r.loadList("C:/Users/Miran/git/AoDLab3/src/resources/data_640000.txt", 640000);
smallerL = r.loadList("C:/Users/Miran/git/AoDLab3/src/resources/data_6400.txt", 6400);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// Collections.sort(biggerL);
// Collections.sort(biggerL, Collections.reverseOrder());
System.out.println("Enqueue: ");
int amount = 640000;
long beginEnqueue = System.currentTimeMillis();
List<Integer> a = biggerL.subList(0, amount);
// Enqueue
for (Integer integer : a) {
try {
pq.enqueue(integer);
} catch (DuplicateItemException e) {
e.printStackTrace();
}
}
for (Integer integer : smallerL) {
try {
pq.enqueue(integer);
} catch (DuplicateItemException e) {
e.printStackTrace();
}
}
long exetimeEnqueue = System.currentTimeMillis() - beginEnqueue;
System.out.println(exetimeEnqueue);
System.out.println("Dequeue: ");
// Dequeue
long beginDequeue = System.currentTimeMillis();
for (@SuppressWarnings("unused") Integer integer : a) {
try {
pq.dequeue();
} catch (EmptyQueueException e) {
e.printStackTrace();
}
}
for (@SuppressWarnings("unused") Integer integer : smallerL) {
try {
pq.dequeue();
} catch (EmptyQueueException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
long exetimeDequeue = System.currentTimeMillis() - beginDequeue;
System.out.println(exetimeDequeue);
}
}
| true
|
e7d1c80a00c748af0ccb09311dd54a16aa7954d7
|
Java
|
hamzah0553/Projekt-uge-2017
|
/KinoXP/src/View/CreateLogin.java
|
UTF-8
| 1,906
| 2.6875
| 3
|
[] |
no_license
|
package View;
import Controller.EmployeeController;
import Models.Employee;
import System.View;
import javafx.geometry.*;
import javafx.geometry.Insets;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.PasswordField;
import javafx.scene.control.TextField;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.GridPane;
import javafx.scene.text.Text;
import javafx.stage.Stage;
import java.awt.*;
public class CreateLogin extends View
{
private EmployeeController controller;
public CreateLogin(EmployeeController controller){
this.controller = controller;
}
public void setCreateLogin(Stage stage)
{
BorderPane borderPane = new BorderPane();
GridPane gridPane = new GridPane();
TextField username = new TextField();
PasswordField password = new PasswordField();
TextField name = new TextField();
TextField theaterID = new TextField();
TextField role = new TextField();
gridPane.add(new Text("Opret medarbejder login"),0,0);
gridPane.add(new Label("Brugernavn: "), 0,1);
gridPane.add(username, 1,1);
gridPane.add(new Label("Kodeord"), 0,2);
gridPane.add(password, 1,2);
gridPane.add(new Label("Navn: "),0,3);
gridPane.add(name, 1,3);
gridPane.add(new Label("Rolle: "),0,4);
gridPane.add(role, 1,4);
Button saveButton = new Button("Gem");
saveButton.setOnAction(event -> {
Employee employee = new Employee(0, name.getText(), role.getText());
controller.createLogin(username.getText(), password.getText(), employee);
});
gridPane.setAlignment(Pos.TOP_CENTER);
gridPane.setPadding(new Insets(30,20,20,20));
borderPane.setCenter(gridPane);
setScene(borderPane, saveButton, stage);
}
}
| true
|
dc92d84c3366679eed323e9b11b756256092cf77
|
Java
|
wxjhub/ec_warn
|
/src/lrms/com/vprisk/lrms/excel/ExcelTemplate.java
|
UTF-8
| 631
| 2.140625
| 2
|
[] |
no_license
|
package com.vprisk.lrms.excel;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.InvocationTargetException;
import java.text.ParseException;
import java.util.List;
public interface ExcelTemplate {
public ByteArrayOutputStream createFixationSheet(List<?> list,
Class<?> clazz);
public List inputExcel(Class<?> clazz, InputStream inputStream,List<String> errors) throws SecurityException, NoSuchMethodException,
IllegalArgumentException, InstantiationException,
IllegalAccessException, InvocationTargetException, ParseException, NoSuchFieldException;
}
| true
|
05f8b937984bee8ed169a4f4559128e7076a9fd5
|
Java
|
blainechai/TOSCA-chef
|
/src/main/java/kr/ac/hanyang/model/definition/PolicyDefinition.java
|
UTF-8
| 2,452
| 2.609375
| 3
|
[] |
no_license
|
package kr.ac.hanyang.model.definition;
import kr.ac.hanyang.model.basemodel.validator.DefinitionValidator;
import kr.ac.hanyang.model.basemodel.validator.TemplateValidator;
import kr.ac.hanyang.model.KeyName;
import kr.ac.hanyang.model.KeyNames;
import java.util.LinkedHashMap;
import java.util.Map;
/** 3.7.6 Policy definition
*/
/**
* Keyname
* Requred
* type
* Description
type
yes
string
The required name of the policy type the policy definition is based upon.
description
no
description
The optional description for the policy definition.
properties
no list of property assignments
An optional list of property value assignments for the policy definition.
targets
no
string[]
An optional list of valid Node Templates or Groups the Policy can be applied to.
/**
* Grammar
* <policy_name>:
* type: <policy_type_name>
* description: <policy_description>
* properties:
* <property_assignments>
* targets: [<list_of_policy_targets>]
*
* policy_name: represents the required symbolic name of the policy as a string.
* policy_type_name: represents the name of the policy the definition is based upon.
* policy_description: contains an optional description of the policy.
* property_assignments: represents the optional list of property assignments for the policy definition that provide values for properties defined in its declared Policy type.
* list_of_policy_targets: represents the optional list of names of node templates or groups that the policy is to applied to.
*/
//TODO: PolicyType의 list로 구현하여 어떤 모양을 지정하는 방식으로 구현
public class PolicyDefinition extends DefinitionValidator {
public PolicyDefinition(){}
public PolicyDefinition(Map data) {
super();
this.data = data;
keyNames.add(new KeyName("type", true, "string", "The required name of the policy type the policy definition is based upon."));
keyNames.add(new KeyName("description" , false, "description", "The optional description for the policy definition."));
keyNames.add(new KeyName("properties", false, "list of property assignments", "An optional list of property value assignments for the policy definition."));
keyNames.add(new KeyName("targets", false, "string[]", "An optional list of valid Node Templates or Groups the Policy can be applied to."));
}
}
| true
|
604912dc35aa4406919950c7b3dce4a0b6885798
|
Java
|
xiaohuatzhu/note
|
/src/main/java/cn/tedu/note/controller/AccessFilterServelt.java
|
UTF-8
| 1,763
| 2.5
| 2
|
[] |
no_license
|
package cn.tedu.note.controller;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
public class AccessFilterServelt implements Filter {
public void destroy() {
}
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
// 登录和弹出框都放行
String login = "/log_in.html";
String alert = ".*alert_.*.html";
// 强转
HttpServletRequest req = (HttpServletRequest) request;
HttpServletResponse res = (HttpServletResponse) response;
HttpSession session = req.getSession();
// 获取请求的uri 项目名/路径名
String uri = req.getRequestURI();
System.out.println("AccessFilterServelt.doFilter()->access:" + uri);
if (uri.endsWith(login) || uri.matches(alert)) {
// 登录和弹出框都放行
chain.doFilter(req, res);
return;
}
// 获取session中的user
Object user = session.getAttribute("loginUser");
if (user == null) {
// 未登录,转发到登录界面,此处要用全路径 项目名/路径名
res.sendRedirect(req.getContextPath() + "/log_in.html");
// 此处要return, 不然和后面的响应一起会导致二次响应异常
// 规定一次请求只能有一次响应,不然会抛出异常
return;
}
// 已登录,放行
chain.doFilter(req, res);
}
public void init(FilterConfig arg0) throws ServletException {
}
}
| true
|
2d5f09540b05fd3a70e8c8f086c8d717ce7efa25
|
Java
|
hyeonhee185/middle-java
|
/servletTest2/src/kr/or/ddit/util/CryptoUtil.java
|
UTF-8
| 4,214
| 3.09375
| 3
|
[] |
no_license
|
package kr.or.ddit.util;
import java.io.UnsupportedEncodingException;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
public class CryptoUtil {
// 단방향 암호화하는 메서드
// 변수 str : 암호화할 데이터가 저장된 변수
public static String sha512(String str) throws NoSuchAlgorithmException, UnsupportedEncodingException {
// 단방향 암호화 알고리즘 이름 : MD5, SHA-256, SHA-3, SHA-512
MessageDigest md = MessageDigest.getInstance("SHA-512");
md.update(str.getBytes("UTF-8"));
return Base64.getEncoder().encodeToString(md.digest());
}
// 양방향 암호화 하기
/**
* AES 256 방식으로 암호화 하는 메서드
* @param str 암호화할 문자열
* @param key 암호키 문자열(16자 이상)
* @return 암호화된 문자열
* @throws UnsupportedEncodingException
* @throws NoSuchPaddingException
* @throws NoSuchAlgorithmException
* @throws InvalidAlgorithmParameterException
* @throws InvalidKeyException
* @throws BadPaddingException
* @throws IllegalBlockSizeException
*/
public static String encryptAES256(String str, String key) throws UnsupportedEncodingException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException {
byte[] keyBytes = new byte[16];
System.arraycopy(key.getBytes("UTF-8"), 0, keyBytes, 0, keyBytes.length);
// 비밀키 생성
SecretKeySpec keySpec = new SecretKeySpec(keyBytes, "AES");
// Cipher 생성 및 초기화
// 알고리즘/모드/패딩
Cipher c = Cipher.getInstance("AES/CBC/PKCS5Padding");
// 초기화 벡터(Initial Vector, IV)
// - 암호문이 패턴화되지 않도록 사용하는 데이터
// - 암호화 작업의 첫번째 블록에 사용되는 값
String iv = key.substring(0, 16);
byte[] ivBytes = new byte[16];
System.arraycopy(iv.getBytes("UTF-8"), 0, ivBytes, 0, ivBytes.length);
// 암호를 옵션 종류에 맞게 초기화 한다.
// 옵션 종류 : ENCRYPT_MODE(암호화모드), DECRYPT_MODE(복호화모드)
c.init(Cipher.ENCRYPT_MODE, keySpec, new IvParameterSpec(ivBytes));
// 암호문 생성
byte[] encrypted = c.doFinal(str.getBytes("UTF-8"));
return Base64.getEncoder().encodeToString(encrypted);
}
/**
* 암호화된 데이터를 원래의 데이터로 복원하는 메서드
* @param str 암호화된 문자열
* @param key 암호키 문자열
* @return 원래 데이터로 복원된 문자열
* @throws UnsupportedEncodingException
* @throws NoSuchPaddingException
* @throws NoSuchAlgorithmException
* @throws InvalidAlgorithmParameterException
* @throws InvalidKeyException
* @throws BadPaddingException
* @throws IllegalBlockSizeException
*/
public static String decryptAES256(String str, String key) throws UnsupportedEncodingException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException {
byte[] keyByes = new byte[16];
System.arraycopy(key.getBytes("UTF-8"), 0, keyByes, 0, keyByes.length);
// 비밀키 생성
SecretKeySpec keySpec = new SecretKeySpec(keyByes, "AES");
Cipher c = Cipher.getInstance("AES/CBC/PKCS5Padding");
String iv = key.substring(0,16);
byte[] ivBytes = new byte[16];
System.arraycopy(iv.getBytes("UTF-8"), 0, ivBytes, 0, ivBytes.length);
c.init(Cipher.DECRYPT_MODE, keySpec, new IvParameterSpec(ivBytes));
byte[] byteStr = Base64.getDecoder().decode(str); // 암호문을 decoding한다.
return new String(c.doFinal(byteStr), "UTF-8");
}
}
| true
|
bac140c82901af0873b393491dfc5d5bfee6cd46
|
Java
|
amitwadhiani/mongo
|
/src/main/java/co/arctern/api/provider/service/serviceimpl/LoginFlowServiceImpl.java
|
UTF-8
| 913
| 2.15625
| 2
|
[] |
no_license
|
package co.arctern.api.provider.service.serviceimpl;
import co.arctern.api.provider.constant.LoginState;
import co.arctern.api.provider.dao.LoginFlowDao;
import co.arctern.api.provider.domain.Login;
import co.arctern.api.provider.domain.LoginFlow;
import co.arctern.api.provider.service.LoginFlowService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class LoginFlowServiceImpl implements LoginFlowService {
private final LoginFlowDao loginFlowDao;
@Autowired
public LoginFlowServiceImpl(LoginFlowDao loginFlowDao) {
this.loginFlowDao = loginFlowDao;
}
@Override
public LoginFlow create(Login login, LoginState state) {
LoginFlow loginFlow = new LoginFlow();
loginFlow.setLogin(login);
loginFlow.setLoginState(state);
return loginFlowDao.save(loginFlow);
}
}
| true
|
83a85c893b21016300af6b036c27c96d864f0967
|
Java
|
ZouYongpeng/WoChat_Bmob
|
/app/src/main/java/com/example/wochat_bmob/bean/User.java
|
UTF-8
| 1,069
| 2.453125
| 2
|
[] |
no_license
|
package com.example.wochat_bmob.bean;
import com.example.wochat_bmob.db.NewFriend;
import cn.bmob.v3.BmobUser;
/**
* Created by 邹永鹏 on 2018/5/4.
* 专门的用户类——BmobUser来自动处理用户账户管理所需的功能
* BmobUser除了从BmobObject继承的属性外,还有几个特定的属性:
* username: 用户的用户名(必需)。
* password: 用户的密码(必需)。
* email: 用户的电子邮件地址(可选)。
* emailVerified:邮箱认证状态(可选)。
* mobilePhoneNumber:手机号码(可选)。
* mobilePhoneNumberVerified:手机号码的认证状态(可选)。
*/
public class User extends BmobUser {
private String avatar;
public User(){}
public User(NewFriend friend){
setObjectId(friend.getUid());
setUsername(friend.getName());
setAvatar(friend.getAvatar());
}
public String getAvatar() {
return avatar;
}
public void setAvatar(String avatar) {
this.avatar = avatar;
}
}
| true
|
d258461cf2d6cb9b99789cfb772f6241ed764d53
|
Java
|
sebastianarnold/TeXoo
|
/texoo-entity-linking/src/main/java/de/datexis/nel/model/NamedEntity.java
|
UTF-8
| 1,897
| 2.484375
| 2
|
[
"Apache-2.0"
] |
permissive
|
package de.datexis.nel.model;
import com.google.common.collect.Multimap;
import com.google.common.collect.TreeMultimap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Collection;
/**
* Knowledge Base entry for a named entity.
* @author Sebastian Arnold <sarnold@beuth-hochschule.de>
*/
public class NamedEntity {
protected final Logger log = LoggerFactory.getLogger(getClass());
protected String id;
protected String name;
protected Collection<String> aliases;
protected String description;
protected Multimap<String, String> links = TreeMultimap.create();
/**
* @return the unique identifier of this entity (e.g. Wikidata ID)
*/
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
/**
* @return the canonical name for this entity
*/
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
/**
* @return a collection of alias names for this entity. Please make sure to include the canonical name.
*/
public Collection<String> getAliases() {
return aliases;
}
public void setAliases(Collection<String> aliases) {
this.aliases = aliases;
}
/**
* @return a description of this entity, can be used for training
*/
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
/**
* @return a multimap for links to foreign keys, e.g. "wikipedia" -> url, "UMLS" -> CUI
*/
public Multimap<String, String> getLinks() {
return links;
}
public void setLinks(Multimap<String, String> links) {
this.links = links;
}
public Collection<String> getLinks(String key) {
return links.get(key);
}
public void addLink(String key, String value) {
links.put(key, value);
}
}
| true
|
23b4b20875a5afb0e61881b54747b1229b53ec98
|
Java
|
hdulqs/NC65_SCM_SO
|
/saleinvoice/src/client/nc/ui/so/m32/billui/action/add/RefAddAction.java
|
GB18030
| 8,256
| 1.679688
| 2
|
[] |
no_license
|
package nc.ui.so.m32.billui.action.add;
import java.awt.event.ActionEvent;
import java.util.ArrayList;
import java.util.List;
import nc.vo.pub.BusinessException;
import nc.vo.pub.VOStatus;
import nc.vo.pub.pf.PfAddInfo;
import nc.vo.pubapp.pattern.exception.ExceptionUtils;
import nc.vo.pubapp.util.VORowNoUtils;
import nc.vo.scmpub.res.billtype.ICBillType;
import nc.vo.scmpub.res.billtype.SOBillType;
import nc.vo.so.m32.entity.SaleInvoiceBVO;
import nc.vo.so.m32.entity.SaleInvoiceVO;
import nc.vo.so.m32.paravo.CombinCacheVO;
import nc.vo.so.m32.paravo.CombinResultVO;
import nc.vo.so.m32.paravo.RefAddLineParaVO;
import nc.vo.so.m32.util.HeadTotalCalcUtil;
import nc.vo.trade.checkrule.VOChecker;
import nc.itf.scmpub.IScmpubMaintain;
import nc.itf.scmpub.reference.uap.group.SysInitGroupQuery;
import nc.itf.uap.pf.busiflow.PfButtonClickContext;
import nc.bs.framework.common.NCLocator;
import nc.ui.pub.pf.PfUtilClient;
import nc.ui.pubapp.uif2app.actions.AbstractReferenceAction;
import nc.ui.pubapp.uif2app.funcnode.trantype.TrantypeFuncUtils;
import nc.ui.so.m32.billui.model.SaleInvoiceManageModel;
import nc.ui.so.m32.billui.pub.SaleInvoiceCombin;
import nc.ui.so.m32.billui.view.SaleInvoiceEditor;
import nc.ui.uif2.UIState;
/**
* ۷Ʊ
*
* @since 6.3
* @version 2012-12-21 10:52:30
* @author yaogj
*/
public class RefAddAction extends AbstractReferenceAction {
/**
*
*/
private static final long serialVersionUID = 8278944084279171430L;
private SaleInvoiceEditor editor;
private SaleInvoiceManageModel model;
/**
* RefAddAction Ĺ
*/
public RefAddAction() {
super();
}
@Override
public void doAction(ActionEvent e) throws Exception {
PfButtonClickContext context = this.createPfButtonClickContext();
PfUtilClient.childButtonClickedNew(context);
SaleInvoiceVO[] newvos = null;
if (PfUtilClient.isCloseOK()) {
newvos = (SaleInvoiceVO[]) PfUtilClient.getRetVos();
if (VOChecker.isEmpty(newvos)) {
return;
}
// תǰ
this.beforeTranProcessor(newvos);
// ŲǻʾĻ
CombinResultVO combinres = this.combinSaleInvoices(newvos);
if (combinres.getBcombinflag()) {
newvos = combinres.getCombinvos();
}
// ܽ
this.getModel().setCombinCacheVO(combinres.getCacheVO());
// ݽ洦
this.getTransferViewProcessor().processBillTransfer(newvos);
}
}
/**
* ۷ƱEditor
* <p>
* <b>˵</b>
*
* @return <p>
* @author ӱ
* @time 2010-4-29 07:24:42
*/
public SaleInvoiceEditor getEditor() {
return this.editor;
}
/**
* ۷Ʊmodel
* <p>
* <b>˵</b>
*
* @return <p>
* @author ӱ
* @time 2010-4-29 07:25:28
*/
public SaleInvoiceManageModel getModel() {
return this.model;
}
/**
* ť
*/
@Override
public boolean isEnabled() {
return this.getModel().getUiState() == UIState.NOT_EDIT;
}
/**
*
* @param view ƱƬ
*/
public void setEditor(SaleInvoiceEditor view) {
this.editor = view;
}
/**
*
* @param model Ʊmodel
*/
public void setModel(SaleInvoiceManageModel model) {
this.model = model;
this.model.addAppEventListener(this);
}
/**
* ùתǰ
* <p>
* <b>˵</b>
*
* @param newvos
* <p>
* @author ӱ
* @time 2010-4-29 07:28:04
*/
protected void beforeTranProcessor(SaleInvoiceVO[] newvos) {
if (newvos != null && newvos.length > 0) {
// к
for (SaleInvoiceVO newvo : newvos) {
VORowNoUtils.setVOsRowNoByRule(newvo.getAllChildrenVO(),
SaleInvoiceBVO.CROWNO);
}
// ͷϼֵ
HeadTotalCalcUtil.getInstance().calcHeadTotalValue(newvos);
}
}
protected CombinResultVO combinSaleInvoices(SaleInvoiceVO[] newvos) {
CombinResultVO combinres = null;
CombinCacheVO cachevo = this.getModel().getCombinCacheVO();
if (cachevo.getBcombinflag()) {
List<SaleInvoiceBVO> alNewBodys = new ArrayList<SaleInvoiceBVO>();
List<SaleInvoiceVO> alNewHeads = new ArrayList<SaleInvoiceVO>();
for (SaleInvoiceVO vo : newvos) {
alNewHeads.add(vo);
for (SaleInvoiceBVO bvo : vo.getChildrenVO()) {
alNewBodys.add(bvo);
}
}
IScmpubMaintain srv =
NCLocator.getInstance().lookup(IScmpubMaintain.class);
/**
* ֻӱID ԭҪidж
* IDŵǰ
*/
String[] ids = null;
try {
ids = srv.getIDs(alNewBodys.size());
}
catch (BusinessException ex) {
ExceptionUtils.wrappException(ex);
}
if (null != ids) {
int i = 0;
for (SaleInvoiceVO vo : newvos) {
vo.getParentVO().setStatus(VOStatus.NEW);
for (SaleInvoiceBVO bvo : vo.getChildrenVO()) {
bvo.setPrimaryKey(ids[i]);
bvo.setStatus(VOStatus.NEW);
i++;
}
}
}
SaleInvoiceCombin combinutil = new SaleInvoiceCombin();
combinres = combinutil.combinSaleInvoices(newvos, cachevo);
}
else {
combinres = new CombinResultVO(false);
}
return combinres;
}
public PfButtonClickContext createPfButtonClickContext() {
PfButtonClickContext context = new PfButtonClickContext();
context.setParent(this.getModel().getContext().getEntranceUI());
context.setSrcBillType(this.getSourceBillType());
context.setPk_group(this.getModel().getContext().getPk_group());
context.setUserId(this.getModel().getContext().getPk_loginUser());
// ýڵɽͷģôӦôͣ
context.setCurrBilltype(SOBillType.Invoice.getCode());
context.setUserObj(null);
context.setSrcBillId(null);
context.setBusiTypes(this.getBusitypes());
// IJԭõķж漰ֻһṹ¼ӵIJ
// εĽͼ
context.setTransTypes(this.getTranstypes());
// ־ڽĿĽͷʱĿĽ͵ݣֵ1ݽӿڶ壩
// 2ã-1ݽͷ飩
context.setClassifyMode(PfButtonClickContext.ClassifyByBusiflow);
if (SysInitGroupQuery.isICEnabled()) {
try {
RefAddLineParaVO userobj = new RefAddLineParaVO();
String trantype =
TrantypeFuncUtils.getTrantype(this.getModel().getContext());
PfAddInfo[] vosInfoAdd =
PfUtilClient.retAddInfo(SOBillType.Invoice.getCode(), trantype,
this.getModel().getContext().getPk_group(), this.getModel()
.getContext().getPk_loginUser(), true);
// ûгƱİť
if (null == vosInfoAdd) {
return context;
}
for (PfAddInfo voInfoAdd : vosInfoAdd) {
if (ICBillType.SaleOut.getCode().equals(voInfoAdd.getSrc_billtype())) {
List<String> busitypes = voInfoAdd.getBusitypes();
userobj
.setBusitypes(busitypes.toArray(new String[busitypes.size()]));
}
}
context.setUserObj(userobj);
}
catch (Exception e) {
ExceptionUtils.wrappException(e);
}
}
return context;
}
/**
* ҵ
*
* @param pbillVOs
*/
// private void setDefaultValue(SaleInvoiceVO[] pbillVOs) {
// SaleInvoiceVO[] vos = pbillVOs;
// UFDate date = AppContext.getInstance().getBusiDate();
// for (SaleInvoiceVO vo : vos) {
// vo.getParentVO().setDbilldate(date);
// SaleInvoiceBVO[] bvos = vo.getChildrenVO();
// for (SaleInvoiceBVO bvo : bvos) {
// bvo.setDbilldate(date);
// }
// }
// }
}
| true
|
ac458ffa6e0ff66692943bf7c45b21905d96f97e
|
Java
|
VislaPoland/aptapp-backend
|
/backend/src/main/java/com/creatix/service/AccountDeviceService.java
|
UTF-8
| 4,503
| 2.109375
| 2
|
[] |
no_license
|
package com.creatix.service;
import com.creatix.configuration.DeviceProperties;
import com.creatix.domain.dao.AccountDao;
import com.creatix.domain.dao.DeviceDao;
import com.creatix.domain.dto.account.device.AccountDeviceDto;
import com.creatix.domain.entity.store.account.Account;
import com.creatix.domain.entity.store.account.device.Device;
import com.creatix.domain.enums.PlatformType;
import com.creatix.security.AuthorizationManager;
import com.creatix.security.RoleSecured;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import javax.persistence.EntityNotFoundException;
import javax.servlet.http.HttpSession;
import java.util.Objects;
@Service
@Transactional
public class AccountDeviceService {
private static final Object syncLock = new Object();
@Autowired
private DeviceProperties deviceProperties;
@Autowired
private DeviceDao deviceDao;
@Autowired
private AccountDao accountDao;
@Autowired
private AuthorizationManager authorizationManager;
@Autowired
private HttpSession httpSession;
@Nonnull
public Device retrieveDevice(@Nonnull String deviceUDID, @Nonnull PlatformType platformType) {
Objects.requireNonNull(deviceUDID, "Device UDID is null");
Objects.requireNonNull(platformType, "Platform type is null");
Device device;
synchronized ( syncLock ) {
device = deviceDao.findByUDIDAndPlatformType(deviceUDID, platformType);
if ( device == null ) {
device = new Device();
device.setUdid(deviceUDID);
device.setPlatform(platformType);
}
// clear delete date
device.setDeletedAt(null);
deviceDao.persist(device);
}
if ( this.authorizationManager.hasCurrentAccount() ) {
final Account account = this.getAccount(this.authorizationManager.getCurrentAccount().getId());
if (device.getAccount() == null || (device.getAccount() != null && device.getAccount().getId().equals(account.getId()))) {
device.setAccount(account);
deviceDao.persist(device);
}
}
return device;
}
@RoleSecured
@Nonnull
public Device register(@Nonnull Long accountId, @Nonnull Long deviceId, @Nonnull AccountDeviceDto request) {
Objects.requireNonNull(accountId);
Objects.requireNonNull(deviceId);
Objects.requireNonNull(request);
Objects.requireNonNull(request.getPushToken());
final Device device = this.getDevice(deviceId);
final Account account = this.getAccount(accountId);
authorizationManager.checkAccess(device, account);
device.setPushToken(request.getPushToken());
device.setAccount(account);
deviceDao.persist(device);
return device;
}
@RoleSecured
@Nullable
public Device assignDeviceToAccount(@Nonnull Account account) {
Objects.requireNonNull(account);
PlatformType platformType = (PlatformType) httpSession.getAttribute(deviceProperties.getSessionKeyPlatform());
if (platformType == PlatformType.Web) {
return null;
}
Object deviceObject = httpSession.getAttribute(deviceProperties.getSessionKeyDevice());
if ( !(deviceObject instanceof Device) ) {
throw new SecurityException("Device is not recognized.");
}
final Device device = this.getDevice(((Device) deviceObject).getId());
device.setAccount(account);
deviceDao.persist(device);
return device;
}
@Nonnull
private Device getDevice(@Nonnull Long deviceId) {
Objects.requireNonNull(deviceId);
final Device device = this.deviceDao.findById(deviceId);
if ( device == null ) {
throw new EntityNotFoundException(String.format("Device id=%d not found", deviceId));
}
return device;
}
@Nonnull
private Account getAccount(@Nonnull Long accountId) {
Objects.requireNonNull(accountId);
final Account account = this.accountDao.findById(accountId);
if ( account == null ) {
throw new EntityNotFoundException(String.format("Account id=%d not found", accountId));
}
return account;
}
}
| true
|
9ebb045df13bf41f34fbbeb3a4464f38eaefeca3
|
Java
|
Himanshu-jain2597/Coding-DS-Algo-Java
|
/Recursion/FindAllIndexes.java
|
UTF-8
| 1,034
| 3.40625
| 3
|
[] |
no_license
|
/* package codechef; // don't place package name! */
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
class Codechef
{
public static void main (String[] args) throws java.lang.Exception
{
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int [] arr = new int[n];
for(int i=0;i<n;i++) {
arr[i] = sc.nextInt();
}
int[] arr1 = OccuranceArray(arr,4,0,0);
for(int i=0;i<arr1.length;i++) {
System.out.println(arr1[i]);
}
}
public static int[] OccuranceArray(int arr[],int element,int si,int count) {
if(si==arr.length) {
int [] base = new int[count];
return base;
}
int [] indices = null;
if(arr[si]==element) {
count=count+1;
indices = OccuranceArray(arr,element,si+1,count);
indices[count-1] = si;
}
else {
indices = OccuranceArray(arr,element,si+1,count);
}
return indices;
}
}
| true
|
8e9977ff896280b023581140746c3ec8fb36c5c7
|
Java
|
EEIT98Team01/RemoteRepository1127
|
/CowBaby/src/main/java/model/dao/OrderDetailDao.java
|
UTF-8
| 1,733
| 2.265625
| 2
|
[] |
no_license
|
package model.dao;
import java.util.List;
import java.util.Map;
import model.bean.OrderDetailBean;
public interface OrderDetailDao {
// 由orderDetailID取得相對應資料
public OrderDetailBean findById(int id);
// 新增 OrderDetail 資料用
public OrderDetailBean insert(OrderDetailBean bean);
// 編輯 OrderDetail 資料用
public OrderDetailBean update(OrderDetailBean bean);
// 取得所有 OrderDetail 資料
public List<OrderDetailBean> find();
// 取得所有 OrderDetail 資料中某頁的n筆資料,供分頁功能使用
public List<OrderDetailBean> find(int page, int rows);
// 取得所有 OrderDetail 資料中某頁的n筆資料,供分頁功能使用,OrderDetail資料會先依某條件進行排序
public List<OrderDetailBean> find(int page, int rows, String sortCondition);
// 取得符合某條件之 OrderDetail 資料(K為欄位名稱, V為條件)
public List<OrderDetailBean> findByCondition(Map<String, String> condition);
// 取得符合某條件之 OrderDetail 資料(K為欄位名稱, V為條件)中某頁的n筆資料,供分頁功能使用
public List<OrderDetailBean> findByCondition(Map<String, String> condition, int page, int rows);
// 取得符合某條件之 OrderDetail 資料(K為欄位名稱, V為條件)中某頁的n筆資料,供分頁功能使用,符合條件之資料會先依某條件進行排序
public List<OrderDetailBean> findByCondition(Map<String, String> condition, int page, int rows, String sortCondition);
// 取得所有 OrderDetail 數量
public int getQuantity();
// 取得符合某條件之 OrderDetail 數量
public int getConditionQuantity(Map<String, String> condition);
}
| true
|
e790f32de5e86ed0392a6ad101439e760435e5a6
|
Java
|
j2web/WebProject
|
/PCIS_DAO/src/hk/com/mtr/pcis/dao/entity/co/CompanyType.java
|
UTF-8
| 2,385
| 2.328125
| 2
|
[] |
no_license
|
package hk.com.mtr.pcis.dao.entity.co;
import hk.com.mtr.pcis.dao.entity.sa.User;
import java.sql.Timestamp;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import org.apache.commons.lang.builder.EqualsBuilder;
import org.apache.commons.lang.builder.HashCodeBuilder;
@Entity
@Table(name="COMPANY_TYPE")
public class CompanyType {
public CompanyType() {
super();
}
public CompanyType(String coType, Integer adminFee,
String description, String updateUser, Timestamp updateTime) {
super();
this.coType = coType;
this.adminFee = adminFee;
this.description = description;
this.updateUser = updateUser;
this.updateTime = updateTime;
}
@Override
public int hashCode() {
return new HashCodeBuilder().append(getCoType()).toHashCode();
}
@Override
public boolean equals(Object object) {
if ((this == object))
return true;
if (object == null || !(object instanceof User)) {
return false;
}
CompanyType other = (CompanyType) object;
boolean equal = new EqualsBuilder().append(this.getCoType(), other.getCoType()).isEquals();
return equal;
}
@Id
@Column(name="CO_TYPE", nullable=false, length=7)
private String coType;
@Column(name="ADMIN_FEE", nullable=true, length=3)
private Integer adminFee;
@Column(name="DESCRIPTION", nullable=true, length=50)
private String description;
@Column(name="UPDUSER", nullable=true, length=15)
private String updateUser;
@Column(name="UPDTIME", nullable=false)
@Temporal(value=TemporalType.TIMESTAMP)
private Timestamp updateTime;
public String getCoType() {
return coType;
}
public void setCoType(String coType) {
this.coType = coType;
}
public Integer getAdminFee() {
return adminFee;
}
public void setAdminFree(Integer adminFee) {
this.adminFee = adminFee;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getUpdateUser() {
return updateUser;
}
public void setUpdateUser(String updateUser) {
this.updateUser = updateUser;
}
public Timestamp getUpdateTime() {
return updateTime;
}
public void setUpdateTime(Timestamp updateTime) {
this.updateTime = updateTime;
}
}
| true
|
f13a4588b97d9f5261f9b13d6f1bcf98dd672e7c
|
Java
|
Ahrijin/ShoppingCard
|
/app/src/main/java/jinyuanyuan/bw/com/androidprojects/activity/RgisterActivity.java
|
UTF-8
| 2,542
| 1.921875
| 2
|
[] |
no_license
|
package jinyuanyuan.bw.com.androidprojects.activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.xw.repo.XEditText;
import java.util.HashMap;
import java.util.Map;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import jinyuanyuan.bw.com.androidprojects.LoginActivity;
import jinyuanyuan.bw.com.androidprojects.R;
import jinyuanyuan.bw.com.androidprojects.bean.EnrollBean;
import jinyuanyuan.bw.com.androidprojects.presenter.PresenterImpls;
import jinyuanyuan.bw.com.androidprojects.utils.Contacts;
import jinyuanyuan.bw.com.androidprojects.view.IView;
public class RgisterActivity extends AppCompatActivity implements IView {
@BindView(R.id.rgisters)
Button btn;
@BindView(R.id.tel)
XEditText tel;
@BindView(R.id.xedit_yan)
XEditText xeditYan;
@BindView(R.id.account)
TextView account;
private PresenterImpls presenterImpls;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_rgister);
ButterKnife.bind(this);
presenterImpls = new PresenterImpls(this);
}
@OnClick({R.id.rgisters,R.id.account})
public void onViewClicked(View view) {
switch (view.getId()) {
case R.id.rgisters:
String tels = tel.getTrimmedString().trim();
String code = xeditYan.getTrimmedString().trim();
Map<String, Object> maps = new HashMap<>();
Map<String, Object> map = new HashMap<>();
map.put("phone", tels);
map.put("pwd", code);
presenterImpls.postHeader(Contacts.REGISTER, maps,map, EnrollBean.class);
break;
case R.id.account:
startActivity(new Intent(RgisterActivity.this, LoginActivity.class));
break;
}
}
@Override
public void setSuccess(Object datas) {
EnrollBean enrollBean = (EnrollBean) datas;
if (enrollBean.getMessage().equals("注册成功")) {
Toast.makeText(this, enrollBean.getMessage(), Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, enrollBean.getMessage(), Toast.LENGTH_SHORT).show();
}
}
@Override
public void setError(Object errors) {
}
}
| true
|
4ac3b3984cea9e9deb83b113ea4a1eb488e190fc
|
Java
|
priscilaluz/TCC
|
/TCC/tcc-common/src/main/java/tcc/common/business/CursoService.java
|
UTF-8
| 1,589
| 1.992188
| 2
|
[] |
no_license
|
package tcc.common.business;
import java.util.List;
import tcc.common.entity.Aviso;
import tcc.common.entity.Categoria;
import tcc.common.entity.Curso;
import tcc.common.entity.Etapa;
import tcc.common.enums.DisponibilidadeCurso;
import tcc.common.enums.SituacaoCurso;
import tcc.common.vo.ListaPaginacao;
/**
*
* @author ADM
*/
public interface CursoService {
Curso salvarCurso(Curso curso);
Curso copiarCurso(String nomeCurso, Long idCurso, Long idUsuario);
void excluirCurso(Long idCurso);
void updateDisponibilidadeCurso(Long idCurso, DisponibilidadeCurso disponibilidade);
Curso buscarCursoPorId(Long idCurso);
Curso buscarCursoPorIdConcluido(Long idCurso);
List<Curso> buscarCursoPorIdProfessor(Long idProfessor);
ListaPaginacao buscarCursoPorFiltro(Long idUsuario, String parteNome, Long idCategoria, SituacaoCurso situacaoCurso,
DisponibilidadeCurso disponibilidade, Long idAluno, Integer paginaAtual);
Long buscarCountCursoPorFiltro(Long idUsuario, SituacaoCurso situacaoCurso, Long idCategoria);
Etapa salvarEtapa(Etapa etapa);
void excluirEtapa(Long idCurso, Long idEtapa);
List<Etapa> buscarEtapa(Long idCurso, Integer nivel);
Etapa buscarEtapaPorId(Long idEtapa, boolean resposta);
boolean addAlunosAoCurso(Long idCurso, List<Long> idsAluno);
Aviso salvarAviso(Aviso aviso);
void excluirAviso(Long idAviso);
Aviso buscarAvisosPorId(Long id);
List<Aviso> buscarAvisosPorCurso(Long idCurso);
}
| true
|
22467c428135618e819d9e8eca4d95595e600920
|
Java
|
AprilYoLies/leaf-with-comment
|
/leaf-core/src/main/java/com/sankuai/inf/leaf/snowflake/SnowflakeIDGenImpl.java
|
UTF-8
| 5,835
| 2.5
| 2
|
[
"Apache-2.0"
] |
permissive
|
package com.sankuai.inf.leaf.snowflake;
import com.google.common.base.Preconditions;
import com.sankuai.inf.leaf.IDGen;
import com.sankuai.inf.leaf.common.Result;
import com.sankuai.inf.leaf.common.Status;
import com.sankuai.inf.leaf.common.Utils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Random;
public class SnowflakeIDGenImpl implements IDGen {
@Override
public boolean init() {
return true;
}
static private final Logger LOGGER = LoggerFactory.getLogger(SnowflakeIDGenImpl.class);
private final long twepoch = 1288834974657L; // 时间元时刻
private final long workerIdBits = 10L; // worker id 所占的位数
private final long maxWorkerId = -1L ^ (-1L << workerIdBits);//最大能够分配的workerid =1023
private final long sequenceBits = 12L; // 序列号所占的位长度
private final long workerIdShift = sequenceBits; // worker id 所应该移动的位数
private final long timestampLeftShift = sequenceBits + workerIdBits; // 时间戳应该移动的位数
private final long sequenceMask = -1L ^ (-1L << sequenceBits); // 序列号掩码
private long workerId;
private long sequence = 0L; // 初始序列号
private long lastTimestamp = -1L; // 初始时间戳
public boolean initFlag = false; // 初始化标志
private static final Random RANDOM = new Random();
private int port;
// 主要是构建了 SnowflakeZookeeperHolder,负责和 zookeeper 的交互,然后尝试从 zookeeper 获取 worker id,失败的情况下从本地获取 worker id
public SnowflakeIDGenImpl(String zkAddress, int port) {
this.port = port; // 缓存 port
SnowflakeZookeeperHolder holder = new SnowflakeZookeeperHolder(Utils.getIp(), String.valueOf(port), zkAddress);
initFlag = holder.init(); // 这里就是一个尝试从 zookeeper 中获取 worker id 的过程,如果在获取 worker id 的过程中出现错误,那么就使用本地缓存的 worker id
if (initFlag) { // 如果成功的拿到了 worker id
workerId = holder.getWorkerID(); // 缓存 worker id
LOGGER.info("START SUCCESS USE ZK WORKERID-{}", workerId); // 日志记录当前启动的 worker id
} else {
Preconditions.checkArgument(initFlag, "Snowflake Id Gen is not init ok");
} // worker id 是有效的
Preconditions.checkArgument(workerId >= 0 && workerId <= maxWorkerId, "workerID must gte 0 and lte 1023");
}
// 获取时间戳,和上一个 id 的时间戳比对,如果不一致,跟 worker id 和序列号拼凑成 id 返回,否则变更序列号,再拼凑出 id 返回,如果变更序列号可能导致 id 重复,那么人为将时间戳等待到之后的时刻,再拼凑 id 返回
public synchronized Result get(String key) {
long timestamp = timeGen(); // 获取当前的系统时间
if (timestamp < lastTimestamp) { // 如果时间发生了回拨
long offset = lastTimestamp - timestamp;
if (offset <= 5) { // 如果回拨值小于 5
try {
wait(offset << 1); // 那么就人为的等待两倍的回拨值
timestamp = timeGen(); // 重新获取系统时间
if (timestamp < lastTimestamp) { // 如果人为调整后,时间还是有回拨现象,返回异常
return new Result(-1, Status.EXCEPTION); // 返回错误 result
}
} catch (InterruptedException e) { // 如果人为等待的过程中,线程被中断了,那么日志记录错误,返回错误 result
LOGGER.error("wait interrupted");
return new Result(-2, Status.EXCEPTION);
}
} else {
return new Result(-3, Status.EXCEPTION); // 如果回拨时长超过 5,那么就返回错误 result
}
}
if (lastTimestamp == timestamp) { // 如果时间戳一致,也就是在 1ms 内多次请求,唯一 id 就需要通过序列号来区分
sequence = (sequence + 1) & sequenceMask; // 计算此时的序列号
if (sequence == 0) { // 如果序列号为 0
//seq 为0的时候表示是下一毫秒时间开始对seq做随机
sequence = RANDOM.nextInt(100); // 随机获得序列值
timestamp = tilNextMillis(lastTimestamp); // 自旋直到下一个 lastTimestamp 时刻之后,返回此时的时间戳(这里是为了防止在 1ms 时间内,sequence 递增太多,导致重复,从而用时间来区分)
}
} else { // 执行到这里,说明时刻发生了变化,已经确保了 id 的唯一性,所以 sequence 随机一个就行
//如果是新的ms开始
sequence = RANDOM.nextInt(100);
}
lastTimestamp = timestamp; // 记录下当前时间戳
long id = ((timestamp - twepoch) << timestampLeftShift) | (workerId << workerIdShift) | sequence; // 根据时间戳、worker id、序列号来构建唯一 id
return new Result(id, Status.SUCCESS); // 返回构建出来的 id 值
}
// 自旋直到下一个 lastTimestamp 时刻之后,返回此时的时间戳
protected long tilNextMillis(long lastTimestamp) {
long timestamp = timeGen(); // 当前时间戳
while (timestamp <= lastTimestamp) { // 直到时间戳变为 lastTimestamp 时刻之后的时间戳
timestamp = timeGen();
}
return timestamp;
}
// 获取当前时间戳
protected long timeGen() {
return System.currentTimeMillis();
}
public long getWorkerId() {
return workerId;
}
}
| true
|
388c2a5d3353d8d7eca16f232fa5d878044294e3
|
Java
|
Raldoron/testOSMapp
|
/app/src/main/java/com/example/raldoron/testosmapp/Constants.java
|
UTF-8
| 1,094
| 1.835938
| 2
|
[] |
no_license
|
package com.example.raldoron.testosmapp;
/**
* Created by Raldoron on 02.11.15.
*/
public class Constants {
public static final String CONSUMER_KEY = "gQc05g3J3qtUpailrnGENr6jSJy3GK4c0rkIqkZ3";
public static final String CONSUMER_SECRET = "JxLDRMO5lW46jYQnovjIKZbi4JsqL9Ut5nw6VkNr";
public static final String REQUEST_URL = "https://www.openstreetmap.org/oauth/request_token";
public static final String ACCESS_URL = "https://www.openstreetmap.org/oauth/access_token";
public static final String AUTHORIZE_URL = "https://www.openstreetmap.org/oauth/authorize";
public static final String CALLBACK_SCHEME = "oauthscheme";
public static final String CALLBACK_URL = CALLBACK_SCHEME + "://callback";
public static final String OSM_SERVER_ADDRESS = "http://api06.dev.openstreetmap.org";
public static final String OSM_API_BASE_URL = OSM_SERVER_ADDRESS+"/api";
public static final String OSM_API_VERSION = "0.6";
public static final String OSM_CREATOR_INFO = "Raldoron testOSMapp";
public static final int RequestCode = 913;
public static final String TaginfoAPI_URI = "http://taginfo.openstreetmap.org/";
}
| true
|
365bf816a89b754a6e0564c4c549f4db6bacf8fb
|
Java
|
rak19852012/TestProject
|
/TestProject1/src/Abc.java
|
UTF-8
| 133
| 1.796875
| 2
|
[] |
no_license
|
import org.testng.annotations.Test;
public class Abc {
@Test
public void add()
{
System.out.println("add");
}
}
| true
|
a55cc40cfa14cbba483b49928d2ecea115b04068
|
Java
|
Messiah89/Pojazd-
|
/Pojazd.java
|
UTF-8
| 1,387
| 2.65625
| 3
|
[] |
no_license
|
package com.company;
class Pojazd {
int rokProdukcji;
String rodzajSilnika;
String kolor;
String masa;
void uruchomiSilnik() {
System.out.println("Silnik uruchomiono");
}
}
class Kołowe extends Pojazd {
String rozmiarOpony;
void uruchomiSilnik(String rodzajSilnika) {
}
}
class Ciężarówka extends Kołowe {
String udźwig;
void podnieśSkrzynie() {
}
}
class Osobowe extends Kołowe {
int ilośćOsób;
}
class Sedan extends Osobowe {
String model;
String symbol;
}
class Skoda extends Sedan {
{
class SuperB extends Skoda {
}
class Octawia extends Skoda {
}
}
class VW extends Sedan {
}
{
class Golf extends VW {
}
}
}
class Pickup extends Osobowe {
}
class Szynowe extends Pojazd {
void uruchomiSilnik() {
System.out.println("uruchomiono silnik pojazdu szynowego");
}
}
class Pociąg extends Szynowe {
static String Właściciel("P.K.P.");
}
class Gąsienicowe extends Pojazd {
String moc;
void uruchomiSilnik() {
super.uruchomiSilnik();
System.out.println("Jest to pojazd gąsienicowy");
}
}
class Czołg extends Gąsienicowe {
}
class Spychacz extends Gąsienicowe {
}
| true
|
5b43f82ecda05010dd5313813a6c1933f54c2e51
|
Java
|
katho/SpringMVCDemo
|
/MySpringWebApp/src/com/grupo4/controller/IndexController.java
|
UTF-8
| 1,169
| 2.015625
| 2
|
[] |
no_license
|
package com.grupo4.controller;
import javax.servlet.http.HttpSession;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.bind.support.SessionStatus;
import com.grupo4.pojo.Usuario;
@Controller
//@SessionAttributes({"resultado", "attrib1", "attrib2"})
@SessionAttributes("resultado")
public class IndexController
{
@RequestMapping("/")
public String showIndex(Model model)
{
model.addAttribute("resultado", "Atributo de Session");
return "index";
}
@RequestMapping("/about")
public String showAbout(/*SessionStatus status*/ Model model)
{
model.addAttribute("mensaje", "Atributo de about");
//status.setComplete();
return "about";
}
@RequestMapping("/admin")
public String showAdmin(Model model)
{
model.addAttribute("mensaje", "Hola desde admin");
model.addAttribute("resultado", "Atributo de Session");
return "admin";
}
}
| true
|
3db1c5616e5686fb222e5a0ce0e07eeb1883d982
|
Java
|
amokashi/sblXTRACT
|
/src/sblxtract/RunMain.java
|
UTF-8
| 329
| 1.820313
| 2
|
[] |
no_license
|
package sblxtract;
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author Emco1
*/
public class RunMain {
public static void main(String[] args) {
SBLXtractUI sblUI = new SBLXtractUI();
sblUI.setVisible(true);
}
}
| true
|
f5bd70ae0828b990bdd683d13f49eac6a3f53736
|
Java
|
dalalsunil1986/units-converter-200
|
/src/main/java/missioncollege/cis063/unitsconverter/AnglesConvert.java
|
UTF-8
| 2,804
| 2.59375
| 3
|
[] |
no_license
|
package missioncollege.cis063.unitsconverter;
import android.os.Bundle;
import android.app.Activity;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
public class AnglesConvert extends Activity {
Spinner anglesSpinner;
EditText anglesEdit;
TextView [] tvAngles = new TextView[2];
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.angles);
anglesSpinner = (Spinner) findViewById(R.id.spnAngles);
anglesEdit = (EditText) findViewById(R.id.editAngles);
tvAngles[0] = (TextView) findViewById(R.id.txtValueAngles0);
tvAngles[1] = (TextView) findViewById(R.id.txtValueAngles1);
anglesEdit.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
public void onTextChanged(CharSequence s, int start, int before, int count) {
update();
}
});
anglesSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
update();
}
@Override
public void onNothingSelected(AdapterView<?> parentView) {}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.angles_convert, menu);
return true;
}
public void update() {
int sigFig = 5; // significant figures displayed
if (anglesEdit.getText().toString().length() > 0) {
double value = Double.parseDouble(anglesEdit.getText().toString());
int fromUnits = anglesSpinner.getSelectedItemPosition();
for (int i = 0; i < tvAngles.length; i++) {
tvAngles[i].setText(String.valueOf(clipNumber(convert(value, fromUnits, i), sigFig)));
}
}
}
public double convert (double size, int fromUnits, int toUnits) {
// 0=degrees, 1=radians
final double[] conv = {1.0, 57.2957795};
return size * conv[fromUnits] / conv[toUnits];
}
public static double clipNumber(double num, int n) {
// num is the number; n is number of significant figures returned
if(num == 0)
return 0;
final double d = Math.ceil(Math.log10(num < 0 ? -num: num));
final int power = n - (int) d;
final double magnitude = Math.pow(10, power);
final long shifted = Math.round(num*magnitude);
return shifted/magnitude;
}
}
| true
|
1adaadcb7bd0122c270fff364083d2cec21be987
|
Java
|
fjwutong/WonderfulCollection
|
/ANDROID/WonderfulCollection/src/com/android/wonderfulcollection/UserInfo.java
|
UTF-8
| 1,904
| 2.4375
| 2
|
[] |
no_license
|
package com.android.wonderfulcollection;
public class UserInfo {
private String uid;//用户UID
private String screen_name;//用户昵称
private String name;//友好显示名称
private String location;//用户所在地
private String profile_image_url;//用户头像地址,50×50像素
private String gender;//性别,m:男、f:女、n:未知
private String avatar_large;//用户大头像地址
@Override
public String toString() {
return "UserInfo [uid=" + uid + ", screen_name=" + screen_name
+ ", name=" + name + ", location=" + location
+ ", profile_image_url=" + profile_image_url + ", gender="
+ gender + ", avatar_large=" + avatar_large + "]";
}
public UserInfo() {
}
public String getUid() {
return uid;
}
public void setUid(String uid) {
this.uid = uid;
}
public String getScreen_name() {
return screen_name;
}
public void setScreen_name(String screen_name) {
this.screen_name = screen_name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
public String getProfile_image_url() {
return profile_image_url;
}
public void setProfile_image_url(String profile_image_url) {
this.profile_image_url = profile_image_url;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getAvatar_large() {
return avatar_large;
}
public void setAvatar_large(String avatar_large) {
this.avatar_large = avatar_large;
}
}
| true
|
34bc81620a3468039f3038bc0bf6254080723eed
|
Java
|
erturkkadir/transform
|
/app/src/main/java/com/syshuman/kadir/transform/fft/FFT.java
|
UTF-8
| 1,562
| 2.671875
| 3
|
[
"Apache-2.0"
] |
permissive
|
package com.syshuman.kadir.transform.fft;
/**
* Created by kerturkx on 2017-10-19.
*/
public class FFT {
public FFT() {
}
public void fft_real(Complex c_data) {
final int n = c_data.d_real.length;
final double norm = Math.sqrt(1.0 / n);
for (int i = 0, j = 0; i < n; i++) {
if (j >= i) {
double tr = c_data.d_real[j] * norm;
c_data.d_real[j] = c_data.d_real[i] * norm;
c_data.d_imag[j] = 0.0;
c_data.d_real[i] = tr;
c_data.d_imag[i] = 0.0;
}
int m = n / 2;
while (m >= 1 && j >= m) {
j -= m;
m /= 2;
}
j += m;
}
for (int mmax = 1, istep = 2 * mmax; mmax < n; mmax = istep, istep = 2 * mmax) {
double delta = (Math.PI / mmax);
for (int m = 0; m < mmax; m++) {
double w = m * delta;
double wr = Math.cos(w);
double wi = Math.sin(w);
for (int i = m; i < n; i += istep) {
int j = i + mmax;
double tr = wr * c_data.d_real[j] - wi * c_data.d_imag[j];
double ti = wr * c_data.d_imag[j] + wi * c_data.d_real[j];
c_data.d_real[j] = c_data.d_real[i] - tr;
c_data.d_imag[j] = c_data.d_imag[i] - ti;
c_data.d_real[i] += tr;
c_data.d_imag[i] += ti;
}
}
}
}
}
| true
|
44467724b182eda1a1b500387f99c45d00375bd8
|
Java
|
heiyanbin/lintcode
|
/104_merge-k-sorted-lists/merge-k-sorted-lists.java
|
UTF-8
| 1,176
| 3.28125
| 3
|
[] |
no_license
|
/*
@Copyright:LintCode
@Author: heiyanbin
@Problem: http://www.lintcode.com/problem/merge-k-sorted-lists
@Language: Java
@Datetime: 14-12-29 06:01
*/
/**
* Definition for ListNode.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int val) {
* this.val = val;
* this.next = null;
* }
* }
*/
public class Solution {
/**
* @param lists: a list of ListNode
* @return: The head of one sorted list.
*/
public ListNode mergeKLists(List<ListNode> lists) {
PriorityQueue<ListNode> pq = new PriorityQueue<ListNode>(10,
new Comparator<ListNode>() {
public int compare(ListNode a, ListNode b) {
if (a == null) return -1;
if (b == null) return 1;
return a.val - b.val;
}
});
for ( ListNode e : lists) {
if (e != null) pq.offer(e);
}
ListNode dummy = new ListNode(-1);
for (ListNode prev = dummy; !pq.isEmpty(); ) {
prev.next = pq.poll();
prev = prev.next;
if (prev.next != null) pq.offer(prev.next);
}
return dummy.next;
}
}
| true
|
affd328a250805ccfac668ab5a533b3af5a873f9
|
Java
|
chandan2019/LogicalPrograms
|
/LogicalPrograms/src/com/array/slidingwindow/fixedsize/CountOccurencesOfAnagrams.java
|
UTF-8
| 1,193
| 3.703125
| 4
|
[] |
no_license
|
package com.array.slidingwindow.fixedsize;
import java.util.HashMap;
import java.util.Map;
public class CountOccurencesOfAnagrams {
public static void main(String[] args) {
String s = "aabaaebaa";
String pattern = "aaba";
int findOccurence = findOccurence(s, pattern);
System.out.println("findOccurence " + findOccurence);
}
public static int findOccurence(String s, String pattern) {
int i = 0, j=0;
Map<Character, Integer> map = new HashMap<>();
int count = 0;
int resultCount = 0;
int k = pattern.length();
while(j<pattern.length()) {
map.put(pattern.charAt(j), map.getOrDefault(pattern.charAt(j), 0) + 1);
count = map.size();
j++;
}
j = 0;
while(j<s.length()) {
map.put(s.charAt(j), map.getOrDefault(s.charAt(j), 0) - 1);
if(map.get(s.charAt(j)) == 0) {
count--;
}
if(j-i+1<k) {
j++;
}else if(j-i+1 == k) {
if(count == 0)//calculating the result
resultCount++;
map.put(s.charAt(i), map.getOrDefault(s.charAt(i), 0) + 1);
if(map.get(s.charAt(i)) == 1) {
count++;
}
j++;
i++;
}
}
return resultCount;
}
}
| true
|
8f93f0e80df49645b6ac3c47a402739e2174ad9b
|
Java
|
Karriem/cput.karriem.tp2
|
/Immutable_Domain_Model_Assignment/src/test/java/com/karriem/tp2/immutable_domain_model_assignment/DomainTest/EmployeesTest/MaintenanceStaffNGTest.java
|
UTF-8
| 1,987
| 2.265625
| 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 com.karriem.tp2.immutable_domain_model_assignment.DomainTest.EmployeesTest;
import com.karriem.tp2.immutable_domain_model_assignment.Config.EmployeesConfig.MaintenanceConfig;
import com.karriem.tp2.immutable_domain_model_assignment.Service.EmployeesService.MaintenanceService;
import org.junit.Assert;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import static org.testng.Assert.*;
import org.testng.annotations.AfterClass;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
/**
*
* @author karriem
*/
public class MaintenanceStaffNGTest {
private static ApplicationContext ctx;
private static MaintenanceService service;
public MaintenanceStaffNGTest() {
}
// TODO add test methods here.
// The methods must be annotated with annotation @Test. For example:
//
@Test
public void createMaintenance() {
Assert.assertEquals(service.createMain().get(0).getPostalAddress(), "544 hfhsdxb");
}
@Test
public void updateMaintenance(){
Assert.assertEquals(service.createNewMain().get(0).getPostalAddress(), "34 asdfjj");
}
@BeforeClass
public static void setUpClass() throws Exception {
ctx = new AnnotationConfigApplicationContext(MaintenanceConfig.class);
service = (MaintenanceService)ctx.getBean("main");
}
@AfterClass
public static void tearDownClass() throws Exception {
}
@BeforeMethod
public void setUpMethod() throws Exception {
}
@AfterMethod
public void tearDownMethod() throws Exception {
}
}
| true
|
a46981a11c38651e356c589e0068a699cba60437
|
Java
|
lipeng1223/BCCH
|
/src/main/java/com/bc/util/BellOrderItemTitleComparator.java
|
UTF-8
| 585
| 2.640625
| 3
|
[] |
no_license
|
package com.bc.util;
import java.util.Comparator;
import com.bc.orm.BellOrderItem;
public class BellOrderItemTitleComparator implements Comparator<BellOrderItem> {
@Override
public int compare(BellOrderItem o1, BellOrderItem o2) {
if (o1.getTitle() != null && o2.getTitle() != null){
return o1.getTitle().compareTo(o2.getTitle());
} else if (o1.getTitle() == null && o2.getTitle() != null){
return -1;
} else if (o2.getTitle() == null && o1.getTitle() != null){
return 1;
}
return 0;
}
}
| true
|
eb7b5e43a3f9e8a920427051c937d2ce77b44bdf
|
Java
|
PhilippToeglhofer/Morrowporo-3.0-with-Oracle-Database
|
/src/Model/Hearth.java
|
UTF-8
| 357
| 2.84375
| 3
|
[] |
no_license
|
package Model;
/**
* Created by Kata on 09.04.2018.
*/
public class Hearth {
private int hearths = 3;
public int getHearths(){
return hearths;
}
public void loose_aHearth(){
if (hearths > 0) { hearths--; }
}
public void get_aHearth(){
hearths++;
}
public void set3Hearths() { hearths = 3; }
}
| true
|