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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
d27b902a0b40b236391f702583a0a174e49a5625
|
Java
|
uralalanya/bpl-wfm-server
|
/wfm-query/src/main/java/com/bplsoft/wfm/model/UserModel.java
|
UTF-8
| 1,430
| 2.21875
| 2
|
[] |
no_license
|
package com.bplsoft.wfm.model;
import com.bplsoft.common.model.BaseModel;
import javax.persistence.*;
@Entity
@Table(name = "USER_MODEL")
public class UserModel extends BaseModel<Integer> {
@Id
@GeneratedValue(strategy = GenerationType.AUTO, generator = "UM_SEQ")
@SequenceGenerator(name = "UM_SEQ", sequenceName = "UM_SEQ", allocationSize = 1)
@Column(name = "UM_ID", updatable = false, nullable = false)
private Integer id;
private String username;
private String password;
private String site;
private String name;
private Integer age;
@Override
public Integer getId() {
return id;
}
@Override
public void setId(Integer id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getSite() {
return site;
}
public void setSite(String site) {
this.site = site;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
}
| true
|
b828e73bdc746ebab33b1519c62dc5a5513bb884
|
Java
|
mjschaub/chess-game
|
/src/board/GameFrame.java
|
UTF-8
| 3,936
| 3.1875
| 3
|
[] |
no_license
|
package board;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
/**
* @author mjschau2
* The creation of the GUI
*/
public class GameFrame extends JPanel
{
private static final long serialVersionUID = 1L;
private JFrame myFrame;
private JPanel myPanel;
private JButton tiles[][];
private GameLoop currGame;
public JLabel score;
private static int previousPlayerOneScore = 0;
private static int previousPlayerTwoScore = 0;
/**
* constructor for the GameFrame or GUI
*/
public GameFrame(final Board board)
{
super(new GridLayout(8,8));
currGame = new GameLoop();
setMyFrame(new JFrame("Chess game"));
myPanel = new JPanel();
tiles = new JButton[8][8];
getMyFrame().setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
getMyFrame().setResizable(false);
getMyFrame().setLayout(new BorderLayout());
getMyFrame().setPreferredSize(new Dimension(600, 700));
getMyFrame().setFocusable(true);
getMyFrame().pack();
JButton newBForfeit = new JButton("Game Options");
newBForfeit.setPreferredSize(new Dimension(60,60));
newBForfeit.setBackground(Color.white);
newBForfeit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("game should be forfeited");
currGame.forfeitOrRestart(e);
}
});
getMyFrame().add(newBForfeit,BorderLayout.BEFORE_FIRST_LINE);
getMyFrame().setVisible(true);
for(int x = 0; x < 8; x++)
{
for(int y = 0; y < 8; y++)
{
JButton newB = new JButton();
newB.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("piece was clicked");
currGame.mouseClicked(e);
}
});
newB.setPreferredSize(new Dimension(68,68));
if((x + y)%2 == 0)
newB.setBackground(Color.cyan);
else
newB.setBackground(Color.lightGray);
if(board.getPiece(x,y) != null)
{
newB.setIcon(new ImageIcon(getClass().getResource("image/"+board.getPiece(x, y).draw())));
}
tiles[x][y] = newB;
myPanel.add(tiles[x][y]);
}
}
getMyFrame().add(myPanel,BorderLayout.CENTER);
getMyFrame().setVisible(true);
score = new JLabel("Score - Player 1: "+getPreviousPlayerOneScore()+" Player 2: "+getPreviousPlayerTwoScore());
score.setFont(new Font("Serif", Font.PLAIN, 20));
getMyFrame().add(score,BorderLayout.PAGE_END);
getMyFrame().setVisible(true);
}
/**
* gets the button tiles
* @return the jbuttons
*/
public JButton[][] getTiles()
{
return this.tiles;
}
/**
* gets the jframe object
* @return the myFrame
*/
public JFrame getMyFrame()
{
return myFrame;
}
/**
* sets the classes jframe object
* @param myFrame the myFrame to set
*/
public void setMyFrame(JFrame myFrame)
{
this.myFrame = myFrame;
}
/**
* gets the first player's score
* @return the previousPlayerOneScore
*/
public static int getPreviousPlayerOneScore()
{
return previousPlayerOneScore;
}
/**
* sets the first player's score
* @param previousPlayerOneScore the previousPlayerOneScore to set
*/
public static void setPreviousPlayerOneScore(int previousPlayerOne)
{
previousPlayerOneScore = previousPlayerOne;
}
/**
* gets the second player's score
* @return the previousPlayerTwoScore
*/
public static int getPreviousPlayerTwoScore()
{
return previousPlayerTwoScore;
}
/**
* sets the second players score
* @param previousPlayerTwoScore the previousPlayerTwoScore to set
*/
public static void setPreviousPlayerTwoScore(int previousPlayerTwo)
{
previousPlayerTwoScore = previousPlayerTwo;
}
}
| true
|
3c0d8f25a6e4b61146fa63eac4a16c9316a93905
|
Java
|
zjnktion/json
|
/src/cn/zjnktion/json/model/JsonPrimary.java
|
UTF-8
| 425
| 2.296875
| 2
|
[] |
no_license
|
package cn.zjnktion.json.model;
/**
* @author zjnktion
*/
public class JsonPrimary implements Json, JsonValue {
private String value;
public JsonPrimary(String value) {
this.value = value;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
@Override
public Object value() {
return value;
}
}
| true
|
71625453b17ca9e585b0d41628fb65b26281a053
|
Java
|
4l3x4ndre/airforce
|
/app/src/main/java/com/example/alexandre/tabbedairforce/Constantes.java
|
UTF-8
| 363
| 1.507813
| 2
|
[] |
no_license
|
package com.example.alexandre.tabbedairforce;
public class Constantes {
// voir si tu utilises les constantes ici présentes ou si tu veux passer par les
// sharedPreferences au autre chose
// j'ai préféré les constantes, l'accès y est plus rapide
public static String alt;
public static String qnhS;
public static String TempS;
}
| true
|
9c49f9ade89ee9a85427836196704640d6571732
|
Java
|
bobbyfengb1124/RabbitMQ-Maven
|
/src/main/java/Constants.java
|
UTF-8
| 358
| 1.6875
| 2
|
[] |
no_license
|
class Constants {
static final String PASSWORD = "admin";
static final String USER_NAME = "admin";
static final String VIRTUAL_HOST = "/";
static final int PORT = 5672;
final static String EXCHANGE_NAME = "SIMPLE_EXCHANGE";
final static String QUEUE_NAME = "SIMPLE_QUEUE";
static final String BROKER_IP = "192.168.207.3";
}
| true
|
d34bc778e5a3fc515601efbc0a06cd56092c31d9
|
Java
|
garryInWeb/spring_wheel
|
/litespring/src/test/java/org/litespring/text/v7/ApplicationTestV7.java
|
UTF-8
| 834
| 1.945313
| 2
|
[] |
no_license
|
package org.litespring.text.v7;
import org.junit.Test;
import org.litespring.context.ApplicationContext;
import org.litespring.context.support.ClassPathXmlApplicationContext;
import org.litespring.service.v7.PetStoreService;
import javax.sql.DataSource;
import java.sql.SQLException;
/**
* Created by zhengtengfei on 2018/9/20.
*/
public class ApplicationTestV7 {
@Test
public void testGetBeanProperty() throws SQLException {
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("petstore-v7.xml");
applicationContext.getBean("dataSource");
PetStoreService iPetStoreService = (PetStoreService)applicationContext.getBean("petStore");
try {
iPetStoreService.placeOrder1();
} catch (Exception e) {
e.printStackTrace();
}
}
}
| true
|
1dc75a14c46cac249606761e6c3e2418b0015bfc
|
Java
|
naitik270/MyApp
|
/app/src/main/java/com/demo/nspl/restaurantlite/Navigation_Drawer/HomeFragment.java
|
UTF-8
| 1,608
| 2.125
| 2
|
[] |
no_license
|
package com.demo.nspl.restaurantlite.Navigation_Drawer;
import android.os.Bundle;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.demo.nspl.restaurantlite.ErrorLog.ErrorExceptionHandler;
import com.demo.nspl.restaurantlite.Global.ClsGlobal;
import com.demo.nspl.restaurantlite.R;
/**
* A simple {@link Fragment} subclass.
*/
public class HomeFragment extends Fragment {
public HomeFragment() {
// Required empty public constructor
}
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (!(Thread.getDefaultUncaughtExceptionHandler() instanceof ErrorExceptionHandler)) {
Thread.setDefaultUncaughtExceptionHandler(new ErrorExceptionHandler(
getContext(), "HomeFragment"));
}
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
getActivity().setTitle("Home");
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v= inflater.inflate(R.layout.fragment_home, container, false);
ClsGlobal.isFristFragment = true;
return v;
}
@Override
public void onDestroy() {
super.onDestroy();
ClsGlobal.isFristFragment = false;
}
}
| true
|
69ea384905318d3257f24550a0325f221e203745
|
Java
|
MusicAdam/Eugene
|
/eug-shared/src/com/gearworks/eug/shared/exceptions/EntityBuildException.java
|
UTF-8
| 213
| 1.96875
| 2
|
[] |
no_license
|
package com.gearworks.eug.shared.exceptions;
public class EntityBuildException extends Exception {
private static final long serialVersionUID = 1;
public EntityBuildException(String msg){
super(msg);
}
}
| true
|
23d1cb026f304ebfe54d7ba5c413beae4dee4cee
|
Java
|
zamedic/morse-sftpssh
|
/src/main/java/com/marcarndt/morse/command/commandlets/sftpfile/CompleteAddFile.java
|
UTF-8
| 1,235
| 2.375
| 2
|
[] |
no_license
|
package com.marcarndt.morse.command.commandlets.sftpfile;
import com.marcarndt.morse.MorseBot;
import com.marcarndt.morse.command.commandlet.Commandlet;
import com.marcarndt.morse.service.SSHService;
import com.marcarndt.morse.telegrambots.api.objects.Message;
import java.util.List;
import javax.ejb.Stateless;
import javax.inject.Inject;
/**
* Created by arndt on 2017/05/05.
*/
@Stateless
public class CompleteAddFile implements Commandlet {
@Inject
SSHService sshService;
@Override
public boolean canHandleCommand(Message message, String state) {
return state.equals(AddFileDetails.AddSftpFileDetailsState);
}
@Override
public void handleCommand(Message message, String state, List<String> parameters,
MorseBot morseBot) {
String description = parameters.get(0);
String path = message.getText();
sshService.addFile(description, path);
morseBot.sendMessage("Added file " + description + " with path " + path,
message.getChatId().toString());
}
@Override
public String getNewState(Message message, String command) {
return null;
}
@Override
public List<String> getNewStateParams(Message message, String state, List<String> parameters) {
return null;
}
}
| true
|
d43583df367c54ce310032d631b123a4e3a4d114
|
Java
|
1342190832/youbenben
|
/bizcore/WEB-INF/youbenben_core_src/com/youbenben/youbenben/payingoff/PayingOffManager.java
|
UTF-8
| 3,128
| 1.648438
| 2
|
[] |
no_license
|
package com.youbenben.youbenben.payingoff;
import java.math.BigDecimal;
import java.util.Date;
import java.util.Map;
import com.terapico.caf.DateTime;
import com.terapico.caf.Images;
import com.youbenben.youbenben.YoubenbenUserContext;
import com.youbenben.youbenben.BaseEntity;
import com.youbenben.youbenben.BaseManager;
import com.youbenben.youbenben.SmartList;
public interface PayingOffManager extends BaseManager{
public PayingOff createPayingOff(YoubenbenUserContext userContext, String who,String paidForId,Date paidTime,BigDecimal amount) throws Exception;
public PayingOff updatePayingOff(YoubenbenUserContext userContext,String payingOffId, int payingOffVersion, String property, String newValueExpr,String [] tokensExpr) throws Exception;
public PayingOff loadPayingOff(YoubenbenUserContext userContext, String payingOffId, String [] tokensExpr) throws Exception;
public PayingOff internalSavePayingOff(YoubenbenUserContext userContext, PayingOff payingOff) throws Exception;
public PayingOff internalSavePayingOff(YoubenbenUserContext userContext, PayingOff payingOff,Map<String,Object>option) throws Exception;
public PayingOff transferToAnotherPaidFor(YoubenbenUserContext userContext, String payingOffId, String anotherPaidForId) throws Exception;
public void delete(YoubenbenUserContext userContext, String payingOffId, int version) throws Exception;
public int deleteAll(YoubenbenUserContext userContext, String secureCode ) throws Exception;
public void onNewInstanceCreated(YoubenbenUserContext userContext, PayingOff newCreated)throws Exception;
/*======================================================DATA MAINTENANCE===========================================================*/
//public EmployeeSalarySheetManager getEmployeeSalarySheetManager(YoubenbenUserContext userContext, String payingOffId, String employeeId, String currentSalaryGradeId, BigDecimal baseSalary, BigDecimal bonus, BigDecimal reward, BigDecimal personalTax, BigDecimal socialSecurity, BigDecimal housingFound, BigDecimal jobInsurance ,String [] tokensExpr) throws Exception;
public PayingOff addEmployeeSalarySheet(YoubenbenUserContext userContext, String payingOffId, String employeeId, String currentSalaryGradeId, BigDecimal baseSalary, BigDecimal bonus, BigDecimal reward, BigDecimal personalTax, BigDecimal socialSecurity, BigDecimal housingFound, BigDecimal jobInsurance , String [] tokensExpr) throws Exception;
public PayingOff removeEmployeeSalarySheet(YoubenbenUserContext userContext, String payingOffId, String employeeSalarySheetId, int employeeSalarySheetVersion,String [] tokensExpr) throws Exception;
public PayingOff updateEmployeeSalarySheet(YoubenbenUserContext userContext, String payingOffId, String employeeSalarySheetId, int employeeSalarySheetVersion, String property, String newValueExpr,String [] tokensExpr) throws Exception;
/*
*/
public Object listByPaidFor(YoubenbenUserContext userContext,String paidForId) throws Exception;
public Object listPageByPaidFor(YoubenbenUserContext userContext,String paidForId, int start, int count) throws Exception;
}
| true
|
2a3e851f433c0180e08cef887674ee51dc31c8b9
|
Java
|
JorgeRebelo/iHouse
|
/src/org/academiadecodigo/enuminatti/ihouse/server/model/ReadWrite.java
|
UTF-8
| 1,124
| 2.625
| 3
|
[] |
no_license
|
package org.academiadecodigo.enuminatti.ihouse.server.model;
import java.io.*;
/**
* Created by codecadet on 14/11/17.
*/
public class ReadWrite {
public void write(String content, String filepath) {
FileWriter fileWriter;
try {
fileWriter = new FileWriter(filepath);
BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
bufferedWriter.write(content);
bufferedWriter.flush();
bufferedWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public String read(String content) {
FileReader reader = null;
try {
reader = new FileReader(content);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
BufferedReader bufferedReader = new BufferedReader(reader);
String result = null;
try {
result = bufferedReader.readLine();
bufferedReader.close();
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
}
| true
|
23cc2d91ad5c66f272353e6da4fbb25b2f64c0ad
|
Java
|
polinankoleva/BigDataQuerying
|
/exSheet3/PageRank/src/main/java/ex1c/FriendsOfUserRetrievalReducer.java
|
UTF-8
| 2,585
| 3.46875
| 3
|
[] |
no_license
|
package ex1c;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Reducer;
/**
* One reducer per each user. It formats all friends of an user in a list as
* (user1, user2, ....). The output is just a user mapped to a list of its
* friends. Besides, to one specific reducer, all users will be sent. It is
* responsible for counting their total number and send it to the driver class.
* This information is used in the next map/reduce phase.
*
* @author Polina Koleva
*
*/
public class FriendsOfUserRetrievalReducer extends
Reducer<Text, Text, Text, Text> {
// the key for the reducer where the counting of total number of users is
// done
private final String USER_COUNT_REDUCER_KEY = "userNodesCountReducer";
private Text usersCountReducerKey = new Text(USER_COUNT_REDUCER_KEY);
@Override
public void reduce(Text key, Iterable<Text> values, Context context)
throws IOException, InterruptedException {
// if the incoming key is the same as for the reducer where counting is
// done
if (key.equals(usersCountReducerKey)) {
// stores all distinct users in a list
ArrayList<String> distinctUsers = new ArrayList<String>();
Iterator<Text> iterator = values.iterator();
int usersCount = 0;
while (iterator.hasNext()) {
Text user = iterator.next();
// if an user is not in "our distinct users" list
// add it and increment the counter for total number of users
// otherwise - just continue to the next user
if (!distinctUsers.contains(user.toString())) {
distinctUsers.add(user.toString());
usersCount++;
}
}
// stores the total number of users in a counter
// driver, other mappers and reducers can read this value
context.getCounter(CustomCounters.USERS_COUNT).setValue(usersCount);
} else {
// just format all friends of an user - (user2, user3, user4,...)
String outputValue = formatOutputValue(values);
// set as key userId
context.write(key, new Text(outputValue));
}
}
// format data as the output pattern - (user1, user2, user3, ..)
public String formatOutputValue(Iterable<Text> values) {
StringBuilder sb = new StringBuilder();
sb.append("(");
Iterator<Text> iterator = values.iterator();
if (!iterator.hasNext()) {
return null;
}
while (iterator.hasNext()) {
Text next = iterator.next();
if (!iterator.hasNext()) {
sb.append(next.toString());
} else {
sb.append(next.toString() + ", ");
}
}
sb.append(")");
return sb.toString();
}
}
| true
|
14bd260ee2a51e9814cd14aee7cfd8283bf36cf7
|
Java
|
richardrodgers/mds
|
/webapi/src/main/java/org/dspace/webapi/content/ContentResource.java
|
UTF-8
| 19,512
| 2.015625
| 2
|
[
"MIT"
] |
permissive
|
/**
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* http://www.dspace.org/license/
*/
package org.dspace.webapi.content;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Produces;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.ResponseBuilder;
import javax.ws.rs.core.UriBuilder;
import javax.ws.rs.core.UriInfo;
import static javax.ws.rs.core.MediaType.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.dspace.authorize.AuthorizeException;
import org.dspace.webapi.EntityRef;
import org.dspace.webapi.Injectable;
import org.dspace.webapi.content.domain.ContentEntity;
import org.dspace.webapi.content.domain.MetadataEntity;
import org.dspace.webapi.content.domain.SiteEntity;
import org.dspace.webapi.content.domain.ViewEntity;
/**
* ContentResource is a JAX-RS root resource providing a RESTful API for DSpaceObjects.
* Service interface provides basic CRUD operations.
*
* @author richardrodgers
*/
@Path("content")
@Produces({APPLICATION_XML, APPLICATION_JSON})
public class ContentResource {
private static Logger log = LoggerFactory.getLogger(ContentResource.class);
private final ContentDao contentDao = new ContentDao();
@Context UriInfo uriInfo;
// create the site
@POST @Path("/")
@Consumes({APPLICATION_XML, APPLICATION_JSON})
public Response createSite(EntityRef entityRef) {
SiteEntity entity = null;
try {
entity = contentDao.createSiteEntity(entityRef);
} catch (AuthorizeException authE) {
throw new WebApplicationException(Response.Status.UNAUTHORIZED);
} catch (IOException | SQLException sqlE) {
throw new WebApplicationException(Response.Status.INTERNAL_SERVER_ERROR);
}
inject(entity);
return Response.created(entity.getURI()).build();
}
// get the entity for the site
@GET @Path("site")
public SiteEntity getSite() {
SiteEntity entity = null;
try {
entity = contentDao.getSiteEntity();
} catch (SQLException sqlE) {
throw new WebApplicationException(Response.Status.INTERNAL_SERVER_ERROR);
} catch (IllegalArgumentException iaE) {
throw new WebApplicationException(Response.Status.NOT_FOUND);
}
// Inject URIs into this entity
inject(entity);
return entity;
}
// remove the site data (not the site contents)
@DELETE @Path("site")
public Response removeSite() {
try {
contentDao.removeSite();
return Response.noContent().build();
} catch (AuthorizeException authE) {
throw new WebApplicationException(Response.Status.UNAUTHORIZED);
} catch (IllegalArgumentException iaE) {
throw new WebApplicationException(Response.Status.NOT_FOUND);
} catch (IOException | SQLException sqlE) {
throw new WebApplicationException(Response.Status.INTERNAL_SERVER_ERROR);
}
}
// get a site entity communities sub-resource list this seems wrong
@GET @Path("site/communities")
public List<EntityRef> getSiteCommunitiesList() {
return getSiteRefList("communities", null);
}
// get a site entity sub-resource list
@GET @Path("site/{subres}")
public List<EntityRef> getSiteResourceList(@PathParam("subres") String subres) {
return getSiteRefList(subres, null);
}
// create a new root in the content hierarchy - i.e a top-level community
@POST @Path("site/communities")
@Consumes({APPLICATION_XML, APPLICATION_JSON})
public Response createRoot(EntityRef entityRef) {
ContentEntity entity = null;
try {
entity = contentDao.createEntity(null, null, null, entityRef);
} catch (AuthorizeException authE) {
throw new WebApplicationException(Response.Status.UNAUTHORIZED);
} catch (IOException | SQLException sqlE) {
throw new WebApplicationException(Response.Status.INTERNAL_SERVER_ERROR);
}
// Inject URIs into this entity
inject(entity);
return Response.created(entity.getURI()).build();
}
// gets the site logo media object
@GET @Path("site/logo")
public Response getSiteLogoMedia() {
try {
MediaReader reader = contentDao.getMediaReader(null, null);
return Response.ok(reader.getStream()).type(reader.getMimeType()).build();
} catch (IllegalArgumentException iaE) {
throw new WebApplicationException(Response.Status.NOT_FOUND);
} catch (IOException | SQLException exp) {
throw new WebApplicationException(Response.Status.INTERNAL_SERVER_ERROR);
} catch (AuthorizeException authE) {
throw new WebApplicationException(Response.Status.UNAUTHORIZED);
}
}
// update the site logo
@PUT @Path("site/logo")
public Response updateSiteLogo(InputStream in) {
try {
contentDao.updateLogo(null, null, in);
} catch (AuthorizeException authE) {
throw new WebApplicationException(Response.Status.UNAUTHORIZED);
} catch (IOException | SQLException sqlE) {
throw new WebApplicationException(Response.Status.INTERNAL_SERVER_ERROR);
} catch (IllegalArgumentException iaE) {
throw new WebApplicationException(Response.Status.NOT_FOUND);
}
return Response.ok().build();
}
// create a new subresource in the site e.g. a top-level community from a package
@POST @Path("site/package/{name}")
@Consumes("application/zip")
public Response rootfromPackage(
@PathParam("name") String name,
InputStream in) {
ContentEntity entity = null;
try {
entity = contentDao.entityFromPackage(null, null, name, in);
} catch (AuthorizeException authE) {
throw new WebApplicationException(Response.Status.UNAUTHORIZED);
} catch (IllegalArgumentException iaE) {
throw new WebApplicationException(Response.Status.NOT_FOUND);
} catch (IOException | SQLException sqlE) {
throw new WebApplicationException(Response.Status.INTERNAL_SERVER_ERROR);
}
inject(entity);
return Response.created(entity.getURI()).build();
}
// get a site entity metadata set
@GET @Path("site/mdset/{name}")
public ContentEntity getSiteMetadataSet(@PathParam("name") String name) {
MetadataEntity mdEntity = null;
try {
mdEntity = contentDao.getMetadataSet(null, null, name);
} catch (SQLException sqlE) {
log.error("SQL exception: " + sqlE.getMessage());
sqlE.printStackTrace();
throw new WebApplicationException(Response.Status.INTERNAL_SERVER_ERROR);
} catch (IllegalArgumentException iaE) {
throw new WebApplicationException(Response.Status.NOT_FOUND);
}
// Inject URIs into this entity
inject(mdEntity);
return mdEntity;
}
// get a site entity metadata view
@GET @Path("site/mdview/{name}")
public ContentEntity getSiteMetadataView(@PathParam("name") String name) {
ViewEntity mdEntity = null;
try {
mdEntity = contentDao.getMetadataView(null, null, name);
} catch (SQLException sqlE) {
throw new WebApplicationException(Response.Status.INTERNAL_SERVER_ERROR);
} catch (IllegalArgumentException iaE) {
throw new WebApplicationException(Response.Status.NOT_FOUND);
}
// Inject URIs into this entity
inject(mdEntity);
return mdEntity;
}
// update a site entity metadata set
@PUT @Path("site/mdset/{name}")
@Consumes({APPLICATION_XML, APPLICATION_JSON})
public ContentEntity updateSiteMetadata(
@PathParam("name") String name,
MetadataEntity updEntity) {
MetadataEntity mdEntity = null;
try {
mdEntity = contentDao.updateMetadata(null, null, name, updEntity);
} catch (AuthorizeException authE) {
throw new WebApplicationException(Response.Status.UNAUTHORIZED);
} catch (SQLException sqlE) {
throw new WebApplicationException(Response.Status.INTERNAL_SERVER_ERROR);
} catch (IllegalArgumentException iaE) {
throw new WebApplicationException(Response.Status.NOT_FOUND);
}
// Inject URIs into this entity
inject(mdEntity);
return mdEntity;
}
// get a content entity (community, collection, item, bitstream)
@GET @Path("{prefix}/{id}")
public ContentEntity getContent(
@PathParam("prefix") String prefix,
@PathParam("id") String id) {
ContentEntity entity = null;
try {
entity = contentDao.getEntity(prefix, id);
} catch (SQLException sqlE) {
throw new WebApplicationException(Response.Status.INTERNAL_SERVER_ERROR);
} catch (IllegalArgumentException iaE) {
throw new WebApplicationException(Response.Status.NOT_FOUND);
}
// Inject URIs into this entity
inject(entity);
return entity;
}
// remove a content entity
@DELETE @Path("{prefix}/{id}")
public Response removeContent(
@PathParam("prefix") String prefix,
@PathParam("id") String id) {
try {
contentDao.removeEntity(prefix, id);
return Response.noContent().build();
} catch (AuthorizeException authE) {
throw new WebApplicationException(Response.Status.UNAUTHORIZED);
} catch (IllegalArgumentException iaE) {
throw new WebApplicationException(Response.Status.NOT_FOUND);
} catch (IOException | SQLException sqlE) {
throw new WebApplicationException(Response.Status.INTERNAL_SERVER_ERROR);
}
}
// get an entity sub-resource list
@GET @Path("{prefix}/{id}/{subres}")
public List<EntityRef> getResourceList(
@PathParam("prefix") String prefix,
@PathParam("id") String id,
@PathParam("subres") String subres) {
return getRefList(prefix + "/" + id, subres, null);
}
// create an entity sub-resource
@POST @Path("{prefix}/{id}/{subres}")
@Consumes({APPLICATION_XML, APPLICATION_JSON})
public Response createContent(
@PathParam("prefix") String prefix,
@PathParam("id") String id,
@PathParam("subres") String subres,
EntityRef entityRef) {
ContentEntity entity = null;
try {
entity = contentDao.createEntity(prefix, id, subres, entityRef);
} catch (AuthorizeException authE) {
throw new WebApplicationException(Response.Status.UNAUTHORIZED);
} catch (IllegalArgumentException iaE) {
throw new WebApplicationException(Response.Status.NOT_FOUND);
} catch (IOException | SQLException sqlE) {
throw new WebApplicationException(Response.Status.INTERNAL_SERVER_ERROR);
}
inject(entity);
return Response.created(entity.getURI()).build();
}
// update the content entity's logo
@PUT @Path("{prefix}/{id}/logo")
public Response updateLogo(
@PathParam("prefix") String prefix,
@PathParam("id") String id,
InputStream in) {
try {
contentDao.updateLogo(prefix, id, in);
} catch (AuthorizeException authE) {
throw new WebApplicationException(Response.Status.UNAUTHORIZED);
} catch (IOException | SQLException sqlE) {
throw new WebApplicationException(Response.Status.INTERNAL_SERVER_ERROR);
} catch (IllegalArgumentException iaE) {
throw new WebApplicationException(Response.Status.NOT_FOUND);
}
return Response.ok().build();
}
// get an item's filtered bitstreams
@GET @Path("{prefix}/{id}/filter/{name}")
public List<EntityRef> getItemBitstreams(
@PathParam("prefix") String prefix,
@PathParam("id") String id,
@PathParam("name") String name) {
return getRefList(prefix + "/" + id, "bitstream", name);
}
// get an entity metadata set
@GET @Path("{prefix}/{id}/mdset/{name}")
public ContentEntity getMetadataSet(
@PathParam("prefix") String prefix,
@PathParam("id") String id,
@PathParam("name") String name) {
MetadataEntity mdEntity = null;
try {
mdEntity = contentDao.getMetadataSet(prefix, id, name);
} catch (SQLException sqlE) {
log.error("SQL exception: " + sqlE.getMessage());
sqlE.printStackTrace();
throw new WebApplicationException(Response.Status.INTERNAL_SERVER_ERROR);
} catch (IllegalArgumentException iaE) {
throw new WebApplicationException(Response.Status.NOT_FOUND);
}
// Inject URIs into this entity
inject(mdEntity);
return mdEntity;
}
// get an entity metadata view
@GET @Path("{prefix}/{id}/mdview/{name}")
public ContentEntity getMetadataView(
@PathParam("prefix") String prefix,
@PathParam("id") String id,
@PathParam("name") String name) {
ViewEntity mdEntity = null;
try {
mdEntity = contentDao.getMetadataView(prefix, id, name);
} catch (SQLException sqlE) {
throw new WebApplicationException(Response.Status.INTERNAL_SERVER_ERROR);
} catch (IllegalArgumentException iaE) {
throw new WebApplicationException(Response.Status.NOT_FOUND);
}
// Inject URIs into this entity
inject(mdEntity);
return mdEntity;
}
// update an entity metadata set
@PUT @Path("{prefix}/{id}/mdset/{name}")
@Consumes({APPLICATION_XML, APPLICATION_JSON})
public ContentEntity updateMetadata(
@PathParam("prefix") String prefix,
@PathParam("id") String id,
@PathParam("name") String name,
MetadataEntity updEntity) {
MetadataEntity mdEntity = null;
try {
mdEntity = contentDao.updateMetadata(prefix, id, name, updEntity);
} catch (AuthorizeException authE) {
throw new WebApplicationException(Response.Status.UNAUTHORIZED);
} catch (SQLException sqlE) {
throw new WebApplicationException(Response.Status.INTERNAL_SERVER_ERROR);
} catch (IllegalArgumentException iaE) {
throw new WebApplicationException(Response.Status.NOT_FOUND);
}
// Inject URIs into this entity
inject(mdEntity);
return mdEntity;
}
// get an entity media object (= the bitstream bytes)
@GET @Path("{prefix}/{id}/media/{name}")
public Response getMedia(
@PathParam("prefix") String prefix,
@PathParam("id") String id) {
try {
MediaReader reader = contentDao.getMediaReader(prefix, id);
return Response.ok(reader.getStream()).type(reader.getMimeType()).build();
} catch (IllegalArgumentException iaE) {
throw new WebApplicationException(Response.Status.NOT_FOUND);
} catch (IOException | SQLException exp) {
throw new WebApplicationException(Response.Status.INTERNAL_SERVER_ERROR);
} catch (AuthorizeException authE) {
throw new WebApplicationException(Response.Status.UNAUTHORIZED);
}
}
// get an entity package object
@GET @Path("{prefix}/{id}/package/{name}")
public Response getPackage(
@PathParam("prefix") String prefix,
@PathParam("id") String id,
@PathParam("name") String name) {
try {
PackageReader reader = contentDao.getPackageReader(prefix, id, name);
return Response.ok(reader.getStream()).type(reader.getMimeType()).build();
} catch (IllegalArgumentException iaE) {
throw new WebApplicationException(Response.Status.NOT_FOUND);
} catch (IOException | SQLException exp) {
log.error("SQL exception: " + exp.getMessage());
exp.printStackTrace();
throw new WebApplicationException(Response.Status.INTERNAL_SERVER_ERROR);
} catch (AuthorizeException authE) {
log.error("Auth exception: " + authE.getMessage());
authE.printStackTrace();
throw new WebApplicationException(Response.Status.UNAUTHORIZED);
}
}
// create an entity from a packaged representation (SIP)
@POST @Path("{prefix}/{id}/package/{name}")
@Consumes("application/zip")
public Response contentFromPackage(
@PathParam("prefix") String prefix,
@PathParam("id") String id,
@PathParam("name") String name,
InputStream in) {
ContentEntity entity = null;
try {
entity = contentDao.entityFromPackage(prefix, id, name, in);
} catch (AuthorizeException authE) {
throw new WebApplicationException(Response.Status.UNAUTHORIZED);
} catch (IllegalArgumentException iaE) {
throw new WebApplicationException(Response.Status.NOT_FOUND);
} catch (IOException | SQLException sqlE) {
throw new WebApplicationException(Response.Status.INTERNAL_SERVER_ERROR);
}
inject(entity);
return Response.created(entity.getURI()).build();
}
private void inject(Injectable injectable) {
Map<String, String> sites = injectable.getUriInjections();
for (String key : sites.keySet()) {
UriBuilder ub = uriInfo.getBaseUriBuilder();
ub = ub.path("content");
for (String part: sites.get(key).split(":")) {
ub = ub.path(part);
}
injectable.injectUri(key, ub.build());
}
}
private List<EntityRef> getRefList(String handle, String refType, String filter) {
List<EntityRef> refList = null;
try {
refList = contentDao.getContentReferences(handle, refType, filter);
} catch (SQLException sqlE) {
throw new WebApplicationException(Response.Status.INTERNAL_SERVER_ERROR);
}
// inject URIs for each reference
for (EntityRef ref : refList) {
inject(ref);
}
return refList;
}
private List<EntityRef> getSiteRefList(String refType, String filter) {
List<EntityRef> refList = null;
try {
refList = contentDao.getSiteReferences(refType, filter);
} catch (SQLException sqlE) {
throw new WebApplicationException(Response.Status.INTERNAL_SERVER_ERROR);
}
// inject URIs for each reference
for (EntityRef ref : refList) {
inject(ref);
}
return refList;
}
}
| true
|
37f24e6a07113ba4feb382c1b9ee14d70e4c0fdf
|
Java
|
Nick-Brooks21/UserBBQMenu
|
/src/controller/addItemServlet.java
|
UTF-8
| 1,256
| 2.390625
| 2
|
[] |
no_license
|
package controller;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import model.FoodList;
/**
* Servlet implementation class addItemServlet
*/
@WebServlet("/addItemServlet")
public class addItemServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public addItemServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
String type = request.getParameter("type");
String newQuantity = request.getParameter("quantity");
int quantity = Integer.parseInt(newQuantity);
FoodList fl = new FoodList(type, quantity);
BBQMenuHelper bmh = new BBQMenuHelper();
bmh.insertItem(fl);
getServletContext().getRequestDispatcher("/index.html").forward(request, response);
}
}
| true
|
9017ce35b66c8b1415ad35e2a29fbee8501685bd
|
Java
|
keyking-coin/code
|
/other/src/com/joymeng/slg/net/handler/impl/OpenBagHandler.java
|
UTF-8
| 1,346
| 2.046875
| 2
|
[] |
no_license
|
package com.joymeng.slg.net.handler.impl;
import com.joymeng.common.util.MessageSendUtil;
import com.joymeng.log.NewLogManager;
import com.joymeng.services.core.buffer.JoyBuffer;
import com.joymeng.services.core.message.JoyNormalMessage.UserInfo;
import com.joymeng.services.core.message.JoyProtocol;
import com.joymeng.slg.domain.object.bag.RoleBagAgent;
import com.joymeng.slg.domain.object.role.Role;
import com.joymeng.slg.net.ParametersEntity;
import com.joymeng.slg.net.handler.ServiceHandler;
import com.joymeng.slg.net.mod.RespModuleSet;
import com.joymeng.slg.net.resp.CommunicateResp;
public class OpenBagHandler extends ServiceHandler{
@Override
public void _deserialize(JoyBuffer in,ParametersEntity params) {
}
@Override
public JoyProtocol handle(UserInfo info,ParametersEntity params) throws Exception{
CommunicateResp resp = newResp(info);
Role role = world.getRole(info.getUid());
if (role == null){
NewLogManager.misTakeLog("OpenBagHandler getRole is null");
resp.fail();
return resp;
}
RoleBagAgent bagAgent = role.getBagAgent();
if(bagAgent == null){
NewLogManager.misTakeLog("OpenBagHandler getRoleBagAgent is null");
resp.fail();
return resp;
}
RespModuleSet rms = new RespModuleSet();
bagAgent.sendBagToClient(rms);
MessageSendUtil.sendModule(rms,info);
return resp;
}
}
| true
|
55d133f78f9847f45af2ef8b8b4d3189c9c337f1
|
Java
|
TulipSxL/toolbox
|
/src/main/java/cn/sxl/toolbox/repository/HsHeroRepository.java
|
UTF-8
| 477
| 2.046875
| 2
|
[
"MIT"
] |
permissive
|
package cn.sxl.toolbox.repository;
import cn.sxl.toolbox.entity.HsHero;
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.List;
/**
* @author SxL
* @since 1.7.0
* 2020-01-09 15:07
*/
public interface HsHeroRepository extends JpaRepository<HsHero, Integer> {
/**
* 获取所有在线或下线的英雄
* @param state 是否在线 1为在线
* @return 英雄列表
*/
List<HsHero> getAllByState(boolean state);
}
| true
|
07de9a29dadd9bab1b6bfa46d448e87838b00a09
|
Java
|
alexeyglazov/kronos
|
/src/java/com/mazars/management/reports/InvoicingProcessReport.java
|
UTF-8
| 13,753
| 1.773438
| 2
|
[] |
no_license
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.mazars.management.reports;
import com.mazars.management.db.comparators.CurrencyComparator;
import com.mazars.management.db.domain.Client;
import com.mazars.management.db.domain.Country;
import com.mazars.management.db.domain.CountryCurrency;
import com.mazars.management.db.domain.Currency;
import com.mazars.management.db.domain.Employee;
import com.mazars.management.db.domain.FeesAdvance;
import com.mazars.management.db.domain.FeesInvoice;
import com.mazars.management.db.domain.FeesItem;
import com.mazars.management.db.domain.FeesPayment;
import com.mazars.management.db.domain.Group;
import com.mazars.management.db.domain.Module;
import com.mazars.management.db.domain.ProjectCode;
import com.mazars.management.db.domain.Subdepartment;
import com.mazars.management.db.util.HibernateUtil;
import com.mazars.management.db.util.ProjectCodeListUtil;
import com.mazars.management.db.vo.YearMonthDate;
import com.mazars.management.web.forms.InvoiceRequestsFilter;
import com.mazars.management.web.forms.InvoicingProcessReportForm;
import com.mazars.management.web.forms.ProjectCodeListLimiter;
import com.mazars.management.web.forms.ProjectCodeListSorter;
import java.util.Collections;
import java.util.Date;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import org.hibernate.Query;
import org.hibernate.Session;
/**
*
* @author glazov
*/
public class InvoicingProcessReport {
public class ProjectCodeBlock {
private Group group;
private Client client;
private ProjectCode projectCode;
private FeesItem feesItem;
private List<FeesAdvance> feesAdvances = new LinkedList<FeesAdvance>();
private List<FeesInvoice> feesInvoices = new LinkedList<FeesInvoice>();
private List<FeesPayment> feesPayments = new LinkedList<FeesPayment>();
public FeesItem getFeesItem() {
return feesItem;
}
public void setFeesItem(FeesItem feesItem) {
this.feesItem = feesItem;
}
public Group getGroup() {
return group;
}
public void setGroup(Group group) {
this.group = group;
}
public List<FeesAdvance> getFeesAdvances() {
return feesAdvances;
}
public void setFeesAdvances(List<FeesAdvance> feesAdvances) {
this.feesAdvances = feesAdvances;
}
public List<FeesInvoice> getFeesInvoices() {
return feesInvoices;
}
public void setFeesInvoices(List<FeesInvoice> feesInvoices) {
this.feesInvoices = feesInvoices;
}
public List<FeesPayment> getFeesPayments() {
return feesPayments;
}
public void setFeesPayments(List<FeesPayment> feesPayments) {
this.feesPayments = feesPayments;
}
public Client getClient() {
return client;
}
public void setClient(Client client) {
this.client = client;
}
public ProjectCode getProjectCode() {
return projectCode;
}
public void setProjectCode(ProjectCode projectCode) {
this.projectCode = projectCode;
}
}
private List<ProjectCodeBlock> projectCodeBlocks = new LinkedList<ProjectCodeBlock>();
private Set<FeesItem> feesItems = new HashSet<FeesItem>();
private Employee currentUser;
private Module module;
private InvoicingProcessReportForm form;
private YearMonthDate formStartDate;
private YearMonthDate formEndDate;
private InvoicingProcessReportForm.DocumentType formDocumentTypeToSearch;
private InvoicingProcessReportForm.DocumentType formDocumentTypeToShow;
private InvoicingProcessReportForm.View formView;
private Date createdAt;
private List<Currency> currencies = new LinkedList<Currency>();
private Currency mainCurrency;
public List<ProjectCodeBlock> getProjectCodeBlocks() {
return projectCodeBlocks;
}
public void setProjectCodeBlocks(List<ProjectCodeBlock> projectCodeBlocks) {
this.projectCodeBlocks = projectCodeBlocks;
}
public Employee getCurrentUser() {
return currentUser;
}
public void setCurrentUser(Employee currentUser) {
this.currentUser = currentUser;
}
public Module getModule() {
return module;
}
public void setModule(Module module) {
this.module = module;
}
public InvoicingProcessReportForm getForm() {
return form;
}
public void setForm(InvoicingProcessReportForm form) {
this.form = form;
}
public YearMonthDate getFormStartDate() {
return formStartDate;
}
public void setFormStartDate(YearMonthDate formStartDate) {
this.formStartDate = formStartDate;
}
public YearMonthDate getFormEndDate() {
return formEndDate;
}
public void setFormEndDate(YearMonthDate formEndDate) {
this.formEndDate = formEndDate;
}
public InvoicingProcessReportForm.DocumentType getFormDocumentTypeToSearch() {
return formDocumentTypeToSearch;
}
public void setFormDocumentTypeToSearch(InvoicingProcessReportForm.DocumentType formDocumentTypeToSearch) {
this.formDocumentTypeToSearch = formDocumentTypeToSearch;
}
public InvoicingProcessReportForm.DocumentType getFormDocumentTypeToShow() {
return formDocumentTypeToShow;
}
public void setFormDocumentTypeToShow(InvoicingProcessReportForm.DocumentType formDocumentTypeToShow) {
this.formDocumentTypeToShow = formDocumentTypeToShow;
}
public InvoicingProcessReportForm.View getFormView() {
return formView;
}
public void setFormView(InvoicingProcessReportForm.View formView) {
this.formView = formView;
}
public Date getCreatedAt() {
return createdAt;
}
public void setCreatedAt(Date createdAt) {
this.createdAt = createdAt;
}
public List<Currency> getCurrencies() {
return currencies;
}
public void setCurrencies(List<Currency> currencies) {
this.currencies = currencies;
}
public Currency getMainCurrency() {
return mainCurrency;
}
public void setMainCurrency(Currency mainCurrency) {
this.mainCurrency = mainCurrency;
}
public InvoicingProcessReport (InvoicingProcessReportForm form, Module module, Employee currentUser) {
this.form = form;
this.module = module;
this.currentUser = currentUser;
Session hs = HibernateUtil.getSessionFactory().getCurrentSession();
Country country = currentUser.getCountry();
currencies.addAll(CountryCurrency.getCurrencies(country));
Collections.sort(currencies, new CurrencyComparator());
mainCurrency = CountryCurrency.getMainCurrency(country);
this.formStartDate = form.getStartDate();
this.formEndDate = form.getEndDate();
this.formDocumentTypeToSearch = form.getDocumentTypeToSearch();
this.formDocumentTypeToShow = form.getDocumentTypeToShow();
this.formView = form.getView();
}
public void build() {
buildFeesItemReport();
if(! projectCodeBlocks.isEmpty()) {
buildFeesAdvanceReport();
buildFeesInvoiceReport();
buildFeesPaymentReport();
}
this.createdAt = new Date();
}
private void buildFeesItemReport() {
List<ProjectCode> projectCodes = new LinkedList<ProjectCode>();
InvoiceRequestsFilter invoiceRequestsFilter = new InvoiceRequestsFilter();
ProjectCodeListSorter sorter = new ProjectCodeListSorter();
ProjectCodeListLimiter limiter = new ProjectCodeListLimiter();
List<Subdepartment> allowedSubdepartments = Subdepartment.getAllowedSubdepartments(null, null, null, currentUser, module);
projectCodes = ProjectCodeListUtil.getProjectCodeFilteredList(this.form.getProjectCodeListFilter(), invoiceRequestsFilter, sorter, limiter, allowedSubdepartments);
if(projectCodes.isEmpty()) {
return;
}
Session hs = HibernateUtil.getSessionFactory().getCurrentSession();
String query = "select g, c, pc, fi from ProjectCode as pc ";
query += "inner join pc.client as c ";
query += "inner join pc.feesItem as fi ";
query += "left join c.group as g ";
if(this.form.getStartDate() != null && this.form.getEndDate() != null) {
query += "left join fi.feesAdvances as fa ";
query += "left join fi.feesInvoices as fin ";
query += "left join fi.feesPayments as fp ";
}
query += "where pc in (:projectCodes) ";
if(this.form.getStartDate() != null && this.form.getEndDate() != null) {
if(InvoicingProcessReportForm.DocumentType.ALL.equals(this.form.getDocumentTypeToSearch())) {
query += "and ( ";
query += "(fa.date>=:startDate and fa.date<=:endDate) ";
query += "or (fin.date>=:startDate and fin.date<=:endDate) ";
query += "or (fp.date>=:startDate and fp.date<=:endDate) ";
query += ") ";
} else if(InvoicingProcessReportForm.DocumentType.INVOICE_TO_ISSUE.equals(this.form.getDocumentTypeToSearch())) {
query += "and (fa.date>=:startDate and fa.date<=:endDate) ";
} else if(InvoicingProcessReportForm.DocumentType.INVOICE_ISSUED.equals(this.form.getDocumentTypeToSearch())) {
query += "and (fin.date>=:startDate and fin.date<=:endDate) ";
} else if(InvoicingProcessReportForm.DocumentType.PAYMENT.equals(this.form.getDocumentTypeToSearch())) {
query += "and (fp.date>=:startDate and fp.date<=:endDate) ";
}
}
query += "group by pc ";
Query hq = hs.createQuery(query);
hq.setParameterList("projectCodes", projectCodes);
if(this.form.getStartDate() != null && this.form.getEndDate() != null) {
hq.setParameter("startDate", this.getForm().getStartDate().getCalendar());
hq.setParameter("endDate", this.getForm().getEndDate().getCalendar());
}
List<Object[]> selection = (List<Object[]>)hq.list();
for(Object[] tuple : selection) {
Group group = (Group)tuple[0];
Client client = (Client)tuple[1];
ProjectCode projectCode = (ProjectCode)tuple[2];
FeesItem feesItem = (FeesItem)tuple[3];
this.feesItems.add(feesItem);
ProjectCodeBlock projectCodeBlock = new ProjectCodeBlock();
projectCodeBlock.setClient(client);
projectCodeBlock.setGroup(group);
projectCodeBlock.setProjectCode(projectCode);
projectCodeBlock.setFeesItem(feesItem);
this.projectCodeBlocks.add(projectCodeBlock);
}
}
private void buildFeesAdvanceReport() {
Session hs = HibernateUtil.getSessionFactory().getCurrentSession();
String query = "select fi, fa from FeesItem as fi inner join fi.feesAdvances as fa ";
query += "where fi in (:feesItems) ";
Query hq = hs.createQuery(query);
hq.setParameterList("feesItems", this.feesItems);
List<Object[]> selection = (List<Object[]>)hq.list();
for(Object[] tuple : selection) {
FeesItem feesItem = (FeesItem)tuple[0];
FeesAdvance feesAdvance = (FeesAdvance)tuple[1];
ProjectCodeBlock projectCodeBlock = getProjectCodeBlock(feesItem);
projectCodeBlock.getFeesAdvances().add(feesAdvance);
}
}
private void buildFeesInvoiceReport() {
Session hs = HibernateUtil.getSessionFactory().getCurrentSession();
String query = "select fi, fin from FeesItem as fi inner join fi.feesInvoices as fin ";
query += "where fi in (:feesItems) ";
Query hq = hs.createQuery(query);
hq.setParameterList("feesItems", this.feesItems);
List<Object[]> selection = (List<Object[]>)hq.list();
for(Object[] tuple : selection) {
FeesItem feesItem = (FeesItem)tuple[0];
FeesInvoice feesInvoice = (FeesInvoice)tuple[1];
ProjectCodeBlock projectCodeBlock = getProjectCodeBlock(feesItem);
projectCodeBlock.getFeesInvoices().add(feesInvoice);
}
}
private void buildFeesPaymentReport() {
Session hs = HibernateUtil.getSessionFactory().getCurrentSession();
String query = "select fi, fp from FeesItem as fi inner join fi.feesPayments as fp ";
query += "where fi in (:feesItems) ";
Query hq = hs.createQuery(query);
hq.setParameterList("feesItems", this.feesItems);
List<Object[]> selection = (List<Object[]>)hq.list();
for(Object[] tuple : selection) {
FeesItem feesItem = (FeesItem)tuple[0];
FeesPayment feesPayment = (FeesPayment)tuple[1];
ProjectCodeBlock projectCodeBlock = getProjectCodeBlock(feesItem);
projectCodeBlock.getFeesPayments().add(feesPayment);
}
}
private ProjectCodeBlock getProjectCodeBlock(FeesItem feesItem) {
for(ProjectCodeBlock projectCodeBlock : this.projectCodeBlocks) {
if(projectCodeBlock.getFeesItem().equals(feesItem)) {
return projectCodeBlock;
}
}
return null;
}
}
| true
|
4df09b1043735d40a20dc811cef895518abaedb9
|
Java
|
yahier/ExSt
|
/app/src/main/java/yahier/exst/adapter/DongtaiAddBusinessCardAdapter.java
|
UTF-8
| 4,418
| 2.1875
| 2
|
[] |
no_license
|
package yahier.exst.adapter;
import android.content.Context;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.stbl.stbl.R;
import com.stbl.stbl.common.CommonAdapter;
import com.stbl.stbl.common.MyApplication;
import com.stbl.stbl.item.UserItem;
import com.stbl.stbl.util.ImageUtils;
import com.stbl.stbl.util.PicassoUtil;
import java.util.ArrayList;
import java.util.List;
public class DongtaiAddBusinessCardAdapter extends CommonAdapter {
Context mContext;
List<UserItem> list;
public DongtaiAddBusinessCardAdapter(Context mContext) {
this.mContext = mContext;
list = new ArrayList<UserItem>();
}
public void setData(List<UserItem> list) {
this.list = list;
notifyDataSetChanged();
}
public void addData(List<UserItem> list) {
this.list.addAll(list);
notifyDataSetChanged();
}
@Override
public int getCount() {
return list.size();
}
class Holder {
ImageView img;
TextView name, signature;
View btnAdd;
public TextView mAgeTv;
public TextView mLocationTv;
public ImageView ivGender;//性别
}
@Override
public View getView(final int i, View con, ViewGroup parent) {
Holder ho = null;
if (con == null) {
ho = new Holder();
con = LayoutInflater.from(mContext).inflate(R.layout.dongtai_add_business_card_item, null);
ho.img = (ImageView) con.findViewById(R.id.imgUser);
ho.name = (TextView) con.findViewById(R.id.name);
// ho.userGenderAge = (TextView) con.findViewById(R.id.user_gender_age);
// ho.city = (TextView) con.findViewById(R.id.user_city);
ho.signature = (TextView) con.findViewById(R.id.user_signature);
ho.btnAdd = (View) con.findViewById(R.id.btnAdd);
ho.mAgeTv = (TextView) con.findViewById(R.id.tv_age);
ho.mLocationTv = (TextView) con
.findViewById(R.id.tv_location);
ho.ivGender = (ImageView) con.findViewById(R.id.iv_gender);
con.setTag(ho);
} else
ho = (Holder) con.getTag();
final UserItem user = list.get(i);
//PicassoUtil.load(mContext, user.getImgmiddleurl(), ho.img);
ImageUtils.loadHead(user.getImgmiddleurl(), ho.img);
// ho.name.setText(user.getNickname());
ho.name.setText(user.getAlias() == null || user.getAlias().equals("") ? user.getNickname() : user.getAlias());
if (user.getSignature() == null || user.getSignature().equals("")) {
ho.signature.setVisibility(View.INVISIBLE);
} else {
ho.signature.setVisibility(View.VISIBLE);
ho.signature.setText(mContext.getString(R.string.signature) + ":" + user.getSignature());
}
if (user.getAge() == 0) {
ho.mAgeTv.setVisibility(View.GONE);
} else {
ho.mAgeTv.setVisibility(View.VISIBLE);
ho.mAgeTv.setText(String.format(MyApplication.getContext().getString(R.string.im_age), user.getAge()));
}
ho.ivGender.setVisibility(View.VISIBLE);
if (user.getGender() == UserItem.gender_boy) {
ho.ivGender.setImageResource(R.drawable.icon_male);
} else if (user.getGender() == UserItem.gender_girl) {
ho.ivGender.setImageResource(R.drawable.icon_female);
} else {
ho.ivGender.setVisibility(View.GONE);
}
if (TextUtils.isEmpty(user.getCityname())) {
ho.mLocationTv.setVisibility(View.GONE);
} else {
ho.mLocationTv.setVisibility(View.VISIBLE);
ho.mLocationTv.setText(user.getCityname());
}
ho.btnAdd.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
adapterListener.onChoosedFinish(user);
}
});
return con;
}
OnAdapterListener adapterListener;
public void setOnAdapterListener(OnAdapterListener adapterListener) {
this.adapterListener = adapterListener;
}
public interface OnAdapterListener {
void onChoosedFinish(UserItem user);
}
}
| true
|
50504b42b5bd4d3846acb6a746129757b12cc52e
|
Java
|
RimasTr/sprouts
|
/src/uk/ac/ed/inf/sprouts/bruteforcers/ImprovedMoveBruteforcer.java
|
UTF-8
| 5,223
| 2.875
| 3
|
[] |
no_license
|
package uk.ac.ed.inf.sprouts.bruteforcers;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Random;
import java.util.Set;
import uk.ac.ed.inf.sprouts.external.AllMovesGenerator;
import uk.ac.ed.inf.sprouts.external.Game;
import uk.ac.ed.inf.sprouts.external.Move;
import uk.ac.ed.inf.sprouts.internal.ChildrenGenerator;
import uk.ac.ed.inf.sprouts.internal.InternalPosition;
import uk.ac.ed.inf.sprouts.utils.Output;
/**
* An old implementation of the brute-force search. Not used anymore.
*
* @author Rimas
*/
public class ImprovedMoveBruteforcer implements MoveBruteforcer {
private Game game;
private Move winningMove;
private HashMap<String, Move> possiblePositions;
private HashMap<String, Boolean> alreadyComputedPositions;
public ImprovedMoveBruteforcer(Game game) {
this.game = game;
}
public void compute() {
alreadyComputedPositions = new HashMap<String, Boolean>();
possiblePositions = getPossiblePositions(game);
Output.debug("Possible moves: " + possiblePositions.size());
for (String position : possiblePositions.keySet()) {
Output.debug("Checking " + possiblePositions.get(position).toNotation());
if (!isWin(position)) {
winningMove = possiblePositions.get(position);
Output.debug("Different positions: " + alreadyComputedPositions.size());
return;
}
}
Output.debug("Different positions: " + alreadyComputedPositions.size());
//Output.debug(alreadyComputedPositions.toString());
}
public boolean hasWinningMove() {
return winningMove != null;
}
public Move getWinningMove() {
return winningMove;
}
public Move getRandomMove() {
if (game.isOver()) {
return null;
}
Random random = new Random();
List<String> keys = new ArrayList<String>(possiblePositions.keySet());
String randomKey = keys.get(random.nextInt(keys.size()));
return possiblePositions.get(randomKey);
}
private boolean isWin(String currentPosition) {
//Output.debug("Calculating " + currentPosition);
if (currentPosition.length() <= 1) {
return false;
}
if (alreadyComputedPositions.containsKey(currentPosition)) {
return alreadyComputedPositions.get(currentPosition);
}
Set<String> possiblePositions = getPossibleInternalPositions(currentPosition);
// TODO: remove, debug
for (String position : possiblePositions) {
if (!isWin(position)) {
if (!checkIfMatches(currentPosition, true)) {
Output.debug("Wins by going to " + position);
}
alreadyComputedPositions.put(currentPosition, true);
//Output.debug(currentPosition + "\ttrue");
return true;
}
}
if (!checkIfMatches(currentPosition, false)) {
// Output.debug("All distinct moves: ");
// for (String position : possiblePositions.keySet()) {
// Output.debug(possiblePositions.get(position).getMove().toNotation());
}
// Output.debug("All moves: ");
// getPossiblePositions(game, true);
// }
//Output.debug(currentPosition + "\tfalse");
alreadyComputedPositions.put(currentPosition, false);
return false;
}
private boolean checkIfMatches(String position, boolean expectedValue) {
// if (!position.equals(pos)) {
// return true;
// }
if (alreadyComputedPositions.containsKey(position)) {
// Output.debug("-- Get: " + alreadyComputedPositions.get(position));
if (alreadyComputedPositions.get(position) != expectedValue) {
Output.debug("----------------- Doesn't match: " + position);
Output.debug("Should have been: " + expectedValue);
Output.debug("Position: ");
Output.debug("" + game.getPosition());
Output.debug("Moves history:");
for (Move intMove : game.getMovesHistory()) {
Output.debug(intMove.toNotation());
}
return false;
}
return true;
} else {
// Output.debug("Adding " + expectedValue);
//
// Output.debug("Position: ");
// Output.debug(game.getPosition());
// Output.debug("Moves history:");
// for (Move intMove : game.getMovesHistory()) {
// Output.debug(intMove.toNotation());
// }
return true;
}
}
private Set<String> getPossibleInternalPositions(String position) {
return new ChildrenGenerator(InternalPosition.fromString(position))
.generateAllChildrenStrings();
}
private HashMap<String, Move> getPossiblePositions(Game game) {
AllMovesGenerator allMovesGenerator = new AllMovesGenerator();
Set<Move> moves = allMovesGenerator.generateAllMoves(game.getPosition());
HashMap<String, Move> possiblePositions = new HashMap<String, Move>();
for (Move move : moves) {
Game clone = game.deepClone();
clone.makeMove(move);
InternalPosition internalPosition = InternalPosition.fromExternal(clone.getPosition());
String internalPositionString = internalPosition.toString();
possiblePositions.put(internalPositionString, move);
}
return possiblePositions;
}
public HashMap<String, Boolean> getComputedPositions() {
return alreadyComputedPositions;
}
}
| true
|
c323dac1b99ba5ca67317e689f78f280ded7e727
|
Java
|
xwtflydream/spring
|
/netty-demo/monitor-manger/src/main/java/com/zykx/monitor/manager/controller/ServerMonitorLogController.java
|
UTF-8
| 1,113
| 1.953125
| 2
|
[] |
no_license
|
package com.zykx.monitor.manager.controller;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zykx.monitor.manager.entity.ServerInfo;
import com.zykx.monitor.manager.entity.ServerMonitorLog;
import com.zykx.monitor.manager.service.ServerInfoService;
import com.zykx.monitor.manager.service.ServerMonitorLogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
/**
* 服务状态监控记录Controller类
*/
@RestController
@RequestMapping("/server_status_log")
public class ServerMonitorLogController {
@Autowired
ServerMonitorLogService serverMonitorLogService;
@GetMapping("/page/{current}/{size}")
public Page<ServerMonitorLog> page(@PathVariable("current") int current, @PathVariable("size") int size) {
return serverMonitorLogService.page(current, size);
}
@PostMapping("/batch_insert")
public int batchInsert(@RequestBody List<ServerMonitorLog> logList) throws Exception {
return serverMonitorLogService.batchInsert(logList);
}
}
| true
|
02e53a8921f2178796e78f0dbc4b2d8c948509b8
|
Java
|
smartatone/smartatone-study
|
/smartatone-practice/smartatone-practice-spring/src/main/java/com/smartatone/BeanFactoryPostProcessPractice/v2_complicateProperty/test4/MyConsumerBean.java
|
UTF-8
| 634
| 2.28125
| 2
|
[] |
no_license
|
package com.smartatone.BeanFactoryPostProcessPractice.v2_complicateProperty.test4;
import java.util.Properties;
import org.springframework.beans.factory.InitializingBean;
import com.smartatone.BeanFactoryPostProcessPractice.v2_complicateProperty.ConsumerBean;
public class MyConsumerBean extends ConsumerBean implements InitializingBean {
@Override
public void afterPropertiesSet() {
Properties defaultProperties = new Properties();
defaultProperties.put("name", "new java");
Properties newDefaultProperties = new Properties(defaultProperties);
setProperties(newDefaultProperties);
}
}
| true
|
a9b7c2c6c00e781b267a090ab1a81da580554784
|
Java
|
nevella/alcina
|
/framework/entity/src/cc/alcina/framework/entity/MetricLoggingBase.java
|
UTF-8
| 4,994
| 1.890625
| 2
|
[] |
no_license
|
/*
* 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 cc.alcina.framework.entity;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import cc.alcina.framework.common.client.logic.reflection.ClearStaticFieldsOnAppShutdown;
import cc.alcina.framework.common.client.logic.reflection.Registration;
import cc.alcina.framework.common.client.util.Ax;
import cc.alcina.framework.common.client.util.CommonUtils;
/**
* @author Nick Reddel
*/
@Registration(ClearStaticFieldsOnAppShutdown.class)
public class MetricLoggingBase {
final static Logger logger = LoggerFactory.getLogger(MetricLogging.class);
private Map<String, Long> metricStart;
private Map<String, Long> metricStartThreadIds;
private Map<String, Long> ticksSum;
private Map<String, Long> ticks;
private Map<String, Long> sum;
private Map<String, Long> averageCount;
private Long thisLoggerThreadId = null;
private Set<String> terminated;
private Map<String, String> keyToKeyWithParents;
private boolean muted = false;
protected MetricLoggingBase() {
}
public void average(String key) {
if (averageCount.containsKey(key)) {
String message = Ax.format("Metric: %s avg %sms", key,
sum.get(key) / averageCount.get(key));
System.out.println(message);
}
}
public long end(String key) {
return end(key, "");
}
public long end(String key, Logger logger) {
return end(key, null, logger);
}
public long end(String key, String extraInfo) {
return end(key, extraInfo, null);
}
public void endTicks(String key) {
long cn = System.nanoTime();
key = keyWithParents(key, false);
if (!ticksSum.containsKey(key)) {
ticksSum.put(key, 0L);
}
if (!ticks.containsKey(key)) {
ticks.put(key, cn);
}
ticksSum.put(key, ticksSum.get(key) + (cn - ticks.get(key)));
}
public boolean isMuted() {
return muted;
}
public synchronized void reset() {
if (isMuted()) {
System.out.println("Unmuting muted metric thread");
Thread.dumpStack();
}
setMuted(false);
metricStart = new LinkedHashMap<String, Long>();
metricStartThreadIds = new LinkedHashMap<String, Long>();
sum = new HashMap<String, Long>();
averageCount = new HashMap<String, Long>();
keyToKeyWithParents = new HashMap<String, String>();
ticks = new HashMap<String, Long>();
ticksSum = new HashMap<String, Long>();
terminated = new HashSet<String>();
}
public void setMuted(boolean muted) {
this.muted = muted;
}
public synchronized void setStart(String key, long time) {
key = keyWithParents(key, false);
metricStart.put(key, time);
metricStartThreadIds.put(key, getCurrentThreadId());
}
public synchronized void start(String key) {
setStart(key, System.currentTimeMillis());
}
public void startTicks(String key) {
key = keyWithParents(key, false);
ticks.put(key, System.nanoTime());
}
private synchronized long end(String key, String extraInfo,
Logger overrideLogger) {
key = keyWithParents(key, true);
if (!metricStart.containsKey(key) && !ticksSum.containsKey(key)) {
System.out.println("Warning - metric end without start - " + key);
return -1;
}
long delta = ticksSum.containsKey(key) ? ticksSum.get(key) / 1000000
: System.currentTimeMillis() - metricStart.get(key);
ticksSum.remove(key);
String units = "ms";
String message = Ax.format("Metric: %s - %s %s%s", key, delta, units,
CommonUtils.isNullOrEmpty(extraInfo) ? "" : " - " + extraInfo);
if (!muted) {
Logger out = overrideLogger == null ? logger : overrideLogger;
out.debug(message);
}
if (!averageCount.containsKey(key)) {
averageCount.put(key, 0L);
sum.put(key, 0L);
}
averageCount.put(key, averageCount.get(key) + 1);
sum.put(key, sum.get(key) + delta);
terminated.add(key);
return delta;
}
private Long getCurrentThreadId() {
return Thread.currentThread().getId();
}
private synchronized String keyWithParents(String key, boolean end) {
if (end) {
return keyToKeyWithParents.get(key);
}
String withParents = "";
for (String parentKey : metricStart.keySet()) {
Long tid = metricStartThreadIds.get(parentKey);
if (!terminated.contains(parentKey)
&& (tid.equals(thisLoggerThreadId)
|| tid.equals(getCurrentThreadId()))) {
withParents = parentKey + "/";
}
}
withParents += key;
keyToKeyWithParents.put(key, withParents);
return withParents;
}
}
| true
|
0915eaf5b149ed8e96d497089a235e4bdfd62787
|
Java
|
hectorroberto/treinamentos
|
/JavaSE/src/marcosBrizeno/chainofrespon/BancoC.java
|
UTF-8
| 332
| 2.546875
| 3
|
[] |
no_license
|
package marcosBrizeno.chainofrespon;
public class BancoC extends BancoChain {
public BancoC() {
super(IDBancos.bancoC);
}
@Override
protected void efetuaPagamento() {
System.out.println("Pagamento efetuado no banco C");
}
@Override
protected void quemSou() {
System.out.println("Sou Banco C");
}
}
| true
|
4dacb2c486ee864b9b512dc06c95faa529e189f0
|
Java
|
chldbwjd70/jobadream
|
/jobadream/src/main/java/edu/kh/job/chat/websocket/ChatWebSocketHandler.java
|
UTF-8
| 4,321
| 2.5625
| 3
|
[] |
no_license
|
package edu.kh.job.chat.websocket;
import java.text.SimpleDateFormat;
import java.util.Collections;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import edu.kh.job.chat.model.service.ChatService;
import edu.kh.job.chat.model.vo.ChatMessage;
import edu.kh.job.member.model.vo.Member;
public class ChatWebSocketHandler extends TextWebSocketHandler {
@Autowired
private ChatService service;
private Set<WebSocketSession> sessions
= Collections.synchronizedSet(new HashSet<WebSocketSession>());
@Override
public void afterConnectionEstablished(WebSocketSession session) throws Exception {
sessions.add(session);
}
// 클라이언트로 부터 텍스트를 받았을 때 실행되는 메소드
@Override
protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
// 매개변수 WebSocketSession session : "보내기" 버튼을 누른 사람의 SockJS가 넘어옴
// 매개변수 TextMessage message : JSON으로 변환된 문자열이 담겨있다.
// 전달 받은 내용 확인
// System.out.println("전달 받은 내용 : " + message.getPayload());
// JSON 형태의 문자열을 JsonObject로 변경하여 값을 꺼내쓸 수 있는 형태로 변환
JsonObject convertedObj = new Gson().fromJson(message.getPayload(), JsonObject.class);
System.out.println(convertedObj);
// 변경된 JsonObject에서 값 추출
// JsonObject.get("key") -> (Object)value 반환
String memberName = convertedObj.get("memberName").toString();
String chat = convertedObj.get("chat").toString();
memberName = memberName.substring(1, memberName.length()-1);
chat = chat.substring(1, chat.length()-1);
//System.out.println("채팅 입력자 : " + memberName);
//System.out.println("채팅 내용 : " + chat);
// 채팅 내용 DB 삽입 구문
// 메세지를 보낸 사람의 채팅방 번호
int chatRoomNo = Integer.parseInt(convertedObj.get("chatRoomNo").toString().replaceAll("\"", ""));
// 회원 번호를 얻어오는 방법
// 1) WebSocketSession -> Session -> loginMember -> memberNo
// 2) convertedObj에 있는 memberNo 사용
int memberNo = Integer.parseInt(convertedObj.get("memberNo").toString().replaceAll("\"", ""));
// CHAT_MESSAGE 테이블에 삽입하려는 내용을 하나의 VO에 담기
ChatMessage cm = new ChatMessage();
cm.setMemberNo(memberNo);
cm.setChatRoomNo(chatRoomNo);
cm.setMessage(chat);
// 채팅 메세지를 DB에 삽입하는 Service 호출
int result = service.insertMessage(cm);
convertedObj.remove("chat");
System.out.println("cm.getMessage() : "+ cm.getMessage());
convertedObj.addProperty("chat", cm.getMessage());
if(result > 0) {
// 채팅이 이루어진 시간을 만들어서 convertedObj에 추가
SimpleDateFormat sdf = new SimpleDateFormat("yyyy년 MM월 dd일 HH:mm:ss");
convertedObj.addProperty("createDate", sdf.format(new Date()));
// 필드에 있는 sessions에는 현재 채팅방에 들어온 모든 회원의 Session이 담겨있다.
// -> 여기서 채팅방 번호가 일치하는 회원한테만 메세지를 전달
for(WebSocketSession s : sessions) {
// 각 회원이 가지고 있는 session 값 중 "chatRoomNo"를 얻어오기
int joinChatRoomNo = ((Integer)s.getAttributes().get("chatRoomNo"));
// 채팅방 페이지에 접속한 회원의 방번호와
// 메세지를 보낸사람의 방번호가 같을 경우 == 같은 채팅방
if(chatRoomNo == joinChatRoomNo) {
// 서버 -> 클라이언트로 웹 소켓을 이용해 메세지 전달
s.sendMessage( new TextMessage( new Gson().toJson(convertedObj) ));
}
}
}
}
// 클라이언트 - 서버간 연결이 종료될 때 실행되는 메소드
@Override
public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
sessions.remove(session);
}
}
| true
|
1718e8d8462310b8c51f68f42ee77814c9794235
|
Java
|
sanrinconr/learningSpring
|
/5- POO/src/com/bankAccount/CuentaCorriente.java
|
UTF-8
| 1,359
| 3.171875
| 3
|
[] |
no_license
|
package com.bankAccount;
public class CuentaCorriente {
private String nombre;
private String numero;
private double saldo;
public CuentaCorriente(CuentaCorriente cuenta){
this.nombre = cuenta.nombre;
this.numero = cuenta.numero;
this.saldo = cuenta.saldo;
}
public CuentaCorriente(String nombre, String numero){
this.nombre = nombre;
this.numero = numero;
}
public void ingreso(double value){
this.saldo += value;
}
public void egreso(double value){
this.saldo -= value;
}
public void reingreso(double value){
egreso(value);
}
public void transferencia(double value, CuentaCorriente cuentaDestino) throws Exception {
if(this.saldo - value < 0){
throw new Exception("No hay saldo para la transferencia :)");
}
this.saldo -= value;
cuentaDestino.ingreso(value);
}
public String getNombre() {
return nombre;
}
public void setNombre(String nombre) {
this.nombre = nombre;
}
public String getNumero() {
return numero;
}
public void setNumero(String numero) {
this.numero = numero;
}
public double getSaldo() {
return saldo;
}
public void setSaldo(double saldo) {
this.saldo = saldo;
}
}
| true
|
3da091d9228a5148dfa3e503dc564b494c402c6b
|
Java
|
hhzhang333/OpenStack-shen
|
/src/main/java/cn/edu/seu/openstack/dao/WholeCpuLoadDao.java
|
UTF-8
| 230
| 1.625
| 2
|
[] |
no_license
|
package cn.edu.seu.openstack.dao;
import cn.edu.seu.openstack.domain.WholeCpuLoad;
import java.util.List;
/**
* Created by a on 2018/3/7.
*/
public interface WholeCpuLoadDao {
public List<WholeCpuLoad> selectCpuLoad();
}
| true
|
9000f53af19a0edb78a9820b783614d72c670300
|
Java
|
joey-yoonsung/spring-boot-web-dev
|
/ch02/src/main/java/filter/FilterEx.java
|
UTF-8
| 951
| 2.34375
| 2
|
[] |
no_license
|
package filter;
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.annotation.WebFilter;
@WebFilter("*.jsp")
public class FilterEx implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
System.out.println(filterConfig);
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
util.HtmlBuilder
builder = new util.HtmlBuilder(response.getWriter()).startHtml().writeHead("before print\n");
chain.doFilter(request, response);
builder.writeBody("\nafter print").endHtml();
}
@Override
public void destroy() {
}
}
| true
|
6754eb26724bad06217fe960623450e1c89350c2
|
Java
|
joubamatrix/maxasin-app
|
/maxasin-domain/src/main/java/com/project/maxasin/client/Ventes.java
|
UTF-8
| 1,559
| 2.234375
| 2
|
[] |
no_license
|
package com.project.maxasin.client;
import java.util.Date;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
@Entity
public class Ventes {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long codeVentes;
private double montant;
private Date dateVentes;
private int quantite;
private String nomProduit;
@ManyToOne
@JoinColumn(name = "CODE_CL")
private Client client;
public int getQuantite() {
return quantite;
}
public void setQuantite(int quantite) {
this.quantite = quantite;
}
public Long getCodeVentes() {
return codeVentes;
}
public void setCodeVentes(Long codeVentes) {
this.codeVentes = codeVentes;
}
public double getMontant() {
return montant;
}
public void setMontant(double montant) {
this.montant = montant;
}
public Date getDateVentes() {
return dateVentes;
}
public void setDateVentes(Date dateVentes) {
this.dateVentes = dateVentes;
}
public String getNomProduit() {
return nomProduit;
}
public void setNomProduit(String nomProduit) {
this.nomProduit = nomProduit;
}
public Client getClient() {
return client;
}
public void setClient(Client client) {
this.client = client;
}
public Ventes(Long codeVentes, double montant, Date dateVentes) {
super();
this.codeVentes = codeVentes;
this.montant = montant;
this.dateVentes = dateVentes;
}
public Ventes() {
super();
}
}
| true
|
0c697029669fe677cb4130dd36591d4c53adce88
|
Java
|
ignoumania/MTBS
|
/src/main/java/com/mtbs/reservation/BlockedSeatRepository.java
|
UTF-8
| 428
| 1.914063
| 2
|
[
"MIT"
] |
permissive
|
package com.mtbs.reservation;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import com.mtbs.models.BlockedSeat;
public interface BlockedSeatRepository extends CrudRepository<BlockedSeat, Integer> {
int countByUserId(int userId);
@Query(nativeQuery = true, value = "select mtbs.remove_timedout_records()")
void releaseTimedoutBlockedSeats();
}
| true
|
d050efd852582dc743ac67ee93c4b3ce7b52e286
|
Java
|
Explorer1092/biubiubiu
|
/framwork/WeTest/target/test-classes/com/weibo/global/JsonCommon.java
|
UTF-8
| 3,826
| 2.359375
| 2
|
[] |
no_license
|
package com.weibo.global;
import java.io.IOException;
import java.util.Map;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonParser.Feature;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
//import com.alibaba.fastjson.JSON;
public class JsonCommon {
// jackSon 反序列化 java对象
public static Object getJavabean(String jsonString, Class classes)
throws JsonParseException, JsonMappingException, IOException {
if (jsonString == null || jsonString.equals("") || classes == null)
return null;
ObjectMapper mapper = new ObjectMapper();
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES,
false);
mapper.configure(Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);
// System.out.println("---------------------------"+classes.getName());
Object myObject = mapper.readValue(jsonString, classes);
return myObject;
}
/** @author yanlei3
* write for the JSONobject with unset key
*/
public static Map<String, Object> getMap(String jsonString)
throws JsonParseException, JsonMappingException, IOException {
if (jsonString == null || jsonString.equals(""))
return null;
ObjectMapper mapper = new ObjectMapper();
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES,
false);
mapper.configure(Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);
// System.out.println("---------------------------"+classes.getName());
Map<String,Object> myMap = mapper.readValue(jsonString, Map.class);
return myMap;
}
@JsonIgnore
public static Object[] getJavabeans(String jsonString, Class classes)
throws JsonParseException, JsonMappingException, IOException {
if (jsonString == null || jsonString.equals("") || classes == null)
return null;
ObjectMapper mapper = new ObjectMapper();
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES,
false);
mapper.configure(Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);
Object[] myObject = (Object[]) mapper.readValue(jsonString, classes);
return myObject;
}
////使用fastjson 反序列为java 对象
// @SuppressWarnings("unchecked")
// public static Object getJavabean(String jsonString, @SuppressWarnings("rawtypes") Class classes) {
// if (jsonString == null || jsonString.equals("") || classes == null)
// return null;
//// ObjectMapper mapper = new ObjectMapper();
//// mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES,
//// false);
//// mapper.configure(Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);
//// // System.out.println("---------------------------"+classes.getName());
//// Object myObject = mapper.readValue(jsonString, classes);
//// return myObject;
// Object myObject = JSON.parseObject(jsonString, classes);
// return myObject;
// }
//
// @SuppressWarnings("unchecked")
// @JsonIgnore
// public static Object[] getJavabeans(String jsonString, @SuppressWarnings("rawtypes") Class classes) {
// if (jsonString == null || jsonString.equals("") || classes == null)
// return null;
//// ObjectMapper mapper = new ObjectMapper();
//// mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES,
//// false);
//// mapper.configure(Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);
// Object[] myObject = (Object[]) JSON.parseObject(jsonString, classes);
// return myObject;
// }
public static String writeEntity2Json(Object object) throws IOException {
String jsonResult = null;
ObjectMapper objectMapper = new ObjectMapper();
jsonResult = objectMapper.writeValueAsString(object);
return jsonResult;
}
}
| true
|
33bac9ce1bacb0faecef601a2a2b925486d0fc74
|
Java
|
WanderingSeed/Common-Library
|
/src/com/morgan/library/widget/dialog/HeightPickerWidget.java
|
UTF-8
| 3,157
| 2.421875
| 2
|
[
"Apache-2.0"
] |
permissive
|
package com.morgan.library.widget.dialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.widget.NumberPicker;
import android.widget.NumberPicker.OnValueChangeListener;
import android.widget.TextView;
import com.morgan.library.R;
import com.morgan.library.utils.StrUtils;
/**
* 一个身高选取器。
*
* @author Morgan.Ji
*
*/
public class HeightPickerWidget extends Dialog {
private NumberPicker mPicker;
private TextView mTitleTextView, mFinishBtn;
private static final int FIRST_HEIGHT = 140;
private static final int START_HEIGHT = 160;
private static final int LAST_HEIGHT = 200;
public static final String UNIT = "cm";
private android.view.View.OnClickListener mOnFinishClickListener;
private boolean mShowValueOnTitle = true;
private String mTitle;
private int mCurrentValue;
public HeightPickerWidget(Context context) {
super(context, R.style.picker_dialog);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.number_picker_dialog);
mPicker = (NumberPicker) findViewById(R.id.numberPicker);
mPicker.setMinValue(FIRST_HEIGHT);
mPicker.setMaxValue(LAST_HEIGHT);
mPicker.setValue(START_HEIGHT);
mPicker.setFocusable(true);
mPicker.setFocusableInTouchMode(true);
mTitleTextView = (TextView) findViewById(R.id.title);
mFinishBtn = (TextView) findViewById(R.id.finish);
mFinishBtn.setOnClickListener(mFinishClickListener);
mPicker.setOnValueChangedListener(mOnValueChangeListener);
mPicker.setWrapSelectorWheel(false);
if (!StrUtils.isEmpty(mTitle)) {
mTitleTextView.setText(mTitle);
}
if (mCurrentValue != 0) {
mPicker.setValue(mCurrentValue);
}
if (mShowValueOnTitle) {
mTitleTextView.setText(mPicker.getValue() + UNIT);
}
this.setOnDismissListener(mOnDissmissListener);
}
private OnDismissListener mOnDissmissListener = new OnDismissListener() {
@Override
public void onDismiss(DialogInterface dialog) {
}
};
private android.view.View.OnClickListener mFinishClickListener = new android.view.View.OnClickListener() {
@Override
public void onClick(View v) {
HeightPickerWidget.this.dismiss();
mOnFinishClickListener.onClick(v);
}
};
private OnValueChangeListener mOnValueChangeListener = new OnValueChangeListener() {
@Override
public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
if (mShowValueOnTitle) {
mTitleTextView.setText(newVal + UNIT);
}
}
};
public void setInitValue(int value) {
if (null == mPicker) {
mCurrentValue = value;
}
}
public String getCurrentValue() {
return mPicker.getValue() + UNIT;
}
public void setTitle(String title) {
mTitle = title;
}
public void setOnFinishClickListener(
android.view.View.OnClickListener clickListener) {
this.mOnFinishClickListener = clickListener;
}
public boolean isShowValueOnTitle() {
return mShowValueOnTitle;
}
public void setShowValueOnTitle(boolean mShowValueOnTitle) {
this.mShowValueOnTitle = mShowValueOnTitle;
}
}
| true
|
2c87ecb3cce18672b8e5717d3cef1c3dbf3384d4
|
Java
|
silver-ring/designpatterns
|
/test/designpatterns/example/behivor/template/EmailNotificationTest.java
|
UTF-8
| 1,130
| 2.625
| 3
|
[] |
no_license
|
package designpatterns.example.behivor.template;
import org.junit.jupiter.api.Test;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class EmailNotificationTest {
@Test
final public void calculateBill() {
Map<Long, BigDecimal> items = new HashMap<>();
items.put(10L, BigDecimal.valueOf(15));
items.put(20L, BigDecimal.valueOf(30));
items.put(30L, BigDecimal.valueOf(17));
items.put(40L, BigDecimal.valueOf(28));
items.put(50L, BigDecimal.valueOf(100));
BillCalculator billWithDiscount = new BillWithDiscount();
BigDecimal billWithDiscountResult = billWithDiscount.calculateBill(items);
assertEquals(BigDecimal.valueOf(190), billWithDiscountResult);
BillCalculator billWithTaxAndTotalDiscount = new BillWithTaxAndTotalDiscount();
BigDecimal billWithTaxAndTotalDiscountResult = billWithTaxAndTotalDiscount.calculateBill(items);
assertEquals(BigDecimal.valueOf(209).setScale(2), billWithTaxAndTotalDiscountResult);
}
}
| true
|
bfddcba273580e20a180ba5e5ee6d6f1bcfa10ab
|
Java
|
QIONG-0531/First-repo
|
/练习06/Demo36.java
|
UTF-8
| 726
| 3.46875
| 3
|
[] |
no_license
|
import java.util.Arrays;
import java.util.HashSet;
public class Demo36 {
public boolean IsContinuous(int [] numbers) {
//1.使用set存储不为0的数字,去除重复数字
//2.验证0的个数加上set的大小是否等于5
//set里的最大值和最小值 差值小于5
HashSet<Integer> set=new HashSet<>();
Arrays.sort(numbers);
int count=0;
for(int x:numbers){
if(x==0){
count++;
}else{
set.add(x);
}
}
if(set.size()+count!=5){
return false;
}
if((numbers[4]-numbers[count])<5){
return true;
}
return false;
}
}
| true
|
e3539b4d3b4b576162eac0768aabbcf1d9e37bca
|
Java
|
kevinnerd/algorithm008-class01
|
/Week_02/350.两个数组的交集-ii.java
|
UTF-8
| 2,386
| 3.53125
| 4
|
[] |
no_license
|
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/*
* @lc app=leetcode.cn id=350 lang=java
*
* [350] 两个数组的交集 II
*
* https://leetcode-cn.com/problems/intersection-of-two-arrays-ii/description/
*
* algorithms
* Easy (47.53%)
* Likes: 265
* Dislikes: 0
* Total Accepted: 79.6K
* Total Submissions: 166.4K
* Testcase Example: '[1,2,2,1]\n[2,2]'
*
* 给定两个数组,编写一个函数来计算它们的交集。
*
* 示例 1:
*
* 输入: nums1 = [1,2,2,1], nums2 = [2,2]
* 输出: [2,2]
*
*
* 示例 2:
*
* 输入: nums1 = [4,9,5], nums2 = [9,4,9,8,4]
* 输出: [4,9]
*
* 说明:
*
*
* 输出结果中每个元素出现的次数,应与元素在两个数组中出现的次数一致。
* 我们可以不考虑输出结果的顺序。
*
*
* 进阶:
*
*
* 如果给定的数组已经排好序呢?你将如何优化你的算法?
* 如果 nums1 的大小比 nums2 小很多,哪种方法更优?
* 如果 nums2 的元素存储在磁盘上,磁盘内存是有限的,并且你不能一次加载所有的元素到内存中,你该怎么办?
*
*
*/
// @lc code=start
class Solution {
public int[] intersect(int[] nums1, int[] nums2) {
if (nums1.length > nums2.length) {
return intersect(nums2, nums1);
}
Map<Integer, Integer> intersectMap = new HashMap<>(nums1.length);
for (int i = 0; i < nums1.length; i++) {
intersectMap.put(nums1[i], intersectMap.getOrDefault(nums1[i], 0) + 1);
}
return findIntersection(nums2, intersectMap);
}
private int[] findIntersection(int[] nums2,
Map<Integer, Integer> intersectMap) {
List<Integer> res = new ArrayList<>(nums2.length);
for (int i = 0; i < nums2.length; i++) {
if (intersectMap.containsKey(nums2[i])
&& intersectMap.get(nums2[i]) > 0) {
res.add(nums2[i]);
intersectMap.put(nums2[i], intersectMap.get(nums2[i]) - 1);
}
}
return toArr(res);
}
private int[] toArr(List<Integer> list) {
int[] arr = new int[list.size()];
for (int i = 0; i < arr.length; i++) {
arr[i] = list.get(i);
}
return arr;
}
}
// @lc code=end
| true
|
adb88418bd1bb5b73e24ebcf37cb292456bb7949
|
Java
|
SeanHoerger/Catan
|
/SettlersOfCatan/src/catan/VertexArray.java
|
UTF-8
| 3,975
| 3.078125
| 3
|
[] |
no_license
|
package catan;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import javax.swing.JFrame;
public class VertexArray {
private Vertex[] vertexes;
public VertexArray(){
vertexes = new Vertex[54];
for(int i = 0; i < vertexes.length; i++) {
vertexes[i] = new Vertex();
}
this.setLocations();
}
public void addNeighbor(int i, Tile neighbor) {
vertexes[i].addNeighbor(neighbor);
}
public void resetNeighbors() {
for(int i = 0; i < vertexes.length; i++) {
vertexes[i].resetNeighbors();
}
}
public void test(Graphics g) {
for(int i = 0; i < vertexes.length; i++) {
Vertex vertex = vertexes[i];
g.setColor(Color.BLACK);
g.setFont(new Font (Font.SANS_SERIF, Font.BOLD, BoardDisplay.SCALAR));
g.drawString("" + i + ": " + vertex.neighborString(), vertex.getX(), vertex.getY());
}
}
public Vertex[] getArray() {
return vertexes;
}
public int getLength() {
return vertexes.length;
}
public Vertex getVertex(int index) {
return vertexes[index];
}
private void setLocations() {
int xPos = BoardDisplay.XSTART;
int yPos = BoardDisplay.YSTART;
int i = 0;
// row one - 3 vertexes
for(int j = 0; j < 3; j++) {
vertexes[i] = new Vertex(xPos, yPos, 0);
xPos = xPos+6*BoardDisplay.SCALAR;
i++;
}
xPos = BoardDisplay.XSTART-3*BoardDisplay.SCALAR;
yPos = yPos+2*BoardDisplay.SCALAR;
// row two - 4 vertexes
for(int j = 0; j < 4; j++) {
vertexes[i] = new Vertex(xPos, yPos, 0);
xPos = xPos+6*BoardDisplay.SCALAR;
i++;
}
xPos = BoardDisplay.XSTART-3*BoardDisplay.SCALAR;
yPos = yPos+3*BoardDisplay.SCALAR;
// row three - 4 vertexes
for(int j = 0; j < 4; j++) {
vertexes[i] = new Vertex(xPos, yPos, 0);
xPos = xPos+6*BoardDisplay.SCALAR;
i++;
}
xPos = BoardDisplay.XSTART-6*BoardDisplay.SCALAR;
yPos = yPos+2*BoardDisplay.SCALAR;
// row four - 5 vertexes
for(int j = 0; j < 5; j++) {
vertexes[i] = new Vertex(xPos, yPos, 0);
xPos = xPos+6*BoardDisplay.SCALAR;
i++;
}
xPos = BoardDisplay.XSTART-6*BoardDisplay.SCALAR;
yPos = yPos+3*BoardDisplay.SCALAR;
// row five - 5 vertexes
for(int j = 0; j < 5; j++) {
vertexes[i] = new Vertex(xPos, yPos, 0);
xPos = xPos+6*BoardDisplay.SCALAR;
i++;
}
xPos = BoardDisplay.XSTART-9*BoardDisplay.SCALAR;
yPos = yPos+2*BoardDisplay.SCALAR;
// row six - 6 vertexes
for(int j = 0; j < 6; j++) {
vertexes[i] = new Vertex(xPos, yPos, 0);
xPos = xPos+6*BoardDisplay.SCALAR;
i++;
}
xPos = BoardDisplay.XSTART-9*BoardDisplay.SCALAR;
yPos = yPos+3*BoardDisplay.SCALAR;
// row seven - 6 vertexes
for(int j = 0; j < 6; j++) {
vertexes[i] = new Vertex(xPos, yPos, 0);
xPos = xPos+6*BoardDisplay.SCALAR;
i++;
}
xPos = BoardDisplay.XSTART-6*BoardDisplay.SCALAR;
yPos = yPos+2*BoardDisplay.SCALAR;
// row eight - 5 vertexes
for(int j = 0; j < 5; j++) {
vertexes[i] = new Vertex(xPos, yPos, 0);
xPos = xPos+6*BoardDisplay.SCALAR;
i++;
}
xPos = BoardDisplay.XSTART-6*BoardDisplay.SCALAR;
yPos = yPos+3*BoardDisplay.SCALAR;
// row nine - 5 vertexes
for(int j = 0; j < 5; j++) {
vertexes[i] = new Vertex(xPos, yPos, 0);
xPos = xPos+6*BoardDisplay.SCALAR;
i++;
}
xPos = BoardDisplay.XSTART-3*BoardDisplay.SCALAR;
yPos = yPos+2*BoardDisplay.SCALAR;
// row ten - 4 vertexes
for(int j = 0; j < 4; j++) {
vertexes[i] = new Vertex(xPos, yPos, 0);
xPos = xPos+6*BoardDisplay.SCALAR;
i++;
}
xPos = BoardDisplay.XSTART-3*BoardDisplay.SCALAR;
yPos = yPos+3*BoardDisplay.SCALAR;
// row eleven - 4 vertexes
for(int j = 0; j < 4; j++) {
vertexes[i] = new Vertex(xPos, yPos, 0);
xPos = xPos+6*BoardDisplay.SCALAR;
i++;
}
xPos = BoardDisplay.XSTART;
yPos = yPos+2*BoardDisplay.SCALAR;
// row twelve - 3 vertexes
for(int j = 0; j < 3; j++) {
vertexes[i] = new Vertex(xPos, yPos, 0);
xPos = xPos+6*BoardDisplay.SCALAR;
i++;
}
}
}
| true
|
34d2ab128be2142d11445c855b6ab91312b4a61f
|
Java
|
vishalbagde/jspExampleWithGradle
|
/src/main/java/demo/Main.java
|
UTF-8
| 3,829
| 2.90625
| 3
|
[] |
no_license
|
package demo;
import model.*;
import java.lang.annotation.Annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.util.List;
import java.util.Scanner;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;
import javax.persistence.TypedQuery;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import model.PersonName;
/*
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@interface SmartPhone{
String os() default "symbian";
int version();
}
@SmartPhone(os="android",version=6)
class A
{
public void show()
{
}
public void showMyDataFromLastYearDatabase()
{
System.out.println("in A");
}
}
class B extends A
{
@Override
@SuppressWarnings("unchecked")
public void showMyDataFromLastYearDatabase()
{
System.out.println("in A");
}
@Deprecated
public void show()
{
}
}
*/
public class Main {
/*
public enum operation {
INSERT(1), UPDATE(2), DELETE(3), DISPLAY(4), EXIT(5), IDLE(6);
private int value;
private operation(int value) {
this.value = value;
}
public void setOperation(int value) {
this.value = value;
}
public int getOperation() {
return this.value;
}
}
*/
public static void main(String src[]) {
EntityManagerFactory emf = Persistence.createEntityManagerFactory("pu");
EntityManager em = emf.createEntityManager();
// CriteriaBuilder cb =em.getCriteriaBuilder();
// CriteriaQuery<Person> createQuery= cb.createQuery(Person.class);
// Root<Person> from= createQuery.from(Person.class);
// createQuery.select(from);
// TypedQuery<Person> typedQuery= em.createQuery(createQuery);
//
// List<Person> list =typedQuery.getResultList();
// for(Person p:list)
// {
// System.out.println(p.toString());
// }
//
// List<Object[]> persons=em.createNativeQuery("select * from person").getResultList();
// persons.forEach((o)->System.out.println(o[1]));
em.getTransaction().begin();
Contact c=new Contact();
Query query =em.createQuery("update Contact set phone_no = '9898989898' where contact_id = 13");
query.executeUpdate();
em.getTransaction().commit();
emf.close();
em.close();
/*
A a=new A();
Class x=a.getClass();
Annotation an=x.getAnnotation(SmartPhone.class);
SmartPhone s=(SmartPhone) an;
System.out.println(s.os());
*/
/*
operation op = operation.IDLE;
do {
Scanner in = new Scanner(System.in);
System.out.println("1.INSERT");
System.out.println("2.UPDATE");
System.out.println("3.DELETE");
System.out.println("4.DISPLAY");
System.out.println("5.EXIT");
System.out.print("Select Option:");
int ch = in.nextInt();
op.setOperation(ch);
System.out.println(op.getOperation());
if(op.equals(operation.INSERT))
System.out.println("insert op");
switch (op) {
case INSERT:
System.out.println("INSERT");
break;
case UPDATE:
break;
case DELETE:
break;
case DISPLAY:
break;
case EXIT:
System.out.println("Exit");
break;
default:
}
} while (op == operation.EXIT);
*/
/*
*
* EntityManagerFactory creEmp = Persistence.createEntityManagerFactory("pu");
* EntityManager em = creEmp.createEntityManager(); em.getTransaction().begin();
* PersonName pn = new PersonName(); pn.setFname("vishal");
* pn.setMname("govind"); pn.setLname("bagde");
*
* em.persist(pn); em.getTransaction().commit(); em.close(); creEmp.close();
*
*/
}
}
| true
|
fcbbe35d0092c67ae113fb0e40963b42c705bf2c
|
Java
|
orbekk/master
|
/same-android/src/main/java/com/orbekk/same/android/GameView.java
|
UTF-8
| 5,979
| 2.53125
| 3
|
[
"Apache-2.0"
] |
permissive
|
/**
* Copyright 2012 Kjetil Ørbekk <kjetil.orbekk@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.orbekk.same.android;
import java.util.concurrent.atomic.AtomicBoolean;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import com.orbekk.same.Variable;
import com.orbekk.same.VariableUpdaterTask;
public class GameView extends SurfaceView implements SurfaceHolder.Callback {
private Logger logger = LoggerFactory.getLogger(getClass());
private GameThread thread;
static class Player {
public Player() {
}
public Player(float posX, float posY) {
this.posX = posX;
this.posY = posY;
}
public float posX;
public float posY;
}
static class GameThread extends Thread
implements Variable.OnChangeListener<Player> {
private Logger logger = LoggerFactory.getLogger(getClass());
private int height = 0;
private int width = 0;
private SurfaceHolder holder;
private Paint background;
private Variable<Player> player;
private VariableUpdaterTask<Player> updater;
private AtomicBoolean shouldRedraw = new AtomicBoolean(true);
private Paint color = new Paint();
public GameThread(SurfaceHolder holder, Variable<Player> player) {
this.holder = holder;
this.player = player;
background = new Paint();
background.setARGB(255, 0, 0, 0);
color.setARGB(255, 255, 0, 0);
}
public void setUp() {
player.addOnChangeListener(this);
updater = new VariableUpdaterTask<Player>(player);
updater.set(new Player(0.5f, 0.5f));
updater.start();
}
public void tearDown() {
player.removeOnChangeListener(this);
updater.interrupt();
}
public void setSize(int width, int height) {
synchronized(holder) {
this.width = width;
this.height = height;
}
}
private void doDraw(Canvas c) {
c.drawRect(0.0f, 0.0f, width+1.0f, height+1.0f, background);
Player player_ = player.get();
if (player_ == null) {
return;
}
c.drawCircle(player_.posX * width, player_.posY * height,
20.0f, color);
}
@Override public void run() {
while (true) {
Canvas c = null;
try {
c = holder.lockCanvas();
if (c != null) {
synchronized(holder) {
doDraw(c);
}
}
} finally {
if (c != null) {
holder.unlockCanvasAndPost(c);
}
}
synchronized (this) {
if (Thread.interrupted()) {
break;
}
try {
while (!shouldRedraw.get()) {
wait();
}
} catch (InterruptedException e) {
break;
}
}
}
}
private synchronized void setShouldRedraw() {
shouldRedraw.set(true);
notifyAll();
}
private synchronized void setPosition(final float x, final float y) {
if (player.get() == null || player.get().posX != x ||
player.get().posY != y) {
Player newPlayer = new Player(x / width, y / height);
updater.set(newPlayer);
}
}
@Override
public synchronized void valueChanged(Variable<Player> unused) {
logger.info("Variable updated.");
player.update();
setShouldRedraw();
}
}
public GameView(Context context, Variable<Player> player) {
super(context);
getHolder().addCallback(this);
thread = new GameThread(getHolder(), player);
}
public void setUp() {
thread.setUp();
}
public void tearDown() {
thread.tearDown();
}
@Override
protected void onDraw(Canvas canvas) {
Paint paint = new Paint();
paint.setARGB(255, 255, 0, 0);
canvas.drawCircle(50.0f, 50.0f, 50.0f, paint);
}
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
logger.info("SurfaceChanged(w={}, h={})", width, height);
thread.setSize(width, height);
}
@Override
public void surfaceCreated(SurfaceHolder holder) {
logger.info("SurfaceCreated()");
thread.start();
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
logger.info("SurfaceDestroyed()");
thread.interrupt();
}
@Override
public boolean onTouchEvent(MotionEvent e) {
thread.setPosition(e.getX(), e.getY());
return true;
}
}
| true
|
09aae9cc4527be23d427226aa8d20744ec5a4e35
|
Java
|
priteshbhole/AddressBookGUI
|
/java 2/EntryTest.java
|
UTF-8
| 2,206
| 3.046875
| 3
|
[] |
no_license
|
import static org.junit.Assert.*;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
/**
* The test class EntryTest.
*
* @author Pritesh Bhole
* @version 19 May 2015
*/
public class EntryTest extends Exception
{
private Entry entry1;
/**
* Default constructor for test class EntryTest
*/
public EntryTest()
{
}
/**
* Sets up the test fixture.
*
* Called before every test case method.
*/
@Before
public void setUp()
{
entry1 = new Entry("pritesh", "bhole", "gowland", "newcastle", "NE4 4NE");
}
/**
* Tears down the test fixture.
*
* Called after every test case method.
*/
@After
public void tearDown()
{
}
@Test
public void testConstructor()
{
assertNotNull(entry1);;
}
@Test
public void testGetFirstName()
{
assertTrue(entry1.getFirstName() == "pritesh" );
}
@Test
public void testGetLastName()
{
assertTrue(entry1.getLastName() == "bhole" );
}
@Test
public void testGetTown()
{
assertTrue(entry1.getTown() == "newcastle" );
}
@Test
public void testGetStreet()
{
assertTrue(entry1.getStreet() == "gowland" );
}
@Test
public void testGetPostCode()
{
assertTrue(entry1.getPostCode() == "NE4 4NE" );
}
@Test
public void testInvalidPostCode()
{
Entry entry2 = new Entry("","","","","");
Entry entry3 =new Entry("pr","bh","gowland", "newcastle", "NE4NE");
assertTrue(entry2.getPostCode() == "???" );
assertTrue(entry3.getPostCode() == "???" );
}
@Test
public void testToString()
{
assertTrue(entry1.equals(entry1));
}
@Test
public void testEquals()
{
Entry entry2 = new Entry("pritesh", "bhole", "gowland", "newcastle", "NE4 4NE");
assertTrue( entry1.equals( entry2 ));
}
@Test
public void testNotEqual()
{
Entry entry2 = new Entry("jo", "m", "gowland", "newcastle", "NE4 4NE");
assertFalse( entry1.equals( entry2 ));
}
}
| true
|
8ce4c3cf4633d4fdfd089a2e8a63fda8e5fe86f9
|
Java
|
djorder93/diplomski3
|
/src/java/domen/Termin.java
|
UTF-8
| 3,295
| 2.171875
| 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 domen;
import java.io.Serializable;
import java.util.Date;
import javax.persistence.EmbeddedId;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import javax.persistence.Transient;
import javax.xml.bind.annotation.XmlRootElement;
/**
*
* @author Djox
*/
@Entity
@Table(name = "termin")
@XmlRootElement
@NamedQueries({
@NamedQuery(name = "Termin.findAll", query = "SELECT t FROM Termin t"),
@NamedQuery(name = "Termin.findByMedSestra", query = "SELECT t FROM Termin t WHERE t.terminPK.medSestra = :medSestra"),
@NamedQuery(name = "Termin.findByPacijent", query = "SELECT t FROM Termin t WHERE t.terminPK.pacijent = :pacijent"),
@NamedQuery(name = "Termin.findByDatum", query = "SELECT t FROM Termin t WHERE t.terminPK.datum = :datum")})
public class Termin implements Serializable {
private static final long serialVersionUID = 1L;
@EmbeddedId
protected TerminPK terminPK;
@JoinColumn(name = "pacijent", referencedColumnName = "jmbg", insertable = false, updatable = false)
@ManyToOne(optional = false, fetch = FetchType.EAGER)
private Pacijent pacijent1;
@JoinColumn(name = "medSestra", referencedColumnName = "id", insertable = false, updatable = false)
@ManyToOne(optional = false, fetch = FetchType.EAGER)
private Medsestra medsestra;
public Termin() {
terminPK = new TerminPK();
}
public Termin(TerminPK terminPK) {
this.terminPK = terminPK;
}
public Termin(int medSestra, String pacijent, Date datum) {
this.terminPK = new TerminPK(medSestra, pacijent, datum);
}
public TerminPK getTerminPK() {
return terminPK;
}
public void setTerminPK(TerminPK terminPK) {
this.terminPK = terminPK;
}
public Pacijent getPacijent1() {
return pacijent1;
}
public void setPacijent1(Pacijent pacijent1) {
this.pacijent1 = pacijent1;
}
public Medsestra getMedsestra() {
return medsestra;
}
public void setMedsestra(Medsestra medsestra) {
this.medsestra = medsestra;
}
@Override
public int hashCode() {
int hash = 0;
hash += (terminPK != null ? terminPK.hashCode() : 0);
return hash;
}
@Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Termin)) {
return false;
}
Termin other = (Termin) object;
if ((this.terminPK == null && other.terminPK != null) || (this.terminPK != null && !this.terminPK.equals(other.terminPK))) {
return false;
}
return true;
}
@Override
public String toString() {
return "domen.Termin[ terminPK=" + terminPK + " ]";
}
}
| true
|
041e01340d78c413bdd148746bac6ca98bc38bd2
|
Java
|
teneous/practice-rabbitmq
|
/api/src/main/java/com/trifail/practice/api/advance/reachable/confirmed/Consumer.java
|
UTF-8
| 1,592
| 2.5625
| 3
|
[] |
no_license
|
package com.trifail.practice.api.advance.reachable.confirmed;
import com.rabbitmq.client.*;
import com.trifail.practice.api.utils.ConnectionCenterFactory;
import static com.trifail.practice.api.Constant.*;
import java.io.IOException;
import java.util.concurrent.TimeoutException;
/**
* 消息确认模式,无论成功还是失败,broker将发送一个消息确认事件给发送者
* 消息发送者--msg-->Broker
* Broker--confirm-->消息发送者
*/
public class Consumer {
public static void main(String[] args) throws IOException, TimeoutException {
ConnectionFactory connectFactory = ConnectionCenterFactory.getConnectFactory();
Connection connection = connectFactory.newConnection();
Channel channel = connection.createChannel();
channel.exchangeDeclare(ADV_CONFIRM_EXCHANGE, TOPIC, true);
channel.queueDeclare(ADV_CONFIRM_QUEUE, true, false, false, null);
channel.queueBind(ADV_CONFIRM_QUEUE, ADV_CONFIRM_EXCHANGE, ADV_CONFIRM_ROUTING_KEY);
channel.basicConsume(ADV_CONFIRM_QUEUE, true, new DefaultConsumer(channel) {
@Override
public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) {
System.out.println("--------------");
System.out.println("consumerTag:" + consumerTag);
System.out.println("envelope:" + envelope.toString());
System.out.println("body:" + new String(body));
System.out.println("--------------");
}
});
}
}
| true
|
92067948d09faf1417f82cfcfa690b8eff846a87
|
Java
|
hallvard/tdt4250
|
/no.hal.pg.runtime/src/no/hal/pg/runtime/engine/util/AbstractServiceProvider.java
|
UTF-8
| 1,193
| 2.0625
| 2
|
[] |
no_license
|
package no.hal.pg.runtime.engine.util;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.EObject;
import no.hal.pg.runtime.RuntimePackage;
import no.hal.pg.runtime.Service;
import no.hal.pg.runtime.engine.IServiceProvider;
public abstract class AbstractServiceProvider implements IServiceProvider {
protected EClass eClass;
protected EClass serviceClass;
public AbstractServiceProvider() {
}
public void setEClass(EClass eClass) {
this.eClass = eClass;
}
public void setServiceClass(EClass serviceClass) {
if (serviceClass == null || RuntimePackage.eINSTANCE.getService().isSuperTypeOf(serviceClass)) {
this.serviceClass = serviceClass;
}
}
public AbstractServiceProvider(EClass eClass, EClass serviceClass) {
setEClass(eClass);
setServiceClass(serviceClass);
}
@Override
public Service<?> getService(EObject eObject) {
if (eClass != null && eClass.isInstance(eObject) && serviceClass != null) {
Service<?> serviceObject = (Service<?>) serviceClass.getEPackage().getEFactoryInstance().create(serviceClass);
serviceObject.eSet(RuntimePackage.eINSTANCE.getService_Context(), eObject);
return serviceObject;
}
return null;
}
}
| true
|
b169c68fc50edecf42b1fed30e3eff6518c2093c
|
Java
|
sqf-ice/xipki
|
/ca-client-impl/src/main/java/org/xipki/ca/client/impl/PbmMacClientCmpRequestor.java
|
UTF-8
| 2,474
| 1.703125
| 2
|
[
"Apache-2.0"
] |
permissive
|
/*
*
* Copyright (c) 2013 - 2018 Lijun Liao
*
* 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.xipki.ca.client.impl;
import java.security.SecureRandom;
import org.bouncycastle.asn1.cmp.PBMParameter;
import org.bouncycastle.asn1.x500.X500Name;
import org.bouncycastle.asn1.x509.AlgorithmIdentifier;
import org.bouncycastle.asn1.x509.GeneralName;
/**
* TODO.
* @author Lijun Liao
* @since 2.0.0
*/
public class PbmMacClientCmpRequestor implements ClientCmpRequestor {
private final SecureRandom random = new SecureRandom();
private final GeneralName name;
private final boolean signRequest;
private final char[] password;
// CHECKSTYLE:SKIP
private final byte[] senderKID;
private final AlgorithmIdentifier owf;
private final int iterationCount;
private final AlgorithmIdentifier mac;
public PbmMacClientCmpRequestor(boolean signRequest, X500Name x500name, char[] password,
// CHECKSTYLE:SKIP
byte[] senderKID, AlgorithmIdentifier owf, int iterationCount, AlgorithmIdentifier mac) {
this.signRequest = signRequest;
this.name = new GeneralName(x500name);
this.password = password;
this.senderKID = senderKID;
this.owf = owf;
this.iterationCount = iterationCount;
this.mac = mac;
}
@Override
public GeneralName getName() {
return name;
}
public char[] getPassword() {
return password;
}
// CHECKSTYLE:SKIP
public byte[] getSenderKID() {
return senderKID;
}
public PBMParameter getParameter() {
return new PBMParameter(randomSalt(), owf, iterationCount, mac);
}
public AlgorithmIdentifier getOwf() {
return owf;
}
public int getIterationCount() {
return iterationCount;
}
public AlgorithmIdentifier getMac() {
return mac;
}
@Override
public boolean signRequest() {
return signRequest;
}
private byte[] randomSalt() {
byte[] bytes = new byte[64];
random.nextBytes(bytes);
return bytes;
}
}
| true
|
55658a9a0e2f03c4b4a8ca56da9f1628c11d1d54
|
Java
|
google-code/aci
|
/src/model/Skill.java
|
UTF-8
| 761
| 3.09375
| 3
|
[] |
no_license
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package model;
/**
*
* @author CUNEYT
*/
public class Skill {
private String title;
private int level;
public Skill() {
}
public Skill(String tit, int lvl) {
title = tit;
level = lvl;
}
public void incrementLevel() {
level += 1;
}
public int getLevel() {
return level;
}
public void setLevel(int level) {
this.level = level;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
@Override
public String toString() {
return getTitle() + " " + getLevel();
}
}
| true
|
1794d981f2ee5b36a17dddbd1de5434193e6d420
|
Java
|
christoffertoppe/Suunnittelumallit
|
/src/tehtava6c/Jauheliha.java
|
UTF-8
| 323
| 2.671875
| 3
|
[] |
no_license
|
package tehtava6c;
public class Jauheliha extends TayteDecorator {
Pizza pizza;
private int hinta = 1;
public Jauheliha(Pizza pizza) {
this.pizza = pizza;
}
@Override
public String kuvaile() {
return pizza.kuvaile() + ", Jauheliha ";
}
@Override
public int hinta() {
return hinta + pizza.hinta();
}
}
| true
|
49ee9af86945c57024f55200a792aec3bdee43bf
|
Java
|
UncleTian/olp
|
/db/dao/CFG_AUTOCODEMapper.java
|
UTF-8
| 450
| 1.851563
| 2
|
[] |
no_license
|
package com.bea.dao;
import com.bea.olp.CFG_AUTOCODE;
import com.bea.olp.CFG_AUTOCODEKey;
public interface CFG_AUTOCODEMapper {
int deleteByPrimaryKey(CFG_AUTOCODEKey key);
int insert(CFG_AUTOCODE record);
int insertSelective(CFG_AUTOCODE record);
CFG_AUTOCODE selectByPrimaryKey(CFG_AUTOCODEKey key);
int updateByPrimaryKeySelective(CFG_AUTOCODE record);
int updateByPrimaryKey(CFG_AUTOCODE record);
}
| true
|
9375928b2ddd662d0fb1a870d4578dfd76bf5c24
|
Java
|
fengmnegchang/Umei
|
/src/com/open/umei/json/m/UmeMPannelHdJson.java
|
UTF-8
| 1,654
| 1.78125
| 2
|
[] |
no_license
|
/**
*****************************************************************************************************************************************************************************
*
* @author :fengguangjing
* @createTime:2016-12-29上午10:54:22
* @version:4.2.4
* @modifyTime:
* @modifyAuthor:
* @description:
*****************************************************************************************************************************************************************************
*/
package com.open.umei.json.m;
import java.util.ArrayList;
import java.util.List;
import com.open.umei.bean.UmeiTypeBean;
import com.open.umei.bean.m.UmeMPannelHdBean;
import com.open.umei.json.CommonJson;
/**
*****************************************************************************************************************************************************************************
*
* @author :fengguangjing
* @createTime:2016-12-29上午10:54:22
* @version:4.2.4
* @modifyTime:
* @modifyAuthor:
* @description:
*****************************************************************************************************************************************************************************
*/
public class UmeMPannelHdJson extends CommonJson {
private List<UmeMPannelHdBean> list;
private ArrayList<UmeiTypeBean> listv = new ArrayList<UmeiTypeBean>();
public List<UmeMPannelHdBean> getList() {
return list;
}
public void setList(List<UmeMPannelHdBean> list) {
this.list = list;
}
public ArrayList<UmeiTypeBean> getListv() {
return listv;
}
public void setListv(ArrayList<UmeiTypeBean> listv) {
this.listv = listv;
}
}
| true
|
0d55b9a1d93df07add9a8ce3d2040fbc159a44cb
|
Java
|
Euchigere/simple-plagiarism-checker
|
/src/main/java/com/emmanuelc/plagiarismchecker/domain/models/enumerations/PrivilegeEnum.java
|
UTF-8
| 123
| 1.921875
| 2
|
[] |
no_license
|
package com.emmanuelc.plagiarismchecker.domain.models.enumerations;
public enum PrivilegeEnum {
READ, WRITE, DELETE
}
| true
|
4f3a9192db68d5cfe7bc1e7f883f88dd93748512
|
Java
|
Schroedernick2/COE_1501
|
/project3/Edge.java
|
UTF-8
| 290
| 2.78125
| 3
|
[] |
no_license
|
//Nicholas Schroeder
//11.8.2018
public class Edge{
private City city1;
private City city2;
//edge from city1 - city2
public Edge(City city1, City city2){
this.city1 = city1;
this.city2 = city2;
}
public City getFirstCity(){ return city1; }
public City getSecondCity(){ return city2; }
}
| true
|
ab500cf3f41a0499dc854a46d9c4304b590455fe
|
Java
|
handsomezhou/programming_notes_for_java_android
|
/Demo/app/src/main/java/com/handsomezhou/demo/util/SecurityUtil.java
|
UTF-8
| 2,162
| 2.703125
| 3
|
[] |
no_license
|
package com.handsomezhou.demo.util;
import com.handsomezhou.demo.model.BusinessReq;
/**
* Created by handsomezhou on 2020/2/25.
*/
public class SecurityUtil {
/**
* deviceId;timestamp;f(x);
* {"appKey":"75aAO5aGaGWA5","clientId":"U0Nc0OJcO00UqcOO","timestamp":1582626145617}
* clientId=f(deviceId);
* appKey=f(clientId+timestamp)
*/
/**
*
* @param deviceId
* @return
*/
public static String getClientId(String deviceId){
return RandomCodeUtil.generateRandomCode(deviceId);
}
/**
*
* @param clientId
* @param timestamp
* @return
*/
public static String getAppKey(String clientId, long timestamp){
String str=timestamp+clientId;
String outOfOrderStr=outOfOrder(str);
return RandomCodeUtil.generateRandomCode(outOfOrderStr);
}
/**
* 固定乱序
* @param str
* @return
*/
private static String outOfOrder(String str){
StringBuffer outOfOrderSb=new StringBuffer();
do{
if(null==str||str.length()<=0){
break;
}
int strLen=str.length();
int sum=0;
for(int i=0;i<strLen; i++){
sum=sum+str.charAt(i);
}
int splitIndex=sum%strLen;
for(int i=splitIndex;i<strLen;i++){
outOfOrderSb.append(str.charAt(i));
}
for(int i=0;i<splitIndex;i++){
outOfOrderSb.append(str.charAt(i));
}
}while (false);
return outOfOrderSb.toString();
}
/**
* 是否合法客户端
* @param businessReq
* @return
*/
public static boolean isLegalClient(final BusinessReq businessReq){
boolean legalClient=false;
do{
if(null==businessReq){
break;
}
if(false==getAppKey(businessReq.getClientId(),businessReq.getTimestamp()).equals(businessReq.getAppKey())){
break;
}
legalClient=true;
}while (false);
return legalClient;
}
}
| true
|
2d7c9cf8be60fa34589469c83c7f1294fdf2eb14
|
Java
|
astensby/bootneo
|
/src/main/java/io/monokkel/neo/bootneo/domain/Beer.java
|
UTF-8
| 1,420
| 2.203125
| 2
|
[] |
no_license
|
package io.monokkel.neo.bootneo.domain;
import org.neo4j.graphdb.Direction;
import org.springframework.data.neo4j.annotation.*;
import java.util.HashSet;
import java.util.Set;
/**
* Created by astensby on 24/08/14.
*/
@NodeEntity
public class Beer {
@GraphId
public Long nodeId;
@Indexed(unique = true)
public long id;
public String name;
public String description;
@Fetch
@RelatedToVia(type="RATED", direction = Direction.INCOMING)
Set<Rating> ratings = new HashSet<Rating>();
public Set<Rating> getRatings() {
return ratings;
}
public void setRatings(Set<Rating> ratings) {
this.ratings = ratings;
}
public Beer(){
}
public Beer(long id, String name, String description) {
this.id = id;
this.name = name;
this.description = description;
}
public Long getNodeId() {
return nodeId;
}
public void setNodeId(Long nodeId) {
this.nodeId = nodeId;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
| true
|
1c5efa9e884d183be3a197afc884bd60f8f05442
|
Java
|
esraafouad2020/Hotel100
|
/HotelReservationSystem/Hotel reservation system/src/com/fcih/swing/hotel/service/ReceptionistService.java
|
UTF-8
| 597
| 1.984375
| 2
|
[] |
no_license
|
package com.fcih.swing.hotel.service;
import com.fcih.swing.hotel.model.Guest;
import com.fcih.swing.hotel.model.Room;
import com.fcih.swing.hotel.model.RoomTypeLookup;
import com.fcih.swing.hotel.model.ViewTypeLookup;
import java.sql.Date;
import java.util.List;
public interface ReceptionistService {
public List<RoomTypeLookup> getAllRoomType();
public List<ViewTypeLookup> getAllViewType();
public List<Room> getFilteredRooms(RoomTypeLookup roomTypeLookup, ViewTypeLookup viewTypeLookup, boolean isBusy);
public List<Guest> getCheckoutsDetails(Date from, Date to);
}
| true
|
e173f1776489fb05514561ead5e0e5cf4a39d828
|
Java
|
valllllll2000/FrescoExperiment
|
/app/src/main/java/com/vaxapp/frescoexperiment/injector/component/ActivityComponent.java
|
UTF-8
| 429
| 1.875
| 2
|
[] |
no_license
|
package com.vaxapp.frescoexperiment.injector.component;
import android.app.Activity;
import com.vaxapp.frescoexperiment.injector.PerActivity;
import com.vaxapp.frescoexperiment.injector.module.ActivityModule;
import dagger.Component;
@PerActivity
@Component(dependencies = ApplicationComponent.class, modules = ActivityModule.class)
public interface ActivityComponent {
//Exposed to sub-graphs.
Activity activity();
}
| true
|
09c6626ba5598e073099f2816f9796a7aca6269c
|
Java
|
AbhishekReddy7299/Book_Store_Management
|
/obsm-cart-module/src/main/java/com/obsm/cart/controller/CartController.java
|
UTF-8
| 1,718
| 2.125
| 2
|
[] |
no_license
|
package com.obsm.cart.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.obsm.cart.exception.CartNotFound;
import com.obsm.cart.model.CustomerCart;
import com.obsm.cart.payload.CartUpdateRequest;
import com.obsm.cart.service.ICartService;
@RestController
@RequestMapping("/cart")
public class CartController {
@Autowired
ICartService service;
@PostMapping("/addCart")
public ResponseEntity<CustomerCart> addCart(@RequestBody CustomerCart cart){
return (service.addCart(cart));
}
@DeleteMapping("/deleteCart/{cartId}")
public ResponseEntity deletecart(@PathVariable long cartId) throws CartNotFound {
return service.deleteCart(cartId);
}
@PutMapping("/updateCart/{cartId}")
public ResponseEntity<CustomerCart> updateCart(@RequestBody CustomerCart cart) throws CartNotFound {
return service.updateCart(cart);
}
@GetMapping("getCart/{cartId}")
public ResponseEntity<CustomerCart> getTask(@PathVariable long cartId) throws CartNotFound {
return service.getCart(cartId);
}
@GetMapping("/getAllCarts")
public ResponseEntity<List<CustomerCart>> getAllCarts() {
return service.getAllCarts();
}
}
| true
|
0fee0eeea3a8d83dc686f8dc19f686ea85975f3a
|
Java
|
BischoffDaniel/jpasecurity-samples
|
/jpasecurity-samples/jpasecurity-spring-2-petclinic-sample/src/main/java/org/springframework/samples/petclinic/web/EditVisitForm.java
|
UTF-8
| 2,863
| 2.109375
| 2
|
[
"Apache-2.0"
] |
permissive
|
/*
* Copyright 2008 Juergen Hoeller, Ken Krebs, Arne Limburg
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions
* and limitations under the License.
*/
package org.springframework.samples.petclinic.web;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.samples.petclinic.Clinic;
import org.springframework.samples.petclinic.Visit;
import org.springframework.samples.petclinic.validation.VisitValidator;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.bind.support.SessionStatus;
/**
* JavaBean form controller that is used to add a new <code>Visit</code> to
* the system.
*
* @author Juergen Hoeller
* @author Ken Krebs
* @author Arne Limburg
*/
@Controller
@RequestMapping("/editVisit.do")
@SessionAttributes("visit")
public class EditVisitForm {
private final Clinic clinic;
@Autowired
public EditVisitForm(Clinic clinic) {
this.clinic = clinic;
}
@InitBinder
public void setAllowedFields(WebDataBinder dataBinder) {
dataBinder.setDisallowedFields(new String[] {"id"});
}
@RequestMapping(method = RequestMethod.GET)
public String setupForm(@RequestParam("visitId") int visitId, Model model) {
Visit visit = this.clinic.loadVisit(visitId);
model.addAttribute("visit", visit);
return "visitForm";
}
@RequestMapping(method = RequestMethod.POST)
public String processSubmit(@ModelAttribute("visit") Visit visit, BindingResult result, SessionStatus status) {
new VisitValidator().validate(visit, result);
if (result.hasErrors()) {
return "visitForm";
} else {
this.clinic.storeVisit(visit);
status.setComplete();
return "redirect:vet.do?vetId=" + visit.getVet().getId();
}
}
}
| true
|
70631a51616a42d38e3dbbd346e9058402082426
|
Java
|
LucasAlesterio/projetos_java
|
/interface_java/src/View/ConsProf.java
|
UTF-8
| 16,480
| 2.328125
| 2
|
[] |
no_license
|
package View;
import javax.swing.JOptionPane;
public class ConsProf extends javax.swing.JFrame {
boolean flag=false;
public ConsProf() {
initComponents();
salvar b = new salvar();
int z;
String valor;String doc;
b.lerquantP();
z= b.quantidadeProf -1;
System.out.println(z);
for(int x=0;x<=z;x++){
for(int y=0;y<=8;y++){
doc=Integer.toString(x+1);
String conteudo = Arquivo.Read(doc+"prof.txt");
valor=conteudo.split(";")[y];
tabela.setValueAt(valor, x, y);
}
}
}
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jButton1 = new javax.swing.JButton();
jScrollPane1 = new javax.swing.JScrollPane();
tabela = new javax.swing.JTable();
save = new javax.swing.JButton();
excluir = new javax.swing.JButton();
jButton4 = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jButton1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Image/arrow-back-icon.png"))); // NOI18N
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
tabela.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{null, null, null, null, null, null, null, null, null},
{null, null, null, null, null, null, null, null, null},
{null, null, null, null, null, null, null, null, null},
{null, null, null, null, null, null, null, null, null},
{null, null, null, null, null, null, null, null, null},
{null, null, null, null, null, null, null, null, null},
{null, null, null, null, null, null, null, null, null},
{null, null, null, null, null, null, null, null, null},
{null, null, null, null, null, null, null, null, null},
{null, null, null, null, null, null, null, null, null},
{null, null, null, null, null, null, null, null, null},
{null, null, null, null, null, null, null, null, null},
{null, null, null, null, null, null, null, null, null},
{null, null, null, null, null, null, null, null, null},
{null, null, null, null, null, null, null, null, null},
{null, null, null, null, null, null, null, null, null},
{null, null, null, null, null, null, null, null, null},
{null, null, null, null, null, null, null, null, null},
{null, null, null, null, null, null, null, null, null},
{null, null, null, null, null, null, null, null, null},
{null, null, null, null, null, null, null, null, null},
{null, null, null, null, null, null, null, null, null},
{null, null, null, null, null, null, null, null, null},
{null, null, null, null, null, null, null, null, null},
{null, null, null, null, null, null, null, null, null},
{null, null, null, null, null, null, null, null, null},
{null, null, null, null, null, null, null, null, null},
{null, null, null, null, null, null, null, null, null},
{null, null, null, null, null, null, null, null, null},
{null, null, null, null, null, null, null, null, null},
{null, null, null, null, null, null, null, null, null},
{null, null, null, null, null, null, null, null, null},
{null, null, null, null, null, null, null, null, null},
{null, null, null, null, null, null, null, null, null},
{null, null, null, null, null, null, null, null, null},
{null, null, null, null, null, null, null, null, null},
{null, null, null, null, null, null, null, null, null},
{null, null, null, null, null, null, null, null, null},
{null, null, null, null, null, null, null, null, null},
{null, null, null, null, null, null, null, null, null},
{null, null, null, null, null, null, null, null, null},
{null, null, null, null, null, null, null, null, null},
{null, null, null, null, null, null, null, null, null},
{null, null, null, null, null, null, null, null, null},
{null, null, null, null, null, null, null, null, null},
{null, null, null, null, null, null, null, null, null},
{null, null, null, null, null, null, null, null, null},
{null, null, null, null, null, null, null, null, null},
{null, null, null, null, null, null, null, null, null},
{null, null, null, null, null, null, null, null, null},
{null, null, null, null, null, null, null, null, null},
{null, null, null, null, null, null, null, null, null},
{null, null, null, null, null, null, null, null, null},
{null, null, null, null, null, null, null, null, null},
{null, null, null, null, null, null, null, null, null},
{null, null, null, null, null, null, null, null, null},
{null, null, null, null, null, null, null, null, null},
{null, null, null, null, null, null, null, null, null},
{null, null, null, null, null, null, null, null, null},
{null, null, null, null, null, null, null, null, null},
{null, null, null, null, null, null, null, null, null},
{null, null, null, null, null, null, null, null, null},
{null, null, null, null, null, null, null, null, null},
{null, null, null, null, null, null, null, null, null},
{null, null, null, null, null, null, null, null, null},
{null, null, null, null, null, null, null, null, null},
{null, null, null, null, null, null, null, null, null},
{null, null, null, null, null, null, null, null, null},
{null, null, null, null, null, null, null, null, null},
{null, null, null, null, null, null, null, null, null},
{null, null, null, null, null, null, null, null, null},
{null, null, null, null, null, null, null, null, null},
{null, null, null, null, null, null, null, null, null},
{null, null, null, null, null, null, null, null, null},
{null, null, null, null, null, null, null, null, null},
{null, null, null, null, null, null, null, null, null},
{null, null, null, null, null, null, null, null, null},
{null, null, null, null, null, null, null, null, null},
{null, null, null, null, null, null, null, null, null},
{null, null, null, null, null, null, null, null, null},
{null, null, null, null, null, null, null, null, null},
{null, null, null, null, null, null, null, null, null},
{null, null, null, null, null, null, null, null, null},
{null, null, null, null, null, null, null, null, null},
{null, null, null, null, null, null, null, null, null},
{null, null, null, null, null, null, null, null, null},
{null, null, null, null, null, null, null, null, null},
{null, null, null, null, null, null, null, null, null},
{null, null, null, null, null, null, null, null, null},
{null, null, null, null, null, null, null, null, null},
{null, null, null, null, null, null, null, null, null},
{null, null, null, null, null, null, null, null, null},
{null, null, null, null, null, null, null, null, null},
{null, null, null, null, null, null, null, null, null},
{null, null, null, null, null, null, null, null, null},
{null, null, null, null, null, null, null, null, null},
{null, null, null, null, null, null, null, null, null},
{null, null, null, null, null, null, null, null, null},
{null, null, null, null, null, null, null, null, null},
{null, null, null, null, null, null, null, null, null}
},
new String [] {
"Nome", "Titulação", "Salario", "CPF", "Area", "CTPS", "Email", "Endereço", "Telefone"
}
) {
Class[] types = new Class [] {
java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class
};
public Class getColumnClass(int columnIndex) {
return types [columnIndex];
}
});
jScrollPane1.setViewportView(tabela);
save.setText("salvar");
save.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
saveActionPerformed(evt);
}
});
excluir.setText("Excluir");
excluir.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
excluirActionPerformed(evt);
}
});
jButton4.setText("Atualizar");
jButton4.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton4ActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jButton1)
.addGap(0, 0, Short.MAX_VALUE))
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 813, Short.MAX_VALUE)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jButton4)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(excluir)
.addGap(18, 18, 18)
.addComponent(save)
.addGap(23, 23, 23))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jButton1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 490, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jButton4)
.addComponent(excluir)
.addComponent(save))
.addContainerGap())
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
new ConsMenu().setVisible(true);
dispose();
// TODO add your handling code here:
}//GEN-LAST:event_jButton1ActionPerformed
private void saveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_saveActionPerformed
salvar b = new salvar();
int linha = tabela.getEditingRow();
int coluna = tabela.getEditingColumn();
String frase="";
Object str;
String a,doc,valor,arquivo;
int z,n;
b.lerquantP();
z=b.quantidadeProf-1;
System.out.println(z);
for(int x=0;x<=z;x++){
for(int y=0;y<=8;y++){
System.out.println("For y");
str=tabela.getValueAt(x,y);
System.out.println("Objeto:"+str);
a=(String)str;
System.out.println(a);
frase=frase+a+";";
}
System.out.println(frase);
doc=Integer.toString(x+1);
arquivo=doc+"prof.txt";
b.gravar(arquivo,frase);
frase="";
}
JOptionPane.showMessageDialog(null,"Dados modificados com sucesso!");
}//GEN-LAST:event_saveActionPerformed
private void excluirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_excluirActionPerformed
int linha=tabela.getSelectedRow();
System.out.println("linha:"+linha);
salvar b = new salvar();
b.lerquantP();
int z=b.quantidadeProf-1;
String frase,arquivo,arquivo1;
for(int x=(linha);x<z;x++){
arquivo=Integer.toString(x+2)+"prof.txt";
frase=Arquivo.Read(arquivo);
arquivo1=Integer.toString(x+1)+"prof.txt";
Arquivo.Write(arquivo1,frase);
}
b.quantidadeProf=b.quantidadeProf-1;
String str;
str=Integer.toString(b.quantidadeProf);
Arquivo.Write("quantP.txt", str);
dispose();
new ConsProf().setVisible(true);
}//GEN-LAST:event_excluirActionPerformed
private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton4ActionPerformed
dispose();
new ConsProf().setVisible(true);
}//GEN-LAST:event_jButton4ActionPerformed
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(ConsProf.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(ConsProf.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(ConsProf.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(ConsProf.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new ConsProf().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton excluir;
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton4;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JButton save;
private javax.swing.JTable tabela;
// End of variables declaration//GEN-END:variables
}
| true
|
1dc6d95bb51f120f6034c7bcbac12b1b07de5da3
|
Java
|
D-Inc/EnderIO
|
/src/main/java/crazypants/enderio/item/darksteel/upgrade/IDarkSteelUpgrade.java
|
UTF-8
| 622
| 1.921875
| 2
|
[
"Unlicense",
"CC-BY-3.0",
"LicenseRef-scancode-public-domain",
"CC0-1.0"
] |
permissive
|
package crazypants.enderio.item.darksteel.upgrade;
import com.enderio.core.api.client.gui.IAdvancedTooltipProvider;
import crazypants.enderio.item.IHasPlayerRenderer;
import net.minecraft.item.ItemStack;
public interface IDarkSteelUpgrade extends IAdvancedTooltipProvider, IHasPlayerRenderer {
String getUnlocalizedName();
int getLevelCost();
boolean isUpgradeItem(ItemStack stack);
boolean canAddToItem(ItemStack stack);
boolean hasUpgrade(ItemStack stack);
void writeToItem(ItemStack stack);
void removeFromItem(ItemStack stack);
ItemStack getUpgradeItem();
String getUpgradeItemName();
}
| true
|
116b6a3fd1dedd70b5687a5bc7afeec4440e3fa1
|
Java
|
treejames/com.neteast
|
/VideoTV/VideoTV/src/com/neteast/videotv/bean/Record.java
|
UTF-8
| 3,590
| 2.34375
| 2
|
[] |
no_license
|
package com.neteast.videotv.bean;
import android.text.TextUtils;
import com.google.common.collect.Lists;
import com.neteast.lib.bean.StreamingMediaRaw;
import com.neteast.lib.bean.VideoDetailRaw;
import com.neteast.lib.bean.VideoInfoRaw;
import java.util.List;
/**
* Created with IntelliJ IDEA.
* User: emellend
* Date: 13-8-20
* Time: 上午10:29
*/
public class Record extends MultiCountVideo {
Record(VideoDetailRaw rawData) {
super(rawData);
}
@Override
protected void setBaseInfo(VideoInfoRaw videoInfo) {
baseInfo = Lists.newArrayList();
baseInfo.add(safeGetBaseInfo("类型:",videoInfo.getDrama() ));
baseInfo.add(safeGetBaseInfo("地区:",videoInfo.getAreaName() ));
baseInfo.add(safeGetBaseInfo("年份:",videoInfo.getPublishAge() ));
baseInfo.add(safeGetBaseInfo("片长:",videoInfo.getTimeSpan() )+"分钟");
}
private boolean completed;
@Override
public void setTitle(String originTitle) {
StreamingMediaRaw.MediaRaw lastestMedia = getLastestMedia();
if (lastestMedia!=null &&!TextUtils.isEmpty(lastestMedia.getSeries())){
if (videoInfo.getCount()>0){
try {
Integer reallyCount = Integer.valueOf(lastestMedia.getSeries());
if (reallyCount==videoInfo.getCount()){
completed=true;
this.title=originTitle+"(全集)";
return;
}
}catch (NumberFormatException e){}
}
this.title=originTitle+"(更新至"+lastestMedia.getSeries()+"集)";
}else {
this.title=originTitle;
}
}
@Override
public StreamingMediaRaw.MediaRaw getLastestMedia() {
String origin = getCurrentOrigin();
if (origin==null){
return null;
}
List<String> pageTitles = getPageTitles(origin);
List<StreamingMediaRaw.MediaRaw> medias;
if (pageTitles==null||pageTitles.size()==0) {
medias=getMedias(origin, null);
}else {
String pageTitle = pageTitles.get(pageTitles.size() - 1);
medias=getMedias(origin, pageTitle);
}
if (medias==null || medias.size()==0){
return null;
}
return medias.get(medias.size()-1);
}
@Override
public String getPlayButtonText() {
if (completed && getFirstMedia()!=null){
return "第"+getFirstMedia().getSeries()+"集";
}
return super.getPlayButtonText(); //To change body of overridden methods use File | Settings | File Templates.
}
@Override
public StreamingMediaRaw.MediaRaw getDefaultPlayMedia() {
if (completed){
return getFirstMedia();
}
return super.getDefaultPlayMedia(); //To change body of overridden methods use File | Settings | File Templates.
}
private StreamingMediaRaw.MediaRaw getFirstMedia() {
String origin = getCurrentOrigin();
if (origin==null){
return null;
}
List<String> pageTitles = getPageTitles(origin);
List<StreamingMediaRaw.MediaRaw> medias;
if (pageTitles==null||pageTitles.size()==0) {
medias=getMedias(origin, null);
}else {
String pageTitle = pageTitles.get(0);
medias=getMedias(origin, pageTitle);
}
if (medias==null || medias.size()==0){
return null;
}
return medias.get(0);
}
}
| true
|
a175eb1d17a7dc2aa3542a43223cfe712855a428
|
Java
|
paulohgama/AulasIA
|
/src/Semana09/ClassficadorBayes.java
|
UTF-8
| 2,472
| 3.140625
| 3
|
[] |
no_license
|
package Semana09;
import weka.classifiers.bayes.NaiveBayes;
import weka.core.DenseInstance;
import weka.core.Instance;
import weka.core.Instances;
import weka.core.converters.ConverterUtils.DataSource;
/**
* @author Paulo Henrique
*/
public class ClassficadorBayes {
public static void main(String[] args) throws Exception {
DataSource arff = new DataSource("data/contact-lenses.arff");
Instances lenses = arff.getDataSet();
lenses.setClassIndex(4);
NaiveBayes bayes = new NaiveBayes();
bayes.buildClassifier(lenses);
/*
{presbyopic,myope,no,reduced,?}
{presbyopic,hypermetrope,no,normal,?}
{young,hypermetrope,yes,normal,?}
*/
//System.out.print(bayes);
Instance desconhecido1 = new DenseInstance(5);
Instance desconhecido2 = new DenseInstance(5);
Instance desconhecido3 = new DenseInstance(5);
desconhecido1.setDataset(lenses);
desconhecido2.setDataset(lenses);
desconhecido3.setDataset(lenses);
desconhecido1.setValue(0, "presbyopic");
desconhecido1.setValue(1, "myope");
desconhecido1.setValue(2, "no");
desconhecido1.setValue(3, "reduced");
desconhecido2.setValue(0, "presbyopic");
desconhecido2.setValue(1, "hypermetrope");
desconhecido2.setValue(2, "no");
desconhecido2.setValue(3, "normal");
desconhecido3.setValue(0, "young");
desconhecido3.setValue(1, "hypermetrope");
desconhecido3.setValue(2, "yes");
desconhecido3.setValue(3, "normal");
double classe1 = bayes.classifyInstance(desconhecido1);
double classe2 = bayes.classifyInstance(desconhecido2);
double classe3 = bayes.classifyInstance(desconhecido3);
System.out.println("Grupo do 1: " + classe1);
System.out.println("Grupo do 2: " + classe2);
System.out.println("Grupo do 3: " + classe3);
desconhecido1.setClassValue(classe1);
desconhecido2.setClassValue(classe2);
desconhecido3.setClassValue(classe3);
System.out.println("Rotulo do 1: " + desconhecido1.stringValue(4));
System.out.println("Rotulo do 2: " + desconhecido2.stringValue(4));
System.out.println("Rotulo do 3: " + desconhecido3.stringValue(4));
}
}
| true
|
87bd4f86e84489d7419af8d336af8cef1773d5f4
|
Java
|
procrastinatingVariable/CoffeeTracker
|
/app/src/main/java/ro/fmi/ip/trei/coffeetracker/PVTTest.java
|
UTF-8
| 6,006
| 2.375
| 2
|
[] |
no_license
|
package ro.fmi.ip.trei.coffeetracker;
import android.app.Activity;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.Random;
/**
* An example full-screen activity that shows and hides the system UI (i.e.
* status bar and navigation/system bar) with user interaction.
*/
public class PVTTest extends AppCompatActivity {
private static class MyHandler extends Handler {}
private final MyHandler mHandler = new MyHandler();
public static class MyRunnable implements Runnable {
private final WeakReference<Activity> mActivity;
public MyRunnable(Activity activity) {
mActivity = new WeakReference<>(activity);
}
@Override
public void run() {
Activity activity = mActivity.get();
if (activity != null) {
}
}
}
public static class WaitForDot extends AsyncTask<Integer, Void, Void> {
@Override
protected void onPostExecute(Void aVoid) {
if(testPicat) {
cron = new MyChronometer(context);
imagine.get().setVisibility(View.VISIBLE);
cron.start();
this.ecran.get().setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
stopCron();
if (numarTeste.getNumarTeste() < 2 ) {
restart.get().setText("Urmatorul test.");
} else {
restart.get().setText("Inchide.");
}
restart.get().setEnabled(true);
}
});
}
}
WeakReference<View> imagine;
WeakReference<TextView> text;
WeakReference<View> ecran;
WeakReference<Button> restart;
WeakReference<ArrayList<Double>> scoreKeeper;
private Context context;
private MyChronometer cron;
private boolean testPicat;
private NumaratorTeste numarTeste;
public void stopCron(){
if(cron != null) {
cron.stop();
Double score = new Double(cron.msElapsed);
this.scoreKeeper.get().add(score);
double sumaScoruri = 0;
for (Double scor : scoreKeeper.get()) {
sumaScoruri += scor ;
}
//(double) cron.msElapsed / 1000
this.text.get().setText(String.format("%.4f" ,sumaScoruri / scoreKeeper.get().size() / 1000) + " secunde.");
}
}
@Override
protected Void doInBackground(Integer... integers) {
try {
testPicat = true;
ecran.get().setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
testPicat = false;
text.get().setText("Trebuie apasat dupa ce apare bulina.");
restart.get().setText("RESTART !!!");
restart.get().setEnabled(true);
}
});
if(testPicat) {
Thread.sleep(integers[0]);
}
}
catch (Exception e){
}
return null;
}
public WaitForDot(View ecran, TextView text, View imagine, Button restart, NumaratorTeste numarTeste, ArrayList<Double> scoreKeeper, Context context) {
this.ecran = new WeakReference<>(ecran);
this.text = new WeakReference<>(text);
this.imagine = new WeakReference<>(imagine);
this.restart = new WeakReference<>(restart);
this.scoreKeeper = new WeakReference<>(scoreKeeper);
this.context = context;
this.numarTeste = numarTeste;
}
}
private final int numarMaximDeSecunde = 5000;
private final int numarMinimDeSecunde = 3000;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pvttest);
final ImageView imagine = findViewById(R.id.yellow_dot);
final TextView text = findViewById(R.id.text);
final View ecran = findViewById(R.id.ecran);
final Button restart = findViewById(R.id.restart);
final NumaratorTeste numaratorTeste = new NumaratorTeste();
final ArrayList<Double> scoreKeeper = new ArrayList<>();
Random r = new Random();
final int milis = r.nextInt(numarMaximDeSecunde - numarMinimDeSecunde) + numarMinimDeSecunde;
WaitForDot wFD = new WaitForDot(ecran, text, imagine, restart, numaratorTeste, scoreKeeper, getApplicationContext());
restart.setEnabled(false);
restart.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
imagine.setVisibility(View.INVISIBLE);
text.setText("");
restart.setEnabled(false);
if (restart.getText().equals("Urmatorul test.")){
numaratorTeste.setNumarTeste(numaratorTeste.getNumarTeste() + 1);
}
if (restart.getText().equals("Inchide.") && scoreKeeper.size() == 3) {
finish();
}
WaitForDot newForDotWaiter = new WaitForDot(ecran, text , imagine, restart, numaratorTeste, scoreKeeper, getApplicationContext());
newForDotWaiter.execute(milis);
}
});
wFD.execute(milis);
}
}
| true
|
0f987405915f8d6e395ebcfaef9b45e10b5c5eff
|
Java
|
felowchu/codepractice
|
/src/Chorus.java
|
UTF-8
| 1,292
| 3.0625
| 3
|
[] |
no_license
|
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Chorus {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while (sc.hasNext()) {
int n = sc.nextInt();
int[] high = new int[n];
for (int i = 0; i < n; i++) {
high[i] = sc.nextInt();
}
int[] dp = new int[n];
for (int i = 0; i < n; i++) {
dp[i] = 1;
for (int j = 0; j < i; j++) {
if (high[i] > high[j] && dp[j] >= dp[i]) {
dp[i] = dp[j] + 1;
}
}
}
int[] db = new int[n];
for (int i = n - 1; i >= 0; i--) {
db[i] = 1;
for (int j = n - 1; j > i; j--) {
if (high[i] > high[j] && db[j] >= db[i]) {
db[i] = db[j] + 1;
}
}
}
int max = Integer.MIN_VALUE;
for (int i = 0; i < n; i++) {
if (dp[i] + db[i] - 1 > max) {
max = dp[i] + db[i] - 1;
}
}
System.out.println(n - max);
}
}
}
| true
|
003a50297194027f8fef97e2d960de95e5448fa4
|
Java
|
kdivml/testers
|
/src/main/java/hu/idomsoft/testers/ui/MainLayout.java
|
UTF-8
| 3,458
| 2.0625
| 2
|
[
"Unlicense"
] |
permissive
|
package hu.idomsoft.testers.ui;
import org.springframework.security.core.context.SecurityContextHolder;
import com.vaadin.flow.component.UI;
import com.vaadin.flow.component.applayout.AppLayout;
import com.vaadin.flow.component.applayout.DrawerToggle;
import com.vaadin.flow.component.button.Button;
import com.vaadin.flow.component.dependency.CssImport;
import com.vaadin.flow.component.html.H1;
import com.vaadin.flow.component.icon.VaadinIcon;
import com.vaadin.flow.component.orderedlayout.HorizontalLayout;
import com.vaadin.flow.component.orderedlayout.VerticalLayout;
import com.vaadin.flow.theme.Theme;
import com.vaadin.flow.theme.lumo.Lumo;
import com.vaadin.flow.component.orderedlayout.FlexComponent;
import com.vaadin.flow.component.orderedlayout.FlexComponent.Alignment;
import hu.idomsoft.testers.ui.views.basedata.BaseDataListView;
import hu.idomsoft.testers.ui.views.overviewlist.OverviewListView;
import hu.idomsoft.testers.ui.views.prefix.PrefixView;
import hu.idomsoft.testers.ui.views.systemtree.SystemTreeView;
@CssImport("./styles/shared-styles.css")
@Theme(value = Lumo.class, variant = Lumo.DARK)
public class MainLayout extends AppLayout {
public MainLayout() {
createHeader();
createDrawer();
}
private void createHeader() {
H1 logo = new H1("Testers");
logo.addClassName("logo");
Button logoutButton = new Button("Kijelentkezés",VaadinIcon.SIGN_OUT.create(), e -> logout());
HorizontalLayout header = new HorizontalLayout(new DrawerToggle(), logo, logoutButton);
header.addClassName("header");
header.setWidth("100%");
header.expand(logo);
header.setDefaultVerticalComponentAlignment(FlexComponent.Alignment.CENTER);
addToNavbar(header);
}
private void createDrawer() {
VerticalLayout drawerLayout = new VerticalLayout();
drawerLayout.setPadding(false);
drawerLayout.setSpacing(false);
drawerLayout.setSizeFull();
drawerLayout.setAlignItems(Alignment.START);
drawerLayout.addClassName("drawer");
H1 categoryModificationsTitle = new H1("Módosítások");
categoryModificationsTitle.addClassName("menu-category-title");
Button systemTreeViewButton = new Button("Alrendszer - Tesztelő, BaseData");
systemTreeViewButton.setWidthFull();
systemTreeViewButton.addClickListener( click -> UI.getCurrent().navigate(SystemTreeView.class));
Button baseDataButton = new Button("BaseData kezelés");
baseDataButton.setWidthFull();
baseDataButton.addClickListener( click -> UI.getCurrent().navigate(BaseDataListView.class));
Button prefixLinkingButton = new Button("BaseData - Prefix");
prefixLinkingButton.setWidthFull();
prefixLinkingButton.addClickListener( click -> UI.getCurrent().navigate(PrefixView.class));
H1 categoryListsTitle = new H1("Listák");
categoryListsTitle.addClassName("menu-category-title");
Button overviewButton = new Button("Áttekintés");
overviewButton.setWidthFull();
overviewButton.addClickListener( click -> UI.getCurrent().navigate(OverviewListView.class));
drawerLayout.add(
categoryModificationsTitle,
systemTreeViewButton,
baseDataButton,
prefixLinkingButton,
categoryListsTitle,
overviewButton
);
addToDrawer(drawerLayout);
}
private void logout() {
SecurityContextHolder.clearContext();
UI.getCurrent().getSession().close();
UI.getCurrent().getPage().reload();
}
}
| true
|
8303175f5d624fa5b92b0028e1ea57188b3675fd
|
Java
|
zhuzhangli/robotTwo
|
/org.xjtusicd3.partner/src/main/java/org/xjtusicd3/partner/view/Faq1_ClassifyView.java
|
UTF-8
| 1,123
| 2
| 2
|
[] |
no_license
|
package org.xjtusicd3.partner.view;
import java.util.List;
import org.xjtusicd3.database.model.ClassifyPersistence;
public class Faq1_ClassifyView {
private String ClassifyId;
private String ClassifyName;
private Faq1_faqContentView content;
private List<Faq1_faqContentView> content2;
public String getClassifyId() {
return ClassifyId;
}
public void setClassifyId(String classifyId) {
ClassifyId = classifyId;
}
public String getClassifyName() {
return ClassifyName;
}
public void setClassifyName(String classifyName) {
ClassifyName = classifyName;
}
public Faq1_faqContentView getContent() {
return content;
}
public void setContent(Faq1_faqContentView faq1View) {
this.content = faq1View;
}
public List<Faq1_faqContentView> getContent2() {
return content2;
}
public void setContent2(List<Faq1_faqContentView> content2) {
this.content2 = content2;
}
public Faq1_ClassifyView(ClassifyPersistence classifyPersistence){
this.ClassifyId = classifyPersistence.getFAQCLASSIFYID();
this.ClassifyName = classifyPersistence.getFAQCLASSIFYNAME();
}
public Faq1_ClassifyView(){
}
}
| true
|
9058ead2cc443c558ff00013cfcf2231c46cbb1c
|
Java
|
Daniel-BG/Topography-Solver
|
/src/com/toposhort/terreno/GeneradorTerreno.java
|
UTF-8
| 3,705
| 2.828125
| 3
|
[] |
no_license
|
package com.toposhort.terreno;
import java.util.ArrayList;
import java.util.Random;
import com.toposhort.estructuras.Coordenada;
public class GeneradorTerreno {
public static Float[][] generadorDiamante(DatosGenerador dg) {
//comparamos que las alturas sean coherentes
assert dg.getAlturaMaxima() >= dg.getAlturaMinima() : "Las alturas máxima debe ser mayor que la mínima";
//comparamos que el desplazamiento base sea positivo
assert dg.getDesplazamientoBase() >= 0: "El desplazamiento base debe ser positivo";
//miramos que las dimensiones sean lo suficientemente grandes
assert dg.getAnchuraMapa() > 1 && dg.getAlturaMapa() > 1 && dg.getDesplazamientoBase() >= 0: "Dimensión muy pequeña o negativa";
Float[][] mapa = new Float[dg.getAnchuraMapa()][dg.getAlturaMapa()];
int diferencia = dg.getAlturaMaxima()-dg.getAlturaMinima()+1;
Random aleatorio = new Random(dg.getSemilla());
//iniciamos las cuatro esquinas para el algoritmo del diamante
mapa[0][0] = (float) (aleatorio.nextInt(diferencia)+dg.getAlturaMinima());
mapa[dg.getAnchuraMapa()-1][0] =(float) (aleatorio.nextInt(diferencia)+dg.getAlturaMinima());
mapa[0][dg.getAlturaMapa()-1] = (float) (aleatorio.nextInt(diferencia)+dg.getAlturaMinima());
mapa[dg.getAnchuraMapa()-1][dg.getAlturaMapa()-1] = (float) (aleatorio.nextInt(diferencia)+dg.getAlturaMinima());
InformadorTerreno info = new InformadorTerreno(
new Coordenada(0,0), new Coordenada(dg.getAnchuraMapa()-1,dg.getAlturaMapa()-1),
0, dg.getDesplazamientoBase(), dg.getReductor());
siguienteIteracion(info, aleatorio,mapa);
return mapa;
}
private static void siguienteIteracion(InformadorTerreno info, Random r, Float[][] mapa) {
if (info.comienzo.noExistenPuntosEntre(info.termino))
return;
//vemos los nodos de las esquinas. la primera letra indica si es inferior(i) o superior(s)
//y la segunda si es izquierdo (I) o derecho (D)
Coordenada centro = new Coordenada((info.termino.x+info.comienzo.x)/2,(info.termino.y+info.comienzo.y)/2);
Float iI = mapa[info.comienzo.x][info.comienzo.y];
Float iD = mapa[info.termino.x][info.comienzo.y];
Float sI = mapa[info.comienzo.x][info.termino.y];
Float sD = mapa[info.termino.x][info.termino.y];
if (mapa[info.comienzo.x][centro.y] == null)
mapa[info.comienzo.x][centro.y] = info.reductor.reduceDos(iI,sI,info,r);
if (mapa[centro.x][info.comienzo.y] == null)
mapa[centro.x][info.comienzo.y] = info.reductor.reduceDos(iI,iD,info,r);
if (mapa[info.termino.x][centro.y] == null)
mapa[info.termino.x][centro.y] = info.reductor.reduceDos(iD,sD,info,r);
if (mapa[centro.x][info.termino.y] == null)
mapa[centro.x][info.termino.y] = info.reductor.reduceDos(sI,sD,info,r);
if (mapa[centro.x][centro.y] == null) {
ArrayList<Float> lista = new ArrayList<Float>();
lista.add(mapa[info.comienzo.x][centro.y]);
lista.add(mapa[centro.x][info.comienzo.y]);
lista.add(mapa[info.termino.x][centro.y]);
lista.add(mapa[centro.x][info.termino.y]);
mapa[centro.x][centro.y] = info.reductor.reduceMultiple(lista,info,r);
}
siguienteIteracion(info.derivaTermino(centro).siguienteIt(),r,mapa);
siguienteIteracion(info.derivaComienzo(centro).siguienteIt(),r,mapa);
siguienteIteracion(info.derivaComienzo(new Coordenada(centro.x,info.comienzo.y))
.derivaTermino(new Coordenada(info.termino.x,centro.y))
.siguienteIt(),r,mapa);
siguienteIteracion(info.derivaComienzo(new Coordenada(info.comienzo.x,centro.y))
.derivaTermino(new Coordenada(centro.x,info.termino.y))
.siguienteIt(),r,mapa);
}
}
| true
|
ad6b3c0da16513df03b119a370cb929adeaf7c84
|
Java
|
Camptalk08/EConnection
|
/src/test/java/com/example/econnect/service/impl/ConnectionRequestServiceTest.java
|
UTF-8
| 3,294
| 2.15625
| 2
|
[] |
no_license
|
package com.example.econnect.service.impl;
import java.util.Optional;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.junit.MockitoJUnitRunner;
import com.example.econnect.dto.ConnectionRequestDTO;
import com.example.econnect.dto.ResponseDTO;
import com.example.econnect.entity.Connection;
import com.example.econnect.entity.Subscriber;
import com.example.econnect.exception.ConnectionRequestException;
import com.example.econnect.repository.ConnectionRepository;
import com.example.econnect.repository.SubscriberRepository;
@RunWith(MockitoJUnitRunner.class)
public class ConnectionRequestServiceTest {
@Mock
SubscriberRepository subscriberRepository;
@Mock
ConnectionRepository connectionRepository;
@InjectMocks
ConnectionServiceImpl connectionServiceImpl;
Subscriber subscriber;
Connection connection;
ConnectionRequestDTO connectionRequestDTO;
ResponseDTO responseDTO;
@Before
public void setup() {
subscriber = new Subscriber();
subscriber.setAdharcardNumber("1234");
subscriber.setAge(26);
subscriber.setAlernateMobileNumber(90L);
subscriber.setEmail("shiva@email.com");
subscriber.setGender("Male");
subscriber.setName("shiva");
subscriber.setPassword("shiva@123");
subscriber.setSubcriberId(1);
connection = new Connection();
connection.setMobileNumberId(1);
connection.setTalkTimeId(1);
connection.setRemarks("");
connection.setStatus("Inprogress");
connectionRequestDTO = new ConnectionRequestDTO();
connectionRequestDTO.setAdharcardNumber("1234");
connectionRequestDTO.setAge(26);
connectionRequestDTO.setAlternateMobileNumber(9030853295L);
connectionRequestDTO.setEmail("shiva@email.com");
connectionRequestDTO.setGender("Male");
connectionRequestDTO.setName("shiva");
connectionRequestDTO.setPassword("shiva@123");
}
@Test
public void connectionRequestTest() {
Mockito.when(subscriberRepository.save(Mockito.any())).thenReturn(subscriber);
Mockito.when(connectionRepository.save(Mockito.any())).thenReturn(connection);
Optional<ResponseDTO> responseDTO = connectionServiceImpl.connectionRequest(connectionRequestDTO, 1, 1);
Assert.assertNotNull(responseDTO);
}
@Test(expected = ConnectionRequestException.class)
public void invalidEmailTest() {
connectionRequestDTO.setEmail("shiva.com");
connectionServiceImpl.connectionRequest(connectionRequestDTO, 1, 1);
}
@Test(expected = ConnectionRequestException.class)
public void invalidPhoneTest() {
connectionRequestDTO.setAlternateMobileNumber(90L);
connectionServiceImpl.connectionRequest(connectionRequestDTO, 1, 1);
}
@Test(expected = ConnectionRequestException.class)
public void userAlreadyExistsTest() {
Mockito.when(subscriberRepository.findByEmail(connectionRequestDTO.getEmail()))
.thenReturn(Optional.of(subscriber));
connectionServiceImpl.connectionRequest(connectionRequestDTO, 1, 1);
}
@Test(expected = ConnectionRequestException.class)
public void connectionNotAvailableTest() {
Mockito.when(connectionRepository.findByMobileNumberId(1)).thenReturn(Optional.of(connection));
connectionServiceImpl.connectionRequest(connectionRequestDTO, 1, 1);
}
}
| true
|
5e0bf0089f06e986853135f623ea3b07c81e2212
|
Java
|
sewlesew/Observer-Design-Pattern-_-GUI-demo-
|
/Client.java
|
UTF-8
| 3,826
| 2.96875
| 3
|
[] |
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 Observer;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.Box;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
/**
*
* @author USER
*/
public class Client extends JFrame implements ActionListener{
JPanel contents;
JTextField addText,removeText;
JButton addBut,removeBut;
Box vbox;
Box hbox,hbox2;
JPanel northPanel;
JTextArea textarea;
Subject subject;
Observer observer;
JLabel label;
public Client(){
contents=new JPanel();
contents.setLayout(new BorderLayout());
this.add(contents);
vbox=Box.createVerticalBox();
hbox=Box.createHorizontalBox();
hbox2=Box.createHorizontalBox();
addBut=new JButton("Add");
removeBut=new JButton("Remove");
Dimension addButDim=removeBut.getPreferredSize();
addBut.setPreferredSize(addButDim);
addText=new JTextField(10);
removeText=new JTextField(10);
hbox.add(addText);
hbox.add(addBut);
hbox.setAlignmentX(LEFT_ALIGNMENT);
hbox2.add(removeText);
hbox2.add(removeBut);
hbox2.setAlignmentX(LEFT_ALIGNMENT);
vbox.add(hbox);
vbox.add(hbox2);
northPanel=new JPanel();
northPanel.add(vbox);
textarea=new JTextArea(20,20);
northPanel.add(textarea);
label=new JLabel("Observer Design Pattern",SwingConstants.CENTER);
label.setFont(new Font(Font.DIALOG,Font.BOLD,19));
contents.add(label,BorderLayout.NORTH);
contents.add(northPanel,BorderLayout.CENTER);
subject=new Subject();
observer=new Observer(subject);
addBut.addActionListener(this);
removeBut.addActionListener(this);
setSize(500,400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setResizable(false);
setVisible(true);
}
public static void main(String[] args){
new Client();
}
@Override
public void actionPerformed(ActionEvent ae) {
Object source=ae.getSource();
if(source==addBut){
String takeText=addText.getText();
subject.setNames(takeText);
String allNames="";
for(String str:observer.getNames()){
allNames+=str+"\n";
}
addText.setText("");
textarea.setText(allNames);
return;
}
if(source==removeBut){
String removedText=removeText.getText();
subject.removeName(removedText);
String allNames="";
for(String str:observer.getNames()){
allNames+=str+"\n";
}
removeText.setText("");
textarea.setText(allNames);
}
}
}
| true
|
8413f8f4709e08e4254d4e1284d127490d76b408
|
Java
|
luciaasen/padsof
|
/p3/moon/JuanRiera_LuciaAsencio/src/icfs/teacher/main/MainTeacherPanel.java
|
UTF-8
| 1,228
| 2.421875
| 2
|
[] |
no_license
|
/**
*
*/
package icfs.teacher.main;
import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.Container;
import javax.swing.*;
import icfs.*;
import icfs.teacher.create.AddCourseView;
import moon.Academy;
import moon.course.Course;
public class MainTeacherPanel extends JPanel{
private LowerPanel lower;
public MainTeacherPanel(){
SpringLayout layout = new SpringLayout();
this.setLayout(layout);
this.setPreferredSize(Academy.DIMENSION);
this.setVisible(true);
this.setBackground(Academy.ORANGE);
this.lower = new MainTeacherLower();
//this.lower = new AddCourseView();
layout.putConstraint(SpringLayout.EAST, lower, 0, SpringLayout.EAST, this);
layout.putConstraint(SpringLayout.WEST, lower, 0, SpringLayout.WEST, this);
//layout.putConstraint(SpringLayout.NORTH, lower, 0, SpringLayout.SOUTH, upper);
//layout.putConstraint(SpringLayout.NORTH, upper, 0, SpringLayout.NORTH, this);
layout.putConstraint(SpringLayout.SOUTH, lower, 0, SpringLayout.SOUTH, this);
//layout.putConstraint(SpringLayout.EAST, upper, 0, SpringLayout.EAST, this);
//layout.putConstraint(SpringLayout.WEST, upper, 0, SpringLayout.WEST, this);
//this.add(upper);
this.add(lower);
}
}
| true
|
d5323b86bb94bffe7d070ba5e739637402f2efdb
|
Java
|
UPenn-CIT599/final-project-team-50
|
/src/PlannerTest.java
|
UTF-8
| 2,744
| 3.09375
| 3
|
[] |
no_license
|
import static org.junit.jupiter.api.Assertions.*;
import java.util.ArrayList;
import java.util.HashMap;
import org.junit.jupiter.api.Test;
class PlannerTest {
@Test
void testGetFloor() {
Planner p = new Planner(9, 2, 2);
FloorPlan floor = p.getFloor();
int[][] floorArray = floor.getfloorPlan();
assertEquals(floorArray[0][0], 1);
}
@Test
void testGetExits() {
Planner p = new Planner(9, 2, 2);
Exit e = p.getExits();
int numberOnFloorForExit = 0;
for (int[] oneExit : e.getExitLocations()) {
int r = oneExit[0];
int c = oneExit[1];
numberOnFloorForExit = p.getFloor().getfloorPlan()[r][c];
assertEquals(numberOnFloorForExit, 2);
}
}
@Test
void testGetPeople() {
Planner p = new Planner(9, 2, 2);
ArrayList<Person> ppl = p.getPeople();
int numberOnFloorForPeople = 0;
for (Person per : ppl) {
int r = per.getInitialLocation()[0];
int c = per.getInitialLocation()[1];
numberOnFloorForPeople = p.getFloor().getfloorPlan()[r][c];
assertEquals(numberOnFloorForPeople, 3);
}
}
@Test
void testGetDistanceWithWall() {
Planner p = new Planner(9, 2, 2);
int[][] res = p.getFloor().getfloorPlan();
System.out.println("The floor looks like below at Time 0:");
for (int i = 0; i < res.length; ++i) {
for (int j = 0; j < res[i].length; ++j) {
if (res[i][j] == 0) {
System.out.print(" ");
} else {
System.out.print(res[i][j]);
}
}
System.out.println();
}
int[] oneExit = p.getExits().getExitLocations().get(0); // test the first exist
int r = oneExit[0];
int c = oneExit[1];
System.out.println("The location of exit A is: (" + r + "," + c + ")");
int[][] distanceGrid = p.getDistanceWithWall(oneExit);
System.out.println("The distance grid of exit A looks like: ");
for (int i = 0; i < distanceGrid.length; ++i) {
for (int j = 0; j < distanceGrid[i].length; ++j) {
System.out.printf("%d\t", distanceGrid[i][j]);
}
System.out.println();
}
ArrayList<Person> people = p.getPeople();
Person per = people.get(0); // test the first person
int h = per.getCurrentLocation()[0];
int l = per.getCurrentLocation()[1];
int[] closetExit = p.getClosetExit(per);
System.out.println("The closest exit for person at (" + h + "," + l + ") is the exit at (" + closetExit[0] + ","
+ closetExit[1] + ")");
}
@Test
void testGetClosetExit() {
Planner p = new Planner (9, 2, 2);
Person per = p.getPeople().get(0);
int[] closetExit = p.getClosetExit(per);
assertEquals(closetExit.length, 2);
}
@Test
void testClosetExit() {
Planner p = new Planner (9, 2, 2);
HashMap<Person, int[]> personToExitIndex = p.closestExit();
int size = personToExitIndex.size();
assertEquals(size, 2);
}
}
| true
|
e578eabf44c7faf4bcaf2b24b999172bb145cd9e
|
Java
|
Praveenkumarkonidena/MLP149
|
/practice/SuperMain.java
|
UTF-8
| 288
| 2.359375
| 2
|
[] |
no_license
|
public class SuperMain extends App{
public SuperMain() {
super();
}
public void display() {
super.show();
super.show1();
}
public static void main(String[] args){
SuperMain t = new SuperMain();
t.display();
}
}
| true
|
318342ce659bd5a9fb3e3faccd436bb06e3be4a3
|
Java
|
poornipanna/JSON_PARSING
|
/src/test/java/Example1.java
|
UTF-8
| 2,253
| 2.9375
| 3
|
[] |
no_license
|
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
public class Example1 {
public static void main(String[] args) {
JSONParser parser = new JSONParser();
try {
Object obj = parser.parse(new FileReader("example1.json"));
JSONObject jsonObject = (JSONObject) obj;
//write code here to parse the json
//print all the platforms
JSONArray platforms = (JSONArray)jsonObject.get("platforms");
JSONObject esrbRatingObject = (JSONObject) jsonObject.get("esrbRating");
Iterator<Object> iterator = platforms.iterator();
while(iterator.hasNext())
{
System.out.println("platform=" +iterator.next());
}
System.out.println("esrbRating, Code is =" +esrbRatingObject.get("code"));
/***************************************************************************************/
//Using Map List
List<Map<String, ?>>platformList = (List<Map<String, ?>>)jsonObject.get("platforms");
for(int i=0; i< platformList.size();i++)
{
System.out.print("Id " +platformList.get(i).get("id").toString());
System.out.print("Platform " +platformList.get(i).get("name").toString());
System.out.println("");
}
Map<String, ?> esrbRating = (Map<String, ?>)jsonObject.get("esrbRating");
System.out.println("Id " +esrbRating.get("id").toString());
System.out.println("Code " +esrbRating.get("code").toString());
System.out.println("Name " +esrbRating.get("name").toString());
System.out.println("");
/**************************************************************************************/
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (org.json.simple.parser.ParseException e) {
e.printStackTrace();
}
}
}
| true
|
c0e1eb376e3947cf8b89ed363d5f09ada4d2ab5f
|
Java
|
renchao1110/hl_demo_renchao
|
/src/com/hl95/sys/action/SysDeptRoleAction.java
|
UTF-8
| 3,468
| 1.828125
| 2
|
[] |
no_license
|
package com.hl95.sys.action;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.lang.StringUtils;
import org.hibernate.criterion.Order;
import org.pj.criterion.core.support.encryptPassword.EncryptPassword;
import org.pj.criterion.core.support.upload.UploadManager;
import org.pj.criterion.core.util.SearchModelUtil;
import org.pj.criterion.core.util.StringUtil;
import org.pj.framework.business.core.action.BusinessAction;
import org.pj.framework.business.support.SearchMode;
import org.pj.framework.business.web.session.UserInfo;
import org.pj.framework.business.web.session.UserSession;
import sun.misc.BASE64Decoder;
import com.hl95.sys.entity.SysAdmin;
import com.hl95.sys.entity.SysDepartment;
import com.hl95.sys.entity.SysDeptRole;
import com.hl95.sys.entity.SysEmployee;
import com.hl95.sys.entity.SysRole;
import com.hl95.sys.service.SysAdminService;
import com.hl95.sys.service.SysDepartmentService;
import com.hl95.sys.service.SysDeptRoleService;
import com.hl95.sys.service.SysEmployeeService;
import com.hl95.sys.service.SysRoleService;
import com.opensymphony.xwork.Action;
public class SysDeptRoleAction extends BusinessAction<SysDeptRole, SysDeptRoleService> {
/**
*
*/
private static final long serialVersionUID = 1L;
private SysDeptRole sysDeptRole;
private SysDeptRoleService sysDeptRoleService;
private SysRoleService sysRoleService;
public SysRoleService getSysRoleService() {
return sysRoleService;
}
public void setSysRoleService(SysRoleService sysRoleService) {
this.sysRoleService = sysRoleService;
}
public SysDeptRole getSysDeptRole() {
if (getProxyEntity() != null) {
return getProxyEntity();
}
return sysDeptRole;
}
public void setSysDeptRole(SysDeptRole sysDeptRole) {
this.sysDeptRole = sysDeptRole;
}
public SysDeptRoleService getSysDeptRoleService() {
return sysDeptRoleService;
}
public void setSysDeptRoleService(SysDeptRoleService sysDeptRoleService) {
this.sysDeptRoleService = sysDeptRoleService;
}
@Override
protected SysDeptRole getFromBean() {
// TODO Auto-generated method stub
return getSysDeptRole();
}
@Override
public void searchModelCallBack() {
// TODO Auto-generated method stub
}
public void ajaxRoleData(){
JSONArray arrayItems=new JSONArray();
try{
List<SysRole> list = this.sysRoleService.getSysRoleByUse();
//获取当前权限
List<SysDeptRole> dList = null;
try{
Long _deptId = Long.valueOf(StringUtils.defaultString(getParameter("_deptId")));
dList = this.sysDeptRoleService.getListByDeptId(_deptId);
}catch (Exception e) {
}
List<Long> lList = new ArrayList<Long>();
if(dList != null && dList.size() > 0){
for(SysDeptRole sdr:dList){
lList.add(sdr.getRoleId().getId());
}
}
if(list!=null){
int index=0;
for(SysRole obj:list){
JSONObject Item=new JSONObject();
Item.put("text", obj.getRoleNameZh());
Item.put("id", obj.getId());
Item.put("cls", "file");
Item.put("leaf", true);
Item.put("allowDrag", false);
Item.put("allowDrop", false);
Item.put("checked", lList.contains((long)obj.getId())?true:false);
arrayItems.add(Item);
index++;
}
}
}catch (Exception e) {
e.printStackTrace();
}
writeJsonByAction(arrayItems.toString());
}
}
| true
|
7523052deaeb027019a5a781c45e2fd0bdc168c2
|
Java
|
harshulfk/inventory-planner
|
/requirement/src/main/java/fk/retail/ip/requirement/internal/repository/JPAForecastRepository.java
|
UTF-8
| 1,146
| 2.078125
| 2
|
[] |
no_license
|
package fk.retail.ip.requirement.internal.repository;
import com.google.common.collect.Lists;
import com.google.inject.Inject;
import fk.retail.ip.requirement.internal.entities.Forecast;
import fk.retail.ip.requirement.internal.entities.Policy;
import fk.sp.common.extensions.jpa.SimpleJpaGenericRepository;
import java.util.List;
import java.util.Set;
import javax.inject.Provider;
import javax.persistence.EntityManager;
import javax.persistence.TypedQuery;
import org.apache.commons.collections4.CollectionUtils;
public class JPAForecastRepository extends SimpleJpaGenericRepository<Forecast, Long> implements ForecastRepository {
@Inject
public JPAForecastRepository(Provider<EntityManager> entityManagerProvider) {
super(entityManagerProvider);
}
@Override
public List<Forecast> fetchByFsns(Set<String> fsns) {
if (CollectionUtils.isEmpty(fsns)) {
return Lists.newArrayList();
}
TypedQuery<Forecast> query = getEntityManager().createNamedQuery("Forecast.fetchByFsns", Forecast.class);
query.setParameter("fsns", fsns);
return query.getResultList();
}
}
| true
|
1addbb071918fed4e46c7394b5ce251fd5341c55
|
Java
|
Shoneys/DataStructures_Spring_2019
|
/gaughan_project1/src/PostfixCalculator.java
|
UTF-8
| 1,743
| 3.484375
| 3
|
[] |
no_license
|
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class PostfixCalculator {
public static void main(String[] args) throws FileNotFoundException {
File file = new File("src/postfix_test.txt"); // searches for the postfix_test.txt in the same directory
Scanner fileScan = new Scanner(file); // fileScan loads the file
while (fileScan.hasNextLine()) {
String input = fileScan.nextLine();
if (!input.equals("")) {
System.out.println(postfixEvaluate(input));
}
}
}
private static int postfixEvaluate(String input) {
Stack s = new Stack<>();
Scanner lineScan = new Scanner(input);
while (lineScan.hasNext()) {
if (lineScan.hasNextInt()) {
s.push(lineScan.nextInt());
} else {
int n1 = (int) s.pop();
int n2 = (int) s.pop();
String op = lineScan.next();
switch (op) {
case "+":
s.push(n1 + n2);
break;
case "-":
s.push(n2 - n1);
break;
case "x":
s.push(n1 * n2);
break;
case "*":
s.push(n1 * n2);
break;
case "/":
s.push(n1 / n2);
break;
// case "p":
// s.push(Math.pow(n1, n2));
// break;
}
}
}
return (int) s.pop();
}
}
| true
|
a4e13d7de11a1302cd8dc00640820fa574183a4a
|
Java
|
LuoHaoYis/ZhuLongSociety_Project_day6_11
|
/frams/src/main/java/com/lhy/frams/LoadType.java
|
UTF-8
| 163
| 1.6875
| 2
|
[] |
no_license
|
package com.lhy.frams;
public class LoadType {
public static final int ONE=200;
public static final int TWO=520;
public static final int THREE=521;
}
| true
|
55b227e10e34306ff899156fcd73f00209169988
|
Java
|
pedrogonzalezgutierrez/spring-rest-jwt
|
/src/main/java/com/kiesoft/service/DTOService.java
|
UTF-8
| 275
| 1.8125
| 2
|
[] |
no_license
|
package com.kiesoft.service;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
public interface DTOService<EntityDTO> {
EntityDTO save(EntityDTO dto);
EntityDTO findOne(Long id);
Page<EntityDTO> findAll(Pageable page);
}
| true
|
7193d64c35425b1a3fd171f21a1f1f06fe4540b2
|
Java
|
zoolian/jmscottBE
|
/jmscott-API/src/main/java/com/jmscott/rest/repository/PasswordRepository.java
|
UTF-8
| 434
| 1.898438
| 2
|
[] |
no_license
|
package com.jmscott.rest.repository;
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.data.querydsl.QuerydslPredicateExecutor;
import org.springframework.stereotype.Repository;
import com.jmscott.rest.model.Password;
@Repository
public interface PasswordRepository extends MongoRepository<Password, String>, QuerydslPredicateExecutor<Password> {
Password findByUserId(String id);
}
| true
|
5f7c2ff3bc3ca6c2a536de7bf300fabe67ddbe98
|
Java
|
ViniciusArnhold/unisinos-chat
|
/client/src/main/java/br/unisinos/client/view/chat/UserCellFactory.java
|
UTF-8
| 1,768
| 2.734375
| 3
|
[] |
no_license
|
package br.unisinos.client.view.chat;
import br.unisinos.commom.User;
import javafx.geometry.Pos;
import javafx.scene.control.ListCell;
import javafx.scene.control.ListView;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.HBox;
import javafx.scene.text.Text;
import javafx.util.Callback;
/**
* @author Vinicius Pegorini Arnhold.
*/
public class UserCellFactory implements Callback<ListView<User>, ListCell<User>> {
/**
* The <code>call</code> method is called when required, and is given a
* single argument of type P, with a requirement that an object of type R
* is returned.
*
* @param param The single argument upon which the returned value should be
* determined.
* @return An object of type R that may be determined based on the provided
* parameter value.
*/
@Override
public ListCell<User> call(ListView<User> param) {
return new ListCell<User>() {
@Override
protected void updateItem(User user, boolean empty) {
super.updateItem(user, empty);
setGraphic(null);
setText(null);
if (user != null) {
Text name = new Text(user.getName());
Image image = new Image(getClass().getClassLoader().getResourceAsStream("image/annon-user.png"), 50, 50, true, true);
ImageView imageView = new ImageView(image);
imageView.setImage(image);
HBox hBox = new HBox();
hBox.getChildren().addAll(imageView, name);
hBox.setAlignment(Pos.CENTER_LEFT);
setGraphic(hBox);
}
}
};
}
}
| true
|
70142952ef1bd72080a3267b583d6d4d5e803c39
|
Java
|
underwindfall/Algorithme
|
/src/leetcode/algo/doubleindex/ReverseOnlyLetters917.java
|
UTF-8
| 750
| 3.59375
| 4
|
[] |
no_license
|
package leetcode.algo.doubleindex;
// https://leetcode-cn.com/problems/reverse-only-letters/
public class ReverseOnlyLetters917 {
//time O(n)
//space O(1)
public String reverseOnlyLetters(String s) {
int lo = 0, ho = s.length() - 1;
char[] ch = s.toCharArray();
while (lo < ho) {
while (lo < ho && !Character.isLetter(ch[lo])) {
lo++;
}
while (lo < ho && !Character.isLetter(ch[ho])) {
ho--;
}
swap(ch, lo, ho);
lo++;
ho--;
}
return new String(ch);
}
void swap(char[] arr, int i , int j) {
char tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
}
}
| true
|
37e6bd9491eeb9991eac1f73dc332b6824119f7e
|
Java
|
BinateStation/Pathrakkaran
|
/pathrakkaran/src/main/java/rkr/binatestation/pathrakkaran/modules/register/RegisterListeners.java
|
UTF-8
| 1,093
| 2.125
| 2
|
[] |
no_license
|
package rkr.binatestation.pathrakkaran.modules.register;
import android.content.Context;
/**
* Created by RKR on 10/12/2016.
* RegisterListeners.
*/
interface RegisterListeners {
interface ViewListener {
void nameFieldError(String errorMessage);
void phoneFieldError(String errorMessage);
void emailFieldError(String errorMessage);
void passwordFieldError(String errorMessage);
void confirmPassword(String errorMessage);
void finishRegistering();
void showProgress();
void hideProgress();
void showAlertDialog(String errorMessage);
}
interface PresenterListener {
void validateInputs(Context context, String name, String phoneNumber, String email, String password, String confirmPassword, int userType);
void registerSuccessfully();
void errorRegistering(String errorMessage);
}
interface InterActorListener {
void register(Context context, String name, String phoneNumber, String email, String password, int userTypeValue, String loginType);
}
}
| true
|
021b6bbd4d9ea958125e75ee1f7fff2de0db1d58
|
Java
|
ismailsirma/MicroserviceDemo
|
/market-consumer-microservice/src/main/java/com/sirmam/market/service/KafkaTradeListenerService.java
|
UTF-8
| 1,194
| 2.109375
| 2
|
[
"MIT"
] |
permissive
|
package com.sirmam.market.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Service;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.sirmam.market.events.TradeEvent;
@Service
public class KafkaTradeListenerService {
// event publish
@Autowired
private ApplicationEventPublisher eventPublisher;
@Autowired
private ObjectMapper mapper;
@KafkaListener(topics = "market")
public void listenTradeEvents(String trade) {
System.err.println("New trade event has arrived from kafka topic: " + trade);
try {
var tradeEvent = mapper.readValue(trade, TradeEvent.class);
eventPublisher.publishEvent(tradeEvent);
}
catch (JsonMappingException e) {
System.err.println("Error: " + e.getMessage());
} catch (JsonProcessingException e) {
System.err.println("Error: " + e.getMessage());
//e.printStackTrace();
}
}
}
| true
|
2556650283894db72064e3c06348411e3012a60f
|
Java
|
nathan1917-cmis/nathan1917-apcs-cmis
|
/StringsEquals/StringStuff.java
|
UTF-8
| 518
| 3.34375
| 3
|
[] |
no_license
|
import javax.swing.JOptionPane;
public class StringStuff
{
public static void main ( String[] args)
{
String password = JOptionPane.showInputDialog("What's the password?");
if (password.equals("There is no real super-sand"))
{
System.out.println("You must be the real magician");
}
else
{
System.out.println("Just no...");
}
} //end method main
}//end class StringStuff
| true
|
7c34ddc1a548b6801c41c9822dfbc718ae79f58d
|
Java
|
winksaville/android-BleTest1
|
/app/src/main/java/com/saville/wink/BleTest1/MainActivity.java
|
UTF-8
| 10,894
| 2.171875
| 2
|
[
"Apache-2.0",
"BSD-2-Clause"
] |
permissive
|
package com.saville.wink.BleTest1;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothManager;
import android.bluetooth.le.BluetoothLeScanner;
import android.bluetooth.le.ScanCallback;
import android.bluetooth.le.ScanResult;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Message;
import android.os.Messenger;
import android.view.Menu;
import android.view.MenuItem;
import android.util.Log;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends Activity {
private final static String TAG = "BleTest1";
private final static int REQUEST_ENABLE_BT = 1;
private final static int REQUEST_PERMISSIONS = 2;
private boolean mHasFeatureBle = false;
private boolean mBtLeSupported = false;
private boolean mBtAllowed = false;
private BluetoothManager mBtManager = null;
private BluetoothAdapter mBtAdapter = null;
private BluetoothLeScanner mBtScanner = null;
private BleSm1 mSm1 = null;
private BleScanSm mBleScanSm = null;
private void startScan() {
mBtScanner = mBtAdapter.getBluetoothLeScanner();
mMyScanCallBack = new MyScanCallback();
mBtScanner.startScan(mMyScanCallBack);
}
private void checkPermissions() {
Log.i(TAG, "checkPermissions:+");
ArrayList<String> permissionsNeeded = new ArrayList<>();
if (checkSelfPermission("android.permission.BLUETOOTH") ==
PackageManager.PERMISSION_DENIED) {
permissionsNeeded.add("android.permission.BLUETOOTH");
}
if (checkSelfPermission("android.permission.BLUETOOTH_ADMIN") ==
PackageManager.PERMISSION_DENIED) {
permissionsNeeded.add("android.permission.BLUETOOTH_ADMIN");
}
if (checkSelfPermission("android.permission.ACCESS_COARSE_LOCATION") ==
PackageManager.PERMISSION_DENIED) {
permissionsNeeded.add("android.permission.ACCESS_COARSE_LOCATION");
}
if (checkSelfPermission("android.permission.ACCESS_FINE_LOCATION") ==
PackageManager.PERMISSION_DENIED) {
permissionsNeeded.add("android.permission.ACCESS_FINE_LOCATION");
}
if (permissionsNeeded.size() > 0) {
Log.i(TAG, "checkPermissions: needed=" + permissionsNeeded);
mBtAllowed = false;
String[] permissionsNeededStringArray =
permissionsNeeded.toArray(new String[permissionsNeeded.size()]);
requestPermissions(permissionsNeededStringArray, REQUEST_PERMISSIONS);
} else {
mBtAllowed = true;
}
Log.i(TAG, "checkPermissions:-");
}
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions,
int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
Log.i(TAG, "onRequestPermissionsResult:+");
if (requestCode == REQUEST_PERMISSIONS) {
if (permissions.length == grantResults.length) {
int grantedCount = 0;
for (int i = 0; i < grantResults.length; i++) {
Log.i(TAG, String.format(
"onRequestPermissionsResult: %d:permission=%s grantResults=%d",
i, permissions[i], grantResults[i]));
if (grantResults[i] == PackageManager.PERMISSION_GRANTED) {
grantedCount += 1;
}
}
if (grantedCount != permissions.length) {
for (int i = 0; i < grantResults.length; i++) {
if (grantResults[i] == PackageManager.PERMISSION_DENIED) {
Log.i(TAG, String.format(
"onRequestPermissionsResult: permission:%s%sgranted",
permissions[i],
grantResults[i] == PackageManager.PERMISSION_DENIED ?
" not " : " "));
}
}
mBtAllowed = false;
showFatalToast("Permissions needed were denied");
} else {
mBtAllowed = true;
startScan();
}
} else {
Log.wtf(TAG, String.format("onRequestPermissionsResult: permissions.length:%d !=" +
"grantResults.length:%d", permissions.length, grantResults.length));
}
} else {
Log.i(TAG, "onRequestPermissionsResult: ignore unknown requestCode=" + requestCode);
}
Log.i(TAG, "onRequestPermissionsResult:-");
}
private void showFatalToast(String text) {
Toast toast = Toast.makeText(this, text, Toast.LENGTH_LONG);
toast.show();
finish();
}
/**
* OnCreate: Activity is created.
*
* @param savedInstanceState
*/
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.i(TAG, "onCreate:+");
mBleScanSm = BleScanSm.makeBleSm("mBleScanSm");
mSm1 = BleSm1.makeBleSm1("mSm1");
mSm1.sendMessage(BleSm1.ON_CREATE, mBleScanSm);
mHasFeatureBle = getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE);
Log.i(TAG, "onCreate: mHasFeatureBle=" + mHasFeatureBle);
if (mHasFeatureBle) {
Log.i(TAG, "onCreate: has Bluetooth LE");
mBtLeSupported = true;
mBtManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
mBtAdapter = mBtManager.getAdapter();
} else {
Log.i(TAG, "onCreate: NO Bluetooth LE");
showFatalToast("Device has no Bluetooth LE/smart feature");
}
setContentView(R.layout.activity_main);
Log.i(TAG, "onCreate:-");
}
@Override
protected void onResume() {
super.onResume();
Log.i(TAG, "onResume:+");
if (mBtLeSupported) {
if (!mBtAdapter.isEnabled()) {
Log.i(TAG, "onResume: bt is NOT enabled, request that it be enabled.");
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
} else if (!mBtAllowed) {
Log.i(TAG, "onResume: !mBtAllowed so checkPermissions");
checkPermissions();
} else {
Log.i(TAG, "onResume: bt is enabled and this app has appropriate permissions");
if (mBtAllowed) {
startScan();
} else {
Log.i(TAG, "onResume: BT is not allowed, at least not yet");
}
}
} else {
Log.i(TAG, "onResume: mBtLe is not supported");
}
Log.i(TAG, "onResume:-");
}
private MyScanCallback mMyScanCallBack;
class MyScanCallback extends ScanCallback {
public MyScanCallback() {
super();
}
@Override
public void onScanResult(int callbackType, ScanResult result) {
super.onScanResult(callbackType, result);
printScanResult("onScanResult", callbackType, result);
}
private void printScanResult(String onScanResult, int callbackType, ScanResult result) {
Log.i(TAG, onScanResult + " callbackType=" + callbackType + ": result=" + result.toString());
}
@Override
public void onBatchScanResults(List<ScanResult> results) {
super.onBatchScanResults(results);
for (ScanResult result : results) {
printScanResult("onBatchScanResults", -1 /*unused*/, result);
}
}
@Override
public void onScanFailed(int errorCode) {
super.onScanFailed(errorCode);
Log.i(TAG, "onScanFailed: errorCode=0x" + Integer.toHexString(errorCode));
}
}
/**
* A Result from startActivityForResult is being returned.
*
* @param requestCode
* @param resultCode
* @param data
*/
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_ENABLE_BT) {
if (resultCode == RESULT_OK) {
Log.i(TAG, "onActivityResult: requestCode=REQUEST_ENABLE_BT RESULT_OK");
} else {
Log.i(TAG, "onActivityResult: requestCode=REQUEST_ENABLE_BT error resultCode="
+ resultCode);
Toast.makeText(MainActivity.this,
"Bluetooth must be enabled for this app to function",
Toast.LENGTH_LONG).show();
finish();
}
} else {
Log.i(TAG, "onActivityResult: ignore unexpected requestCode=" + requestCode);
}
}
@Override
protected void onPause() {
super.onPause();
Log.i(TAG, "onPause:+");
if (mMyScanCallBack != null && mBtScanner != null) {
Log.i(TAG, "onPause: stopScan");
// BUG: For somereason this didn't stop the scanning!!
mBtScanner.stopScan(mMyScanCallBack);
}
Log.i(TAG, "mSm1: dump");
Log.i(TAG, mSm1.toString());
Log.i(TAG, "mBleScanSm: dump");
Log.i(TAG, mBleScanSm.toString());
Log.i(TAG, "onPause:-");
}
@Override
protected void onDestroy() {
super.onDestroy();
Log.i(TAG, "onDestroy");
// Do we need to "close" any of these?
mBtScanner = null;
mBtAdapter = null;
mBtManager = null;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
Log.i(TAG, "onCreateOptionsMenu");
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
Log.i(TAG, "onOptionsItemSelected: id=" + id);
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
| true
|
542e48229785be228f5ccd5832771d26e70dd878
|
Java
|
tparihar/myPrac
|
/Nprac/PreferredCustomer_NTS/src/main/com/ck/reward/controller/LoginController.java
|
UTF-8
| 2,612
| 2.71875
| 3
|
[] |
no_license
|
package com.ck.reward.controller;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import com.ck.reward.entities.Account;
import com.ck.reward.entities.Member;
import com.ck.reward.service.LoginService;
import com.ck.reward.service.MemberService;
/**
*
* @author Bootcamp User 03
* This controller handles login functionality
*/
public class LoginController extends HttpServlet {
private static final long serialVersionUID = 1L;
LoginService loginHandler;
MemberService memberInfoHandler;
public LoginController() {
loginHandler = new LoginService();
memberInfoHandler = new MemberService();
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
HttpSession sessionObj=request.getSession(false);
if(sessionObj.getAttribute("loggedIn")!=null && sessionObj.getAttribute("loggedIn").equals("true")){
response.sendRedirect(request.getContextPath() + "/jsp/account.jsp");
}else{
request.getRequestDispatcher("jsp/login.jsp").forward(request, response);
}
}
/**
* It takes user credentials and calls login and creates session if user
* successfully logins and redirects to account page or else redirects to
* login page.
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String username = request.getParameter("username");
String password = request.getParameter("password");
Account account = new Account();
account.setUserId(username);
account.setPassword(password);
try {
if (!loginHandler.login(account)) {
request.setAttribute("message", "Please try again");
request.getRequestDispatcher("jsp/login.jsp").forward(request, response);
} else {
HttpSession session = request.getSession(true);
session.setAttribute("loggedIn", "true");
System.out.println("account id:"+account.getId());
Member member = memberInfoHandler.getMemberDetail(account.getId());
System.out.println("memberinof"+member.getId());
session.setAttribute("member", member);
response.sendRedirect(request.getContextPath() + "/jsp/account.jsp");
}
} catch (Exception e) {
e.printStackTrace();
request.setAttribute("message", "Please try again later");
request.getRequestDispatcher("jsp/login.jsp").forward(request, response);
}
}
}
| true
|
804a5202ce905ba615baee45f7191fd6127fe693
|
Java
|
ChaitraPrakash/Toys
|
/ToysBackend/src/main/java/com/niit/ToysBackend/model/Supplier.java
|
UTF-8
| 1,311
| 2.359375
| 2
|
[] |
no_license
|
package com.niit.ToysBackend.model;
import java.util.List;
import java.util.UUID;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import org.springframework.stereotype.Component;
@Entity
@Table
@Component
public class Supplier {
@Id
private String supplierId;
private String supplierName;
private String Address;
private String PhoneNumber;
@OneToMany(mappedBy="supplier")
private List<Product> product;
public List<Product> getProduct() {
return product;
}
public void setProduct(List<Product> product) {
this.product = product;
}
public String getSupplierId() {
return supplierId;
}
public Supplier()
{
this.supplierId="SUPP"+UUID.randomUUID().toString().substring(30).toUpperCase();
}
public void setSupplierId(String supplierId) {
this.supplierId = supplierId;
}
public String getSupplierName() {
return supplierName;
}
public void setSupplierName(String supplierName) {
this.supplierName = supplierName;
}
public String getAddress() {
return Address;
}
public void setAddress(String address) {
Address = address;
}
public String getPhoneNumber() {
return PhoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
PhoneNumber = phoneNumber;
}
}
| true
|
a36301369c08bec1576e333723e31577a2263ca5
|
Java
|
CS2103JAN2017-W10-B1/main
|
/src/main/java/seedu/address/logic/commands/HelpCommand.java
|
UTF-8
| 1,548
| 3.265625
| 3
|
[
"MIT"
] |
permissive
|
//@@author A0143409J
package seedu.address.logic.commands;
/**
* Format full help instructions for every command for display.
*/
public class HelpCommand extends Command {
public static final String COMMAND_WORD = "help";
public static final String MESSAGE_USAGE = COMMAND_WORD + ": Shows program usage instructions.\n"
+ "Example: " + COMMAND_WORD;
public static final String SHOWING_HELP_MESSAGE = "Please add command keyword after help.\n"
+ "The basic command words are as follows:\n"
+ "Add, clear, delete, edit, find, finish, list, scroll, view, undo and redo.\n"
+ "Example: help add";
private String usageMessage;
/**
* Create a HelpCommand object with help message for a command
*
* @param helpMessage The message for usage of a specific command
*/
public HelpCommand(String helpMessage) {
super();
usageMessage = helpMessage;
}
/**
* Create a HelpComand object with no specific help message
*/
public HelpCommand() {
super();
}
@Override
public CommandResult execute() {
if (usageMessage == null) {
LOGGER.info(getClass() + " general message shown");
return new CommandResult(SHOWING_HELP_MESSAGE);
} else {
LOGGER.info(getClass() + " usage message for specific command shown");
return new CommandResult(usageMessage);
}
}
@Override
public boolean isUndoable() {
return false;
}
}
| true
|
4ca084c55c5d1a1f4a483afdbff4336803d995d7
|
Java
|
bkalsow/FireEmblemSacredStones
|
/src/main/java/items/weapons/enemy/Stone.java
|
UTF-8
| 682
| 2.59375
| 3
|
[] |
no_license
|
package main.java.items.weapons.enemy;
import main.java.items.weapons.Weapon;
import main.java.items.weapons.WeaponRanks;
import main.java.items.weapons.dark.Dark;
public class Stone extends Weapon implements Dark
{
private final static int maxUses = 5;
private final static int weight = 8;
private final static int might = 0;
private final static int hitChance = 65;
private final static int critChance = 0;
private final static int cost = 0;
public Stone()
{
super(maxUses, cost, "",
WeaponRanks.F, 1, 3, weight, might, hitChance, critChance, 0,
"Inflicts Stone on one enemy.");
setName("Stone");
}
}
| true
|
c7d1e9250cb825c58cfbf002fe98a28cb0e601ab
|
Java
|
brahamax/livrable
|
/StreamTP/src/Lanceur/Test.java
|
UTF-8
| 1,448
| 3.359375
| 3
|
[] |
no_license
|
package Lanceur;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.util.stream.*;
public class Test {
public static void main(String[] args) throws FileNotFoundException {
// TODO Auto-generated method stub
//Liste de personnes
List <Personne> lp= new ArrayList<Personne>();
//Lecture du fichier
File f = new File("/Users/brahamax/eclipse-workspace/StreamTP/src/Lanceur/etudiant.txt");
Scanner lecteur = new Scanner(f);
//Parcours du fichier
String s="";
System.out.println("Liste des étudiants");
while (lecteur.hasNext()){
var a = lecteur.next();
//Parser
if(!a.toString().equals("-"))
{ s=s+a.toString()+" ";
}
else {
//Création de l'objet personne
System.out.println(s.toString());
//Ajout à la liste
lp.add(new Personne(s));
s="";
}
}
//Création du Stream
Stream <Personne> st = lp.stream();
//Utilisation de la methode filtrage
System.out.println("\n\nApres Filtrage");
st.filter(x -> x.getNomcomplet().contains("SO") || x.getNomcomplet().contains("so") )
//Affichage de toutes les personnes qui correspondent au filtrage appliqué
.forEach(x -> System.out.println(x.getNomcomplet()));
}
}
| true
|
5531ac4ad00ebda88a4ae3f41fcecbc48d7adbb8
|
Java
|
RyanTech/juziQuick
|
/src/com/ailk/yd/mapp/client/action/HW0013Action.java
|
UTF-8
| 7,053
| 1.773438
| 2
|
[] |
no_license
|
package com.ailk.yd.mapp.client.action;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang3.StringUtils;
import org.codehaus.jackson.type.TypeReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;
import com.ai.mapp.base.StringUtil;
import com.ai.mapp.base.util.ConvertUtils;
import com.ai.mapp.base.util.DateUtils;
import com.ai.mapp.sys.entity.AgentOrder;
import com.ai.mapp.sys.entity.User;
import com.ai.mapp.sys.service.AgentOrderService;
import com.ai.mapp.sys.service.ProductService;
import com.ai.mapp.sys.util.LanguageInfo;
import com.ailk.butterfly.core.exception.BusinessException;
import com.ailk.butterfly.core.exception.SystemException;
import com.ailk.butterfly.mapp.core.annotation.Action;
import com.ailk.yd.mapp.client.model.HW0013Request;
import com.ailk.yd.mapp.client.model.HW0013Response;
import com.ailk.yd.mapp.model.UserInfo;
import com.ailk.yd.mapp.tibco.action.YD0033Action;
import com.ailk.yd.mapp.tibco.model.YD0033.YD0033Request;
import com.ailk.yd.mapp.tibco.model.YD0033.YD0033Response;
@Service("hw0013")
@Action(bizcode="hw0013",userCheck=true)
@Scope("prototype")
public class HW0013Action extends
AbstractYDBaseActionHandler<HW0013Request, HW0013Response> {
@Autowired
private AgentOrderService agentOrderService;
@Autowired
private ProductService productService;
@Autowired
private YD0033Action yd0033;
public static void main(String[] args) {
String moneyString = ConvertUtils.getMoneyString(10203040509l);
System.err.println(moneyString);
}
@Override
protected void doAction() throws BusinessException, SystemException,
Exception {
HW0013Request req = request;
UserInfo ui = (UserInfo) this.getUserinfo();
AgentOrder condition = new AgentOrder();
if(StringUtil.isEmpty(req.getEndTime()) == false)
condition.setEndTime(DateUtils.getDate(req.getEndTime()+" 23:59:59","yyyy-MM-dd HH:mm:ss"));
if(StringUtil.isEmpty(req.getStartTime()) == false)
condition.setStartTime(DateUtils.getDate(req.getStartTime()+" 00:00:00","yyyy-MM-dd HH:mm:ss"));
if(StringUtil.isEmpty(req.getOrderCode()) == false)
condition.setOrderCode(req.getOrderCode());
if(StringUtil.isEmpty(req.getPayStatus()) == false)
condition.setPayStatus(req.getPayStatus());
if(StringUtil.isEmpty(req.getStatus()) == false)
condition.setStatus(req.getStatus());
if(StringUtil.isEmpty(req.getPayType()) == false)
condition.setPayType(req.getPayType());
if(StringUtil.isEmpty(req.getOrderType()) == false)
condition.setOrderType(req.getOrderType());
if(StringUtil.isEmpty(req.getSvn()) == false)
condition.setContactMobileNum(req.getSvn());
if(StringUtil.isEmpty(ui.getUsercode()) == false)
condition.setCreator(new User(ui.getUsercode()));
if(StringUtil.isEmpty(req.getOrn()) == false)
condition.setTibcoOrn(req.getOrn());
int start = StringUtil.isEmpty(req.getStart()) ? 0 : Integer.valueOf(req.getStart());
int pageSize = StringUtil.isEmpty(req.getSize()) ? 16 : Integer.valueOf(req.getSize());
Collection<AgentOrder> orders = null;
if(StringUtil.isEmpty(req.getStart()) == false && Integer.valueOf(req.getStart()) < 0 )
orders = agentOrderService.listAllAgentOrders(condition);
else
orders = agentOrderService.listAgentOrders(condition, start, pageSize);
List<HW0013Response.Order> rm = new ArrayList<HW0013Response.Order>();
for (Iterator<AgentOrder> it = orders.iterator(); it.hasNext();) {
AgentOrder order = it.next();
HW0013Response.Order d = new HW0013Response.Order();
d.setBalance(order.getBlance()== null?"":order.getBlance().toString());
d.setCreateTime(order.getCreateTime() == null ? "":DateUtils.getDateString(order.getCreateTime(), "dd/MM/yyyy HH:mm:ss"));
d.setOrderCode(order.getOrderCode()== null?"":order.getOrderCode().toString());
d.setOrderType(order.getOrderType()== null?"":order.getOrderType().toString());
d.setPreStore(order.getPreStore()== null?"":order.getPreStore().toString());
d.setProductId(order.getProduct()== null?"":order.getProduct().getBssRangeId().toString());
d.setSim(order.getSim()== null?"":order.getSim());
d.setSvn(order.getSvn());
d.setPayMode(order.getPayMode()== null?"":order.getPayMode().toString());
// d.setDiscountFee(order.getDiscountFee()== null?"":order.getDiscountFee()+"");
// d.setRealFee(order.getRealFee()== null?"":order.getRealFee()+"");
// d.setSaleFee(order.getSaleFee()== null?"":order.getSaleFee()+"");
// d.setTotalFee(order.getSaleFee()== null?"":order.getSaleFee()+"");
// d.setPackageFee(order.getPackageFee() == null?"0":order.getPackageFee()+"");
d.setDiscountFee(order.getDiscountFee()== null?"":ConvertUtils.getMoneyString(order.getDiscountFee()));
d.setRealFee(order.getRealFee()== null?"":ConvertUtils.getMoneyString(order.getRealFee()));
d.setSaleFee(order.getSaleFee()== null?"":ConvertUtils.getMoneyString(order.getSaleFee()));
d.setTotalFee(order.getSaleFee()== null?"":ConvertUtils.getMoneyString(order.getSaleFee()));
d.setPackageFee(order.getPackageFee() == null?"0":ConvertUtils.getMoneyString(order.getPackageFee()));
d.setIsComposite(order.getIsComposite());
d.setCafFromType(order.getCafFormType());
d.setOrderDetails(order.getCafInfo());
String productType=productService.getProductTypeName(order.getProduct(),LanguageInfo.CURR_LANGUAGE);
d.setProductType(productType==null?"":productType);
d.setOrderStatus(order.getStatus()== null?"":order.getStatus());
d.setPayStatus(order.getPayStatus()== null?"":order.getPayStatus());
d.setPin(order.getPin()== null?"":order.getPin());
d.setPackageName(order.getProduct()==null?"":order.getProduct().getPackedName());
d.setSimFee(order.getSimFee() == null?"0":order.getSimFee().toString());
d.setSIMFee(order.getSimFee() == null?"0":order.getSimFee().toString());
d.setNumberFee(order.getNumberFee() == null?"0":order.getNumberFee().toString());
d.setOrn(order.getTibcoOrn() == null?"":order.getTibcoOrn());
d.setAccountLevel(StringUtils.equals(order.getAccountLevel(), "1"));
d.setContactMobileNum(order.getContactMobileNum()==null?"":order.getContactMobileNum());
if(StringUtils.isNotBlank(order.getFeeDetail()))
{
Map<String,BigDecimal> feeDetail = (Map<String,BigDecimal>)mapper.readValue(order.getFeeDetail(), new TypeReference<Map<String,BigDecimal>>(){});
d.setFeeDetail(feeDetail);
}
rm.add(d);
}
if(StringUtils.isNotBlank(request.getOrn())){
YD0033Request yd0033_req = new YD0033Request();
yd0033_req.setReferenceNumber(request.getOrn());
yd0033_req.setReturnCompleteOrder("0");
YD0033Response yd0033_rsp = yd0033.get2Tibco(yd0033_req.returnGetParam());
response.setTibcoOrderStatus(yd0033_rsp.getOrderStatus());
}
response.setOrders(rm);
}
}
| true
|
576bb890f9890fd8d8543a837927aa1adc7af15f
|
Java
|
douglassquirrel/microservices-hackathon-july-2014
|
/Java/src/main/java/com/microserviceshack/rabbitmq/EmitLogTopic.java
|
UTF-8
| 2,347
| 2.703125
| 3
|
[
"MIT"
] |
permissive
|
package com.microserviceshack.rabbitmq;
import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.microserviceshack.Config;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
public class EmitLogTopic {
public static void main(String[] argv) {
Connection connection = null;
Channel channel = null;
try {
ConnectionFactory factory = new ConnectionFactory();
factory.setHost(Config.RABBIT_MQ_SERVER);
connection = factory.newConnection();
channel = connection.createChannel();
channel.exchangeDeclare(Config.EXCHANGE, "topic");
String routingKey = getRouting(argv);
String message = getMessage(argv);
channel.basicPublish(Config.EXCHANGE, routingKey, null, message.getBytes());
System.out.println(" [x] Sent '" + routingKey + "':'" + message + "'");
}
catch (Exception e) {
e.printStackTrace();
}
finally {
if (connection != null) {
try {
connection.close();
}
catch (Exception ignore) {}
}
}
}
private static String getRouting(String[] strings){
// if (strings.length < 1)
// return "anonymous.info";
// return strings[0];
return "ivan";
}
private static String getMessage(String[] strings) throws JsonGenerationException, JsonMappingException, IOException{
// if (strings.length < 2)
// return "Hello World!";
// return joinStrings(strings, " ", 1);
Map<String, String> message = new HashMap<String, String>();
message.put("Hello", "World!");
ObjectMapper mapper = new ObjectMapper();
return mapper.writeValueAsString(message);
}
// private static String joinStrings(String[] strings, String delimiter, int startIndex) {
// int length = strings.length;
// if (length == 0 ) return "";
// if (length < startIndex ) return "";
// StringBuilder words = new StringBuilder(strings[startIndex]);
// for (int i = startIndex + 1; i < length; i++) {
// words.append(delimiter).append(strings[i]);
// }
// return words.toString();
// }
}
| true
|
35d8e40e3fe7af07243d9fcb8b46efb579ff777d
|
Java
|
NBhajikhaye/COPJAVA
|
/JAVA_7May/src/AdditionfuncOverload.java
|
UTF-8
| 1,074
| 3.875
| 4
|
[] |
no_license
|
import java.util.Scanner;
public class AdditionfuncOverload
{
public static void add(int a, int b) {
System.out.println("Addition of ( "+a+" + "+b+" ) = "+(a+b));
}
public static void add(int a, double b) {
System.out.println("Addition of ( "+a+" + "+b+" ) = "+(a+b));
}
public static void add(double a, int b) {
System.out.println("Addition of ( "+a+" + "+b+" ) = "+(a+b));
}
public static void add(double a, double b) {
System.out.println("Addition of ( "+a+" + "+b+" ) = "+(a+b));
}
public static void main(String[] args)
{
int num1, num2;
double num3, num4;
Scanner sc = new Scanner(System.in);
System.out.println("Addition of two numbers using Function Overloading");
System.out.println("Enter two Intger Values");
num1 = sc.nextInt();
num2 = sc.nextInt();
add(num1, num2);
System.out.println("Enter two Floating Point Values");
num3 = sc.nextDouble();
num4 = sc.nextDouble();
add(num3, num4);
add(num1, num3);
add(num4,num2);
sc.close();
}
}
| true
|
3b3f8861f85f67ca2ebc98924f7e7019428084e9
|
Java
|
inevo/nuxeo-template-rendering
|
/nuxeo-template-rendering-deckjs/src/main/java/org/nuxeo/template/DeckJSPDFOperation.java
|
UTF-8
| 3,857
| 1.882813
| 2
|
[] |
no_license
|
/*
* (C) Copyright 2006-2012 Nuxeo SA (http://nuxeo.com/) and contributors.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Lesser General Public License
* (LGPL) version 2.1 which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/lgpl.html
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* Contributors:
* ldoguin
*/
package org.nuxeo.template;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.nuxeo.ecm.automation.OperationContext;
import org.nuxeo.ecm.automation.core.Constants;
import org.nuxeo.ecm.automation.core.annotations.Context;
import org.nuxeo.ecm.automation.core.annotations.Operation;
import org.nuxeo.ecm.automation.core.annotations.OperationMethod;
import org.nuxeo.ecm.core.api.Blob;
import org.nuxeo.ecm.core.api.DocumentModel;
import org.nuxeo.ecm.core.api.blobholder.BlobHolder;
import org.nuxeo.ecm.core.api.impl.blob.FileBlob;
import org.nuxeo.ecm.core.convert.api.ConversionService;
import org.nuxeo.ecm.core.convert.cache.SimpleCachableBlobHolder;
import org.nuxeo.template.jaxrs.context.JAXRSExtensions;
@Operation(id = DeckJSPDFOperation.ID, category = Constants.CAT_CONVERSION, label = "Convert a deckJS slide to a pdf", description = "Convert a deckJS slide to a pdf.")
public class DeckJSPDFOperation {
public static final String ID = "Blob.DeckJSToPDF";
@Context
OperationContext ctx;
@Context
ConversionService conversionService;
@OperationMethod
public Blob run(Blob blob) throws Exception {
DocumentModel templateSourceDocument = (DocumentModel) ctx.get("templateSourceDocument");
DocumentModel templateBasedDocument = (DocumentModel) ctx.get("templateBasedDocument");
String templateName = (String) ctx.get("templateName");
String workingDirPath = System.getProperty("java.io.tmpdir")
+ "/nuxeo-deckJS-cache/" + templateBasedDocument.getId();
File workingDir = new File(workingDirPath);
if (!workingDir.exists()) {
workingDir.mkdirs();
}
JAXRSExtensions jaxRsExtensions = new JAXRSExtensions(
templateBasedDocument, null, templateName);
BlobHolder sourceBh = templateSourceDocument.getAdapter(BlobHolder.class);
for (Blob b : sourceBh.getBlobs()) {
writeToTempDirectory(workingDir, b);
}
BlobHolder templatebasedBh = templateBasedDocument.getAdapter(BlobHolder.class);
for (Blob b : templatebasedBh.getBlobs()) {
writeToTempDirectory(workingDir, b);
}
String content = blob.getString();
String resourcePath = jaxRsExtensions.getResourceUrl("");
content = content.replaceAll(resourcePath, "./");
File index = new File(workingDir, blob.getFilename());
FileWriter fw = new FileWriter(index);
IOUtils.write(content, fw);
fw.flush();
fw.close();
FileBlob indexBlob = new FileBlob(index);
indexBlob.setFilename(blob.getFilename());
BlobHolder bh = conversionService.convert("deckJSToPDF",
new SimpleCachableBlobHolder(indexBlob), null);
FileUtils.deleteDirectory(workingDir);
return bh.getBlob();
}
private void writeToTempDirectory(File workingDir, Blob b) throws IOException {
File f = new File(workingDir, b.getFilename());
File parentFile = f.getParentFile();
parentFile.mkdirs();
b.transferTo(f);
}
}
| true
|
cff124920cdbebd3aef1b85c601e39591bb95f7d
|
Java
|
bellmit/origin
|
/family_order/src/web/com/asiainfo/veris/crm/order/web/person/sundryquery/ibossutil/TimeUtil.java
|
UTF-8
| 567
| 2
| 2
|
[] |
no_license
|
package com.asiainfo.veris.crm.order.web.person.sundryquery.ibossutil;
import com.asiainfo.veris.crm.order.pub.frame.bcf.util.SysDateMgr;
public class TimeUtil {
public static String getTime(int status) throws Exception{
switch (status) {
case 1:
return SysDateMgr.getSysDate()+SysDateMgr.getEndTime235959();
case 0:
return SysDateMgr.getSysDate()+SysDateMgr.getFirstTime00000();
default:
return null;
}
}
public static String getNextMonth(int num)throws Exception{
return SysDateMgr.getAddMonthsNowday(num, SysDateMgr.getSysDate());
}
}
| true
|
2d33f127c549b37f72d6729b6f38b744a19eab8a
|
Java
|
ManjulaPrabhu/INFO5100_ManjulaP
|
/Assignment_7/src/ReverseHello.java
|
UTF-8
| 939
| 3.390625
| 3
|
[] |
no_license
|
public class ReverseHello extends Thread {
String inputString;
static int threadCounter = 51;
public ReverseHello(String inputString) {
this.inputString = inputString;
}
public void run() {
ReverseHello reverseHelloThreadObject = new ReverseHello("Hello from Thread num");
threadCounter--;
if (threadCounter > 0) {
System.out.println(inputString + (threadCounter));
reverseHelloThreadObject.start();
} else {
for (Thread t : Thread.getAllStackTraces().keySet()) {
if (t.getState() == Thread.State.RUNNABLE) {
t.interrupt();
}
}
}
}
public static void main(String[] args) throws InterruptedException {
ReverseHello reverseHelloThread = new ReverseHello("Hello from Thread num");
reverseHelloThread.start();
}
}
| true
|
848c390c98cf8772f210e385f81168efe3fb6021
|
Java
|
dwifdji/real-project
|
/366pai/zeus-core/core-service/src/main/java/com/_360pai/core/dao/account/mapper/TDisposeProviderApplyMapper.java
|
UTF-8
| 800
| 1.75
| 2
|
[] |
no_license
|
package com._360pai.core.dao.account.mapper;
import com._360pai.core.model.account.TAgency;
import org.apache.ibatis.annotations.Mapper;
import com._360pai.core.condition.account.TDisposeProviderApplyCondition;
import com._360pai.core.model.account.TDisposeProviderApply;
import com._360pai.arch.core.abs.BaseMapper;
import java.util.List;
import java.util.Map;
/**
* <p>TDisposeProviderApply数据层的基础操作</p>
* @ClassName: TDisposeProviderApplyMapper
* @Description: TDisposeProviderApply数据层的基础操作
* @author Generator
* @date 2018年08月27日 15时03分03秒
*/
@Mapper
public interface TDisposeProviderApplyMapper extends BaseMapper<TDisposeProviderApply, TDisposeProviderApplyCondition>{
List<TDisposeProviderApply> getList(Map<String, Object> params);
}
| true
|
af53553021bde6acf4129f4afdcf68b0c153e5fe
|
Java
|
hpenev/JavaEE
|
/Test3_practice/src/gasStation1/FuelBoy.java
|
UTF-8
| 332
| 2.90625
| 3
|
[] |
no_license
|
package gasStation1;
public class FuelBoy extends Thread {
private static int ID = 1;
private GasStation gasStation;
public FuelBoy(GasStation gasStation) {
this.gasStation = gasStation;
setName("FuelBoy" + ID++);
}
@Override
public void run() {
while (true) {
gasStation.refuelCars();
}
}
}
| true
|
cf7c05cd051ec5dc9779769127b770233b407c94
|
Java
|
shalinimajumder/project
|
/doctor-details/src/main/java/com/example/doctor/doctordetails/service/PateintService.java
|
UTF-8
| 289
| 1.914063
| 2
|
[] |
no_license
|
package com.example.doctor.doctordetails.service;
import java.util.List;
import java.util.Optional;
import com.example.doctor.doctordetails.model.Patient;
public interface PateintService {
public List<Patient> findAllPatient();
public Optional<Patient> findByid(Integer id);
}
| true
|
c8a482ae11b640e2bc3d866d94d446a2c9e03cfb
|
Java
|
rookiezq/learning
|
/src/main/java/com/rookied/learning/map/MapDemo.java
|
UTF-8
| 325
| 2.578125
| 3
|
[] |
no_license
|
package com.rookied.learning.map;
import java.util.HashMap;
import java.util.Map;
/**
* @author zhangqiang
* @date 2021/4/15
*/
public class MapDemo {
public static void main(String[] args) {
Map<String,Integer> map = new HashMap(16);
map.put(null,1);
System.out.println(map.size());
}
}
| true
|
6d39f17c73195221e1c340208a7de251294ee68f
|
Java
|
ruslan-stosyk/DiscountStorage
|
/app/src/main/java/com/stosh/discountstorage/fragments/settings/ChangeEmailFragment.java
|
UTF-8
| 2,736
| 2.09375
| 2
|
[] |
no_license
|
package com.stosh.discountstorage.fragments.settings;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.Toast;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.stosh.discountstorage.FireBaseSingleton;
import com.stosh.discountstorage.R;
import com.stosh.discountstorage.activities.MainActivity;
import static android.widget.Toast.makeText;
/**
* A simple {@link Fragment} subclass.
*/
public class ChangeEmailFragment extends Fragment implements View.OnClickListener, OnCompleteListener {
private View view;
private EditText editTextEmail;
private Button buttonChange;
private ProgressBar progressBar;
private FireBaseSingleton fireBase;
public static ChangeEmailFragment getInstance(@Nullable Bundle data) {
ChangeEmailFragment fragment = new ChangeEmailFragment();
fragment.setArguments(data == null ? new Bundle() : data);
return fragment;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_settings_change_email, container, false);
init();
fireBase = FireBaseSingleton.getInstance();
return view;
}
private void init() {
editTextEmail = (EditText) view.findViewById(R.id.editTextSettingChangeEmail);
buttonChange = (Button) view.findViewById(R.id.btnSettingChangeEmail);
buttonChange.setOnClickListener(this);
progressBar = (ProgressBar) view.findViewById(R.id.progressBarSettingEmail);
}
@Override
public void onClick(View v) {
String email;
email = editTextEmail.getText().toString();
if (TextUtils.isEmpty(email)) {
editTextEmail.setError(getString(R.string.email_is_empty));
return;
}
progressBar.setVisibility(View.VISIBLE);
fireBase.changeEmail(email, this);
}
@Override
public void onComplete(@NonNull Task task) {
if (task.isSuccessful()) {
makeText(
getActivity(),
getString(R.string.email_update),
Toast.LENGTH_LONG
).show();
fireBase.singOut();
progressBar.setVisibility(View.GONE);
getActivity().startActivity(new Intent(getActivity(), MainActivity.class));
getActivity().finish();
} else {
makeText(
getActivity(),
getString(R.string.failed_update_email),
Toast.LENGTH_LONG
).show();
progressBar.setVisibility(View.GONE);
}
}
}
| true
|
8e776ddc1439684cfe8d8f1962377ce4e1d1e3f5
|
Java
|
tienthanh2509/iWownController
|
/iwown/src/main/java/tk/d13ht01/bracelet/adapter/AppsAdapter.java
|
UTF-8
| 3,145
| 2.109375
| 2
|
[
"Apache-2.0"
] |
permissive
|
/*
* Copyright (c) 2017 PT Studio. All rights reserved.
* Licensed under Apache License 2.0 (https://github.com/tienthanh2509/iWownController/blob/master/LICENSE)
*/
package tk.d13ht01.bracelet.adapter;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.support.annotation.NonNull;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.List;
import tk.d13ht01.bracelet.R;
import tk.d13ht01.bracelet.common.Constants;
import tk.d13ht01.bracelet.model.AppNotification;
/**
* Created by Aloyan Dmitry on 16.09.2015
*/
public class AppsAdapter extends ArrayAdapter<ApplicationInfo> {
private List<ApplicationInfo> appsList = null;
private Context context;
private PackageManager packageManager;
public AppsAdapter(Context context, int textViewResourceId, List<ApplicationInfo> appsList) {
super(context, textViewResourceId, appsList);
this.context = context;
this.appsList = appsList;
packageManager = context.getPackageManager();
}
@Override
public int getCount() {
return ((null != appsList) ? appsList.size() : 0);
}
@Override
public ApplicationInfo getItem(int position) {
return ((null != appsList) ? appsList.get(position) : null);
}
@Override
public long getItemId(int position) {
return position;
}
@NonNull
@Override
public View getView(int position, View convertView, @NonNull ViewGroup parent) {
View view = convertView;
if (null == view) {
LayoutInflater layoutInflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = layoutInflater.inflate(R.layout.applist_item, null);
}
ApplicationInfo data = appsList.get(position);
if (null != data) {
CheckBox checkBox = (CheckBox) view.findViewById(R.id.checkbox);
checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
String packageName = (String) buttonView.getTag();
if (isChecked) {
AppNotification.disableApp(packageName);
} else {
AppNotification.enableApp(packageName, Constants.ALERT_TYPE_MESSAGE);
}
}
});
((TextView) view.findViewById(R.id.title)).setText(data.loadLabel(packageManager));
((TextView) view.findViewById(R.id.description)).setText(data.packageName);
((ImageView) view.findViewById(R.id.icon))
.setImageDrawable(data.loadIcon(packageManager));
view.setTag(position);
}
return view;
}
}
| true
|
c444d1b21b447ee561e45e30d7dd3007a0b52ded
|
Java
|
prashanthkumarchilukamari/CoreJavaPractice
|
/src/pc/corejava/fundamentals/StaticKeyWordSample.java
|
UTF-8
| 1,055
| 4.03125
| 4
|
[] |
no_license
|
package pc.corejava.fundamentals;
public class StaticKeyWordSample {
static int count = 0; // This variable is common for all objects
static{
System.out.println("This block will be executed during the class loading");
// this.display(); // CTE : Can't use this inside static context
// super.display(); // CTE : Can't use super inside static context
}
/*
int index = 0; // instance variable
{ // instance block
index =10;
}
*/
public static void display(){
System.out.println("We can access this method with out creating the object");
System.out.println("Static variable count value is : " + count);
count++;
}
public static void main(String[] args) {
StaticKeyWordSample.display(); // Accessing the static method using the class name
StaticKeyWordSample obj1 = new StaticKeyWordSample();
StaticKeyWordSample obj2 = new StaticKeyWordSample();
System.out.println("obj1 count value is : " + obj1.count);
System.out.println("obj2 count value is : " + obj2.count);
}
}
| true
|
e001d1ac2d38e38e8a8d69d688cfdb6696104cd0
|
Java
|
matan45/javaopengl
|
/shadows/ShadowShader.java
|
UTF-8
| 626
| 2.296875
| 2
|
[] |
no_license
|
package shadows;
import maths.Matrix4f;
import shader.ShaderProgram;
public class ShadowShader extends ShaderProgram {
private int location_mvpMatrix;
protected ShadowShader(String vs, String frag) {
super(vs, frag);
}
@Override
protected void getAllUniformLocations() {
location_mvpMatrix = super.getUniformLocation("mvpMatrix");
}
protected void loadMvpMatrix(Matrix4f mvpMatrix) {
super.loadMatrix(location_mvpMatrix, mvpMatrix);
}
@Override
protected void bindAttributes() {
super.bindAttribute(0, "in_position");
super.bindAttribute(1, "in_textureCoords");
}
}
| true
|