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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
c4e1fa9dc6c92d5a58c6a04776fb33ebc913247d | Java | hellozin/greading | /src/test/java/org/greading/api/vote/VoteServiceTest.java | UTF-8 | 2,041 | 2.15625 | 2 | [] | no_license | package org.greading.api.vote;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.ArrayList;
import java.util.List;
import javax.transaction.Transactional;
import org.greading.api.member.Member;
import org.greading.api.member.MemberService;
import org.greading.api.request.JoinRequest;
import org.greading.api.util.DevelopUtils;
import org.greading.api.vote.selection.Selection;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
@Transactional
class VoteServiceTest {
@Autowired
private MemberService memberService;
@Autowired
private VoteService voteService;
@Test
void test() {
List<Selection> selections = new ArrayList<>();
selections.add(new Selection("first selection"));
selections.add(new Selection("second selection"));
selections.add(new Selection("third selection"));
Vote vote = voteService.createVote("first vote", selections);
List<Selection> all = vote.getSelections();
long lastSelectionId = all.get(all.size() - 1).getId();
final int mockUserCount = 2;
Member[] mockUsers = new Member[mockUserCount];
for (int i = 0; i < mockUserCount; i++) {
JoinRequest joinRequest = new JoinRequest(
"id" + i, "pw" + i, "mail" + i, "none");
mockUsers[i] = memberService.signUp(joinRequest);
}
vote = voteService.vote(vote.getId(), lastSelectionId, mockUsers[0].getId());
int lastSelectionCount = vote.getSelection(lastSelectionId).orElseThrow().getSelectUserIds().size();
assertEquals(1, lastSelectionCount);
vote = voteService.vote(vote.getId(), lastSelectionId, mockUsers[1].getId());
lastSelectionCount = vote.getSelection(lastSelectionId).orElseThrow().getSelectUserIds().size();
assertEquals(2, lastSelectionCount);
DevelopUtils.printPretty(vote);
}
} | true |
1ecc97294899840ce350fe9d380369248a246184 | Java | JonghanCha-TJProject/AddressProject | /AddressProject/app/src/main/java/com/android/addressproject/Activity/Memdel.java | UTF-8 | 2,511 | 2.125 | 2 | [] | no_license | package com.android.addressproject.Activity;
import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import com.android.addressproject.NetworkTask.CUDNetworkTask;
import com.android.addressproject.R;
public class Memdel extends AppCompatActivity {
Button btn_memdel;
String urlAddr = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_memdel);
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setDisplayHomeAsUpEnabled(true);
}
// 20.12.31 세미추가 회원탈퇴기능 ---------------------------------
// Intent intent = getIntent();
String checkId = PreferenceManager.getString(Memdel.this,"id");
btn_memdel = findViewById(R.id.btn_memdel);
btn_memdel.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//Toast.makeText(Memdel.this, "addno값 : " + checkId, Toast.LENGTH_SHORT).show();
urlAddr = "http://" + ShareVar.macIP + ":8080/test/memDel.jsp?checkId="+checkId;
connectDeleteData();
Toast.makeText(Memdel.this, "탈퇴되었습니다.", Toast.LENGTH_SHORT).show();
Intent intentMD = new Intent(Memdel.this, LoginActivity.class);
startActivity(intentMD);
}
});
}
//뒤로가기
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
// 뒤로가기
switch (item.getItemId()){
case android.R.id.home:
onBackPressed();
return true;
}
return super.onOptionsItemSelected(item);
}
// 20.12.31 회원탈퇴 세미 ---------------------------------------------------
private void connectDeleteData(){
try{
CUDNetworkTask deleteworkTask = new CUDNetworkTask(Memdel.this, urlAddr);
deleteworkTask.execute().get();
}catch (Exception e){
e.printStackTrace();
}
finish();
}
// 끝 ------------------------------------------------------------------
} | true |
1b2b9b840a78ed33a3081b3e1062ef90de6a245d | Java | umesolutions/umeapprest | /umeapprest/src/main/java/com/umesolutions/e2eapp/service/RequestLoginService.java | UTF-8 | 296 | 1.757813 | 2 | [] | no_license | package com.umesolutions.e2eapp.service;
import java.sql.SQLException;
import com.umesolutions.e2eapp.dto.LoginDetails;
public interface RequestLoginService {
public LoginDetails getLoginInfo(String userName, String password);
public boolean addLoginDetails(LoginDetails loginDetails);
}
| true |
9c2ee89ec60489901d1a3769b7499660aee9d2f5 | Java | Prolanches/Prolanches | /src/main/java/br/com/ProjecJava/model/Status_Pedido.java | UTF-8 | 1,066 | 2.6875 | 3 | [] | no_license | /*
* Este é o pacote responsavel pelas Classes Model
*/
package br.com.ProjecJava.model;
import br.com.ProjecJava.dto.Status_PedidoDTO;
/**
* Esta é a classe do Status_Pedido
*
* @author Noturno
*
*/
public class Status_Pedido {
/**
* Este são os atributos do Status do Pedido
*/
private Integer codigo;
private String nome;
/**
* Este é o construtor do Status_Pedido, abaixo estão seus parametros
*
* @param codigo
* Id do Bando de Dados
* @param nome
* nome do Status do Pedido
*/
public Status_Pedido() {
}
public Status_Pedido(Integer codigo, String nome) {
this.codigo = codigo;
this.nome = nome;
}
public Integer getCodigo() {
return codigo;
}
public void setCodigo(Integer codigo) {
this.codigo = codigo;
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public Status_PedidoDTO toDTO() {
return new Status_PedidoDTO(this.getCodigo(), this.getNome());
}
} | true |
1a3a162666a28e539590f4526e36110e6a3b2a62 | Java | paulBRp/javaNeatbensEjercicios | /cls9ProyactoColegio/src/main/java/com/mycompany/cls9proyactocolegio/Colegio.java | UTF-8 | 1,352 | 2.703125 | 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 com.mycompany.cls9proyactocolegio;
/**
*
* @author paul
*/
public class Colegio {
private Aula[] aula;
Director director;
String nombre;
public Colegio(){
}
public Colegio( Aula[] aula, Director director, String nombre){
this.aula=aula;
this.director=director;
this.nombre=nombre;
}
public Aula[] getAula(){
return aula;
}
public String getNombre(){
return nombre;
}
public Director getDirector(){
return director;
}
public void setAula(Aula[] aula){
this.aula=aula;
}
public void setNombre(String nombre){
this.nombre=nombre;
}
public void setDirector(Director sirector){
this.director=director;
}
public double getNotaMedia(){
double sumatotal=0.0;
for(int i=0;i<aula.length;i++){
sumatotal=sumatotal+aula[i].getNotamediaAula();
}
return (sumatotal/aula.length)*(this.getDirector().getValoracion()*0.3);
}
public Alumno getMejorAlumnoColegio(){
for(int i=0;i<aula.length;i++){
}
}
}
| true |
21b2cb93b8146f0a1069d84e0b53ccea94d2470e | Java | Eljah/jamwiki | /wiki/tags/release-0.6.2/jamwiki/src/main/java/org/jamwiki/servlets/LinkToServlet.java | UTF-8 | 2,567 | 2.140625 | 2 | [] | no_license | /**
* Licensed under the GNU LESSER GENERAL PUBLIC LICENSE, version 2.1, dated February 1999.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the latest version of the GNU Lesser General
* Public License as published by the Free Software Foundation;
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program (LICENSE.txt); if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
package org.jamwiki.servlets;
import java.util.Collection;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.jamwiki.WikiBase;
import org.jamwiki.WikiException;
import org.jamwiki.WikiMessage;
import org.jamwiki.utils.WikiLogger;
import org.jamwiki.utils.WikiUtil;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.ModelAndView;
/**
* Used to display all topics that contain links to the current topic.
*/
public class LinkToServlet extends JAMWikiServlet {
private static final WikiLogger logger = WikiLogger.getLogger(LinkToServlet.class.getName());
protected static final String JSP_LINKTO = "linkto.jsp";
/**
*
*/
protected ModelAndView handleJAMWikiRequest(HttpServletRequest request, HttpServletResponse response, ModelAndView next, WikiPageInfo pageInfo) throws Exception {
this.linksTo(request, next, pageInfo);
return next;
}
/**
*
*/
private void linksTo(HttpServletRequest request, ModelAndView next, WikiPageInfo pageInfo) throws Exception {
String virtualWiki = WikiUtil.getVirtualWikiFromURI(request);
String topicName = WikiUtil.getTopicFromRequest(request);
if (!StringUtils.hasText(topicName)) {
throw new WikiException(new WikiMessage("common.exception.notopic"));
}
WikiMessage pageTitle = new WikiMessage("linkto.title", topicName);
pageInfo.setPageTitle(pageTitle);
// grab search engine instance and find
Collection results = WikiBase.getSearchEngine().findLinkedTo(virtualWiki, topicName);
next.addObject("results", results);
next.addObject("link", topicName);
pageInfo.setContentJsp(JSP_LINKTO);
pageInfo.setTopicName(topicName);
}
}
| true |
bbb1951dc47fe86ea87e66784675f8fa32ad7425 | Java | vinhqdang/utcnsvn | /ivc/src/ivc/commands/GetUserCopyCommand.java | UTF-8 | 3,643 | 2.328125 | 2 | [] | no_license | /**
*
*/
package ivc.commands;
import ivc.data.IVCProject;
import ivc.data.exception.Exceptions;
import ivc.data.operation.Operation;
import ivc.data.operation.OperationHistory;
import ivc.data.operation.OperationHistoryList;
import ivc.managers.ConnectionManager;
import ivc.server.rmi.ServerIntf;
import ivc.util.Constants;
import java.rmi.RemoteException;
import java.util.Iterator;
/**
* @author danielan
*
*/
public class GetUserCopyCommand implements CommandIntf {
private String hostAddress;
private IVCProject ivcProject;
private String filePath;
private StringBuffer fileContent;
@Override
/*
* * Computes the current version of the remote file based on the operations stored in
* the log files of the current user workspace
*/
public Result execute(CommandArgs args) {
hostAddress = (String) args.getArgumentValue(Constants.HOST_ADDRESS);
ivcProject = (IVCProject) args.getArgumentValue(Constants.IVCPROJECT);
filePath = (String) args.getArgumentValue(Constants.FILE_PATH);
fileContent = new StringBuffer();
ConnectionManager conMg = ConnectionManager.getInstance(ivcProject.getName());
// get base version
ServerIntf server = conMg.getServer();
if (server != null) {
try {
fileContent = server.getBaseVersionForFile(ivcProject.getServerPath(),
filePath);
} catch (RemoteException e) {
return new Result(true, Exceptions.COULD_NOT_GET_BASEVERSION_FORFILE, e);
}
int version = 1;
OperationHistoryList rul = new OperationHistoryList();
if (hostAddress.equalsIgnoreCase(Constants.COMMITED)) {
version = Integer.MAX_VALUE;
} else {
rul = ivcProject.getRemoteUncommitedLog(hostAddress);
if (rul != null && rul.getOperationHistForFile(filePath) != null) {
version = rul.getOperationHistForFile(filePath).getOperations()
.getLast().getFileVersion();
}
}
// apply commited transformations
try {
OperationHistoryList cl = server.returnHeadVersion(ivcProject
.getServerPath());
OperationHistory fileOps = cl.getOperationHistForFile(filePath);
if (fileOps != null) {
for (Iterator<Operation> iterator = fileOps.getOperations()
.descendingIterator(); iterator.hasNext();) {
Operation operation = iterator.next();
if (operation.getOperationType() == Operation.CHARACTER_ADD
|| operation.getOperationType() == Operation.CHARACTER_DELETE) {
if (operation.getFileVersion() <= version) {
try {
fileContent = operation
.applyContentTransformation(fileContent);
} catch (Exception e) {
}
}
}
}
}
} catch (RemoteException e1) {
return new Result(true, Exceptions.COULD_NOT_GET_COMMITEDLOG, e1);
}
// apply uncommitted operations
if (!hostAddress.equalsIgnoreCase(Constants.COMMITED)) {
if (rul != null && rul.getOperationHistForFile(filePath) != null) {
OperationHistory rulOps = rul.getOperationHistForFile(filePath);
if (rulOps != null) {
for (Iterator<Operation> iterator = rulOps.getOperations()
.descendingIterator(); iterator.hasNext();) {
Operation operation = iterator.next();
if (operation.getOperationType() == Operation.CHARACTER_ADD
|| operation.getOperationType() == Operation.CHARACTER_DELETE) {
fileContent = operation
.applyContentTransformation(fileContent);
}
}
}
}
}
}
Result res = new Result(true, "Success", null);
res.setResultData(fileContent);
return res;
}
}
| true |
a294393c2f62b8b061fd133b47b917f5c310982a | Java | Fhui/JavaSeDemo | /src/com/test/java/sql/utils/CommonDbUtilsTest.java | UTF-8 | 6,236 | 2.859375 | 3 | [] | no_license | package com.test.java.sql.utils;
import com.test.java.domain.Person;
import com.test.java.sql.DatabaseUtils;
import org.apache.commons.dbutils.DbUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.*;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;
public class CommonDbUtilsTest {
private static Connection mConnection;
public static void main(String[] args) throws SQLException {
mConnection = DatabaseUtils.getConnection();
// insert();
// update();
// delete();
// testArrayHandler();
// testArrayListHandler();
// testBeanHandler();
// testBeanListHandler();
// testColumnListHandler();
// testScalarHandler();
// testMapHandler();
testMapListHandler();
}
/**
* 测试 mapListHandler
* 将结果集的每一行记录封装到map集合中
* 将map集合封装到一个list中
* @throws SQLException
*/
public static void testMapListHandler() throws SQLException{
String sql = "select * from person";
QueryRunner runner = new QueryRunner();
List<Map<String, Object>> query = runner.query(mConnection, sql, new MapListHandler());
for (Map<String, Object> map : query) {
for(String key: map.keySet()){
System.out.print(key + "---" + map.get(key));
}
System.out.println("\n");
}
}
/**
* 测试 mapHandler
* 将结果集的第一行封装到map集合中
* @throws SQLException sql exception
*/
public static void testMapHandler() throws SQLException{
String sql = "select * from person";
QueryRunner runner = new QueryRunner();
Map<String, Object> map = runner.query(mConnection, sql, new MapHandler());
for(String key : map.keySet()){
System.out.println(key + "---" + map.get(key));
}
}
/**
* 测试 scalarHandler
* 常用语单数据查询
* @throws SQLException sql exception
*/
public static void testScalarHandler() throws SQLException{
String sql = "select count(*) from person";
QueryRunner runner = new QueryRunner();
Object query = runner.query(mConnection, sql, new ScalarHandler<>());
System.out.println(query);
}
/**
*测试 columnListHandler
* 将结果集指定的列字段值封装到一个List中
* @throws SQLException sql exception
*/
public static void testColumnListHandler() throws SQLException{
String sql = "select name from person";
QueryRunner runner = new QueryRunner();
List<Object> query = runner.query(mConnection, sql, new ColumnListHandler<>());
for (Object o : query) {
System.out.println(o);
}
}
/**
* 测试 beanListHandler
* 将结果集的每一条记录都封装到指定的JavaBean中
* 将这些JavaBean封装到一个List中
* @throws SQLException sql exception
*/
public static void testBeanListHandler() throws SQLException{
String sql = "select * from person";
QueryRunner runner = new QueryRunner();
List<Person> query = runner.query(mConnection, sql, new BeanListHandler<>(Person.class));
for (Person person : query) {
System.out.println(person);
}
}
/**
* 测试 beanHandler
* 将结果集的第一条记录封装到一个指定的JavaBean中
* @throws SQLException sql exception
*/
public static void testBeanHandler() throws SQLException{
String sql = "select * from person";
QueryRunner runner = new QueryRunner();
Person person = runner.query(mConnection, sql, new BeanHandler<>(Person.class));
System.out.println(person);
}
/**
* 测试 arrayListHandler
* 将结果集的每一条记录都封装到一个数组中
* 将这些数组封装到一个list中
* @throws SQLException sql exception
*/
public static void testArrayListHandler() throws SQLException{
String sql = "select * from person";
QueryRunner runner = new QueryRunner();
List<Object[]> query = runner.query(mConnection, sql, new ArrayListHandler());
for (Object[] objects : query) {
for (Object object : objects) {
System.out.print(object + "\t");
}
System.out.println("\n");
}
}
/**
* 测试 arrayHandler
* 将结果集的第一条记录封装到一个object数组中
* 数组中的每一个元素就是这条记录的每一个字段的值
* @throws SQLException sql exception
*/
public static void testArrayHandler() throws SQLException {
String sql = "select * from person";
QueryRunner runner = new QueryRunner();
Object[] query = runner.query(mConnection, sql, new ArrayHandler());
for (Object o : query) {
System.out.print(o + "\t");
}
}
public static void update() throws SQLException {
String sql = "update person set name = ?, age = ?, sex = ? where id = ?";
QueryRunner runner = new QueryRunner();
int update = runner.update(mConnection, sql, "张小君", 89, "女", 1);
System.out.println(update == 0 ? "error" : "success");
}
public static void delete() throws SQLException {
String sql = "delete from person where id = ?";
QueryRunner runner = new QueryRunner();
int update = runner.update(mConnection, sql, 4);
System.out.println(update == 0 ? "error" : "success");
}
public static void insert() {
String sql = "insert into person (name, age, sex) values (?, ?, ?)";
QueryRunner runner = new QueryRunner();
Object[] params = {"王国强", 20, "男"};
int update = 0;
try {
update = runner.update(mConnection, sql, params);
} catch (SQLException e) {
e.printStackTrace();
}
DbUtils.closeQuietly(mConnection);
System.out.println(update == 1 ? "success" : "error");
}
}
| true |
1705055021b00a42f5159df4ea581a59c82f7db7 | Java | abhinav0509/Interview-Prepration | /FindClockAngle.java | UTF-8 | 948 | 3.890625 | 4 | [] | no_license | import java.util.Scanner;
public class FindClockAngle {
private static Scanner in;
public static void main(String[] args) {
// TODO Auto-generated method stub
in = new Scanner(System.in);
System.out.println("Enter time in hh:mm format:");
double hour=in.nextDouble();
double min=in.nextDouble();
double angle=calcAngle(hour,min);
System.out.println("The angle is:"+angle );
}
/*The minute hand moves 360 degree in 60 minute(or 6 degree in one minute)
* and hour hand moves 360 degree in 12 hours(or 0.5 degree in 1 minute).
* In h hours and m minutes, the minute hand would move (h*60 + m)*6 and
* hour hand would move (h*60 + m)*0.5.*/
private static double calcAngle(double hour,double min){
double angle;
double hour_angle=0.5*(hour*60+min);
double min_angle=6*min;
angle=Math.abs(hour_angle-min_angle);
angle=Math.min(360-angle,angle);
return angle;
}
}
| true |
ea26663860e8b191009a72c778c9d94090f8b433 | Java | togaurav/enroscar | /test-project/src/jvm/java/com/stanfy/net/cache/SimpleFileCache.java | UTF-8 | 634 | 2.390625 | 2 | [] | no_license | package com.stanfy.net.cache;
import java.io.File;
import com.xtremelabs.robolectric.Robolectric;
/**
* Cache for testing.
* @author Roman Mazur (Stanfy - http://stanfy.com)
*/
public class SimpleFileCache extends BaseFileResponseCache {
/** Name. */
private final String name;
public SimpleFileCache(final String name) {
this.name = name;
final int maxSize = 1024 * 1024 * 1;
setWorkingDirectory(new File(Robolectric.application.getFilesDir(), name));
setMaxSize(maxSize);
}
public String getName() { return name; }
@Override
protected CacheEntry createCacheEntry() { return new CacheEntry(); }
}
| true |
f1c7fcfc6ce7fc5eb023f97c129c08a39a60a779 | Java | 0xcafedaddy/SimpleIM | /src/com/langsin/im/client/Main.java | GB18030 | 4,808 | 2.6875 | 3 | [] | no_license | package com.langsin.im.client;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFormattedTextField;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.text.MaskFormatter;
/**
* ykʱͨϵͳ ͻ 1.ͻ࣬ʾ½ 2.½ɹʾ 3.ṩעṦܣעɹص½
*/
public class Main {
private JFrame jf_login;// ½
// ½ϵyk
private JFormattedTextField jta_ykNum;
private javax.swing.JTextField jta_pwd;
// ȡĵʵ
private ClientConnection conn = ClientConnection.getIns();
// ʾ½:
public void showLoginUI() throws Exception {
jf_login = new javax.swing.JFrame("½:");
java.awt.FlowLayout fl = new java.awt.FlowLayout();
jf_login.setLayout(fl);
jf_login.setSize(200, 160);
// yk,ʽΪֻ
MaskFormatter mfName = new MaskFormatter("##########");
jta_ykNum = new JFormattedTextField();
mfName.install(jta_ykNum);
jta_ykNum.setColumns(10);
jta_pwd = new javax.swing.JPasswordField(12);
jta_pwd.setColumns(10);
// ûıǩ
JLabel la_name = new JLabel("ID :");
JLabel la_pwd = new JLabel(" :");
jf_login.add(la_name);
jf_login.add(jta_ykNum);
jf_login.add(la_pwd);
jf_login.add(jta_pwd);
javax.swing.JButton bu_login = new javax.swing.JButton("Login");
bu_login.setActionCommand("login");
javax.swing.JButton bu_Register = new javax.swing.JButton("Register");
bu_Register.setActionCommand("reg");
// ½ע¼
ActionListener buttonAction = new ActionListener() {
public void actionPerformed(ActionEvent e) {
String command = e.getActionCommand();
if (command.equals("login")) {
loginAction(); // ִе½
}
if (command.equals("reg")) {
showRegForm();// ע
}
}
};
bu_login.addActionListener(buttonAction);
bu_Register.addActionListener(buttonAction);
jf_login.add(bu_login);
jf_login.add(bu_Register);
jf_login.setLocationRelativeTo(null);//
jf_login.setVisible(true);
}
// ע¼
private void showRegForm() {
final JFrame jf_reg = new JFrame("ע:");
java.awt.FlowLayout fl = new java.awt.FlowLayout();
jf_reg.setLayout(fl);
jf_reg.setSize(200, 160);
final JTextField jta_regNikeName = new JTextField(12);
final JTextField jta_regPwd = new JTextField(12);
JLabel la_regName = new JLabel(" :");
JLabel la_regPwd = new JLabel(" :");
jf_reg.add(la_regName);
jf_reg.add(jta_regNikeName);
jf_reg.add(la_regPwd);
jf_reg.add(jta_regPwd);
JButton bu_reg = new JButton("Register User");
jf_reg.add(bu_reg);
jf_reg.setLocationRelativeTo(null);//
jf_reg.setVisible(true);
// עᰴť¼
ActionListener buttonAction = new ActionListener() {
public void actionPerformed(ActionEvent e) {
// ȡעسƺ
String nikeName = jta_regNikeName.getText().trim();
String pwd = jta_regPwd.getText().trim();
String s = "ʧ!";
if (ClientConnection.getIns().conn2Server()) {// Ϸ
int ykNum = conn.regServer(nikeName, pwd);
s = "עʧ,ʶ:" + ykNum;
if (ykNum != -1) {
s = "עɹ,ID:" + ykNum;
}
}
javax.swing.JOptionPane.showMessageDialog(jf_reg, s);
conn.closeMe();
jf_reg.dispose();
}
};
bu_reg.addActionListener(buttonAction);
}
// ½¼
private void loginAction() {
// 1.ȡykź
String ykStr = jta_ykNum.getText().trim();
int ykNum = Integer.parseInt(ykStr);
String pwd = jta_pwd.getText();
// 2.Ϸ
if (conn.conn2Server()) {// Ϸ
// 3.½
if (conn.loginServer(ykNum, pwd)) {
// 4.ʾ //½ɹˣҪص½
MainUI mainUI = new MainUI(ykNum);
mainUI.showMainUI();
conn.start();// 5.߳
// 6.ûӸ,ΪϢ
conn.addMsgListener(mainUI);
jf_login.dispose();// رյ½
} else {
conn.closeMe();
JOptionPane.showMessageDialog(jf_login, "½ʧ,ȷʺȷ!");
}
} else {
conn.closeMe();
JOptionPane.showMessageDialog(jf_login, "ʧ,ȷϷ,IPͶ˿ȷ!");
}
}
//
public static void main(String[] args) throws Exception {
Main qu = new Main();
qu.showLoginUI();
}
}
| true |
771d07be4d6a7a3f5c81d66c915fbadb9aee230d | Java | Ashwin-Nikam/Automated-Healthcare-System | /Project/src/Frame14.java | UTF-8 | 3,114 | 2.609375 | 3 | [] | no_license | import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.Image;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JLabel;
import java.awt.Font;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class Frame14 extends JFrame {
private JPanel contentPane;
/**
* Launch the application.
*/
/*public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Frame14 frame = new Frame14();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
*/
/**
* Create the frame.
*/
public Frame14() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 750, 483);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JLabel lblAutomatedHealthcareSystem = new JLabel("Automated Healthcare System ");
lblAutomatedHealthcareSystem.setFont(new Font("Times New Roman", Font.PLAIN, 30));
lblAutomatedHealthcareSystem.setBounds(179, 11, 417, 43);
contentPane.add(lblAutomatedHealthcareSystem);
JButton btnAdminLogin = new JButton("Admin Login");
Image img = new ImageIcon(this.getClass().getResource("/admin.png")).getImage();
btnAdminLogin.setIcon(new ImageIcon(img));
btnAdminLogin.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
dispose();
Frame2 f2 = new Frame2();
f2.setVisible(true);
}
});
btnAdminLogin.setFont(new Font("Times New Roman", Font.PLAIN, 25));
btnAdminLogin.setBounds(39, 226, 292, 63);
contentPane.add(btnAdminLogin);
JButton btnUserLogin = new JButton("User Login");
Image img1 = new ImageIcon(this.getClass().getResource("/user.png")).getImage();
btnUserLogin.setIcon(new ImageIcon(img1));
btnUserLogin.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
dispose();
Frame15 f15 = new Frame15();
f15.setVisible(true);
}
});
btnUserLogin.setFont(new Font("Times New Roman", Font.PLAIN, 25));
btnUserLogin.setBounds(397, 226, 292, 63);
contentPane.add(btnUserLogin);
JButton btnExit = new JButton("Exit");
Image img3 = new ImageIcon(this.getClass().getResource("/exit.png")).getImage();
btnExit.setIcon(new ImageIcon(img3));
btnExit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
dispose();
}
});
btnExit.setFont(new Font("Times New Roman", Font.PLAIN, 25));
btnExit.setBounds(214, 332, 292, 63);
contentPane.add(btnExit);
JLabel lblNewLabel = new JLabel("");
Image img2 = new ImageIcon(this.getClass().getResource("/welcome.png")).getImage();
lblNewLabel.setIcon(new ImageIcon(img2));
lblNewLabel.setBounds(300, 65, 143, 134);
contentPane.add(lblNewLabel);
}
}
| true |
f1993d2709be3dad5f8f9dd25a563ace4bf8f9d8 | Java | Roro0/AndroidKiller | /app/src/main/java/edu/feucui/seektreasure/MainActivity.java | UTF-8 | 9,383 | 1.929688 | 2 | [] | no_license | package edu.feucui.seektreasure;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.Toast;
import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.SDKInitializer;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BaiduMapOptions;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.model.LatLng;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
public class MainActivity extends AppCompatActivity implements View.OnClickListener, BaiduMap.OnMapStatusChangeListener, BDLocationListener {
MapView mMapView;
BaiduMap mapMgr;
Button mBtn;
Button mBtnLocal;
RelativeLayout relativeLayout;
LocationClient locationClient;
@BindView(R.id.btn_compass)
Button btnCompass;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
//在使用SDK各组件之前初始化context信息,传入ApplicationContext
//注意该方法要再setContentView方法之前实现
SDKInitializer.initialize(getApplicationContext());//在SDK各功能组件使用之前都需要调用,因此建议该方法放在Application的初始化方法中
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
initView();
}
private void initView() {
//找到MapView
// mMapView = (MapView) findViewById(R.id.bmapView);//找到MapView
relativeLayout = (RelativeLayout) findViewById(R.id.rl_main);
mBtn = (Button) findViewById(R.id.btn_switch_state);//视图转换
mBtnLocal = (Button) findViewById(R.id.btn_local);//定位
//卫星视图和普通视图的切换
mBtn.setOnClickListener(this);
mBtnLocal.setOnClickListener(this);
//地图的状态
MapStatus status = new MapStatus.Builder()
.overlook(0)
.zoom(20)
.build();
BaiduMapOptions option = new BaiduMapOptions()
.zoomControlsEnabled(true)
.zoomGesturesEnabled(true)
.rotateGesturesEnabled(true)
.scaleControlEnabled(true)
.scrollGesturesEnabled(true)
.mapStatus(status);
//动态添加mapView
mMapView = new MapView(this, option);
mMapView.showZoomControls(true);//显示地图缩放控件
mMapView.showScaleControl(true);//显示地图比例尺
relativeLayout.addView(mMapView, 0);//参数0表示该视图是第一视图(布局内含有Button,如果没有0表示该View会抢夺其他view的焦点)
//获取操作地图的控制器
mapMgr = mMapView.getMap();
//地图状态改变监听
mapMgr.setOnMapStatusChangeListener(this);
//定位
}
@Override
protected void onDestroy() {
super.onDestroy();
//在activity执行onDestroy时执行mMapView.onDestroy(),实现地图生命周期管理
mapMgr.setMyLocationEnabled(true);
mMapView.onDestroy();
}
@Override
protected void onResume() {
super.onResume();
//在activity执行onResume时执行mMapView. onResume (),实现地图生命周期管理
mMapView.onResume();
}
@Override
protected void onPause() {
super.onPause();
//在activity执行onPause时执行mMapView. onPause (),实现地图生命周期管理
mMapView.onPause();
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_switch_state:
//切换卫星试图和普通试图
switchMap();
break;
case R.id.btn_local:
//定位
setMyLocation();
break;
case R.id.btn_compass://指南
setCompass();
}
}
/**
* 设置指南
*/
private void setCompass() {
}
/**
* 切换视图
*/
private void switchMap() {
//判断视图的类型
if (mapMgr.getMapType() == BaiduMap.MAP_TYPE_SATELLITE) {
mapMgr.setMapType(BaiduMap.MAP_TYPE_NORMAL);
mBtn.setText("卫星地图");
// int type = mapMgr.getMapType()==BaiduMap.MAP_TYPE_NORMAL?BaiduMap.MAP_TYPE_SATELLITE:BaiduMap.MAP_TYPE_NORMAL;
} else {
mapMgr.setMapType(BaiduMap.MAP_TYPE_SATELLITE);
mBtn.setText("普通地图");
}
}
/**
* 设置定位
*/
private void setMyLocation() {
/**
* 开去定位图层
*初始化LocalClient
*设置一些定位相关的LocalClientOption
*设置监听,定位的监听
*开启定位
*/
mapMgr.setMyLocationEnabled(true); //开去定位图层
locationClient = new LocationClient(getApplication()); //初始化LocalClient
LocationClientOption locOption = locationClient.getLocOption();//设置一些定位相关的LocalClientOption
locOption.setOpenGps(true);//默认打开GPS
locOption.setCoorType("bd0911");//设置地图类型
locOption.setIsNeedAddress(true);//
locOption.setScanSpan(10000);//范围大小
// locOption.setAddrType("all");//返回的定位结果包含地址信息
locationClient.setLocOption(locOption);
//设置监听
locationClient.registerLocationListener(this); //设置监听,定位的监听
locationClient.start();//开启定位
locationClient.requestLocation();//针对某些机型,开启请求定位失败
}
/**
* 地图状态改变监听
*
* @param mapStatus
*/
@Override
public void onMapStatusChangeStart(MapStatus mapStatus) {
}
@Override
public void onMapStatusChange(MapStatus mapStatus) {
Toast.makeText(this, "纬度1:" + mapStatus.target.latitude + ",经度2:" + mapStatus.target.longitude, Toast.LENGTH_SHORT).show();
}
@Override
public void onMapStatusChangeFinish(MapStatus mapStatus) {
}
LatLng myLocal;
/**
* 定位监听:获取定位的信息
*
* @param bdLocation
*/
@Override
public void onReceiveLocation(BDLocation bdLocation) {
//如果没有定位,重新请求有没有定位成功
//获得定位信息
//定位信息设置到地图上
//移动到定位的位置上去
//-----第一次进入:一进到项目需要定位到定位的地方去
//-------点击按钮定位到定位到的地方上
//判断
if (bdLocation == null) {
locationClient.requestLocation();
return;
}
double lng = bdLocation.getLongitude();//经度
double lat = bdLocation.getLatitude();//纬度
Toast.makeText(this, "纬度:" + lng + ",经度:" + lat, Toast.LENGTH_SHORT).show();
/**
* 添加定位的标志
* 1.拿到定位的信息
* 2.给地图设置定位的数据
*/
MyLocationData locationData = new MyLocationData.Builder()
.longitude(lng)//定位的经度
.latitude(lat)//定位的纬度
.accuracy(100f)//定位的景区的大小
.build();
mapMgr.setMyLocationData(locationData);
/**
* 移动我们的位置
* 1.有我们的位置
* 2.移动的话,地图状态是否发生变化
* 3.在地图状态设置位置
* 4.位置变化,地图改变
*/
myLocal = new LatLng(lat, lng);
//移动到指定位置
moveToMyLocatuon();
}
/**
* 移动到我们定位的位置上去
*/
private void moveToMyLocatuon() {
MapStatus mapStatus = new MapStatus.Builder()
.target(myLocal)
.rotate(0)//作用是摆正地图
.zoom(15).build();
//更新地图状态
MapStatusUpdate statusUpdate = MapStatusUpdateFactory.newMapStatus(mapStatus);
mapMgr.animateMapStatus(statusUpdate);
addMarker();
}
/**
* 定位标志
*/
private void addMarker() {
/**
*
* 1.定位位置
* 2.定位图标
*/
MarkerOptions markerOption = new MarkerOptions();
BitmapDescriptor bitmap = BitmapDescriptorFactory.fromResource(R.mipmap.icon_gcoding);
markerOption.position(myLocal).icon(bitmap);
mapMgr.addOverlay(markerOption);
}
@OnClick(R.id.btn_compass)
public void onClick() {
}
//添加标注物和监听
}
| true |
a6180bc3253527071eba8d40a6d63f97ada2e5be | Java | nikita-jpg/Visit | /app/src/main/java/com/example/visit/createteamivent/CreateTeamEvent.java | UTF-8 | 6,235 | 2.109375 | 2 | [] | no_license | package com.example.visit.createteamivent;
import android.content.ContentResolver;
import android.content.Intent;
import android.content.res.Resources;
import android.net.Uri;
import android.os.Bundle;
import android.text.InputType;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import com.example.visit.MainActivity;
import com.example.visit.R;
import com.example.visit.TeamEvent;
import com.example.visit.сache.CacheManager;
import com.google.android.material.textfield.TextInputLayout;
import com.jackandphantom.circularimageview.RoundedImage;
import java.io.IOException;
import static android.app.Activity.RESULT_OK;
import static android.content.ContentValues.TAG;
public class CreateTeamEvent extends Fragment {
private final int PICK_IMAGE_1 = 1;
private final int PICK_IMAGE_2 = 2;
private String titleStr,desc1Str,desc2Str,currentImage1,currentImage2;
private View rootView;
private Button btnSaveTeam;
private TextInputLayout title,desc1,desc2;
private RoundedImage img1,img2;
private CacheManager cacheManager;
private MainActivity mainActivity;
public CreateTeamEvent(CacheManager cacheManager, MainActivity mainActivity)
{
this.cacheManager = cacheManager;
this.mainActivity = mainActivity;
}
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_create_team_event,container,false);
rootView.setVisibility(View.GONE);
btnSaveTeam = rootView.findViewById(R.id.btn_save_team_event);
title = rootView.findViewById(R.id.event_title);
desc1 = rootView.findViewById(R.id.event_desc_1);
desc2 = rootView.findViewById(R.id.event_desc_2);
img1 = rootView.findViewById(R.id.event_photo_1);
img2 = rootView.findViewById(R.id.event_photo_2);
init();
return rootView;
}
private void init()
{
titleStr = "";
desc1Str = "";
desc2Str = "";
//Аватар по умолчанию
Resources resources = getContext().getResources();
Uri uri = Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE + "://" + resources.getResourcePackageName(R.drawable.default_avatar) + '/' + resources.getResourceTypeName(R.drawable.default_avatar) + '/' + resources.getResourceEntryName(R.drawable.default_avatar));
currentImage1 = String.valueOf(uri);
img1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent photoPickerIntent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
photoPickerIntent.setType("image/*");
startActivityForResult(photoPickerIntent, PICK_IMAGE_1);
}
});
currentImage2 = String.valueOf(uri);
img2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent photoPickerIntent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
photoPickerIntent.setType("image/*");
startActivityForResult(photoPickerIntent, PICK_IMAGE_2);
}
});
btnSaveTeam.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
save();
}
});
}
private void save()
{
titleStr = title.getEditText().getText().toString();
if(titleStr.equals(""))
{
Toast.makeText(getContext(),getString(R.string.expTitle),Toast.LENGTH_LONG).show();
return;
}
desc1Str = desc1.getEditText().getText().toString();
desc2Str = desc2.getEditText().getText().toString();
TeamEvent teamEvent = new TeamEvent(titleStr,desc1Str,desc2Str,currentImage1,currentImage2);
cacheManager.teamAdd(teamEvent);
mainActivity.update(teamEvent);
Toast.makeText(getContext(),getString(R.string.saved),Toast.LENGTH_LONG).show();
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent imageReturnedIntent) {
super.onActivityResult(requestCode, resultCode, imageReturnedIntent);
switch(requestCode) {
case PICK_IMAGE_1:
if(resultCode == RESULT_OK){
Uri uri = imageReturnedIntent.getData();
currentImage1 = String.valueOf(uri);
//Грузим фотку
ContentResolver cr = getContext().getContentResolver();
try {
img1.setImageBitmap(android.provider.MediaStore.Images.Media.getBitmap(cr,uri ));
} catch (IOException e) {
Toast.makeText(getContext(), "Ошибка загрузки", Toast.LENGTH_SHORT).show();
Log.d(TAG, "Ошибка загрузки", e);
}
}
break;
case PICK_IMAGE_2:
if(resultCode == RESULT_OK){
Uri uri = imageReturnedIntent.getData();
currentImage2 = String.valueOf(uri);
//Грузим фотку
ContentResolver cr = getContext().getContentResolver();
try {
img2.setImageBitmap(android.provider.MediaStore.Images.Media.getBitmap(cr,uri ));
} catch (IOException e) {
Toast.makeText(getContext(), "Ошибка загрузки", Toast.LENGTH_SHORT).show();
Log.d(TAG, "Ошибка загрузки", e);
}
}
}}
public void Gone()
{
rootView.setVisibility(View.GONE);
}
public void Visible()
{
rootView.setVisibility(View.VISIBLE);
}
}
| true |
519e97cfdc4b942f6a69a5f1815df96390cba80a | Java | onikUone/MoFGBML_ver23 | /src/cilabo/utility/Output.java | UTF-8 | 1,748 | 3.421875 | 3 | [] | no_license | package cilabo.utility;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
public class Output {
/**
* Making new directory "dirName" into "path" by "mkdirs()".<br>
* If parent directory does not exist, this method makes parent directory simultaneously.<br>
* @param path
* @param dirName
*/
public static void makeDir(String path, String dirName) {
String sep = File.separator;
mkdirs(path + sep + dirName);
}
public static void mkdirs(String dirName) {
File newdir = new File(dirName);
newdir.mkdirs();
}
/**
* String用
* @param fileName
* @param str : String
* @param append : boolean : true=append, false=rewrite
*/
public static void writeln(String fileName, String str, boolean append) {
String[] array = new String[] {str};
writeln(fileName, array, append);
}
/**
* ArrayList用
* @param fileName
* @param strs : ArrayList{@literal <String>}
* @param append : boolean : true=append, false=rewrite
*/
public static void writeln(String fileName, ArrayList<String> strs, boolean append) {
String[] array = (String[]) strs.toArray(new String[0]);
writeln(fileName, array, append);
}
/**
* 配列用
* @param fileName
* @param array : String[]
* @param append : boolean : true=append, false=rewrite
*/
public static void writeln(String fileName, String[] array, boolean append){
try {
FileWriter fw = new FileWriter(fileName, append);
PrintWriter pw = new PrintWriter( new BufferedWriter(fw) );
for(int i=0; i<array.length; i++){
pw.println(array[i]);
}
pw.close();
}
catch (IOException ex){
ex.printStackTrace();
}
}
}
| true |
d59a3ba796882df9bb7e6b5fcc72a2b4c905481b | Java | janapfeffer/WDI_2019 | /FootballWebDataIntegration/src/main/java/fusion_fusers/WeightFuserMostRecent.java | UTF-8 | 1,593 | 2.25 | 2 | [] | no_license | package fusion_fusers;
import de.uni_mannheim.informatik.dws.winter.datafusion.AttributeValueFuser;
import de.uni_mannheim.informatik.dws.winter.datafusion.conflictresolution.meta.MostRecent;
import de.uni_mannheim.informatik.dws.winter.model.Correspondence;
import de.uni_mannheim.informatik.dws.winter.model.FusedValue;
import de.uni_mannheim.informatik.dws.winter.model.Matchable;
import de.uni_mannheim.informatik.dws.winter.model.RecordGroup;
import de.uni_mannheim.informatik.dws.winter.model.defaultmodel.Attribute;
import de.uni_mannheim.informatik.dws.winter.processing.Processable;
import models.Player;
/**
* @author group3
*
* Fusion of the weight using the most recent source.
*/
public class WeightFuserMostRecent extends AttributeValueFuser<Float, Player, Attribute>{
public WeightFuserMostRecent() {
super(new MostRecent<Float, Player, Attribute>());
}
@Override
public Float getValue(Player record, Correspondence<Attribute, Matchable> correspondence) {
return record.getWeight();
}
@Override
public void fuse(RecordGroup<Player, Attribute> group, Player fusedRecord,
Processable<Correspondence<Attribute, Matchable>> schemaCorrespondences, Attribute schemaElement) {
FusedValue<Float, Player, Attribute> fused = getFusedValue(group, schemaCorrespondences, schemaElement);
fusedRecord.setWeight(fused.getValue());
fusedRecord.setAttributeProvenance(Player.WEIGHT, fused.getOriginalIds());
}
@Override
public boolean hasValue(Player record, Correspondence<Attribute, Matchable> correspondence) {
return record.hasValue(Player.WEIGHT);
}
}
| true |
c53d411b59d9beb9e7a6ed55dad53ab80664165b | Java | tliu35/CS342_Project_5 | /Card.java | UTF-8 | 966 | 3.828125 | 4 | [] | no_license | /**------------------------------------------------------------------------
* @author Adam Socik
* April 2014
* CS 342 Software Design
*
* A card is a 2 character string with index 0 representing the rank of the
* card and index 1 representing the suit of the card.
* ------------------------------------------------------------------------*/
public class Card
{
private String card;
public Card()
{
card = null;
}
public Card(String card)
{
this.card = card;
}
public void setCard(String s)
{
card = s;
}
public String getCard()
{
return card;
}
public char getRank()
{
return card.charAt(0);
}
public char getSuit()
{
return card.charAt(1);
}
public int getNumericRank()
{
char rank = getRank();
switch (rank)
{
case 'K': return 13;
case 'Q': return 12;
case 'J': return 11;
case 'T': return 10;
case 'A': return 1;
default: return Character.getNumericValue(rank);
}
}
}
| true |
3aa9a12932eb516f95336e33fc9d76359a8eddc3 | Java | mborjesson/GameJam-1.0 | /src/gamejam10/options/Options.java | UTF-8 | 5,960 | 2.671875 | 3 | [] | no_license | package gamejam10.options;
import gamejam10.*;
import java.io.*;
import java.lang.reflect.*;
import java.util.*;
public class Options {
transient static private Options options = null;
transient private Options writableOptions = null;
static public Options getInstance() {
if (options == null) {
try {
options = read();
try {
options.writableOptions = (Options)options.clone();
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
} catch (IOException e) {
e.printStackTrace();
}
if (options == null) {
options = new Options();
}
}
return options;
}
static public Options getWritableInstance() {
return getInstance().writableOptions;
}
transient private int configVersion = 2;
private int width = 1280;
private int height = 720;
private boolean fullscreen = false;
private boolean vsync = true;
private int targetFrameRate = 0;
private boolean showFPS = false;
private boolean soundEnabled = true;
private float musicVolume = 1;
private float soundVolume = 1;
private int multiSample = 2;
private boolean shadersEnabled = true;
private Options() {}
public void setWidth(int width) {
this.width = width;
}
public int getWidth() {
return width;
}
public void setHeight(int height) {
this.height = height;
}
public int getHeight() {
return height;
}
public double getAspectRatio() {
return width/(double)height;
}
public void setSoundEnabled(boolean soundEnabled) {
this.soundEnabled = soundEnabled;
}
public boolean isSoundEnabled() {
return soundEnabled;
}
public void setFullscreen(boolean fullscreen) {
this.fullscreen = fullscreen;
}
public boolean isFullscreen() {
return fullscreen;
}
public void setTargetFrameRate(int targetFrameRate) {
this.targetFrameRate = targetFrameRate;
}
public int getTargetFrameRate() {
return targetFrameRate;
}
public void setVSync(boolean vsync) {
this.vsync = vsync;
}
public boolean isVSync() {
return vsync;
}
public void setShowFPS(boolean showFPS) {
this.showFPS = showFPS;
}
public boolean isShowFPS() {
return showFPS;
}
public void setMultiSample(int multiSample) {
this.multiSample = multiSample;
}
public int getMultiSample() {
return multiSample;
}
public void setShadersEnabled(boolean shadersEnabled) {
this.shadersEnabled = shadersEnabled;
}
public boolean isShadersEnabled() {
return shadersEnabled;
}
public void setMusicVolume(float musicVolume) {
this.musicVolume = musicVolume;
}
public float getMusicVolume() {
return musicVolume;
}
public void setSoundVolume(float soundVolume) {
this.soundVolume = soundVolume;
}
public float getSoundVolume() {
return soundVolume;
}
public void write() throws IOException {
File file = Installer.OPTIONS_FILE;
System.out.println("Writing config to " + file);
OutputStream out = new BufferedOutputStream(new FileOutputStream(file));
Properties props = new Properties();
props.setProperty("configVersion", String.valueOf(configVersion));
for (Field f : getClass().getDeclaredFields()) {
int mod = f.getModifiers();
if (!Modifier.isTransient(mod)) {
try {
String name = f.getName();
String value = String.valueOf(f.get(this));
props.setProperty(name, value);
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}
try {
props.store(out, null);
} finally {
out.close();
}
}
public static Options read() throws IOException {
if (!Installer.OPTIONS_FILE.exists()) {
// write defaults
Options opt = new Options();
opt.write();
return opt;
}
InputStream in = new FileInputStream(Installer.OPTIONS_FILE);
try {
Options opt = new Options();
Properties props = new Properties();
props.load(in);
String versionStr = props.getProperty("configVersion");
int version = 0;
if (versionStr != null) {
try {
version = Integer.valueOf(versionStr);
} catch (NumberFormatException e) {
}
}
if (version == opt.configVersion) {
for (Field f : opt.getClass().getDeclaredFields()) {
int mod = f.getModifiers();
if (!Modifier.isTransient(mod)) {
try {
String name = f.getName();
String value = props.getProperty(name);
if (value == null) {
continue;
}
Class<?> type = f.getType();
if (type == Integer.TYPE || type == Integer.class) {
try {
f.setInt(opt, Integer.valueOf(value));
} catch (NumberFormatException e) {
System.out.println("Could not read value " + value);
}
} else if (type == Boolean.TYPE || type == Boolean.class) {
f.setBoolean(opt, Boolean.valueOf(value));
} else if (type == Float.TYPE || type == Float.class) {
try {
f.setFloat(opt, Float.valueOf(value));
} catch (NumberFormatException e) {
System.out.println("Could not read value " + value);
}
} else if (type == String.class) {
f.set(opt, value);
}
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}
} else {
System.out.println("Wrong version, using default values");
try {
opt.write();
} catch (IOException e) {
}
}
return opt;
} finally {
in.close();
}
}
@Override
protected Object clone() throws CloneNotSupportedException {
Options opt = new Options();
for (Field f : opt.getClass().getDeclaredFields()) {
int mod = f.getModifiers();
if (!Modifier.isStatic(mod) && !Modifier.isFinal(mod)) {
try {
f.set(opt, f.get(this));
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}
return opt;
}
}
| true |
1c36c310e55a018ea9a7d9266198ec0a19f08096 | Java | virgibruno/backendi | /patrones/src/Flyweight/ropaConTest/PrendaFactory.java | UTF-8 | 867 | 2.890625 | 3 | [] | no_license | package Flyweight.ropaConTest;
import java.util.HashMap;
public class PrendaFactory {
// atributos
private static PrendaFactory instance;
private HashMap<String, Prenda> prendas;
// constructor
private PrendaFactory(){
prendas = new HashMap();
}
// métodos
public static PrendaFactory getInstance(){
if (instance == null)
instance = new PrendaFactory();
return instance;
}
public Prenda getPrenda(String tipo){
Prenda p = prendas.get(tipo);
if (p == null) {
p = new Prenda(tipo);
prendas.put(tipo, p);
}
return p;
}
// getters y setters
public HashMap<String, Prenda> getPrendas() {
return prendas;
}
public void setPrendas(HashMap<String, Prenda> prendas) {
this.prendas = prendas;
}
}
| true |
d676eae10c629178dd02a08d9739916807f74856 | Java | JetBrains/intellij-community | /java/java-tests/testData/ig/com/siyeh/igfixes/style/methodRefs2lambda/CaptureOnInvalidatedReference1.java | UTF-8 | 170 | 2.46875 | 2 | [
"Apache-2.0"
] | permissive | import java.util.Optional;
class MyTest {
private static Class<?> test(Optional<Object> value) {
return value.map(Object::get<caret>Class).orElse(int.class);
}
} | true |
ceb1c16caf6cbf0d04cc30b48b28859460cf3457 | Java | vanessa2808/Java-ADP-Vanessa | /21_Hw3_Object_NguyenThiHongYen/src/fraction/ArrayOfFraction.java | UTF-8 | 1,777 | 3.390625 | 3 | [] | no_license | package fraction;
import java.util.Scanner;
public class ArrayOfFraction
{
private static Scanner sc;
private Fraction [] a =new Fraction[100];
private int n;
public void input()
{
sc=new Scanner(System.in);
System.out.println("Enter n: ");
n=sc.nextInt();
for(int i=0;i<n;i++)
{
System.out.println("enter fraction: "+i+": ");
Fraction f=new Fraction();
f.input();
a[i]=f;
}
}
public void output()
{
for(int i=0;i<n;i++) {
a[i].output();
}
}
//in ra phan so co tu chan
public void isEvenFration()
{
for(int i=0;i<n;i++)
{
if(a[i].getnumerator()%2==0)
a[i].output();
}
}
public void isMaxFraction() {
int index=0;
double max=1.0*a[0].devide();
for (int i=1;i<n;i++) {
if(1.0*a[i].devide()>max) {
max=1.0*a[i].devide();
index=i;
}
}
System.out.println("index"+index);
a[index].output();
}
//tinh tong 2 phan so lon nhat
public void sum()
{
Fraction sum=a[0].plus(a[1]);
double max= 1.0*sum.devide();
int index1=0;
int index2=1;
for (int i=1;i<n-1;i++) {
sum=a[i].plus(a[i+1]);
if(1.0*sum.devide()>max) {
max=1.0*sum.devide();
index1=i;
index2=i+1;
}
}
System.out.println("index1: "+index1+"index2: "+index2);
a[index1].output();
a[index2].output();
(a[index1].plus (a[index2])).output();
}
//sort phan so
public void issortdecrease() {
for(int i=0;i<n;i++) {
for(int j=i+1;j<n;j++) {
if(1.0*a[i].devide()>1.0*a[j].devide()) {
Fraction temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}
}
}
public static void main(String []args) {
ArrayOfFraction yen=new ArrayOfFraction();
yen.input();
//yen.sum();
yen.issortdecrease();
yen.output();
/*yen.output();
yen.isEvenFration();
yen.isMaxFraction();*/
}
}
| true |
30d44853a4fa7431559b149c3b46d6a2cacb7681 | Java | actor20170211030627/DevelopHelper | /cpp/src/main/java/com/actor/cpptest/ConstUtils.java | UTF-8 | 986 | 2.53125 | 3 | [
"Apache-2.0"
] | permissive | package com.actor.cpptest;
import android.content.Context;
/**
* description: 常量
* 1.存放一些保密的数据,比如"服务端IP","端口","接口地址","授权的key"等等.
* 2.顺便 so里面验证 app的签名 来防止别人盗用so文件
* 3.使用:
* 1.先在Application里初始化: ConstUtils.jniInit(applicationContext, isDebugMode);
* 2.再调用: ConstUtils.getString(ConstUtils.IP);
*
* @author : ldf
* date : 2018/11/13 on 12
* @version 1.0
*/
public class ConstUtils {
static {
System.loadLibrary("native-lib");
}
/**
* 在Application中初始化
* @param isDebugMode 是否是debug模式
*/
public static native void jniInit(Context context, boolean isDebugMode);
/**
* 获取c里面的内容
* @param key 通过key获取
*/
public static native String getString(String key);
public static final String IP = "IP";
public static final String PORT = "PORT";
}
| true |
a6ba1c363f50ee5484e37cda3d709996a1c52974 | Java | RonFranco98/JavaCheckersAI | /checkers project ron franco/src/checkers/TwoPlayersGame.java | UTF-8 | 30,834 | 2.96875 | 3 | [] | no_license | package checkers;
import javafx.geometry.Pos;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.GridPane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;
import javafx.scene.shape.Rectangle;
import javafx.scene.text.Font;
import javafx.scene.text.Text;
public class TwoPlayersGame {
//vars
private static opening_window OP = new opening_window();
private static String name1;
private static String name2;
private static boolean turn = true;//true = blue; false = red;
private static Group layout = new Group();
private static Scene scene = new Scene(layout, 800 - 12, 800 - 12);
private static Rectangle[][] board_sqers = new Rectangle[8][8];
private static Circle[] RedCircle = new Circle[12];
private static Circle[] BlueCircle = new Circle[12];
private static String[][] PawnLocations = {
{"R", "N", "R", "N", "R", "N", "R", "N"},
{"N", "R", "N", "R", "N", "R", "N", "R"},
{"R", "N", "R", "N", "R", "N", "R", "N"},
{"N", "N", "N", "N", "N", "N", "N", "N"},
{"N", "N", "N", "N", "N", "N", "N", "N"},
{"N", "B", "N", "B", "N", "B", "N", "B"},
{"B", "N", "B", "N", "B", "N", "B", "N"},
{"N", "B", "N", "B", "N", "B", "N", "B"}
};
public void start(String n1, String n2) {
name1 = n1;
name2 = n2;
paint();
PaintPawn();
AddMotionDetectorToAll();
OP.window.setScene(scene);
OP.window.setResizable(false);
}
//graphics
public static void paint() {
boolean BlackWhite = true;//true = black , false = white
for (int i = 0; i < board_sqers.length; i++) {
for (int j = 0; j < board_sqers.length; j++) {
if (BlackWhite == true) {
board_sqers[i][j] = new Rectangle(i * 100, j * 100, 100, 100);
board_sqers[i][j].setFill(Color.rgb(131, 89, 48));
BlackWhite = false;
} else if (BlackWhite == false) {
board_sqers[i][j] = new Rectangle(i * 100, j * 100, 100, 100);
board_sqers[i][j].setFill(Color.rgb(163, 133, 102));
BlackWhite = true;
}
layout.getChildren().add(board_sqers[i][j]);
}
if (BlackWhite == true) {
BlackWhite = false;
} else if (BlackWhite == false) {
BlackWhite = true;
}
}
}
public static void PaintPawn() {
int X = 50;
int Y = 50;
int RedCounter = 0;
int BlueCounter = 0;
for (int i = 0; i < PawnLocations.length; i++) {
for (int j = 0; j < PawnLocations.length; j++) {
if (PawnLocations[i][j] == "R") {
RedCircle[RedCounter] = new Circle(X, Y, 40, Color.rgb(255, 71, 71));
layout.getChildren().add(RedCircle[RedCounter]);
RedCounter++;
} else if (PawnLocations[i][j] == "B") {
BlueCircle[BlueCounter] = new Circle(X, Y, 40, Color.rgb(51, 102, 255));
layout.getChildren().add(BlueCircle[BlueCounter]);
BlueCounter++;
} else if (PawnLocations[i][j] == "RK") {
RedCircle[RedCounter] = new Circle(X, Y, 40, Color.rgb(179, 0, 0));
RedCircle[RedCounter].setStroke(Color.GOLD);
RedCircle[RedCounter].setStrokeWidth(5);
layout.getChildren().add(RedCircle[RedCounter]);
RedCounter++;
} else if (PawnLocations[i][j] == "BK") {
BlueCircle[BlueCounter] = new Circle(X, Y, 40, Color.rgb(0, 49, 204));
BlueCircle[BlueCounter].setStroke(Color.GOLD);
BlueCircle[BlueCounter].setStrokeWidth(5);
layout.getChildren().add(BlueCircle[BlueCounter]);
BlueCounter++;
}
X = X + 100;
}
X = 50;
Y = Y + 100;
}
for (; RedCounter < RedCircle.length; RedCounter++) {
RedCircle[RedCounter] = new Circle(900, 900, 40, Color.rgb(255, 71, 71));
layout.getChildren().add(RedCircle[RedCounter]);
}
for (; BlueCounter < BlueCircle.length; BlueCounter++) {
BlueCircle[BlueCounter] = new Circle(900, 900, 40, Color.rgb(51, 102, 255));
layout.getChildren().add(BlueCircle[BlueCounter]);
}
}
//user movement input function
public static void AddMotionDetector(int i) {
if (turn == true) {
BlueCircle[i].setOnMouseClicked(e -> {
cleanSquerOutLines();
int colum = (int) (((BlueCircle[i].getCenterX()) - 50) / 100);
int row = (int) (((BlueCircle[i].getCenterY()) - 50) / 100);
if (colum > 0 && row > 0) {
if (can_move_left(colum, row) == true) {
makeSquerOutLines(colum - 1, row - 1);
board_sqers[colum - 1][row - 1].setOnMouseClicked(event -> {
move_left(colum, row);
});
}
if (colum > 1 && row > 1) {
if (can_eat_left(colum, row)) {
makeSquerOutLines(colum - 2, row - 2);
board_sqers[colum - 2][row - 2].setOnMouseClicked(event -> {
eat_left(colum, row);
});
}
}
}
if (colum < 7 && row > 0) {
if (can_move_right(colum, row)) {
makeSquerOutLines(colum + 1, row - 1);
board_sqers[colum + 1][row - 1].setOnMouseClicked(event -> {
move_right(colum, row);
});
}
if (colum < 6 && row > 1) {
if (can_eat_right(colum, row)) {
makeSquerOutLines(colum + 2, row - 2);
board_sqers[colum + 2][row - 2].setOnMouseClicked(event -> {
eat_right(colum, row);
});
}
}
}
if (colum > 0 && row < 7) {
if (can_move_left_back(colum, row) == true) {
makeSquerOutLines(colum - 1, row + 1);
board_sqers[colum - 1][row + 1].setOnMouseClicked(event -> {
move_left_back(colum, row);
});
}
if(colum > 1 && row <6){
if(can_eat_left_back(colum , row)){
makeSquerOutLines(colum - 2, row + 2);
board_sqers[colum - 2][row + 2].setOnMouseClicked(event -> {
eat_left_back(colum, row);
});
}
}
}
if (colum < 7 && row < 7) {
if (can_move_right_back(colum, row) == true) {
makeSquerOutLines(colum + 1, row + 1);
board_sqers[colum + 1][row + 1].setOnMouseClicked(event -> {
move_right_back(colum, row);
});
}
if(colum < 6 && row < 6){
if(can_eat_right_back(colum, row)){
makeSquerOutLines(colum + 2, row + 2);
board_sqers[colum + 2][row + 2].setOnMouseClicked(event -> {
eat_right_back(colum, row);
});
}
}
}
});
} else if (turn == false) {
RedCircle[i].setOnMouseClicked(e -> {
cleanSquerOutLines();
int colum = (int) (((RedCircle[i].getCenterX()) - 50) / 100);
int row = (int) (((RedCircle[i].getCenterY()) - 50) / 100);
if (colum > 0 && row > 0) {
if (can_move_left(colum, row)) {
makeSquerOutLines(colum - 1, row - 1);
board_sqers[colum - 1][row - 1].setOnMouseClicked(event -> {
move_left(colum, row);
});
}
if (colum > 1 && row > 1) {
if (can_eat_left(colum, row)) {
makeSquerOutLines(colum - 2, row - 2);
board_sqers[colum - 2][row - 2].setOnMouseClicked(event -> {
eat_left(colum, row);
repaint();
});
}
}
}
if (colum < 7 && row > 0) {
if (can_move_right(colum, row)) {
makeSquerOutLines(colum + 1, row - 1);
board_sqers[colum + 1][row - 1].setOnMouseClicked(event -> {
move_right(colum, row);
});
}
if (colum < 6 && row > 1) {
if (can_eat_right(colum, row)) {
makeSquerOutLines(colum + 2, row - 2);
board_sqers[colum + 2][row - 2].setOnMouseClicked(event -> {
eat_right(colum, row);
});
}
}
}
if (colum > 0 && row < 7) {
if (can_move_left_back(colum, row) == true) {
makeSquerOutLines(colum - 1, row + 1);
board_sqers[colum - 1][row + 1].setOnMouseClicked(event -> {
move_left_back(colum, row);
});
}
if(colum > 1 && row < 6){
if(can_eat_left_back(colum , row)){
makeSquerOutLines(colum - 2, row + 2);
board_sqers[colum - 2][row + 2].setOnMouseClicked(event -> {
eat_left_back(colum, row);
});
}
}
}
if (colum < 7 && row < 7) {
if (can_move_right_back(colum, row) == true) {
makeSquerOutLines(colum + 1, row + 1);
board_sqers[colum + 1][row + 1].setOnMouseClicked(event -> {
move_right_back(colum, row);
});
}
if(colum < 6 && row < 6){
if(can_eat_right_back(colum , row)){
makeSquerOutLines(colum + 2, row + 2);
board_sqers[colum + 2][row + 2].setOnMouseClicked(event -> {
eat_right_back(colum, row);
});
}
}
}
});
}
}
public static void AddMotionDetectorToAll() {
for (int i = 0; i < RedCircle.length; i++) {
AddMotionDetector(i);
}
}
//tools
public static void makeSquerOutLines(int colum, int row) {
board_sqers[colum][row].setStroke(Color.rgb(153, 230, 255));
board_sqers[colum][row].setStrokeWidth(5);
}
public static void cleanSquerOutLines() {
for (int i = 0; i < board_sqers.length; i++) {
for (int j = 0; j < board_sqers.length; j++) {
board_sqers[i][j].setStrokeWidth(0);
}
}
}
public static void LocationConverter() {
String temp;
for (int i = 0; i < PawnLocations.length / 2; i++) {
for (int j = 0; j < PawnLocations.length; j++) {
temp = PawnLocations[i][j];
PawnLocations[i][j] = PawnLocations[(PawnLocations.length - 1) - i][(PawnLocations.length - 1) - j];
PawnLocations[(PawnLocations.length - 1) - i][(PawnLocations.length - 1) - j] = temp;
}
}
}
public static void turnBoard() {
LocationConverter();
layout.getChildren().remove(0, 88);
paint();
PaintPawn();
AddMotionDetectorToAll();
}
public static void repaint() {
layout.getChildren().remove(0, 88);
paint();
PaintPawn();
AddMotionDetectorToAll();
}
//wining functions
public static boolean CheckRedWin() {
boolean bool = true;
for (int i = 0; i < PawnLocations.length; i++) {
for (int j = 0; j < PawnLocations.length; j++) {
if (PawnLocations[i][j] == "B" ||PawnLocations[i][j] == "BK") {
bool = false;
}
}
}
return bool;
}
public static boolean CheckBlueWin() {
boolean bool = true;
for (int i = 0; i < PawnLocations.length; i++) {
for (int j = 0; j < PawnLocations.length; j++) {
if (PawnLocations[i][j] == "R" || PawnLocations[i][j] == "RK") {
bool = false;
}
}
}
return bool;
}
public static void won(String Name, String color) {
GridPane GP = new GridPane();
Text text = new Text(Name + " won!!");
Button rematch_button = new Button("Rematch ?");
text.setFont(Font.font("Tahoma", 72));
if (color == "red") {
text.setFill(Color.RED);
} else if (color == "blue") {
text.setFill(Color.BLUE);
}
GP.add(text,0,0);
GP.add(rematch_button,0,1);
GP.setAlignment(Pos.CENTER);
GP.setVgap(10);
Scene sce = new Scene(GP, 750, 300);
sce.getStylesheets().add("checkers/style.css");
OP.setWindowScene(sce);
rematch_button.setOnAction(e ->{
PawnLocations = new String[][]{
{"R", "N", "R", "N", "R", "N", "R", "N"},
{"N", "R", "N", "R", "N", "R", "N", "R"},
{"R", "N", "R", "N", "R", "N", "R", "N"},
{"N", "N", "N", "N", "N", "N", "N", "N"},
{"N", "N", "N", "N", "N", "N", "N", "N"},
{"N", "B", "N", "B", "N", "B", "N", "B"},
{"B", "N", "B", "N", "B", "N", "B", "N"},
{"N", "B", "N", "B", "N", "B", "N", "B"}
};
OP.window.setScene(scene);
turn = true;
turnBoard();
turnBoard();
});
}
//moving
public static boolean can_move_left(int colum, int row) {
if (PawnLocations[row - 1][colum - 1] == "N") {
return true;
} else {
return false;
}
}
public static void move_left(int colum, int row) {
if (turn == true) {
if (PawnLocations[row][colum] == "B") {
PawnLocations[row - 1][colum - 1] = "B";
} else if (PawnLocations[row][colum] == "BK") {
PawnLocations[row - 1][colum - 1] = "BK";
}
if (row - 1 == 0) {
PawnLocations[row - 1][colum - 1] = "BK";
}
turn = false;
} else if (turn == false) {
if (PawnLocations[row][colum] == "R") {
PawnLocations[row - 1][colum - 1] = "R";
} else if (PawnLocations[row][colum] == "RK") {
PawnLocations[row - 1][colum - 1] = "RK";
}
if (row - 1 == 0) {
PawnLocations[row - 1][colum - 1] = "RK";
}
turn = true;
}
PawnLocations[row][colum] = "N";
turnBoard();
}
public static boolean can_move_right(int colum, int row) {
if (PawnLocations[row - 1][colum + 1] == "N") {
return true;
} else {
return false;
}
}
public static void move_right(int colum, int row) {
if (turn == true) {
if (PawnLocations[row][colum] == "B") {
PawnLocations[row - 1][colum + 1] = "B";
} else if (PawnLocations[row][colum] == "BK") {
PawnLocations[row - 1][colum + 1] = "BK";
}
if (row - 1 == 0) {
PawnLocations[row - 1][colum + 1] = "BK";
}
turn = false;
} else if (turn == false) {
if (PawnLocations[row][colum] == "R") {
PawnLocations[row - 1][colum + 1] = "R";
} else if (PawnLocations[row][colum] == "RK") {
PawnLocations[row - 1][colum + 1] = "RK";
}
if (row - 1 == 0) {
PawnLocations[row - 1][colum + 1] = "RK";
}
turn = true;
}
PawnLocations[row][colum] = "N";
turnBoard();
}
//eating
public static boolean can_eat_left(int colum, int row) {
if (turn == true) {
if ((PawnLocations[row - 1][colum - 1] == "R" || PawnLocations[row - 1][colum - 1] == "RK") && PawnLocations[row - 2][colum - 2] == "N") {
return true;
} else {
return false;
}
} else {
if ((PawnLocations[row - 1][colum - 1] == "B" || PawnLocations[row - 1][colum - 1] == "BK") && PawnLocations[row - 2][colum - 2] == "N") {
return true;
} else {
return false;
}
}
}
public static void eat_left(int colum, int row) {
if (turn == true) {
if (PawnLocations[row][colum] == "B") {
PawnLocations[row - 2][colum - 2] = "B";
} else if (PawnLocations[row][colum] == "BK") {
PawnLocations[row - 2][colum - 2] = "BK";
}
PawnLocations[row - 1][colum - 1] = "N";
PawnLocations[row][colum] = "N";
if (row - 2 == 0) {
PawnLocations[row - 2][colum - 2] = "BK";
}
if (CheckBlueWin() == true) {
won(name1, "blue");
}
if (colum - 2 > 1 && row - 2 > 1) {
if (can_eat_right(colum - 2, row - 2) == false && can_eat_left(colum - 2, row - 2) == false) {
turn = false;
turnBoard();
} else {
turn = true;
repaint();
}
} else {
turn = false;
turnBoard();
}
} else if (turn == false) {
if (PawnLocations[row][colum] == "R") {
PawnLocations[row - 2][colum - 2] = "R";
} else if (PawnLocations[row][colum] == "RK") {
PawnLocations[row - 2][colum - 2] = "RK";
}
PawnLocations[row - 1][colum - 1] = "N";
PawnLocations[row][colum] = "N";
if (row - 2 == 0) {
PawnLocations[row - 2][colum - 2] = "RK";
}
if (CheckRedWin() == true) {
won(name2, "red");
}
if (colum - 2 > 1 && row - 2 > 1) {
if (can_eat_right(colum - 2, row - 2) == false && can_eat_left(colum - 2, row - 2) == false) {
turn = true;
turnBoard();
} else {
turn = false;
repaint();
}
} else {
turn = true;
turnBoard();
}
}
}
public static boolean can_eat_right(int colum, int row) {
if (turn == true) {
if ((PawnLocations[row - 1][colum + 1] == "R" || PawnLocations[row - 1][colum + 1] == "RK") && PawnLocations[row - 2][colum + 2] == "N") {
return true;
} else {
return false;
}
} else {
if ((PawnLocations[row - 1][colum + 1] == "B" || PawnLocations[row - 1][colum + 1] == "BK") && PawnLocations[row - 2][colum + 2] == "N") {
return true;
} else {
return false;
}
}
}
public static void eat_right(int colum, int row) {
if (turn == true) {
if (PawnLocations[row][colum] == "B") {
PawnLocations[row - 2][colum + 2] = "B";
} else if (PawnLocations[row][colum] == "BK") {
PawnLocations[row - 2][colum + 2] = "BK";
}
PawnLocations[row - 1][colum + 1] = "N";
PawnLocations[row][colum] = "N";
if (row - 2 == 0) {
PawnLocations[row - 2][colum + 2] = "BK";
}
if (CheckBlueWin() == true) {
won(name1, "blue");
}
if (colum + 2 < 6 && row - 2 > 1) {
if (can_eat_left(colum + 2, row - 2) == false && can_eat_right(colum + 2, row - 2) == false) {
turn = false;
turnBoard();
} else {
turn = true;
repaint();
}
} else {
turn = false;
turnBoard();
}
} else if (turn == false) {
if (PawnLocations[row][colum] == "R") {
PawnLocations[row - 2][colum + 2] = "R";
} else if (PawnLocations[row][colum] == "RK") {
PawnLocations[row - 2][colum + 2] = "RK";
}
PawnLocations[row - 1][colum + 1] = "N";
PawnLocations[row][colum] = "N";
if (row - 2 == 0) {
PawnLocations[row - 2][colum + 2] = "RK";
}
if (CheckRedWin() == true) {
won(name2, "red");
}
if (colum + 2 < 6 && row - 2 > 1) {
if (can_eat_left(colum + 2, row - 2) == false && can_eat_right(colum + 2, row - 2) == false) {
turn = true;
turnBoard();
} else {
turn = false;
repaint();
}
} else {
turn = true;
turnBoard();
}
}
}
//moving back
public static boolean can_move_left_back(int colum, int row) {
if (PawnLocations[row + 1][colum - 1] == "N" && (PawnLocations[row][colum] == "BK" || PawnLocations[row][colum] == "RK")) {
return true;
} else {
return false;
}
}
public static void move_left_back(int colum, int row) {
if (turn == true) {
if (PawnLocations[row][colum] == "B") {
PawnLocations[row + 1][colum - 1] = "B";
} else if (PawnLocations[row][colum] == "BK") {
PawnLocations[row + 1][colum - 1] = "BK";
}
if (row - 1 == 0) {
PawnLocations[row + 1][colum - 1] = "BK";
}
turn = false;
} else if (turn == false) {
if (PawnLocations[row][colum] == "R") {
PawnLocations[row + 1][colum - 1] = "R";
} else if (PawnLocations[row][colum] == "RK") {
PawnLocations[row + 1][colum - 1] = "RK";
}
if (row - 1 == 0) {
PawnLocations[row + 1][colum - 1] = "RK";
}
turn = true;
}
PawnLocations[row][colum] = "N";
turnBoard();
}
public static boolean can_move_right_back(int colum, int row) {
if (PawnLocations[row + 1][colum + 1] == "N" && (PawnLocations[row][colum] == "BK" || PawnLocations[row][colum] == "RK")) {
return true;
} else {
return false;
}
}
public static void move_right_back(int colum, int row) {
if (turn == true) {
if (PawnLocations[row][colum] == "B") {
PawnLocations[row + 1][colum + 1] = "B";
} else if (PawnLocations[row][colum] == "BK") {
PawnLocations[row + 1][colum + 1] = "BK";
}
if (row - 1 == 0) {
PawnLocations[row + 1][colum + 1] = "BK";
}
turn = false;
} else if (turn == false) {
if (PawnLocations[row][colum] == "R") {
PawnLocations[row + 1][colum + 1] = "R";
} else if (PawnLocations[row][colum] == "RK") {
PawnLocations[row + 1][colum + 1] = "RK";
}
if (row - 1 == 0) {
PawnLocations[row + 1][colum + 1] = "RK";
}
turn = true;
}
PawnLocations[row][colum] = "N";
turnBoard();
}
//eating back
public static boolean can_eat_left_back(int colum, int row) {
if (turn == true) {
if (((PawnLocations[row + 1][colum - 1] == "R" || PawnLocations[row + 1][colum - 1] == "RK") && PawnLocations[row + 2][colum - 2] == "N") && PawnLocations[row][colum] == "BK") {
return true;
} else {
return false;
}
} else {
if (((PawnLocations[row + 1][colum - 1] == "B" || PawnLocations[row + 1][colum - 1] == "BK") && PawnLocations[row + 2][colum - 2] == "N") && (PawnLocations[row][colum] == "RK")) {
return true;
} else {
return false;
}
}
}
public static void eat_left_back(int colum, int row) {
if (turn == true) {
PawnLocations[row + 2][colum - 2] = "BK";
PawnLocations[row + 1][colum - 1] = "N";
PawnLocations[row][colum] = "N";
if (CheckBlueWin() == true) {
won(name1, "blue");
}
if (colum - 2 > 1 && row + 2 > 1) {
if (can_eat_right_back(colum - 2, row + 2) == false && can_eat_left_back(colum - 2, row + 2) == false && can_eat_right(colum - 2, row + 2) == false && can_eat_left(colum - 2, row + 2) == false) {
turn = false;
turnBoard();
} else {
turn = true;
repaint();
}
} else {
turn = false;
turnBoard();
}
} else if (turn == false) {
PawnLocations[row + 2][colum - 2] = "RK";
PawnLocations[row + 1][colum - 1] = "N";
PawnLocations[row][colum] = "N";
if (CheckRedWin() == true) {
won(name2, "red");
}
if (colum - 2 > 1 && row + 2 > 1) {
if (can_eat_right_back(colum - 2, row + 2) == false && can_eat_left_back(colum - 2, row + 2) == false && can_eat_right(colum - 2, row + 2) == false && can_eat_left(colum - 2, row + 2) == false) {
turn = true;
turnBoard();
} else {
turn = false;
repaint();
}
} else {
turn = true;
turnBoard();
}
}
}
public static boolean can_eat_right_back(int colum, int row) {
if (turn == true) {
if (((PawnLocations[row + 1][colum + 1] == "R" || PawnLocations[row + 1][colum + 1] == "RK") && PawnLocations[row + 2][colum + 2] == "N") && PawnLocations[row][colum] == "BK") {
return true;
} else {
return false;
}
} else {
if (((PawnLocations[row + 1][colum + 1] == "B" || PawnLocations[row + 1][colum + 1] == "BK") && PawnLocations[row + 2][colum + 2] == "N") && PawnLocations[row][colum] == "RK") {
return true;
} else {
return false;
}
}
}
public static void eat_right_back(int colum, int row) {
if (turn == true) {
PawnLocations[row + 2][colum + 2] = "BK";
PawnLocations[row + 1][colum + 1] = "N";
PawnLocations[row][colum] = "N";
if (CheckBlueWin() == true) {
won(name1, "blue");
}
if (colum + 2 < 6 && row + 2 < 6) {
if (can_eat_left_back(colum + 2, row + 2) == false && can_eat_right_back(colum + 2, row + 2) == false && can_eat_left(colum + 2, row + 2) == false && can_eat_right(colum + 2, row + 2) == false) {
turn = false;
turnBoard();
} else {
turn = true;
repaint();
}
} else {
turn = false;
turnBoard();
}
} else if (turn == false) {
PawnLocations[row + 2][colum + 2] = "RK";
PawnLocations[row + 1][colum + 1] = "N";
PawnLocations[row][colum] = "N";
if (CheckRedWin() == true) {
won(name2, "red");
}
if (colum + 2 < 6 && row + 2 < 6) {
if (can_eat_left(colum + 2, row + 2) == false && can_eat_right(colum + 2, row + 2) == false && can_eat_left_back(colum + 2, row + 2) == false && can_eat_right_back(colum + 2, row + 2) == false) {
turn = true;
turnBoard();
} else {
turn = false;
repaint();
}
} else {
turn = true;
turnBoard();
}
}
}
} | true |
ab760db7194c8b721cde5ed8ecba5581ce40e198 | Java | Exibot/Dei | /Producto.java | UTF-8 | 572 | 3.984375 | 4 | [] | no_license | import java.util.Scanner;
public class Producto{
public static void main(String[] args){
Scanner entrada = new Scanner( System.in );
int numero1;
int numero2;
int numero3;
int valorFinal;
System.out.println("Ingrese el Primer Numero");
numero1 = entrada.nextInt();
System.out.println("Ingrese el Segundo Numero");
numero2 = entrada.nextInt();
System.out.println("Ingrese el Tercer Numero");
numero3 = entrada.nextInt();
valorFinal = numero1 * numero2 * numero3;
System.out.printf("El valor del producto es de %d\n", valorFinal);
}
} | true |
6dec61fb5ec6f28c9de3f5160db0b10420344f3b | Java | yang92/dormitory | /Dormitory/src/main/java/com/dormitory/util/DateUtil.java | UTF-8 | 11,041 | 3.234375 | 3 | [] | no_license | package com.dormitory.util;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Locale;
public class DateUtil {
/**
* 현재 년월 - YYYYMM
*/
public static String getMonth() {
String month;
Calendar cal = Calendar.getInstance(Locale.getDefault());
StringBuffer buf = new StringBuffer();
buf.append(Integer.toString(cal.get(Calendar.YEAR)));
month = Integer.toString(cal.get(Calendar.MONTH) + 1);
if (month.length() == 1)
month = "0" + month;
buf.append(month);
return buf.toString();
}
/**
* 현재 년월일 - YYYYMMDD
*/
public static String getDate() {
String month, day;
Calendar cal = Calendar.getInstance(Locale.getDefault());
StringBuffer buf = new StringBuffer();
buf.append(Integer.toString(cal.get(Calendar.YEAR)));
month = Integer.toString(cal.get(Calendar.MONTH) + 1);
if (month.length() == 1)
month = "0" + month;
day = Integer.toString(cal.get(Calendar.DATE));
if (day.length() == 1)
day = "0" + day;
buf.append(month);
buf.append(day);
return buf.toString();
}
/**
* 현재 시간 - HHMISS
*/
public static String getTime() {
String hour, min, sec;
Calendar cal = Calendar.getInstance(Locale.getDefault());
StringBuffer buf = new StringBuffer();
hour = Integer.toString(cal.get(Calendar.HOUR_OF_DAY));
if (hour.length() == 1)
hour = "0" + hour;
min = Integer.toString(cal.get(Calendar.MINUTE));
if (min.length() == 1)
min = "0" + min;
sec = Integer.toString(cal.get(Calendar.SECOND));
if (sec.length() == 1)
sec = "0" + sec;
buf.append(hour);
buf.append(min);
buf.append(sec);
return buf.toString();
}
/**
* 특정날짜에 일자를 더한 값
*
* @param DateTime
* YYMMDDHHMMSS
* @param plusDay
* 더할 일자
* @return 특정날짜에 일자를 더한 값
*/
public static String getAddDay(String DateTime, int plusDay) {
if (DateTime == null)
return "";
if (DateTime.length() == 8)
DateTime += "000000";
if (DateTime.equals("99991231")) {
return "99991231000000";
}
if (DateTime.equals("99991231235959")) {
return "99991231235959";
}
int y = Integer.parseInt(DateTime.substring(0, 4));
int m = Integer.parseInt(DateTime.substring(4, 6));
int d = Integer.parseInt(DateTime.substring(6, 8));
java.util.GregorianCalendar sToday = new java.util.GregorianCalendar();
sToday.set(y, m - 1, d);
sToday.add(GregorianCalendar.DAY_OF_MONTH, plusDay);
int day = sToday.get(GregorianCalendar.DAY_OF_MONTH);
int month = sToday.get(GregorianCalendar.MONTH) + 1;
int year = sToday.get(GregorianCalendar.YEAR);
String sNowyear = String.valueOf(year);
String sNowmonth = "";
String sNowday = "";
if (month < 10)
sNowmonth = "0" + String.valueOf(month);
else
sNowmonth = String.valueOf(month);
if (day < 10)
sNowday = "0" + String.valueOf(day);
else
sNowday = String.valueOf(day);
return sNowyear + sNowmonth + sNowday + DateTime.substring(8, 14);
}
/**
* 특정날짜에 달을 더한 값
*
* @param DateTime
* YYMMDDHHMMSS
* @param plusDay
* 더할 일자
* @return 특정날짜에 일자를 더한 값
*/
public static String getAddMonth(String DateTime, int plusMonth) {
if (DateTime == null)
return "";
if (DateTime.length() == 8)
DateTime += "000000";
if (DateTime.equals("99991231")) {
return "99991231000000";
}
if (DateTime.equals("99991231235959")) {
return "99991231235959";
}
int y = Integer.parseInt(DateTime.substring(0, 4));
int m = Integer.parseInt(DateTime.substring(4, 6));
int d = Integer.parseInt(DateTime.substring(6, 8));
java.util.GregorianCalendar sToday = new java.util.GregorianCalendar();
sToday.set(y, m - 1, d);
sToday.add(GregorianCalendar.MONTH, plusMonth);
int day = sToday.get(GregorianCalendar.DAY_OF_MONTH);
int month = sToday.get(GregorianCalendar.MONTH) + 1;
int year = sToday.get(GregorianCalendar.YEAR);
String sNowyear = String.valueOf(year);
String sNowmonth = "";
String sNowday = "";
if (month < 10)
sNowmonth = "0" + String.valueOf(month);
else
sNowmonth = String.valueOf(month);
if (day < 10)
sNowday = "0" + String.valueOf(day);
else
sNowday = String.valueOf(day);
return sNowyear + sNowmonth + sNowday + DateTime.substring(8, 14);
}
/**
* 어제 날짜 - YYYYMMDD
*/
public static String getYesterday() {
java.util.GregorianCalendar sToday = new java.util.GregorianCalendar();
sToday.add(GregorianCalendar.DAY_OF_MONTH, -1);
int day = sToday.get(GregorianCalendar.DAY_OF_MONTH);
int month = sToday.get(GregorianCalendar.MONTH) + 1;
int year = sToday.get(GregorianCalendar.YEAR);
String sNowyear = String.valueOf(year);
String sNowmonth = "";
String sNowday = "";
if (month < 10)
sNowmonth = "0" + String.valueOf(month);
else
sNowmonth = String.valueOf(month);
if (day < 10)
sNowday = "0" + String.valueOf(day);
else
sNowday = String.valueOf(day);
return sNowyear + sNowmonth + sNowday;
}
/**
* 내일 날짜 - YYYYMMDD
*/
public static String getTomorrow() {
java.util.GregorianCalendar sToday = new java.util.GregorianCalendar();
sToday.add(GregorianCalendar.DAY_OF_MONTH, 1);
int day = sToday.get(GregorianCalendar.DAY_OF_MONTH);
int month = sToday.get(GregorianCalendar.MONTH) + 1;
int year = sToday.get(GregorianCalendar.YEAR);
String sNowyear = String.valueOf(year);
String sNowmonth = "";
String sNowday = "";
if (month < 10)
sNowmonth = "0" + String.valueOf(month);
else
sNowmonth = String.valueOf(month);
if (day < 10)
sNowday = "0" + String.valueOf(day);
else
sNowday = String.valueOf(day);
return sNowyear + sNowmonth + sNowday;
}
/**
* 년도 1900 - 9999, 월 01 - 12, 일 01 - 31, 시 00 - 23, 분 00 - 59, 초 00 - 59
*
* @param param
* 검사 문자열
*
* @return 검사결과
*/
public static boolean isDate(String param) {
if (param == null || param.length() != 8)
return false;
try {
int year = Integer.parseInt(param.substring(0, 4));
int month = Integer.parseInt(param.substring(4, 6));
int day = Integer.parseInt(param.substring(6, 8));
if (year < 1900 || year > 9999)
return false;
if (month < 1 || month > 12)
return false;
if (day < 1 || day > 31)
return false;
return true;
} catch (Exception e) {
return false;
}
}
/**
* 년도 1900 - 9999, 월 01 - 12, 일 01 - 31, 시 00 - 23, 분 00 - 59, 초 00 - 59
*
* @param param
* 검사 문자열
*
* @return 검사결과
*/
public static boolean isTime(String param) {
if (param == null || param.length() != 6)
return false;
try {
int hour = Integer.parseInt(param.substring(0, 2));
int min = Integer.parseInt(param.substring(2, 4));
int sec = Integer.parseInt(param.substring(4, 6));
if (hour < 0 || hour > 23)
return false;
if (min < 0 || min > 59)
return false;
if (sec < 0 || sec > 59)
return false;
return true;
} catch (Exception e) {
return false;
}
}
/**
* 현재년월에서 다음 한달후 년월을 불러온다.
*
* @param month
* YYYY-MM 타입으로 년월
* @return 년월을 String으로 리턴한다.
*/
public static String getNextMonth(String month) {
String lsYear = null;
String lsMonth = null;
int liYear = Integer.parseInt(month.substring(0, 4));
int liMonth = Integer.parseInt(month.substring(5, 7));
if (liMonth == 12) {
liMonth = 1;
liYear++;
} else
liMonth++;
lsYear = liYear + "";
if (liMonth < 10)
lsMonth = "0" + liMonth;
else
lsMonth = "" + liMonth;
return lsYear + "-" + lsMonth;
}// end of getNextMonth
/**
* 현재년월에서 이전 한달전 년월을 불러온다.
*
* @param Month
* YYYYMM 타입으로 년월
* @return 년월을 String으로 리턴한다.
*/
public static String getPrevMonth(String Month) {
String lsYear = null;
String lsMonth = null;
int liYear = Integer.parseInt(Month.substring(0, 4));
int liMonth = Integer.parseInt(Month.substring(5, 7));
if (liMonth == 1) {
liMonth = 12;
liYear--;
} else
liMonth--;
lsYear = liYear + "";
if (liMonth < 10)
lsMonth = "0" + liMonth;
else
lsMonth = liMonth + "";
return lsYear + "-" + lsMonth;
}// end of getPrevMonth
/**
* @param date
* YYYY-MM-DD 포멧이나 YYYY-DD 포멧의 날짜
* @return 해당 달의 마지막 날
*/
public static String getLastDay(String date) {
return getLastDay(Integer.parseInt(date.substring(0, 4)),
Integer.parseInt(date.substring(5, 7)), false);
}
/**
* @param yyyy
* 년
* @param mm
* 월
* @return 해당 달의 마지막 날
*/
public static String getLastDay(String yyyy, String mm) {
return getLastDay(Integer.parseInt(yyyy), Integer.parseInt(mm), false);
}
/**
* @param yyyy
* 년
* @param mm
* 월
* @param isNowDate
* - 구하려는 달이 현재달일 경우 현재 날짜를 리턴할지
* @return 해당 달의 마지막 날
*/
public static String getLastDay(String yyyy, String mm, boolean isNowDate) {
return getLastDay(Integer.parseInt(yyyy), Integer.parseInt(mm),
isNowDate);
}
/**
* @param yyyy
* 년
* @param mm
* 월
* @param isNowDate
* - 구하려는 달이 현재달일 경우 현재 날짜를 리턴할지
* @return 해당 달의 마지막 날
*/
public static String getLastDay(int yyyy, int mm, boolean isNowDate) {
Calendar calendar = Calendar.getInstance();
String str = "";
if (isNowDate && mm == calendar.get(Calendar.MONTH) + 1) {
str = calendar.get(Calendar.DATE) + "";
} else {
calendar.set(yyyy, mm - 1, 1);
calendar.add(Calendar.MONTH, 1);
calendar.add(Calendar.DATE, -1);
int date = calendar.get(Calendar.DATE);
str = date < 10 ? "0" + date : date + "";
}
return str;
}
/**
* 날짜 간격 구하기
*
* @throws ParseException
*/
public static long diffOfDate(String begin, String end)
throws ParseException {
SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd");
Date beginDate = formatter.parse(begin);
Date endDate = formatter.parse(end);
long diff = endDate.getTime() - beginDate.getTime();
long diffDays = diff / (24 * 60 * 60 * 1000);
return diffDays;
}
} | true |
61404b8699d6723672fc92641cbaf9116073b674 | Java | kcnwst/BcitJ2eeProject | /4911---timesheets/COMP4911Project/JavaSource/comp4911/models/Employee.java | UTF-8 | 5,210 | 2.96875 | 3 | [] | no_license | package comp4911.models;
import java.io.Serializable;
import java.sql.Date;
import java.sql.Time;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToOne;
import javax.persistence.Table;
import javax.persistence.Transient;
/**
* The employee class which represents all the
* data that is being used to describe an employee that
* is stored in the database.
*
* @author
*
*/
@Entity
@Table(name="Employees")
public class Employee implements Serializable {
/**
* Default serial version ID;
*/
private static final long serialVersionUID = 1L;
/**
* The corresponding employee's number in the system.
* Which is named "EmpNum" in the "Employee" table.
*/
@Id
@Column(name="EmpNum")
private int empNumber;
/**
* The relationship of the Employee table verses the Credential table,
* which a one to one relationship, joint column at the field "UserId"
*/
@OneToOne
@JoinColumn(name="UserId")
private Credential credential;
/**
* The user's first name, named the "EmpFname" column
* in the "Employee" table.
*/
@Column(name="EmpFname")
private String firstName;
/**
* The user's last name, named the "EmpLname" column
* in the "Employee" table.
*/
@Column(name="EmpLname")
private String lastName;
/**
* The supervisor's employee number, name the "SupervisorEmpNum"
* column in the "Employee" table.
*/
@Column(name="SupervisorEmpNum")
private int supNum;
/**
* The number of vacation days for each employee, named
* the "VacationDays" column in the "Employee" table.
*/
@Column(name="VacationDays")
private int vacDays;
/**
* The date that the employee was hired, named "HireDate"
* column in the "Employee" table.
*/
@Column(name="HireDate")
private Date hireDate;
/**
* The email that each employee own's.
*/
@Column(name="Email")
private String email;
/**
* The id that identifies which pay rate each employee
* is assigned to.
*/
@Column(name="PayRateId")
private String payRateId;
/**
* Shows whether a user in the system is active or not.
*/
@Transient
private boolean active;
/**
* Empty constructor of the Employee class.
*/
public Employee() {}
/**
* Gets the corresponding employee number.
*
* @return empNumber
*/
public int getEmpNumber() {
return empNumber;
}
/**
* Sets the employee number.
*
* @param empNumber
*/
public void setEmpNumber(int empNumber) {
this.empNumber = empNumber;
}
/**
* Gets the credentials for an employee.
*
* @return credential
*/
public Credential getCredential() {
return credential;
}
/**
* Sets the credential for a corresponding employee.
*
* @param credential
*/
public void setCredential(Credential credential) {
this.credential = credential;
}
/**
* Gets the first name of an employee.
*
* @return firstName
*/
public String getFirstName() {
return firstName;
}
/**
* Sets the first name of an employee.
*
* @param firstName
*/
public void setFirstName(String firstName) {
this.firstName = firstName;
}
/**
* Gets the last name of an employee.
*
* @return lastName
*/
public String getLastName() {
return lastName;
}
/**
* Sets the last name of an employee.
*
* @param lastName
*/
public void setLastName(String lastName) {
this.lastName = lastName;
}
/**
* Gets the status of an employee, if he is active or not.
*
* @return active
*/
public boolean isActive() {
return active;
}
/**
* Sets the activity statues of an employee.
*
* @param active
*/
public void setActive(boolean active) {
this.active = active;
}
/**
* Gets the hired date that was recorded.
*
* @return hireDate
*/
public Date getHireDate() {
return hireDate;
}
/**
* Sets the hired date of an employee.
*
* @param hireDate
*/
public void setHireDate(Date hireDate) {
this.hireDate = hireDate;
}
/**
* Gets the pay rate id for an employee.
*
* @return payRateId
*/
public String getPayRateId() {
return payRateId;
}
/**
* Sets the pay rate Id of an employee.
*
* @param payRateId
*/
public void setPayRateId(String payRateId) {
this.payRateId = payRateId;
}
/**
* Gets the email of an employee.
*
* @return email
*/
public String getEmail() {
return email;
}
/**
* Sets the email address for an employee.
*
* @param email
*/
public void setEmail(String email) {
this.email = email;
}
/**
* Gets the corresponding employee's supervisor's employee number.
*
* @return supNum
*/
public int getSupNum() {
return supNum;
}
/**
* Sets the corresponding employee's supervisor's employee number.
*
* @param supNum
*/
public void setSupNum(int supNum) {
this.supNum = supNum;
}
/**
* Gets the vacations days for an employee.
*
* @return vacDays
*/
public int getVacDays() {
return vacDays;
}
/**
* Sets the vacation days of an employee.
*
* @param vacDays
*/
public void setVacDays(int vacDays) {
this.vacDays = vacDays;
}
}
| true |
ab9863254246ca9ba40b8f4064d9503ab960681c | Java | DLennertz/TrabalhoJava1 | /TrabalhoDeConclusaoJava1/src/pessoal/Funcionario.java | UTF-8 | 138 | 1.695313 | 2 | [] | no_license | package pessoal;
import java.io.IOException;
public interface Funcionario{
public void relatorioNumeroContas() throws IOException;
}
| true |
2c1873f514a8a5c43cebc5b60731ac540b5915a7 | Java | songdada1995/shardingsphere-jdbc-demo | /src/test/java/com/example/java/Test1.java | UTF-8 | 875 | 2.75 | 3 | [] | no_license | package com.example.java;
import com.example.utils.DateUtils;
import org.apache.commons.collections4.CollectionUtils;
import java.util.ArrayList;
import java.util.List;
public class Test1 {
public static void main(String[] args) {
List<String> dateStrList = new ArrayList<>();
dateStrList.add("2020-04-01 05:15:20");
dateStrList.add("2021-02-02 05:15:20");
dateStrList.add("2021-03-12 09:15:20");
dateStrList.add("2021-10-12 09:15:20");
dateStrList.add("2021-04-01 15:15:20");
List<String> betweenMinAndMaxDateStrList = DateUtils.getBetweenMinAndMaxMonthStrList(dateStrList, "yyyy-MM-dd HH:mm:ss", "yyyyMM");
if (CollectionUtils.isNotEmpty(betweenMinAndMaxDateStrList)) {
for (String s : betweenMinAndMaxDateStrList) {
System.out.println(s);
}
}
}
}
| true |
fc5e79815805498f85e12cad87c5980092925e55 | Java | iBotSpeak/iBot | /ibot-core/src/main/java/pl/themolka/ibot/storage/IObjectId.java | UTF-8 | 127 | 1.8125 | 2 | [] | no_license | package pl.themolka.ibot.storage;
import org.bson.types.ObjectId;
public interface IObjectId {
ObjectId getObjectId();
}
| true |
64617bd0d3f4eb1b17ea2e30b3c0985d4ecb01ba | Java | dannyhuo/data-producer | /src/test/java/com/data/dataproducer/TestKafka.java | UTF-8 | 981 | 2.171875 | 2 | [] | no_license | package com.data.dataproducer;
import org.apache.kafka.clients.admin.AdminClient;
import org.apache.kafka.clients.admin.KafkaAdminClient;
import org.apache.kafka.clients.admin.ListTopicsResult;
import org.apache.kafka.clients.admin.NewTopic;
import java.util.*;
import java.util.concurrent.ExecutionException;
/**
* @author danny
* @date 2019/9/5 5:02 PM
*/
public class TestKafka {
public static void main(String[] args) throws ExecutionException, InterruptedException {
Map<String, Object> conf = new HashMap<>();
conf.put("bootstrap.servers", "localhost:9092");
AdminClient client = AdminClient.create(conf);
List<NewTopic> newTopics = new ArrayList<>();
client.createTopics(newTopics);
ListTopicsResult topics = client.listTopics();
Set set = topics.names().get();
Iterator iter = set.iterator();
while (iter.hasNext()) {
System.out.println(iter.next());
}
}
}
| true |
7bf7d8582c04891a9e3ca4fea3c743cc761523a8 | Java | RAF3197/PROP | /Project/src/screens/game/create/cells/CellsController.java | UTF-8 | 4,065 | 2.3125 | 2 | [] | no_license | package screens.game.create.cells;
import classes.Hidato;
import classes.Partida;
import classes.enums.TAdjacency;
import classes.enums.TCellShape;
import classes.enums.TDifficulty;
import classes.taulell.Taulell;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.RadioButton;
import javafx.scene.input.MouseEvent;
import javafx.scene.paint.Paint;
import javafx.scene.shape.Polygon;
import javafx.scene.shape.Rectangle;
import javafx.stage.Stage;
import lib.Manager;
import lib.Utils;
import java.net.URL;
import java.util.ResourceBundle;
public class CellsController implements Initializable {
@FXML
private Polygon triangle, hexagon;
@FXML
private Rectangle quadrat;
@FXML
private RadioButton radioCostats, radioBoth;
private Taulell taulell;
@Override
public void initialize(URL location, ResourceBundle resources) {
this.taulell = Manager.getPartida().getHidato().getTaulell();
this.triangle.getStyleClass().add("game_creation_polygon_selected");
this.taulell.setTipusCela(TCellShape.TRIANGLE);
this.taulell.setTipusAdjacencia(TAdjacency.SIDE);
this.radioCostats.selectedProperty().addListener(new ChangeListener<Boolean>() {
@Override
public void changed(ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue) {
if (newValue) {
taulell.setTipusAdjacencia(TAdjacency.SIDE);
}
}
});
this.radioBoth.selectedProperty().addListener(new ChangeListener<Boolean>() {
@Override
public void changed(ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue) {
if (newValue) {
taulell.setTipusAdjacencia(TAdjacency.BOTH);
}
}
});
}
@FXML
private void handleTriangleClick(MouseEvent event) {
this.triangle.getStyleClass().add("game_creation_polygon_selected");
this.quadrat.getStyleClass().remove("game_creation_polygon_selected");
this.hexagon.getStyleClass().remove("game_creation_polygon_selected");
this.taulell.setTipusCela(TCellShape.TRIANGLE);
}
@FXML
private void handleQuadratClick(MouseEvent event) {
this.triangle.getStyleClass().remove("game_creation_polygon_selected");
this.quadrat.getStyleClass().add("game_creation_polygon_selected");
this.hexagon.getStyleClass().remove("game_creation_polygon_selected");
this.taulell.setTipusCela(TCellShape.SQUARE);
}
@FXML
private void handleHexagonClick(MouseEvent event) {
this.triangle.getStyleClass().remove("game_creation_polygon_selected");
this.quadrat.getStyleClass().remove("game_creation_polygon_selected");
this.hexagon.getStyleClass().add("game_creation_polygon_selected");
this.taulell.setTipusCela(TCellShape.HEXAGON);
}
@FXML
private void handleConstructButton(ActionEvent event) {
this.taulell.generateTaulell();
Hidato h = new Hidato(this.taulell);
try {
h.initParams(this.taulell.getTipusCela(), this.taulell.getTipusAdjacencia(), this.taulell.getNombreFiles(), this.taulell.getNombreColumnes());
if(this.taulell.getNumCaselles() < 22) h.setDificultat(TDifficulty.EASY);
else if (this.taulell.getNumCaselles() < 30) h.setDificultat(TDifficulty.MEDIUM);
else h.setDificultat(TDifficulty.HARD);
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
Manager.registerGame(new Partida(h, Manager.getUser()));
new Utils().openScreen("screens/game/create/create.fxml", "Create hidato", null, null, null, (Stage)this.triangle.getScene().getWindow(), false);
}
}
| true |
16b33bd234df3030209cf66c92eedb1e91b1bc2d | Java | pranadheer10/Assignments | /ShoppingCart/Assignment/src/com/assignment/overload/Overloading.java | UTF-8 | 472 | 3.359375 | 3 | [] | no_license | package com.assignment.overload;
public class Overloading {
public static void main(String[] args) {
employee("dhiru");
employee("James",1000);
}
// same method but different parameters
public static String employee(String name){
System.out.println(name+ " is non paid employee");
return name;
}
public static String employee(String name, int n){
System.out.println(name+" is paid employee with salory "+n );
return "name";
}
}
| true |
cab5c7eba9876b91289bce9d00fa440443e15518 | Java | GAlexMES/ConnectorLib | /src/main/java/de/szut/dqi12/cheftrainer/connectorlib/messagetemplates/TransfermarktUpdateMessageTemplate.java | UTF-8 | 1,293 | 2.515625 | 3 | [] | no_license | package de.szut.dqi12.cheftrainer.connectorlib.messagetemplates;
import org.json.JSONObject;
import de.szut.dqi12.cheftrainer.connectorlib.dataexchange.Market;
import de.szut.dqi12.cheftrainer.connectorlib.dataexchange.Transaction;
import de.szut.dqi12.cheftrainer.connectorlib.messageids.ClientToServer_MessageIDs;
import de.szut.dqi12.cheftrainer.connectorlib.messageids.MIDs;
/**
* The {@link TransfermarktUpdateMessageTemplate} is used by various messages, that do something with the {@link Market} or {@link Transaction}s.
* @author Alexander Brennecke
*
*/
abstract class TransfermarktUpdateMessageTemplate extends MessageTemplate{
private final static String ID = ClientToServer_MessageIDs.TRANSFER_MARKET;
private String messageType;
/**
* Constructor
* @param messageType the ID of the message, the extends the {@link TransfermarktUpdateMessageTemplate}
*/
public TransfermarktUpdateMessageTemplate(String messageType) {
super(ID);
this.messageType = messageType;
}
@Override
public void createMessageContent(){
JSONObject information = createJSON();
JSONObject message = new JSONObject();
message.put(MIDs.TYPE, messageType);
message.put(MIDs.INFORMATION, information);
messageContent = message.toString();
}
abstract JSONObject createJSON();
}
| true |
2ee48920c70e5c49c4b830c8a0164f281bda1ede | Java | shixy96/utilityRoom | /SensitiveWordAnalysis/SemanticAnalysisPlatform/src/main/java/course/web/common/DateUtility.java | UTF-8 | 5,418 | 2.5625 | 3 | [] | no_license | package course.web.common;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;
import org.apache.commons.lang3.StringUtils;
public class DateUtility {
public static final String dtSimple = "yyyy-MM-dd HH:mm:ss";
public static final String dtSimpleCommon = "yyyy-MM-dd HH:mm";
public static final String dSimple = "yyyy-MM-dd";
public static final String tSimple = "HH:mm:ss";
public static final String dtDense = "yyyyMMddHHmmss";
public static final String dDense = "yyyyMMdd";
public static final String tDense = "HHmmss";
public static final String milliDense = "yyyyMMddHHmmssSSS";
public static final String dtWeeHours = "yyyy-MM-dd 00:00:00";
public static String getDTDenseDate() {
return LocalDateTime.now().format(DateTimeFormatter.ofPattern(dtDense));
}
public static String getDTSimpleDate() {
return LocalDateTime.now().format(DateTimeFormatter.ofPattern(dtSimple));
}
public static String getDDenseDate() {
return LocalDateTime.now().format(DateTimeFormatter.ofPattern(dDense));
}
public static String getDSimpleDate() {
return LocalDateTime.now().format(DateTimeFormatter.ofPattern(dSimple));
}
public static String getTDenseDate() {
return LocalDateTime.now().format(DateTimeFormatter.ofPattern(tDense));
}
public static String getTSimpleDate() {
return LocalDateTime.now().format(DateTimeFormatter.ofPattern(tSimple));
}
public static String getMilliDenseDate(Long timestamp) {
return timestamp != null
? LocalDateTime.ofInstant(new Date(timestamp).toInstant(), ZoneId.systemDefault())
.format(DateTimeFormatter.ofPattern(milliDense))
: LocalDateTime.now().format(DateTimeFormatter.ofPattern(milliDense));
}
public static Date parseDateTime(String dateStr, String format) throws DateTimeParseException {
return parseDateTime(dateStr, format, Locale.getDefault(), TimeZone.getDefault());
}
public static Date parseDateTime(String dateStr, String format, Locale locale, TimeZone timeZone)
throws DateTimeParseException {
if (StringUtils.isBlank(dateStr)) {
return null;
} else {
return Date.from(LocalDateTime
.parse(dateStr,
DateTimeFormatter.ofPattern(format).withLocale(locale).withZone(timeZone.toZoneId()))
.atZone(timeZone.toZoneId()).toInstant());
}
}
public static Date parseDate(String dateStr, String format) throws DateTimeParseException {
return parseDate(dateStr, format, Locale.getDefault(), TimeZone.getDefault());
}
public static Date parseDate(String dateStr, String format, Locale locale, TimeZone timeZone)
throws DateTimeParseException {
if (StringUtils.isBlank(dateStr)) {
return null;
} else {
return Date
.from(LocalDate
.parse(dateStr,
DateTimeFormatter.ofPattern(format).withLocale(locale)
.withZone(timeZone.toZoneId()))
.atStartOfDay(ZoneId.systemDefault()).toInstant());
}
}
public static Date getDTWeeHours() throws DateTimeParseException {
return parseDate(LocalDateTime.now().format(DateTimeFormatter.ofPattern(dtWeeHours)), dtWeeHours);
}
public static String dateToString(Date date, String format) {
if (date == null)
return "";
DateFormat df = new SimpleDateFormat(format);
return df.format(date);
}
public static String getAppointedDay(int n, String format) {
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.DAY_OF_MONTH, n);
return dateToString(calendar.getTime(), format);
}
public static Date getAppointedDay(int n) {
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.DAY_OF_MONTH, n);
return calendar.getTime();
}
public static int getOrderOfDay(String dateStr, String format, int limit) throws DateTimeParseException {
Date date = parseDate(dateStr, format);
return limit - ((int) ((new Date().getTime() - date.getTime()) / 24 / 60 / 60 / 1000));
}
public static String qingShuFormatTime(int time) {
int hour = time / (60 * 60);
int min = (time / 60) % 60;
int second = time % 60;
if (hour != 0 || min != 0 || second != 0) {
return (hour > 0 ? hour + "小时" : "") + (min > 0 ? min + "分" : "") + (second > 0 ? second + "秒" : "");
}
return "0";
}
public static String praseSecToTime(int time) {
String timeStr = "0";
int hour = 0;
int minute = 0;
int second = 0;
if (time <= 0) {
return timeStr;
} else {
minute = time / 60;
if (minute < 60) {
if (Math.floor((time / 60)) > 0) {
second = time % 60;
timeStr = minute + "分" + second + "秒";
} else {
timeStr = time + "秒";
}
} else {
hour = minute / 60;
minute = minute % 60;
second = time - hour * 3600 - minute * 60;
timeStr = hour + "小时" + minute + "分" + second + "秒";
}
}
return timeStr;
}
public static Date nowAddSeconds(int n) {
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.SECOND, n);
return calendar.getTime();
}
public static String paresLongToStringDate(long time) {
if (time <= 0) {
return "0";
}
SimpleDateFormat sdf = new SimpleDateFormat(dtSimple);
Date date = new Date(time);
return sdf.format(date);
}
}
| true |
3c23e8c545eed742a2b92e50df835e966bac217e | Java | qzxqqa/javaLearn | /demo/src/com/imooc/animal/Cat.java | UTF-8 | 213 | 3.0625 | 3 | [
"MIT"
] | permissive | package com.imooc.animal;
public class Cat {
// 成员属性:昵称、年龄、体重、品种
String name;
double month;
// 成员方法:
public void run() {
System.out.println("小猫快跑");
}
}
| true |
cde511e4481725a1a4399a0c4f0ce0b71e2f005f | Java | jitendrakr93/JLC_ALL_PROGRAMS | /Hibernate Lab39/src/com/jlcindia/hibernate/Lab39.java | UTF-8 | 1,129 | 2.71875 | 3 | [] | no_license | package com.jlcindia.hibernate;
import java.util.List;
import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
public class Lab39 {
public static void main(String[] args) {
Transaction tx=null;
try{
SessionFactory sf=HibernateUtil.getSessionFactory();
Session session=sf.openSession();
tx=session.beginTransaction();
Query q=session.createQuery("from Contact c");
q.setCacheable(true);
List<Contact> list=q.list();
for(Contact c:list){
System.out.println(c);
}
System.out.println("***");
Query q1=session.createQuery("from Contact c");
q1.setCacheable(true);
List<Contact> list1=q1.list();
for(Contact c:list1){
System.out.println(c);
}
/*Criteria ct=session.createCriteria(Contact.class);
ct.setCacheable(true);
list=q.list();
for(Contact c:list)
System.out.println(c);*/
tx.commit();
Thread.currentThread().sleep(5000);
session.close();
}catch(Exception e){
e.printStackTrace();
if(tx!=null){
tx.rollback();
}
}
}
}
| true |
f5e9cde786eaec7b44c89bacde284f39295bacf2 | Java | Dannyhh/Periodic-Table-App | /app/src/main/java/ros_dhhiggins/example/com/periodictable/MainKeyScreen.java | UTF-8 | 5,415 | 2.46875 | 2 | [] | no_license | /*
* Created by Danny Higgins on 3/16/2017.
* This class creates the main key page to learn about types of elements
*/
package ros_dhhiggins.example.com.periodictable;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Point;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.PopupWindow;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import static android.view.ViewGroup.LayoutParams.WRAP_CONTENT;
public class MainKeyScreen extends AppCompatActivity { //creates the screen
private Point p;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_key_screen);
TableLayout mainGrid = (TableLayout) findViewById(R.id.keyGrid);
genButtons(MainKeyScreen.this,mainGrid);
}
//the following method creates the buttons for the main screen
public void genButtons(final Activity context,TableLayout mainGrid ){
ImageButton[] keyButtons = new ImageButton[10];
String[] keyNames = new String[10];
keyNames[0]= "actinide";
keyNames[1]= "alkali";
keyNames[2]= "alkaline";
keyNames[3]= "basicmetal";
keyNames[4]= "halogen";
keyNames[5]= "lanthanide";
keyNames[6]= "noble";
keyNames[7]= "nonmetal";
keyNames[8]= "semimetal";
keyNames[9]= "transition";
for(int i = 0; i<=9; i++) {
keyButtons[i] = new ImageButton(context);
keyButtons[i].setImageResource(getImage(context, keyNames[i]));
keyButtons[i].setBackgroundResource(0);
setButtonClick(i, keyButtons[i]);
}
for (int j = 1; j <= 5; j++) {
TableRow tempRow = new TableRow(this);
tempRow.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT,
TableRow.LayoutParams.WRAP_CONTENT));
if (j == 1) {
tempRow.addView(keyButtons[0]);
tempRow.addView(keyButtons[1]);
}
else if(j==2){
tempRow.addView(keyButtons[2]);
tempRow.addView(keyButtons[3]);
}
else if(j==3){
tempRow.addView(keyButtons[4]);
tempRow.addView(keyButtons[5]);
}
else if(j==4){
tempRow.addView(keyButtons[6]);
tempRow.addView(keyButtons[7]);
}
else if(j==5){
tempRow.addView(keyButtons[8]);
tempRow.addView(keyButtons[9]);
}
mainGrid.addView(tempRow, new TableLayout.LayoutParams(TableLayout.LayoutParams.WRAP_CONTENT,
TableLayout.LayoutParams.WRAP_CONTENT));
}
}
//the following method gets the images for the buttons
private static int getImage(Context context, String name) {
return context.getResources().getIdentifier(name, "drawable",
context.getPackageName());
}
//the following method sets the onClick for the buttons
private void setButtonClick(final int i, final ImageButton buttonToSet) {
int[] location = new int[2];
buttonToSet.getLocationOnScreen(location);
p = new Point();
p.x = location[0];
p.y = location[1];
buttonToSet.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
showPopup(i);
}
});
}
//the following method creates the onClick for the back button
public void goBack(View view){
Intent back = new Intent(MainKeyScreen.this, MainActivity.class);
startActivity(back);
}
//the following method creates the popup
private void showPopup(int buttonClicked) {
Resources res = getResources();
String[] elementInfo = res.getStringArray(R.array.element_type_info);
LayoutInflater inflater = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View layout = inflater.inflate(R.layout.key_info_popup, (ViewGroup) findViewById(R.id.info_popup_group), false);
final PopupWindow pwindo = new PopupWindow(layout, ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT, true);
pwindo.setWidth(WRAP_CONTENT);
pwindo.setHeight(WRAP_CONTENT);
pwindo.setFocusable(true);
pwindo.setOutsideTouchable(true);
pwindo.showAtLocation(layout, Gravity.CENTER_HORIZONTAL,0,0);
//set the textView
TextView txt = (TextView) layout.findViewById(R.id.type_info);
for(int j=0; j<=12; j++){
if(buttonClicked == j){
txt.setText(elementInfo[j]);
}
}
Button btnClosePopup = (Button) layout.findViewById(R.id.close);
btnClosePopup.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
pwindo.dismiss();
}
});
}
}
| true |
ad4c3e446bfd4a26b1745ad75f5b1e2bc08166ba | Java | liferay/liferay-faces-showcase | /jsf-showcase-webapp/src/main/java/com/liferay/faces/showcase/servlet/UploadedFileCleanupListener.java | UTF-8 | 2,005 | 2.3125 | 2 | [
"Apache-2.0"
] | permissive | /**
* Copyright (c) 2000-2022 Liferay, Inc. All rights reserved.
*
* 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.liferay.faces.showcase.servlet;
import java.io.File;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
import com.liferay.faces.util.logging.Logger;
import com.liferay.faces.util.logging.LoggerFactory;
/**
* This class provides the ability to listen for session destroyed events so that temporary files can be deleted.
*
* @author Kyle Stiemann
*/
public class UploadedFileCleanupListener implements HttpSessionListener {
// Logger
private static final Logger logger = LoggerFactory.getLogger(UploadedFileCleanupListener.class);
public void sessionCreated(HttpSessionEvent httpSessionEvent) {
// no-op
}
/**
* This method will be called by the servlet container when either the session expires or the user logs out of the
* portal. Its purpose is to delete any uploaded temporary files from the file system.
*/
public void sessionDestroyed(HttpSessionEvent httpSessionEvent) {
try {
String sessionId = httpSessionEvent.getSession().getId();
String parent = UploadedFileUtil.getTempDir();
String folderName = sessionId;
File folder = new File(parent, folderName);
File[] fileList = folder.listFiles();
if (fileList != null) {
fileList = fileList.clone();
for (File file : fileList) {
file.delete();
}
}
}
catch (Exception e) {
logger.error(e);
}
}
}
| true |
500dd73a8443aa18d0ce92c3d6fcd596068c9585 | Java | chandni24/Algorithms | /stacks&queues/PriorityQueue.java | UTF-8 | 1,400 | 3.84375 | 4 | [] | no_license | /*
*
* Priority Queue Implementation
*
* @author Chandni
*/
public class PriorityQueue {
node head = null;
node top = null;
class node{
char c;
int priority;
node next;
}
public static void main(String[] args) {
PriorityQueue q = new PriorityQueue();
q.enqueue('a', 1);
q.enqueue('b', 2);
q.enqueue('c', 4);
q.enqueue('d', 3);
System.out.println(q.getHighestPriority().c);
q.printQueue();
}
public void enqueue(char e, int p) {
node n = new node();
n.c = e;
n.priority = p;
if(head == null){
head = n;
n.next = null;
top = n;
}
else {
top.next = n;
top = n;
}
}
public node dequeue() {
node n = head;
if(head.next!=null)
head = head.next;
return n;
}
public node getHighestPriority() {
node n = head;
node n_high = null;
int max = 0;
while(n!=null) {
if(max < n.priority) {
max = n.priority;
n_high = n;
}
n = n.next;
}
return n_high;
}
//To Be Fixed
// public node deleteHighestPriority() {
// node n = head;
// node prev = null;
// node curr = null;
// int max = 0;
// while(n!=null) {
// if(max < n.priority) {
// max = n.priority;
// curr = n;
// }
// prev = n;
// n = n.next;
// }
//
// return prev;
// }
public void printQueue() {
node n = head;
while(n!=null) {
System.out.print(n.c+"\t");
n = n.next;
}
System.out.println();
}
}
| true |
0eeb3e6e6ca91cfba5a88bd47547228d49fc7708 | Java | Patrikvo/Prog4_stageplaatsenAdmin | /src/DAL/Situeert.java | UTF-8 | 4,630 | 2.3125 | 2 | [] | no_license | package DAL;
import java.io.Serializable;
import java.util.List;
import javax.persistence.Basic;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlTransient;
/**
* JPA Enity class Situeert
* @author patrik
*/
@Entity
@Table(name = "situeert")
@XmlRootElement
@NamedQueries({
@NamedQuery(name = "Situeert.findAll", query = "SELECT s FROM Situeert s")
, @NamedQuery(name = "Situeert.findById", query = "SELECT s FROM Situeert s WHERE s.id = :id")
, @NamedQuery(name = "Situeert.findByBeschrijving", query = "SELECT s FROM Situeert s WHERE s.beschrijving = :beschrijving")
,@NamedQuery(name = "Situeert.findBySpecialisatieID", query = "SELECT s FROM Situeert s WHERE s.specialisatieID.id = :id")
})
public class Situeert implements Serializable {
private static final long serialVersionUID = 1L;
/*
JPA: Columns
*/
@Id
@Basic(optional = false)
@Column(name = "ID")
private Integer id;
@Basic(optional = false)
@Column(name = "Beschrijving")
private String beschrijving;
@OneToMany(cascade = CascadeType.ALL, mappedBy = "situeertID", fetch = FetchType.EAGER)
private List<Stageplaats> stageplaatsList;
@JoinColumn(name = "SpecialisatieID", referencedColumnName = "ID")
@ManyToOne(optional = false, fetch = FetchType.EAGER)
private Specialisatie specialisatieID;
/**
* Constructor
*/
public Situeert() {
}
/**
* JPA Column Getter for the field ID
* @return The field ID
*/
public Integer getId() {
return id;
}
/**
* JPA Column Setter for the field ID
* @param id new value for the field ID
*/
public void setId(Integer id) {
this.id = id;
}
/**
* JPA Column Getter for the field beschrijving
* @return The string beschrijving
*/
public String getBeschrijving() {
return beschrijving;
}
/**
* JPA Column Setter for the field beschrijving
* @param beschrijving new string for the field beschrijving
*/
public void setBeschrijving(String beschrijving) {
this.beschrijving = beschrijving;
}
/**
* JPA Column Getter for the field stageplaatsList.
* These are all stageplaatsen from this Situeert.
* @return The List stageplaatsList
*/
@XmlTransient
public List<Stageplaats> getStageplaatsList() {
return stageplaatsList;
}
/**
* JPA Column Setter for the field stageplaatsList
* These are all stageplaatsen from this Situeert.
* @param stageplaatsList new List stageplaatsList
*/
public void setStageplaatsList(List<Stageplaats> stageplaatsList) {
this.stageplaatsList = stageplaatsList;
}
/**
* JPA Column Getter for the field specialisatieID.
* This is the Specialisatie relevant to this Situeert.
* @return The Specialisatie specialisatieID
*/
public Specialisatie getSpecialisatieID() {
return specialisatieID;
}
/**
* JPA Column Setter for the field specialisatieID
* This is the Specialisatie relevant to this Situeert.
* @param specialisatieID new Specialisatie
*/
public void setSpecialisatieID(Specialisatie specialisatieID) {
this.specialisatieID = specialisatieID;
}
/*
Supporting methodes
*/
@Override
public int hashCode() {
int hash = 0;
hash += (id != null ? id.hashCode() : 0);
return hash;
}
@Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Situeert)) {
return false;
}
Situeert other = (Situeert) object;
if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
return false;
}
return true;
}
@Override
public String toString() {
return getBeschrijving();
}
}
| true |
dd632905ac43ee8935bc166decfa3154c3e7ebcd | Java | pab6750/GoogleHashPractice | /src/Slice.java | UTF-8 | 1,051 | 3.515625 | 4 | [] | no_license | import java.util.ArrayList;
public class Slice {
private int row1;
private int row2;
private int col1;
private int col2;
private ArrayList<Cell> cells;
public Slice(int row1, int row2, int col1, int col2) {
this.row1 = row1;
this.row2 = row2;
this.col1 = col1;
this.col2 = col2;
this.cells = new ArrayList<Cell>();
}
public int area() {
int verticalSide = this.row2 - this.row1;
int horizontalSide = this.col2 - this.col1;
return verticalSide * horizontalSide;
}
//setters and getters
public int getRow1() {
return row1;
}
public void setRow1(int row1) {
this.row1 = row1;
}
public ArrayList<Cell> getCells() {
return cells;
}
public void setCells(ArrayList<Cell> cells) {
this.cells = cells;
}
public int getRow2() {
return row2;
}
public void setRow2(int row2) {
this.row2 = row2;
}
public int getCol1() {
return col1;
}
public void setCol1(int col1) {
this.col1 = col1;
}
public int getCol2() {
return col2;
}
public void setCol2(int col2) {
this.col2 = col2;
}
}
| true |
c88fe4c904252d44b569500da184b52c8f8b2599 | Java | stefan0351/media-library | /gui/src/com/kiwisoft/media/books/BookRow.java | UTF-8 | 1,320 | 2.703125 | 3 | [] | no_license | package com.kiwisoft.media.books;
import com.kiwisoft.swing.table.BeanTableRow;
import com.kiwisoft.utils.CompoundComparable;
import com.kiwisoft.utils.StringUtils;
/**
* @author Stefan Stiller
*/
public class BookRow extends BeanTableRow<Book>
{
public static final String ISBN="isbn";
public BookRow(Book book)
{
super(book);
}
@Override
public Comparable getSortValue(int column, String property)
{
if (Book.TITLE.equals(property)) return getUserObject().getIndexBy();
if (Book.SERIES_TITLE.equals(property))
return new CompoundComparable<String, Integer>(getUserObject().getSeriesName(), getUserObject().getSeriesNumber());
return super.getSortValue(column, property);
}
@Override
public Object getDisplayValue(int column, String property)
{
if (Book.AUTHORS.equals(property)) return StringUtils.formatAsEnumeration(getUserObject().getAuthors(), "; ");
if (Book.PAGE_COUNT.equals(property))
{
Integer pageCount=getUserObject().getPageCount();
if (pageCount!=null && pageCount>0) return pageCount;
return null;
}
if (ISBN.equals(property))
{
String isbn=getUserObject().getIsbn13();
if (StringUtils.isEmpty(isbn)) isbn=getUserObject().getIsbn10();
return isbn;
}
return super.getDisplayValue(column, property);
}
}
| true |
8336187e1d8b639aa365580978cd7f40bd324b8c | Java | inf112-v20/Todo | /src/main/java/inf112/core/tile/AbstractTile.java | UTF-8 | 864 | 2.796875 | 3 | [] | no_license | package inf112.core.tile;
import com.badlogic.gdx.math.Vector2;
public abstract class AbstractTile implements ITile{
//private float xVal, yVal;
private Vector2 pos;
private TileId tileId;
private Rotation rotation;
/**
* A base for all Tiles that implements the base necessities for a fully functioning Tile-object
* @param coordinates Position on TileMap
* @param tileId TileId representing Tile
*/
public AbstractTile(Vector2 coordinates, TileId tileId) {
//this.xVal = coordinates.x;
//this.yVal = coordinates.y;
pos = coordinates.cpy();
this.tileId = tileId;
}
@Override
public Vector2 getPos() {
return pos;
}
@Override
public int getId() { return tileId.getId(); }
@Override
public TileId getTileId() {
return tileId;
}
}
| true |
aa99c764e2d63e3029af16fee4ec26e76db42e32 | Java | MrNiceRicee/contactapp | /app/src/main/java/com/example/contactapp/BaseContact.java | UTF-8 | 1,817 | 2.5 | 2 | [] | no_license | package com.example.contactapp;
import android.content.Intent;
public class BaseContact {
private BaseContact_Name name;
private String phone;
private BaseContact_Address address;
private BaseContact_DateOfBirth dateOfBirth;
private String email;
private String url;
private String description;
//necessary to have a name and phonenumber
public BaseContact(BaseContact_Name name, String phone) {
this.name = name;
this.phone = phone;
}
public BaseContact_Name getName() {
return name;
}
public void setName(BaseContact_Name name) {
this.name = name;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
try {
Integer.parseInt(phone);
String phonenum = phone.replaceFirst("(\\d{3})(\\d{3})(\\d+)", "($1) $2-$3");
this.phone = phonenum;
}catch(Exception e){
this.phone = phone;
};
}
public BaseContact_Address getAddress() {
return address;
}
public void setAddress(BaseContact_Address address) {
this.address = address;
}
public BaseContact_DateOfBirth getDateOfBirth() {
return dateOfBirth;
}
public void setDateOfBirth(BaseContact_DateOfBirth dateOfBirth) {
this.dateOfBirth = dateOfBirth;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
} | true |
20e8d4d0b6cad6cf31c78dc31ee3b1a8a0b0c9bd | Java | Yeon22/TopCredu-Study-Java | /과제_강사선생님풀이/과제풀이_컬렉션20180102_2/src/학생성적컬렉션/CStudent.java | UHC | 1,119 | 3.125 | 3 | [] | no_license | package л÷;
import java.util.Scanner;
public class CStudent {
private CInfo m_tStudent;
Scanner sin = new Scanner(System.in);
CStudent(){
m_tStudent = new CInfo();
}
//лԷ
public void Input() {
System.out.print("̸ Է : ");
m_tStudent.strName = sin.nextLine();
System.out.print(" Է : ");
m_tStudent.iKor = Integer.parseInt(sin.nextLine());
System.out.print(" Է : ");
m_tStudent.iEng = Integer.parseInt(sin.nextLine());
System.out.print(" Է : ");
m_tStudent.iMath = Integer.parseInt(sin.nextLine());
}
//л
public void Output() {
System.out.print(m_tStudent.strName+"\t"+m_tStudent.iKor+"\t"+m_tStudent.iEng);
System.out.println("\t"+m_tStudent.iMath+"\t"+m_tStudent.iTotal+"\t"+m_tStudent.fAver);
}
//հ ִ Լ
public void Sum() {
m_tStudent.iTotal = m_tStudent.iKor+m_tStudent.iEng+m_tStudent.iMath;
m_tStudent.fAver = (float)m_tStudent.iTotal/3.0f;
}
public CInfo GetInfo() {
return m_tStudent;
}
}
| true |
9e02ec74cfb4756cdb3ed5d6263c911a939c277c | Java | HugeShawn/spring | /spring/spring_mvc/src/main/java/com/nokia/dao/UserDao.java | UTF-8 | 211 | 1.554688 | 2 | [] | no_license | package com.nokia.dao;
/**
* @program: spring
* @ClassName UserDao
* @description:
* @author: gaoxiang
* @create: 2021-08-20 00:24
* @Version 1.0
**/
public interface UserDao {
public void save();
}
| true |
fa9f15810e8209d35ee770a032a74bceb219a0f7 | Java | xigolle/WakeApp | /app/src/main/java/com/example/joeyd/wakeapp/AlarmReceiver.java | UTF-8 | 1,273 | 2.796875 | 3 | [] | no_license | package com.example.joeyd.wakeapp;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;
/**
* Created by Mathias on 7/01/2016.
*/
public class AlarmReceiver extends BroadcastReceiver {
Context context;
@Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "Checking if awake.", Toast.LENGTH_LONG).show();
this.context = context;
wakeMethod();
}
protected void wakeMethod() {
// accelerometerManager accelerometer = new accelerometerManager(context, MainActivity.instance);
if (!MainActivity.instance.accelerometer.awake) {
TextManager.Send("0478057618", "wake me up", context,1);
MainActivity.instance.accelerometer.awake = false;
Toast.makeText(context, "Rise and shine!", Toast.LENGTH_LONG).show();
}
else if (MainActivity.instance.accelerometer.awake) {
TextManager.Send("0478057618"," I am awake",context,0);
MainActivity.instance.accelerometer.awake = false;
Toast.makeText(context, "You are awake, did you sleep well?", Toast.LENGTH_LONG).show();
}
}
}
| true |
4a61b7a14c77e72b6dc44137bfcc5ba5ef8eac49 | Java | fzc621/NewsApp | /NewsApp/app/src/main/java/com/java/seven/newsapp/api/NewsApi.java | UTF-8 | 5,094 | 2.0625 | 2 | [
"MIT"
] | permissive | package com.java.seven.newsapp.api;
/**
* Created by zzy on 17-9-8.
*/
import android.util.Log;
import com.google.android.gms.common.data.DataBufferObserver;
import com.java.seven.newsapp.bean.LatestNews;
import com.java.seven.newsapp.bean.News;
import com.java.seven.newsapp.bean.Record;
import com.java.seven.newsapp.bean.SimpleNews;
import com.java.seven.newsapp.chinesenews.news.NewsCategory;
import org.litepal.crud.DataSupport;
import java.util.ArrayList;
import java.util.List;
import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Func1;
import rx.schedulers.Schedulers;
public class NewsApi {
private static final int DEFAULT_TIMEOUT = 5;
private NewsServices tsinghuaService;
private static NewsApi tsinghuaApi;
private Retrofit retrofit;
private NewsApi() {
//设置超时时间
OkHttpClient.Builder httpcientBuilder = new OkHttpClient.Builder();
Retrofit retrofit = new Retrofit.Builder()
.client(httpcientBuilder.build())//
.baseUrl(Config.NEWS_URL)
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.addConverterFactory(GsonConverterFactory.create())
.build();
tsinghuaService = retrofit.create(NewsServices.class);
}
public static NewsApi getInstance(){
if (tsinghuaApi == null) {
synchronized (NewsApi.class){
if (tsinghuaApi == null){
tsinghuaApi = new NewsApi();
}
}
}
return tsinghuaApi;
}
public void getLatestNews(Subscriber<LatestNews> subscriber, int size, int pageNo, int[] category){
List<Observable<LatestNews>> array = new ArrayList<>();
for (int i : category) {
array.add(tsinghuaService.getLatestNews(i, size, pageNo)
.subscribeOn(Schedulers.io())
.unsubscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread()));
}
Observable<LatestNews> merge = Observable.merge(array).map(new Func1<LatestNews, LatestNews>() {
@Override
public LatestNews call(LatestNews latestNews) {
for (LatestNews.ListBean bean : latestNews.getList()) {
new SimpleNews().setNewsClassTag(NewsCategory.nameToCode(bean.getNewsClassTag()))
.setNews_ID(bean.getNews_ID())
.setNews_Pictures(bean.getNews_Pictures())
.setNews_Title(bean.getNews_Title())
.setNews_Intro(bean.getNews_Intro())
.setNews_Author(bean.getNews_Author())
.setNews_Time(bean.getNews_Time()).save();
if (DataSupport.where("news_id = ?", bean.getNews_ID()).findFirst(Record.class) != null) {
bean.setRead(true);
}
}
return latestNews;
}
});
merge.subscribe(subscriber);
}
public void getSearchNews(Subscriber<LatestNews> subscriber, String keyWord){
tsinghuaService.getSearchNews(keyWord)
.subscribeOn(Schedulers.io())
.unsubscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(subscriber);
}
public void getDetailNews(Subscriber<News> subscriber, String newsId) {
tsinghuaService.getDetailNews(newsId)
.subscribeOn(Schedulers.io())
.unsubscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(subscriber);
}
public void getNews(Subscriber<LatestNews.ListBean> subscriber, String[] ids) {
List<Observable<News>> array = new ArrayList<>();
for (String id : ids) {
array.add(tsinghuaService.getDetailNews(id)
.subscribeOn(Schedulers.io())
.unsubscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread()));
}
Observable<LatestNews.ListBean> merrge = Observable.merge(array).map(new Func1<News, LatestNews.ListBean>() {
@Override
public LatestNews.ListBean call(News news) {
return new LatestNews.ListBean().setNews_ID(news.getNews_ID())
.setNews_Pictures(news.getNews_Pictures())
.setNews_Title(news.getNews_Title())
.setNews_Author(news.getNews_Author())
.setNews_Intro(news.getNews_Content().substring(0, 20))
.setNews_Time(news.getNews_Time());
}
});
merrge.subscribe(subscriber);
}
}
| true |
aec6eccd36a552baa3a88f50b7d92b00dde95212 | Java | zhangm1993/boot-yql | /src/main/java/com/ideal/manage/dsp/repository/industry/DocumentRepository.java | UTF-8 | 654 | 1.929688 | 2 | [] | no_license | package com.ideal.manage.dsp.repository.industry;
import com.ideal.manage.dsp.bean.industry.Document;
import com.ideal.manage.dsp.repository.framework.BaseRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import java.util.List;
public interface DocumentRepository extends BaseRepository<Document,Long> {
@Query("update Document set delFlag=?2,status=?3 where id in(?1)")
@Modifying
int updateDoc(List<Long> ids,Long delFlag,Long status);
@Query("update Document set status=?2 where id in(?1)")
@Modifying
int updateStatusDoc(List<Long> id,Long status);
}
| true |
fcd05449aee5c1b9d267f9f6728d855f2ce5af6b | Java | Ajony/20201222_bat | /viewscreen/src/main/java/com/h3c/vdi/viewscreen/api/model/request/file/RequestUploadFile.java | UTF-8 | 702 | 1.734375 | 2 | [] | no_license | package com.h3c.vdi.viewscreen.api.model.request.file;
import com.h3c.vdi.viewscreen.api.result.base.BasicUploadFileRecords;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.*;
import lombok.experimental.Accessors;
import org.springframework.web.multipart.MultipartFile;
//@Data
@NoArgsConstructor
@EqualsAndHashCode(callSuper = true)
@ToString(callSuper = true)
@Setter
@Getter
@Accessors(chain = true)
@ApiModel(description = "上传文件")
public class RequestUploadFile extends BasicUploadFileRecords {
private static final long serialVersionUID = 354105240827283502L;
@ApiModelProperty("文件")
private MultipartFile file;
} | true |
03fd4af02cc0fed451d132346bc8cf335b03f8f9 | Java | informatique-cdc/ebad | /src/main/java/fr/icdc/ebad/service/EnvironnementService.java | UTF-8 | 13,393 | 1.554688 | 2 | [
"Apache-2.0"
] | permissive | package fr.icdc.ebad.service;
import com.querydsl.core.types.Predicate;
import fr.icdc.ebad.domain.Application;
import fr.icdc.ebad.domain.Environnement;
import fr.icdc.ebad.domain.GlobalSetting;
import fr.icdc.ebad.domain.Identity;
import fr.icdc.ebad.domain.QEnvironnement;
import fr.icdc.ebad.domain.Scheduling;
import fr.icdc.ebad.domain.util.RetourBatch;
import fr.icdc.ebad.mapper.MapStructMapper;
import fr.icdc.ebad.plugin.dto.EnvironnementDiscoverDto;
import fr.icdc.ebad.plugin.dto.NormeDiscoverDto;
import fr.icdc.ebad.plugin.plugin.EnvironnementConnectorPlugin;
import fr.icdc.ebad.repository.ApplicationRepository;
import fr.icdc.ebad.repository.BatchRepository;
import fr.icdc.ebad.repository.ChaineRepository;
import fr.icdc.ebad.repository.DirectoryRepository;
import fr.icdc.ebad.repository.EnvironnementRepository;
import fr.icdc.ebad.repository.IdentityRepository;
import fr.icdc.ebad.repository.LogBatchRepository;
import fr.icdc.ebad.repository.NormeRepository;
import fr.icdc.ebad.repository.SchedulingRepository;
import fr.icdc.ebad.service.util.EbadServiceException;
import org.jobrunr.scheduling.JobScheduler;
import org.pf4j.PluginRuntimeException;
import org.pf4j.PluginWrapper;
import org.pf4j.spring.SpringPluginManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Nullable;
import javax.validation.constraints.NotNull;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import static fr.icdc.ebad.config.Constants.GLOBAL_SETTINGS_DEFAULT_IDENTITY_ID;
/**
* Created by dtrouillet on 03/03/2016.
*/
@Service
public class EnvironnementService {
public static final int CODE_SUCCESS = 0;
public static final String FR_DATE_FORMAT = "ddMMyyyy";
public static final String US_DATE_FORMAT = "yyyyMMdd";
private static final Logger LOGGER = LoggerFactory.getLogger(EnvironnementService.class);
private static final String SANS_REPONSE = "";
private final ShellService shellService;
private final EnvironnementRepository environnementRepository;
private final BatchRepository batchRepository;
private final LogBatchRepository logBatchRepository;
private final ChaineRepository chaineRepository;
private final DirectoryRepository directoryRepository;
private final NormeRepository normeRepository;
private final MapStructMapper mapStructMapper;
private final List<EnvironnementConnectorPlugin> environnementConnectorPluginList;
private final ApplicationRepository applicationRepository;
private final SpringPluginManager springPluginManager;
private final SchedulingRepository schedulingRepository;
private final JobScheduler jobScheduler;
private final GlobalSettingService globalSettingService;
private final IdentityRepository identityRepository;
public EnvironnementService(ShellService shellService, EnvironnementRepository environnementRepository, BatchRepository batchRepository, LogBatchRepository logBatchRepository, ChaineRepository chaineRepository, DirectoryRepository directoryRepository, NormeRepository normeRepository, MapStructMapper mapStructMapper, List<EnvironnementConnectorPlugin> environnementConnectorPluginList, ApplicationRepository applicationRepository, SpringPluginManager springPluginManager, SchedulingRepository schedulingRepository, JobScheduler jobScheduler, GlobalSettingService globalSettingService, IdentityRepository identityRepository) {
this.shellService = shellService;
this.environnementRepository = environnementRepository;
this.batchRepository = batchRepository;
this.logBatchRepository = logBatchRepository;
this.chaineRepository = chaineRepository;
this.directoryRepository = directoryRepository;
this.normeRepository = normeRepository;
this.mapStructMapper = mapStructMapper;
this.environnementConnectorPluginList = environnementConnectorPluginList;
this.applicationRepository = applicationRepository;
this.springPluginManager = springPluginManager;
this.schedulingRepository = schedulingRepository;
this.jobScheduler = jobScheduler;
this.globalSettingService = globalSettingService;
this.identityRepository = identityRepository;
}
@Nullable
@Transactional(readOnly = true)
public Date getDateTraiement(Long id) {
Environnement environnement = getEnvironnement(id);
try {
RetourBatch retourBatch = shellService.runCommandNew(environnement, "cat " + environnement.getHomePath() + "/" + environnement.getNorme().getCtrlMDate());
if (retourBatch.getReturnCode() == CODE_SUCCESS) {
Date dateTraitement;
String dateStr = retourBatch.getLogOut();
SimpleDateFormat dateFormatCtrlM;
try {
dateFormatCtrlM = new SimpleDateFormat(environnement.getApplication().getDateFichierPattern());
dateTraitement = dateFormatCtrlM.parse(dateStr);
} catch (NullPointerException | ParseException parseException) {
dateFormatCtrlM = new SimpleDateFormat(US_DATE_FORMAT);
dateTraitement = dateFormatCtrlM.parse(dateStr);
}
SimpleDateFormat dateFr = new SimpleDateFormat(FR_DATE_FORMAT);
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Date Traitement = {}", dateFr.format(dateTraitement));
}
return dateTraitement;
}
return null;
} catch (EbadServiceException | ParseException e) {
LOGGER.warn("Erreur lors de la récupération de la date traitement", e);
return null;
}
}
@Transactional(readOnly = true)
public void changeDateTraiement(Long environnementId, Date dateTraitement) throws EbadServiceException {
Environnement environnement = getEnvironnement(environnementId);
SimpleDateFormat dateFormatCtrlM = new SimpleDateFormat(Optional.ofNullable(environnement.getApplication().getDateFichierPattern()).orElse(FR_DATE_FORMAT));
String date = dateFormatCtrlM.format(dateTraitement);
shellService.runCommandNew(environnement, "echo " + date + " > " + environnement.getHomePath() + "/" + environnement.getNorme().getCtrlMDate());
}
//FIXME Mise en place norme
@NotNull
@Transactional(readOnly = true)
public String getEspaceDisque(Long id) {
Environnement environnement = getEnvironnement(id);
try {
RetourBatch retourBatch = shellService.runCommandNew(environnement, "echo $( df -m " + environnement.getHomePath() + " | tail -1 | awk ' { print $4 } ' )");
if (retourBatch.getReturnCode() == CODE_SUCCESS) {
LOGGER.debug("Espace disque = {}", retourBatch.getLogOut());
return retourBatch.getLogOut().replace("%", "");
}
return SANS_REPONSE;
} catch (EbadServiceException e) {
LOGGER.warn("Erreur lors de la récupération de l'espace disque", e);
return SANS_REPONSE;
}
}
@Transactional
public void deleteScheduledJobFromEnvironment(Long environmentId){
List<Scheduling> schedulings = schedulingRepository.findAllByEnvironnementId(environmentId);
schedulings.forEach(scheduling -> {
jobScheduler.delete(String.valueOf(scheduling.getId()));
schedulingRepository.delete(scheduling);
});
}
@Transactional
public void deleteEnvironnement(Environnement environnement, boolean withBatchs) {
logBatchRepository.deleteByEnvironnement(environnement);
chaineRepository.deleteByEnvironnement(environnement);
deleteScheduledJobFromEnvironment(environnement.getId());
if (withBatchs) {
batchRepository.deleteAll(environnement.getBatchs());
}
directoryRepository.deleteByEnvironnement(environnement);
environnementRepository.delete(environnement);
}
@Transactional(readOnly = true)
public Environnement getEnvironnement(Long environnementId) {
return environnementRepository.getById(environnementId);
}
@Transactional
public Environnement saveEnvironnement(Environnement environnement) {
return environnementRepository.saveAndFlush(environnement);
}
@Transactional(readOnly = true)
public Optional<Environnement> findEnvironnement(Long environnementId) {
return environnementRepository.findById(environnementId);
}
@Transactional
public Environnement updateEnvironnement(Environnement env) {
Environnement oldEnv = getEnvironnement(env.getId());
env.setBatchs(oldEnv.getBatchs());
env.setLogBatchs(oldEnv.getLogBatchs());
env.setApplication(oldEnv.getApplication());
return saveEnvironnement(env);
}
@Transactional
@PreAuthorize("@permissionServiceOpen.canImportEnvironment()")
public Set<Environnement> importEnvironments(Long applicationId) throws EbadServiceException {
Application application = applicationRepository.findById(applicationId).orElseThrow(() -> new EbadServiceException("No application with id " + applicationId));
Set<Environnement> environnements = new HashSet<>();
List<NormeDiscoverDto> normeDiscoverDtos = mapStructMapper.convertToNormeDiscoverDtoList(normeRepository.findAll());
GlobalSetting defaultIdentityId = globalSettingService.getValue(GLOBAL_SETTINGS_DEFAULT_IDENTITY_ID);
Identity identity = identityRepository.getById(Long.valueOf(defaultIdentityId.getValue()));
try {
for (EnvironnementConnectorPlugin environnementConnectorPlugin : environnementConnectorPluginList) {
PluginWrapper pluginWrapper = springPluginManager.whichPlugin(environnementConnectorPlugin.getClass());
String pluginId = pluginWrapper.getPluginId();
List<EnvironnementDiscoverDto> environnementDiscoverDtos = environnementConnectorPlugin.discoverFromApp(application.getCode(), application.getName(), normeDiscoverDtos);
for (EnvironnementDiscoverDto environnementDiscoverDto : environnementDiscoverDtos) {
Environnement environnement = environnementRepository
.findAllByExternalIdAndPluginId(environnementDiscoverDto.getId(), pluginId)
.orElse(new Environnement());
environnement.setName(environnementDiscoverDto.getName());
environnement.setHost(environnementDiscoverDto.getHost());
environnement.setHomePath(environnementDiscoverDto.getHome());
environnement.setPrefix(environnementDiscoverDto.getPrefix());
environnement.setNorme(mapStructMapper.convert(environnementDiscoverDto.getNorme()));
environnement.setExternalId(environnementDiscoverDto.getId());
environnement.setPluginId(pluginId);
environnement.setApplication(application);
environnement.setIdentity(identity);
try {
environnementRepository.save(environnement);
environnements.add(environnement);
LOGGER.debug("Environment imported {}", environnementDiscoverDto);
} catch (DataIntegrityViolationException e) {
LOGGER.error("error when try to import environment {}", environnementDiscoverDto, e);
}
}
}
} catch (PluginRuntimeException e) {
LOGGER.error("Une erreur est survenue lors de l'import des environnements : {}", e.getMessage(), e);
environnements = new HashSet<>();
}
return environnements;
}
@Transactional
@PreAuthorize("@permissionServiceOpen.canImportEnvironment()")
public List<Environnement> importEnvironments() throws EbadServiceException {
List<Application> applicationList = applicationRepository.findAll();
List<Environnement> environnementList = new ArrayList<>();
for (Application application : applicationList) {
Set<Environnement> environnements = importEnvironments(application.getId());
application.setEnvironnements(environnements);
applicationRepository.save(application);
environnementList.addAll(environnements);
}
return environnementList;
}
public Page<Environnement> getEnvironmentFromApp(Long appId, Predicate predicate, Pageable pageable) {
Predicate predicateAll = QEnvironnement.environnement.application.id.eq(appId).and(predicate);
return environnementRepository.findAll(predicateAll, pageable);
}
}
| true |
750366443612b7f9d9300356d2b529ffb76ed758 | Java | andreirk/job4j_tracker | /src/main/java/ru/job4j/JavaConfig.java | UTF-8 | 171 | 1.890625 | 2 | [] | no_license | package ru.job4j;
public class JavaConfig implements Config {
@Override
public <T> Class<? extends T> getImplClass(Class<T> ifc) {
return null;
}
}
| true |
1e9d24cee3e6a6d07c9eba0bdff571f05a7f547c | Java | Khalil9022/PBO-Prak | /Tugas/Kuis2/src/PencarianNilai.java | UTF-8 | 798 | 2.71875 | 3 | [] | no_license |
public class PencarianNilai implements InterfaceNilai{
private int nilai1,nilai2,nilai3,nilai4,rata ;
private String check ;
public PencarianNilai (int nilai1, int nilai2, int nilai3, int nilai4) {
this.nilai1 = nilai1 ;
this.nilai2 = nilai2 ;
this.nilai3 = nilai3 ;
this.nilai4 = nilai4 ;
}
private int setRata() {
rata = (nilai1 + nilai2 + nilai3 + nilai4)/4 ;
return rata;
}
@Override
public int getRata() {
return setRata() ;
}
@Override
public String checkLulus() {
if (getRata() > 85 && getRata() <101) {
return check = "LULUS" ;
}
else {
return check = "GAGAL" ;
}
}
}
| true |
0f388701ccc863ab2e5f30d744574d62a538f636 | Java | vuducmanh96/FramgiaINC_AndroidAdvance_RecyclerView_Demo | /app/src/main/java/com/example/ducmanh96/framgiainc_androidadvance_recyclerview_demo/MainActivity.java | UTF-8 | 1,378 | 2.453125 | 2 | [] | no_license | package com.example.ducmanh96.framgiainc_androidadvance_recyclerview_demo;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private RecyclerView mRecyclerView;
private MyAdapter myAdapter;
private List<item> myDataset;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mRecyclerView = findViewById(R.id.my_recyclerView);
mRecyclerView.setHasFixedSize(true);
addDataset();
myAdapter = new MyAdapter(myDataset);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getApplicationContext());
linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
mRecyclerView.setLayoutManager(linearLayoutManager);
mRecyclerView.setAdapter(myAdapter);
}
public void addDataset() {
myDataset = new ArrayList<>();
myDataset.add(new item(R.drawable.batman, "Batman"));
myDataset.add(new item(R.drawable.ironman, "Ironman"));
myDataset.add(new item(R.drawable.wonder_wommen, "Wonder Wommen"));
}
}
| true |
64495a04d156046b5baf061f560c09d1259b2096 | Java | Jagongan-Software-Engineering/kampung-siaga-covid-app | /app/src/main/java/com/seadev/aksi/room/AsesmenDao.java | UTF-8 | 432 | 1.929688 | 2 | [
"MIT"
] | permissive | package com.seadev.aksi.room;
import com.seadev.aksi.model.Asesmen;
import java.util.List;
import androidx.room.Dao;
import androidx.room.Delete;
import androidx.room.Insert;
import androidx.room.Query;
@Dao
public interface AsesmenDao {
@Query("SELECT * FROM Asesmen")
List<Asesmen> getDataAsesmen();
@Insert
void InsertDataAsesmen(Asesmen asesmen);
@Delete
void DeleteDataAsesmen(Asesmen asesmen);
}
| true |
c15d649402e0debb17d61c6e934cc914c4347a3e | Java | izerui/java-designers | /src/main/java/Mediator/Hunter.java | UTF-8 | 166 | 2.21875 | 2 | [] | no_license | package Mediator;
/**
* Hunter party member.
*/
public class Hunter extends PartyMemberBase {
@Override
public String toString() {
return "猎人";
}
}
| true |
8d08afb7ee05aa672d3b8150820b6b3353176c70 | Java | RajeshRaoBN/AlgorithmsNDataStructuresMicrosoftDEV285x | /ListImplementation/src/LinkedListExample.java | UTF-8 | 646 | 3.25 | 3 | [] | no_license | import java.util.LinkedList;
public class LinkedListExample {
public String bookName;
public int millionsSold;
public LinkedListExample next;
public LinkedListExample(String bookName, int millionsSold) {
this.bookName = bookName;
this.millionsSold = millionsSold;
}
public void display() {
System.out.println(bookName + ": " + millionsSold + ",000,000");
}
public String toString() {
return bookName;
}
public static void main(String[] args) {
}
}
class Linklist{
public LinkedListExample firstLink;
public Linklist() {
firstLink = null;
}
} | true |
5c7d4e3442942d5997f1ee82eaf0ecedc9ef6f5f | Java | open-osrs/runelite | /runescape-client/src/main/java/ArchiveDiskActionHandler.java | UTF-8 | 14,247 | 1.710938 | 2 | [
"BSD-2-Clause"
] | permissive | import net.runelite.mapping.Export;
import net.runelite.mapping.Implements;
import net.runelite.mapping.ObfuscatedGetter;
import net.runelite.mapping.ObfuscatedName;
import net.runelite.mapping.ObfuscatedSignature;
@ObfuscatedName("ks")
@Implements("ArchiveDiskActionHandler")
public class ArchiveDiskActionHandler implements Runnable {
@ObfuscatedName("c")
@ObfuscatedSignature(
descriptor = "Llo;"
)
@Export("ArchiveDiskActionHandler_requestQueue")
public static NodeDeque ArchiveDiskActionHandler_requestQueue;
@ObfuscatedName("v")
@ObfuscatedSignature(
descriptor = "Llo;"
)
@Export("ArchiveDiskActionHandler_responseQueue")
public static NodeDeque ArchiveDiskActionHandler_responseQueue;
@ObfuscatedName("q")
@ObfuscatedGetter(
intValue = -962043785
)
public static int field3971;
@ObfuscatedName("f")
@Export("ArchiveDiskActionHandler_lock")
public static Object ArchiveDiskActionHandler_lock;
@ObfuscatedName("j")
@Export("ArchiveDiskActionHandler_thread")
static Thread ArchiveDiskActionHandler_thread;
static {
ArchiveDiskActionHandler_requestQueue = new NodeDeque(); // L: 9
ArchiveDiskActionHandler_responseQueue = new NodeDeque(); // L: 10
field3971 = 0; // L: 11
ArchiveDiskActionHandler_lock = new Object();
} // L: 12
ArchiveDiskActionHandler() {
} // L: 15
public void run() {
try {
while (true) {
ArchiveDiskAction var1;
synchronized(ArchiveDiskActionHandler_requestQueue) { // L: 75
var1 = (ArchiveDiskAction)ArchiveDiskActionHandler_requestQueue.last(); // L: 76
} // L: 77
if (var1 != null) { // L: 78
if (var1.type == 0) { // L: 79
var1.archiveDisk.write((int)var1.key, var1.data, var1.data.length); // L: 80
synchronized(ArchiveDiskActionHandler_requestQueue) { // L: 81
var1.remove(); // L: 82
} // L: 83
} else if (var1.type == 1) { // L: 85
var1.data = var1.archiveDisk.read((int)var1.key); // L: 86
synchronized(ArchiveDiskActionHandler_requestQueue) { // L: 87
ArchiveDiskActionHandler_responseQueue.addFirst(var1); // L: 88
} // L: 89
}
synchronized(ArchiveDiskActionHandler_lock) { // L: 91
if (field3971 <= 1) { // L: 92
field3971 = 0; // L: 93
ArchiveDiskActionHandler_lock.notifyAll(); // L: 94
return; // L: 95
}
field3971 = 600; // L: 97
}
} else {
DynamicObject.method1991(100L); // L: 101
synchronized(ArchiveDiskActionHandler_lock) { // L: 102
if (field3971 <= 1) { // L: 103
field3971 = 0; // L: 104
ArchiveDiskActionHandler_lock.notifyAll(); // L: 105
return; // L: 106
}
--field3971; // L: 108
}
}
}
} catch (Exception var13) { // L: 113
class249.RunException_sendStackTrace((String)null, var13); // L: 114
}
} // L: 116
@ObfuscatedName("hp")
@ObfuscatedSignature(
descriptor = "(I)V",
garbageValue = "1673600098"
)
static final void method5793() {
Script.method1978(false); // L: 5727
Client.field694 = 0; // L: 5728
boolean var0 = true; // L: 5729
int var1;
for (var1 = 0; var1 < Actor.regionLandArchives.length; ++var1) { // L: 5730
if (PcmPlayer.regionMapArchiveIds[var1] != -1 && Actor.regionLandArchives[var1] == null) { // L: 5731 5732
Actor.regionLandArchives[var1] = WorldMapSectionType.archive9.takeFile(PcmPlayer.regionMapArchiveIds[var1], 0); // L: 5733
if (Actor.regionLandArchives[var1] == null) { // L: 5734
var0 = false; // L: 5735
++Client.field694; // L: 5736
}
}
if (ObjectSound.regionLandArchiveIds[var1] != -1 && class145.regionMapArchives[var1] == null) { // L: 5740 5741
class145.regionMapArchives[var1] = WorldMapSectionType.archive9.takeFileEncrypted(ObjectSound.regionLandArchiveIds[var1], 0, WorldMapRegion.xteaKeys[var1]); // L: 5742
if (class145.regionMapArchives[var1] == null) { // L: 5743
var0 = false; // L: 5744
++Client.field694; // L: 5745
}
}
}
if (!var0) { // L: 5750
Client.field549 = 1; // L: 5751
} else {
Client.field547 = 0; // L: 5754
var0 = true; // L: 5755
int var3;
int var4;
for (var1 = 0; var1 < Actor.regionLandArchives.length; ++var1) { // L: 5756
byte[] var15 = class145.regionMapArchives[var1]; // L: 5757
if (var15 != null) { // L: 5758
var3 = (Client.regions[var1] >> 8) * 64 - class28.baseX; // L: 5759
var4 = (Client.regions[var1] & 255) * 64 - WorldMapLabelSize.baseY; // L: 5760
if (Client.isInInstance) { // L: 5761
var3 = 10; // L: 5762
var4 = 10; // L: 5763
}
var0 &= UserComparator10.method2611(var15, var3, var4); // L: 5765
}
}
if (!var0) { // L: 5768
Client.field549 = 2; // L: 5769
} else {
if (Client.field549 != 0) { // L: 5772
SequenceDefinition.drawLoadingMessage("Loading - please wait." + "<br>" + " (" + 100 + "%" + ")", true);
}
Renderable.playPcmPlayers(); // L: 5773
class356.scene.clear(); // L: 5774
for (var1 = 0; var1 < 4; ++var1) { // L: 5775
Client.collisionMaps[var1].clear();
}
int var2;
for (var1 = 0; var1 < 4; ++var1) { // L: 5776
for (var2 = 0; var2 < 104; ++var2) { // L: 5777
for (var3 = 0; var3 < 104; ++var3) { // L: 5778
Tiles.Tiles_renderFlags[var1][var2][var3] = 0; // L: 5779
}
}
}
Renderable.playPcmPlayers(); // L: 5783
class259.method5188(); // L: 5784
var1 = Actor.regionLandArchives.length; // L: 5785
Decimator.method1018(); // L: 5786
Script.method1978(true); // L: 5787
int var5;
if (!Client.isInInstance) { // L: 5788
byte[] var14;
for (var2 = 0; var2 < var1; ++var2) { // L: 5789
var3 = (Client.regions[var2] >> 8) * 64 - class28.baseX; // L: 5790
var4 = (Client.regions[var2] & 255) * 64 - WorldMapLabelSize.baseY; // L: 5791
var14 = Actor.regionLandArchives[var2]; // L: 5792
if (var14 != null) { // L: 5793
Renderable.playPcmPlayers(); // L: 5794
UserComparator1.method8020(var14, var3, var4, GrandExchangeOffer.field4070 * 8 - 48, ApproximateRouteStrategy.field466 * 8 - 48, Client.collisionMaps); // L: 5795
}
}
for (var2 = 0; var2 < var1; ++var2) { // L: 5798
var3 = (Client.regions[var2] >> 8) * 64 - class28.baseX; // L: 5799
var4 = (Client.regions[var2] & 255) * 64 - WorldMapLabelSize.baseY; // L: 5800
var14 = Actor.regionLandArchives[var2]; // L: 5801
if (var14 == null && ApproximateRouteStrategy.field466 < 800) { // L: 5802
Renderable.playPcmPlayers(); // L: 5803
class11.method98(var3, var4, 64, 64); // L: 5804
}
}
Script.method1978(true); // L: 5807
for (var2 = 0; var2 < var1; ++var2) { // L: 5808
byte[] var13 = class145.regionMapArchives[var2]; // L: 5809
if (var13 != null) { // L: 5810
var4 = (Client.regions[var2] >> 8) * 64 - class28.baseX; // L: 5811
var5 = (Client.regions[var2] & 255) * 64 - WorldMapLabelSize.baseY; // L: 5812
Renderable.playPcmPlayers(); // L: 5813
VertexNormal.method4527(var13, var4, var5, class356.scene, Client.collisionMaps); // L: 5814
}
}
}
int var6;
int var7;
int var8;
if (Client.isInInstance) { // L: 5818
int var9;
int var10;
int var11;
for (var2 = 0; var2 < 4; ++var2) { // L: 5819
Renderable.playPcmPlayers(); // L: 5820
for (var3 = 0; var3 < 13; ++var3) { // L: 5821
for (var4 = 0; var4 < 13; ++var4) { // L: 5822
boolean var16 = false; // L: 5823
var6 = Client.instanceChunkTemplates[var2][var3][var4]; // L: 5824
if (var6 != -1) { // L: 5825
var7 = var6 >> 24 & 3; // L: 5826
var8 = var6 >> 1 & 3; // L: 5827
var9 = var6 >> 14 & 1023; // L: 5828
var10 = var6 >> 3 & 2047; // L: 5829
var11 = (var9 / 8 << 8) + var10 / 8; // L: 5830
for (int var12 = 0; var12 < Client.regions.length; ++var12) { // L: 5831
if (Client.regions[var12] == var11 && Actor.regionLandArchives[var12] != null) { // L: 5832
Canvas.method315(Actor.regionLandArchives[var12], var2, var3 * 8, var4 * 8, var7, (var9 & 7) * 8, (var10 & 7) * 8, var8, Client.collisionMaps); // L: 5833
var16 = true; // L: 5834
break;
}
}
}
if (!var16) { // L: 5839
class28.method352(var2, var3 * 8, var4 * 8); // L: 5840
}
}
}
}
for (var2 = 0; var2 < 13; ++var2) { // L: 5845
for (var3 = 0; var3 < 13; ++var3) { // L: 5846
var4 = Client.instanceChunkTemplates[0][var2][var3]; // L: 5847
if (var4 == -1) { // L: 5848
class11.method98(var2 * 8, var3 * 8, 8, 8); // L: 5849
}
}
}
Script.method1978(true); // L: 5853
for (var2 = 0; var2 < 4; ++var2) { // L: 5854
Renderable.playPcmPlayers(); // L: 5855
for (var3 = 0; var3 < 13; ++var3) { // L: 5856
for (var4 = 0; var4 < 13; ++var4) { // L: 5857
var5 = Client.instanceChunkTemplates[var2][var3][var4]; // L: 5858
if (var5 != -1) { // L: 5859
var6 = var5 >> 24 & 3; // L: 5860
var7 = var5 >> 1 & 3; // L: 5861
var8 = var5 >> 14 & 1023; // L: 5862
var9 = var5 >> 3 & 2047; // L: 5863
var10 = (var8 / 8 << 8) + var9 / 8; // L: 5864
for (var11 = 0; var11 < Client.regions.length; ++var11) { // L: 5865
if (Client.regions[var11] == var10 && class145.regionMapArchives[var11] != null) { // L: 5866
Tiles.method2007(class145.regionMapArchives[var11], var2, var3 * 8, var4 * 8, var6, (var8 & 7) * 8, (var9 & 7) * 8, var7, class356.scene, Client.collisionMaps); // L: 5867
break; // L: 5868
}
}
}
}
}
}
}
Script.method1978(true); // L: 5876
Renderable.playPcmPlayers(); // L: 5877
class134.method2905(class356.scene, Client.collisionMaps); // L: 5878
Script.method1978(true); // L: 5879
var2 = Tiles.Tiles_minPlane; // L: 5880
if (var2 > PacketWriter.Client_plane) { // L: 5881
var2 = PacketWriter.Client_plane;
}
if (var2 < PacketWriter.Client_plane - 1) { // L: 5882
var2 = PacketWriter.Client_plane - 1;
}
if (Client.isLowDetail) { // L: 5883
class356.scene.init(Tiles.Tiles_minPlane);
} else {
class356.scene.init(0); // L: 5884
}
for (var3 = 0; var3 < 104; ++var3) { // L: 5885
for (var4 = 0; var4 < 104; ++var4) { // L: 5886
class133.updateItemPile(var3, var4); // L: 5887
}
}
Renderable.playPcmPlayers(); // L: 5890
class4.method11(); // L: 5891
ObjectComposition.ObjectDefinition_cachedModelData.clear(); // L: 5892
PacketBufferNode var17;
if (class353.client.hasFrame()) { // L: 5893
var17 = EnumComposition.getPacketBufferNode(ClientPacket.field3007, Client.packetWriter.isaacCipher); // L: 5895
var17.packetBuffer.writeInt(1057001181); // L: 5896
Client.packetWriter.addNode(var17); // L: 5897
}
if (!Client.isInInstance) { // L: 5899
var3 = (GrandExchangeOffer.field4070 - 6) / 8; // L: 5900
var4 = (GrandExchangeOffer.field4070 + 6) / 8; // L: 5901
var5 = (ApproximateRouteStrategy.field466 - 6) / 8; // L: 5902
var6 = (ApproximateRouteStrategy.field466 + 6) / 8; // L: 5903
for (var7 = var3 - 1; var7 <= var4 + 1; ++var7) { // L: 5904
for (var8 = var5 - 1; var8 <= var6 + 1; ++var8) { // L: 5905
if (var7 < var3 || var7 > var4 || var8 < var5 || var8 > var6) { // L: 5906
WorldMapSectionType.archive9.loadRegionFromName("m" + var7 + "_" + var8); // L: 5907
WorldMapSectionType.archive9.loadRegionFromName("l" + var7 + "_" + var8); // L: 5908
}
}
}
}
HealthBarUpdate.updateGameState(30); // L: 5912
Renderable.playPcmPlayers(); // L: 5913
class361.method6552(); // L: 5914
var17 = EnumComposition.getPacketBufferNode(ClientPacket.field2989, Client.packetWriter.isaacCipher); // L: 5915
Client.packetWriter.addNode(var17); // L: 5916
Calendar.method5504(); // L: 5917
}
}
} // L: 5752 5770 5918
@ObfuscatedName("ir")
@ObfuscatedSignature(
descriptor = "(I)V",
garbageValue = "-232514392"
)
static final void method5779() {
int var0 = UserComparator3.menuX; // L: 8460
int var1 = ViewportMouse.menuY; // L: 8461
int var2 = Language.menuWidth; // L: 8462
int var3 = Player.menuHeight; // L: 8463
int var4 = 6116423; // L: 8464
Rasterizer2D.Rasterizer2D_fillRectangle(var0, var1, var2, var3, var4); // L: 8465
Rasterizer2D.Rasterizer2D_fillRectangle(var0 + 1, var1 + 1, var2 - 2, 16, 0); // L: 8466
Rasterizer2D.Rasterizer2D_drawRectangle(var0 + 1, var1 + 18, var2 - 2, var3 - 19, 0); // L: 8467
TileItem.fontBold12.draw("Choose Option", var0 + 3, var1 + 14, var4, -1); // L: 8468
int var5 = MouseHandler.MouseHandler_x; // L: 8469
int var6 = MouseHandler.MouseHandler_y; // L: 8470
int var7;
int var8;
int var9;
for (var7 = 0; var7 < Client.menuOptionsCount; ++var7) { // L: 8471
var8 = var1 + (Client.menuOptionsCount - 1 - var7) * 15 + 31; // L: 8472
var9 = 16777215; // L: 8473
if (var5 > var0 && var5 < var2 + var0 && var6 > var8 - 13 && var6 < var8 + 3) { // L: 8474
var9 = 16776960;
}
Font var12 = TileItem.fontBold12; // L: 8475
String var13;
if (var7 < 0) { // L: 8478
var13 = ""; // L: 8479
} else if (Client.menuTargets[var7].length() > 0) { // L: 8482
var13 = Client.menuActions[var7] + " " + Client.menuTargets[var7];
} else {
var13 = Client.menuActions[var7]; // L: 8483
}
var12.draw(var13, var0 + 3, var8, var9, 0); // L: 8485
}
var7 = UserComparator3.menuX; // L: 8487
var8 = ViewportMouse.menuY; // L: 8488
var9 = Language.menuWidth; // L: 8489
int var10 = Player.menuHeight; // L: 8490
for (int var11 = 0; var11 < Client.rootWidgetCount; ++var11) { // L: 8492
if (Client.rootWidgetWidths[var11] + Client.rootWidgetXs[var11] > var7 && Client.rootWidgetXs[var11] < var7 + var9 && Client.rootWidgetHeights[var11] + Client.rootWidgetYs[var11] > var8 && Client.rootWidgetYs[var11] < var8 + var10) { // L: 8493
Client.field704[var11] = true;
}
}
} // L: 8496
}
| true |
6a399bff8e95f97bbc775666072b3a49ca17706d | Java | BCSDLab/KOIN_ANDROID | /koin/src/main/java/in/koreatech/koin/data/network/interactor/DiningRestInteractor.java | UTF-8 | 2,446 | 2.359375 | 2 | [] | no_license | package in.koreatech.koin.data.network.interactor;
import android.util.Log;
import java.util.ArrayList;
import java.util.List;
import in.koreatech.koin.core.network.ApiCallback;
import in.koreatech.koin.core.network.RetrofitManager;
import in.koreatech.koin.data.network.entity.Dining;
import in.koreatech.koin.data.network.service.DiningService;
import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.Single;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import retrofit2.HttpException;
public class DiningRestInteractor implements DiningInteractor {
private final String TAG = "DiningRestInteractor";
private final CompositeDisposable compositeDisposable = new CompositeDisposable();
public DiningRestInteractor() {
}
@Override
public void readDiningList(String date, ApiCallback apiCallback) {
RetrofitManager.getInstance().getRetrofit().create(DiningService.class).getDiningMenu(date)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Observer<ArrayList<Dining>>() {
@Override
public void onSubscribe(Disposable d) {
}
@Override
public void onNext(ArrayList<Dining> dinings) {
if (!dinings.isEmpty()) {
apiCallback.onSuccess(dinings);
} else {
apiCallback.onFailure(new Throwable("fail read dining list"));
}
}
@Override
public void onError(Throwable throwable) {
if (throwable instanceof HttpException) {
Log.d(TAG, ((HttpException) throwable).code() + " ");
}
apiCallback.onFailure(throwable);
}
@Override
public void onComplete() {
}
});
}
@Override
public Observable<ArrayList<Dining>> readDingingList(String date) {
return RetrofitManager.getInstance().getRetrofit().create(DiningService.class).getDiningMenu(date);
}
}
| true |
baf27b0da0ff0b398b5e444d1a74400e22834ee5 | Java | ache72/clase5 | /JavaApplication4/src/DAO/DaoConsulta.java | UTF-8 | 1,049 | 2.515625 | 3 | [] | no_license |
package DAO;
import java.sql.*;
import java.io.*;
import javax.swing.JOptionPane;
public class DaoConsulta {
//creando una instancia a la conexion
public static Conexion.Conecta cn=new Conexion.Conecta();
//funcion consulta
public ResultSet consulta1(String codigo_cliente){
ResultSet rs=null;
try{
String sql = "select * from orders where customerid ='"+codigo_cliente+"'";
Statement stmt = null;
stmt = cn.xcon().createStatement();
rs = stmt.executeQuery(sql);
}catch(Exception error){
JOptionPane.showMessageDialog(null, error);
}
return rs;
}
public ResultSet consulta2(int numero_orden){
ResultSet rs=null;
try{
String sql = "select * from [order details] where orderid ='"+numero_orden+"'";
Statement stmt = null;
stmt = cn.xcon().createStatement();
rs = stmt.executeQuery(sql);
}catch(Exception error){
JOptionPane.showMessageDialog(null, error);
}
return rs;
}
}
| true |
ce227e25d662ac8da68ca6065723c67e6a8dabae | Java | primeleaf/krystaldms-community-edition | /DMS Server - Community Edition 2022/src/com/primeleaf/krystal/web/view/cpanel/ManageDocumentClassesView.java | UTF-8 | 6,311 | 2.125 | 2 | [] | no_license | /**
* Created On 05-Jan-2014
* Copyright 2010 by Primeleaf Consulting (P) Ltd.,
* #29,784/785 Hendre Castle,
* D.S.Babrekar Marg,
* Gokhale Road(North),
* Dadar,Mumbai 400 028
* India
*
* All rights reserved.
*
* This software is the confidential and proprietary information
* of Primeleaf Consulting (P) Ltd. ("Confidential Information").
* You shall not disclose such Confidential Information and shall use
* it only in accordance with the terms of the license agreement
* you entered into with Primeleaf Consulting (P) Ltd.
*/
/**
* Created on 05-Jan-2014
*
* Copyright 2003-09 by Primeleaf Consulting (P) Ltd.,
* #29,784/785 Hendre Castle,
* D.S.Babrekar Marg,
* Gokhale Road(North),
* Dadar,Mumbai 400 028
* India
*
* All rights reserved.
*
* This software is the confidential and proprietary information
* of Primeleaf Consulting (P) Ltd. ("Confidential Information").
* You shall not disclose such Confidential Information and shall use
* it only in accordance with the terms of the license agreement
* you entered into with Primeleaf Consulting (P) Ltd.
*/
package com.primeleaf.krystal.web.view.cpanel;
import java.util.ArrayList;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang3.StringEscapeUtils;
import com.primeleaf.krystal.constants.HTTPConstants;
import com.primeleaf.krystal.model.vo.DocumentClass;
import com.primeleaf.krystal.util.StringHelper;
import com.primeleaf.krystal.web.view.WebPageTemplate;
import com.primeleaf.krystal.web.view.WebView;
/**
* @author Rahul Kubadia
*
*/
public class ManageDocumentClassesView extends WebView {
public ManageDocumentClassesView (HttpServletRequest request, HttpServletResponse response) throws Exception{
init(request, response);
}
public void render() throws Exception{
session.setAttribute(HTTPConstants.CSRF_STRING, StringHelper.generateAuthToken());
WebPageTemplate template = new WebPageTemplate(request,response);
template.generateHeader();
printDocumentClasses();
template.generateFooter();
}
private void printBreadCrumbs() throws Exception{
out.println("<ol class=\"breadcrumb\">");
out.println("<li class=\"breadcrumb-item\"><a href=\"/cpanel\">Control Panel</a></li>");
out.println("<li class=\"breadcrumb-item active\">Manage Document Classes</li>");
out.println("</ol>");
}
@SuppressWarnings("unchecked")
private void printDocumentClasses() throws Exception{
printBreadCrumbs();
if(request.getAttribute(HTTPConstants.REQUEST_ERROR) != null){
printErrorDismissable((String)request.getAttribute(HTTPConstants.REQUEST_ERROR));
}
if(request.getAttribute(HTTPConstants.REQUEST_MESSAGE) != null){
printSuccessDismissable((String)request.getAttribute(HTTPConstants.REQUEST_MESSAGE));
}
out.println("<div class=\"card\">");
out.println("<div class=\"card-header\">");
out.println("<div class=\"d-flex justify-content-between\">");
out.println("<div class=\"col-xs-6\">");
out.println("<i class=\"bi text-primary bi-folder2-open \"></i> Manage Document Classes");
out.println("</div>");
out.println("<div class=\"col-xs-6 text-end\">");
out.println("<a href=\"/cpanel/newdocumentclass\"><i class=\"bi text-primary bi-plus-square me-2\"></i>Add Document Class</a>");
out.println("</div>");
out.println("</div>");
out.println("</div>");
try {
ArrayList<DocumentClass> documentClassList = (ArrayList<DocumentClass>) request.getAttribute("CLASSLIST");
if(documentClassList.size() > 0 ){
out.println("<div class=\"table-responsive\">");
out.println("<table id=\"table\" class=\"table table-bordered table-sm table-hover mb-0\">");
out.println("<thead>");
out.println("<tr class=\"text-center\">");
out.println("<th>ID</th>");
out.println("<th>Class Name</th>");
out.println("<th>Class Description</th>");
out.println("<th>Active</th>");
out.println("<th>Version Control</th>");
out.println("<th>Action</th>");
out.println("</tr>");
out.println("</thead>");
out.println("<tbody>");
for (DocumentClass documentClass : documentClassList) {
out.println("<tr class=\"text-center\">");
out.println("<td>"+documentClass.getClassId()+"</td>");
out.println("<td class=\"text-start ps-5 text-primary\"><i class=\"bi bi-server me-3\"></i>" + StringEscapeUtils.escapeHtml4(documentClass.getClassName()) + "</td>");
out.println("<td>" + StringEscapeUtils.escapeHtml4(documentClass.getClassDescription()) + "</td>");
if(documentClass.isVisible()){
out.println("<td><i class=\"bi bi-check-lg text-success\"></i></td>");
}else{
out.println("<td><i class=\"bi bi-x-lg text-danger\"></i></td>");
}
if(documentClass.isRevisionControlEnabled()){
out.println("<td><i class=\"bi bi-check-lg text-success\"></i></td>");
}else{
out.println("<td><i class=\"bi bi-x-lg text-danger\"></i></td>");
}
out.print("<td>");
out.println("<a href=\""+HTTPConstants.BASEURL+"/cpanel/editdocumentclass?classid="+ documentClass.getClassId()+"\">Edit</a>");
out.println(" | <a href=\""+HTTPConstants.BASEURL+"/cpanel/deletedocumentclass?classid="+ documentClass.getClassId()+"&CSRF="+session.getAttribute(HTTPConstants.CSRF_STRING)+"\" title=\"Are you sure, you want to permanently delete this Document Class?\" class=\"confirm\">Delete</a>");
out.println(" | <a href=\""+HTTPConstants.BASEURL+"/cpanel/classindexes?classid="+ documentClass.getClassId() + "\" title=\"Manage Indexes\">Manage Indexes</a>");
out.println(" | <a href=\""+HTTPConstants.BASEURL+"/cpanel/permissions?classid="+ documentClass.getClassId() + "&CSRF="+session.getAttribute(HTTPConstants.CSRF_STRING)+"\" title=\"Manage Permissions\">Manage Permissions</a>");
out.println("</td>");
out.println("</tr>");
}
out.println("</tbody>");
out.println("</table>");
out.println("</div>");//table-responsive
}else{
out.println("Currently there are no document classes available in the system.");
}
out.println("</div>");//panel
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
| true |
3e78d9d3becdb1cc642144ceecd4f7020646885c | Java | dungviettran89/s34j | /s34j-spring/src/main/java/us/cuatoi/s34j/spring/model/ObjectModel.java | UTF-8 | 1,771 | 2.078125 | 2 | [
"Apache-2.0"
] | permissive | package us.cuatoi.s34j.spring.model;
import com.google.gson.Gson;
import org.springframework.data.annotation.Id;
import javax.persistence.Entity;
import javax.persistence.Lob;
@Entity
public class ObjectModel {
@Id
@javax.persistence.Id
private String objectVersion;
private long createdDate = System.currentTimeMillis();
private String bucketName;
private String objectName;
private long length;
@Lob
private String headersJson;
@Lob
private String aclJson;
public long getCreatedDate() {
return createdDate;
}
public void setCreatedDate(long createdDate) {
this.createdDate = createdDate;
}
public String getBucketName() {
return bucketName;
}
public void setBucketName(String bucketName) {
this.bucketName = bucketName;
}
public String getObjectName() {
return objectName;
}
public void setObjectName(String objectName) {
this.objectName = objectName;
}
public String getObjectVersion() {
return objectVersion;
}
public void setObjectVersion(String objectVersion) {
this.objectVersion = objectVersion;
}
public long getLength() {
return length;
}
public void setLength(long length) {
this.length = length;
}
public String getHeadersJson() {
return headersJson;
}
public void setHeadersJson(String headersJson) {
this.headersJson = headersJson;
}
public String getAclJson() {
return aclJson;
}
public void setAclJson(String aclJson) {
this.aclJson = aclJson;
}
@Override
public String toString() {
return getClass().getSimpleName() + new Gson().toJson(this);
}
}
| true |
7c1d8acabef0fee9d8c087069cce85a148d596f6 | Java | chakshujain/Social_media_app | /app/src/main/java/com/example/socialmedia/SettingsActivity.java | UTF-8 | 14,419 | 1.695313 | 2 | [] | no_license | package com.example.socialmedia;
import android.app.ProgressDialog;
import android.content.Intent;
import android.net.Uri;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.google.android.gms.tasks.Continuation;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.Query;
import com.google.firebase.database.ValueEventListener;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;
import com.squareup.picasso.Picasso;
import com.theartofdev.edmodo.cropper.CropImage;
import com.theartofdev.edmodo.cropper.CropImageView;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;
import de.hdodenhof.circleimageview.CircleImageView;
public class SettingsActivity extends AppCompatActivity {
private Toolbar mtoolbar;
private CircleImageView userProfImage;
private EditText userName,userProfName,userStatus,userCountry,userGender,userRelation,userDOB;
private Button UpdateAccountSettingsButton;
private FirebaseAuth mAuth;
private DatabaseReference SettingsRef,PostsUpdateRef,UsersRef;
String currentUserId,downloadUrl;
private static final int gallery_pick = 1;
private Uri imageUri;
private StorageReference UserProfileImageRef;
private ProgressDialog loadingBar;
Query postsupdate;
@Override
protected void onStart() {
super.onStart();
updateUserStatus("online");
}
@Override
protected void onStop() {
super.onStop();
updateUserStatus("online");
}
@Override
protected void onDestroy() {
super.onDestroy();
updateUserStatus("online");
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
mtoolbar = (Toolbar)findViewById(R.id.settings_toolbar);
setSupportActionBar(mtoolbar);
getSupportActionBar().setTitle("Account Settings");
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
mAuth = FirebaseAuth.getInstance();
currentUserId = mAuth.getCurrentUser().getUid();
SettingsRef = FirebaseDatabase.getInstance().getReference().child("users").child(currentUserId);
UsersRef = FirebaseDatabase.getInstance().getReference().child("users");
// PostsUpdateRef = FirebaseDatabase.getInstance().getReference().child("Posts");
// postsupdate = PostsUpdateRef.orderByChild("uid").equalTo(currentUserId);
userProfImage = (CircleImageView)findViewById(R.id.settings_profile_image);
userName = (EditText)findViewById(R.id.settings_username);
userProfName = (EditText)findViewById(R.id.settings_profile_name);
userStatus = (EditText)findViewById(R.id.settings_status);
userCountry = (EditText)findViewById(R.id.settings_country);
userGender = (EditText)findViewById(R.id.settings_gender);
userRelation = (EditText)findViewById(R.id.settings_relationship_status);
userDOB = (EditText)findViewById(R.id.settings_dob);
UpdateAccountSettingsButton = (Button)findViewById(R.id.update_account_settings_button);
UserProfileImageRef = FirebaseStorage.getInstance().getReference().child("profileImages");
loadingBar = new ProgressDialog(this);
SettingsRef.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
if(dataSnapshot.exists()){
String myUsername = dataSnapshot.child("username").getValue().toString();
String myCountry = dataSnapshot.child("country").getValue().toString();
String mydob = dataSnapshot.child("dob").getValue().toString();
String mygender = dataSnapshot.child("gender").getValue().toString();
String myRelationshipStatus = dataSnapshot.child("relationship_status").getValue().toString();
String myStatus = dataSnapshot.child("status").getValue().toString();
String myFullname = dataSnapshot.child("fullname").getValue().toString();
if(dataSnapshot.hasChild("profileimage")) {
String image = dataSnapshot.child("profileimage").getValue().toString();
Picasso.get().load(image).placeholder(R.drawable.profile).into(userProfImage);
}
userName.setText(myUsername);
userCountry.setText(myCountry);
userDOB.setText(mydob);
userGender.setText(mygender);
userRelation.setText(myRelationshipStatus);
userStatus.setText(myStatus);
userProfName.setText(myFullname);
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
UpdateAccountSettingsButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
loadingBar.setTitle("Account Information");
loadingBar.setMessage("Please wait, while we are updating your account information...");
loadingBar.show();
loadingBar.setCanceledOnTouchOutside(true);
String username = userName.getText().toString();
String profilename = userProfName.getText().toString();
String gender = userGender.getText().toString();
String relationship = userRelation.getText().toString();
String dob = userDOB.getText().toString();
String status = userStatus.getText().toString();
String country = userCountry.getText().toString();
ValidateUserInfo(username, profilename, gender, relationship, dob, status, country);
}
});
userProfImage.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent galleryIntent = new Intent();
galleryIntent.setAction(Intent.ACTION_GET_CONTENT);
galleryIntent.setType("image/*");
startActivityForResult(galleryIntent,gallery_pick);
}
});
}
public void updateUserStatus(String state){
String saveCurrentDate,saveCurrentTime;
Calendar calFordDate = Calendar.getInstance();
SimpleDateFormat currentDate = new SimpleDateFormat("dd-MMMM-yyyy");
saveCurrentDate = currentDate.format(calFordDate.getTime());
Calendar calFordTime = Calendar.getInstance();
SimpleDateFormat currentTime = new SimpleDateFormat("HH:mm:aa");
saveCurrentTime = currentTime.format(calFordTime.getTime());
Map currentStateMap = new HashMap();
currentStateMap.put("time",saveCurrentTime);
currentStateMap.put("date",saveCurrentDate);
currentStateMap.put("type",state);
UsersRef.child(currentUserId).child("userState").updateChildren(currentStateMap);
}
// StoringImageToFirebaseStorage();
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode==gallery_pick && resultCode==RESULT_OK && data!=null) {
CropImage.activity()
.setGuidelines(CropImageView.Guidelines.ON)
.setAspectRatio(1, 1)
.start(this);
}
if(requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE)
{
CropImage.ActivityResult result = CropImage.getActivityResult(data);
imageUri = result.getUri();
if (resultCode == RESULT_OK) {
userProfImage.setImageURI(imageUri);
}
}
}
private void ValidateUserInfo(String username, final String profilename, String gender, String relationship, String dob, String status, String country) {
final HashMap usermap = new HashMap();
usermap.put("username",username);
usermap.put("country",country);
usermap.put("dob",dob);
usermap.put("status",status);
usermap.put("relationship_status",relationship);
usermap.put("gender",gender);
usermap.put("fullname",profilename);
final StorageReference filePath = UserProfileImageRef.child(currentUserId + ".jpg");
if(imageUri!=null) {
filePath.putFile(imageUri).continueWithTask(new Continuation<UploadTask.TaskSnapshot, Task<Uri>>() {
@Override
public Task<Uri> then(@NonNull Task<UploadTask.TaskSnapshot> task) throws Exception {
if (!task.isSuccessful()) {
throw task.getException();
}
return filePath.getDownloadUrl();
}
}).addOnCompleteListener(new OnCompleteListener<Uri>() {
@Override
public void onComplete(@NonNull Task<Uri> task) {
if (task.isSuccessful()) {
Uri downUri = task.getResult();
downloadUrl = downUri.toString();
Toast.makeText(SettingsActivity.this, "Image stored in database successfully", Toast.LENGTH_SHORT).show();
if(downloadUrl!=null) {
usermap.put("profileimage", downloadUrl);
}
// postsupdate.addListenerForSingleValueEvent(new ValueEventListener() {
// @Override
// public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
// if(dataSnapshot.exists()){
// for(DataSnapshot child: dataSnapshot.getChildren()){
// String postkey = child.getRef().getKey();
// PostsUpdateRef.child(postkey).child("fullname").setValue(profilename);
// PostsUpdateRef.child(postkey).child("profileimage").setValue(downloadUrl);
// }
// }
// }
//
// @Override
// public void onCancelled(@NonNull DatabaseError databaseError) {
//
// }
// });
SettingsRef.updateChildren(usermap).addOnCompleteListener(new OnCompleteListener() {
@Override
public void onComplete(@NonNull Task task) {
if(task.isSuccessful()){
SendUserToMainActivity();
Toast.makeText(SettingsActivity.this, "Successfully updated Account Information", Toast.LENGTH_SHORT).show();
loadingBar.dismiss();
}
else{
Toast.makeText(SettingsActivity.this, "Failed to update your Account Information", Toast.LENGTH_SHORT).show();
loadingBar.dismiss();
}
}
});
} else {
String message = task.getException().getMessage();
Toast.makeText(SettingsActivity.this, "Error occured: " + message, Toast.LENGTH_SHORT).show();
loadingBar.dismiss();
}
}
});
}
else{
// postsupdate.addListenerForSingleValueEvent(new ValueEventListener() {
// @Override
// public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
// if(dataSnapshot.exists()){
// for(DataSnapshot child: dataSnapshot.getChildren()){
// String postkey = child.getRef().getKey();
// PostsUpdateRef.child(postkey).child("fullname").setValue(profilename);
// }
// }
// }
//
// @Override
// public void onCancelled(@NonNull DatabaseError databaseError) {
//
// }
// });
SettingsRef.updateChildren(usermap).addOnCompleteListener(new OnCompleteListener() {
@Override
public void onComplete(@NonNull Task task) {
if(task.isSuccessful()){
SendUserToMainActivity();
Toast.makeText(SettingsActivity.this, "Successfully updated Account Information", Toast.LENGTH_SHORT).show();
loadingBar.dismiss();
}
else{
Toast.makeText(SettingsActivity.this, "Failed to update your Account Information", Toast.LENGTH_SHORT).show();
loadingBar.dismiss();
}
}
});
}
}
private void StoringImageToFirebaseStorage() {
}
private void SendUserToMainActivity() {
Intent mainIntent = new Intent(SettingsActivity.this,MainActivity.class);
mainIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(mainIntent);
finish();
}
}
| true |
ba9a820d2d9d13323b6faa2683efc6c6ec6744ee | Java | findus/DB_Timetables | /src/main/generated/ReferenceTripRelation.java | UTF-8 | 2,448 | 2 | 2 | [] | no_license | //
// Diese Datei wurde mit der JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.8-b130911.1802 generiert
// Siehe <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// �nderungen an dieser Datei gehen bei einer Neukompilierung des Quellschemas verloren.
// Generiert: 2017.12.16 um 06:26:06 PM CET
//
package main.generated;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlSchemaType;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java-Klasse f�r referenceTripRelation complex type.
*
* <p>Das folgende Schemafragment gibt den erwarteten Content an, der in dieser Klasse enthalten ist.
*
* <pre>
* <complexType name="referenceTripRelation">
* <complexContent>
* <extension base="{}jaxbEntity">
* <sequence>
* <element name="rt" type="{}referenceTrip" minOccurs="0"/>
* <element name="rts" type="{}referenceTripRelationToStop" minOccurs="0"/>
* </sequence>
* </extension>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "referenceTripRelation", propOrder = {
"rt",
"rts"
})
public class ReferenceTripRelation
extends JaxbEntity
{
protected ReferenceTrip rt;
@XmlSchemaType(name = "string")
protected ReferenceTripRelationToStop rts;
/**
* Ruft den Wert der rt-Eigenschaft ab.
*
* @return
* possible object is
* {@link ReferenceTrip }
*
*/
public ReferenceTrip getRt() {
return rt;
}
/**
* Legt den Wert der rt-Eigenschaft fest.
*
* @param value
* allowed object is
* {@link ReferenceTrip }
*
*/
public void setRt(ReferenceTrip value) {
this.rt = value;
}
/**
* Ruft den Wert der rts-Eigenschaft ab.
*
* @return
* possible object is
* {@link ReferenceTripRelationToStop }
*
*/
public ReferenceTripRelationToStop getRts() {
return rts;
}
/**
* Legt den Wert der rts-Eigenschaft fest.
*
* @param value
* allowed object is
* {@link ReferenceTripRelationToStop }
*
*/
public void setRts(ReferenceTripRelationToStop value) {
this.rts = value;
}
}
| true |
7655cc68721cecd3d45bf1d34a28e7514c5ef2c2 | Java | bcappad/projectoAlkemy | /src/main/java/alkemy/challenge/Challenge/Alkemy/service/OrganizationService.java | UTF-8 | 218 | 1.9375 | 2 | [] | no_license | package alkemy.challenge.Challenge.Alkemy.service;
import alkemy.challenge.Challenge.Alkemy.model.Organization;
public interface OrganizationService {
public Organization getById(Integer id) throws Exception;
}
| true |
569a20b2d0dc5d9f2f0bc12ad4ce9f48f180c64f | Java | diamimi/test-sioo | /src/test/java/com/SginTest.java | UTF-8 | 1,203 | 2.234375 | 2 | [] | no_license | package com;
import com.util.FileRead;
import com.util.StoreUtil;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/**
* @Author: HeQi
* @Date:Create in 9:02 2018/8/23
*/
@RunWith(SpringRunner.class)
@SpringBootTest
public class SginTest {
@Autowired
private StoreUtil storeUtil;
@Test
public void ss(){
List<String> list = FileRead.getInstance().read("D:\\hq\\files/11.txt", "GBK");
Set<String> set=new HashSet<>();
list.stream().forEach(s->set.add(storeUtil.getSign(s)));
set.stream().forEach(e-> System.out.println(e));
}
@Test
public void sss(){
String s="【万家乐】天天追延禧,不如买家电。万家乐&海信&华帝皇牌三免一 。活动地址:新潮门洞直走300米海信专卖店\n" +
"电话:0459-5354649";
// String remove = StringUtils.remove(s, "\n");
System.out.println(s);
}
}
| true |
3d1f037a3dff154cefe0a147f9a9185bb4ebda91 | Java | tw0908065156/517europe | /aeurope/src/main/java/cn/tedu/aeurope/controller/OrderPaymentController.java | UTF-8 | 1,223 | 1.835938 | 2 | [] | no_license | package cn.tedu.aeurope.controller;
import javax.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import cn.tedu.aeurope.service.IOrderPaymentService;
import cn.tedu.aeurope.util.JsonResult;
import cn.tedu.aeurope.vo.OrderVO;
@RestController
@RequestMapping("order_payment")
public class OrderPaymentController extends BaseController {
@Autowired
IOrderPaymentService orderPaymentService;
@GetMapping("payable")
public JsonResult<Void> selectPayableAmountByid(Integer orderid){
orderPaymentService.selectPayableAmountByid(orderid);
return new JsonResult<Void>(SUCCESS);
}
@GetMapping("{orderid}/get_order_details")
public JsonResult<OrderVO> selectOrderVOById(@PathVariable("orderid") Integer orderid, HttpSession session){
String clientEmail = getClinetemailFromSession(session);
OrderVO data= orderPaymentService.selectOrderVOById(orderid, clientEmail);
return new JsonResult<OrderVO>(SUCCESS, data);
}
}
| true |
80ca9145c5a861e7e32168af2d24b61bd73ec4e8 | Java | agilego99/spring-cloud-aaron | /gordianknot-conf/gordianknot-conf-client/src/main/java/org/gordianknot/conf/client/util/ReflectUtils.java | UTF-8 | 1,884 | 2.953125 | 3 | [] | no_license | package org.gordianknot.conf.client.util;
import java.lang.reflect.Method;
import org.springframework.util.StringUtils;
public abstract class ReflectUtils {
/**
* 根據字段名調用對象的getter方法,如果字段類型為boolean,則方法名可能為is開頭,也有可能只是以setFieleName的普通方法
* @param fieldName
* @param instance
* @return getter方法調用後的返回值
*/
public static Object callGetMethod(String fieldName, Object instance){
Object result = null;
try{
String mn = "get"+StringUtils.capitalize(fieldName);
Method method = null;
try{
method = getMethod(instance.getClass(), mn);
}catch(NoSuchMethodException nsme){
mn = "is"+StringUtils.capitalize(fieldName);
method = getMethod(instance.getClass(), mn);
}
result = method.invoke(instance, new Object[]{});
}catch(Exception e){
throw new RuntimeException(e.getMessage(), e);
}
return result;
}
/**
* 得到給寫的類或其父類中聲明的方法
* @param entityClass
* @param methodName
* @return
* @throws NoSuchMethodException
*/
public static Method getMethod(Class<?> entityClass, String methodName, Class<?>... type) throws NoSuchMethodException {
try{
Method m = entityClass.getDeclaredMethod(methodName, type);
if(m != null){
return m;
}
}catch(NoSuchMethodException ex){
if(entityClass.getSuperclass() != null && entityClass.getSuperclass() != Object.class){
return getMethod(entityClass.getSuperclass(), methodName, type);
}else{
throw ex;
}
}
return null;
}
}
| true |
b434da4768801e766d15f373611a17bdee6d1c62 | Java | istratford1/JavaLabGit | /JavaLab_Day6/src/javalab/day6/vehiclesOOP/Bus.java | UTF-8 | 1,287 | 2.953125 | 3 | [] | no_license | package javalab.day6.vehiclesOOP;
public class Bus extends Vehicle{
// unique to bus
private Integer numPassengers;
private Integer numDecks;
private String fuelType;
public Bus() {
super();
}
public Bus(String purchaseDate, Integer conditionPerc) {
super(purchaseDate, conditionPerc);
}
// big constructor
public Bus(String colour, String make, String model, double purchasePrice,Integer conditionPerc, String purchaseDate,Integer numPassengers, Integer numDecks, String fuelType) {
super(colour, make, model, purchasePrice, conditionPerc, purchaseDate);
this.numPassengers = numPassengers;
this.numDecks = numDecks;
this.fuelType = fuelType;
}
public Bus(String purchaseDate) {
super(purchaseDate);
}
@Override
public void showStuff(){
System.out.println("***** BUS ******");
super.showStuff();
System.out.println(noNullMsg("Num passengers: " , numPassengers));
System.out.println(noNullMsg("Fuel type: " , fuelType));
System.out.println(noNullMsg("Num decks: " , numDecks));
}
@Override
public void printMaxSpeed() {
// TODO Auto-generated method stub
System.out.println("Max speed is 60Mph");
}
}
| true |
f08a94daa9e7b66e768f419aa40d6143be1de292 | Java | alipay/alipay-sdk-java-all | /v2/src/main/java/com/alipay/api/domain/NimitzColumn.java | UTF-8 | 1,007 | 1.921875 | 2 | [
"Apache-2.0"
] | permissive | package com.alipay.api.domain;
import java.util.List;
import com.alipay.api.AlipayObject;
import com.alipay.api.internal.mapping.ApiField;
import com.alipay.api.internal.mapping.ApiListField;
/**
* Nimitz 列模型
*
* @author auto create
* @since 1.0, 2022-06-13 11:05:19
*/
public class NimitzColumn extends AlipayObject {
private static final long serialVersionUID = 8138922334669346816L;
/**
* 列数据
*/
@ApiListField("cells")
@ApiField("nimitz_cell")
private List<NimitzCell> cells;
/**
* 列数据类型
*/
@ApiField("kind")
private String kind;
/**
* 列名称
*/
@ApiField("name")
private String name;
public List<NimitzCell> getCells() {
return this.cells;
}
public void setCells(List<NimitzCell> cells) {
this.cells = cells;
}
public String getKind() {
return this.kind;
}
public void setKind(String kind) {
this.kind = kind;
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
}
| true |
b0a067b28f57aee16b8dbcc2ebdfd76b19ba39e3 | Java | wael-mkaddem/ViV-Wallet | /ViV-Wallet-api/src/main/java/com/invivoo/vivwallet/api/domain/action/Action.java | UTF-8 | 991 | 1.789063 | 2 | [
"Apache-2.0"
] | permissive | package com.invivoo.vivwallet.api.domain.action;
import com.invivoo.vivwallet.api.domain.payment.Payment;
import com.invivoo.vivwallet.api.domain.user.User;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
import java.math.BigDecimal;
import java.time.LocalDateTime;
@Entity
@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder
public class Action {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private LocalDateTime date;
private ActionType type;
private Long lynxActivityId;
private BigDecimal viv;
private String context;
@ManyToOne
private User achiever;
@ManyToOne
private User creator;
@ManyToOne
private Payment payment;
private boolean isDeleted;
}
| true |
d9982f72269d281a1069319535460d2bd2f7d56a | Java | ljinshuan/bear | /src/main/java/com/taobao/brand/bear/utils/ThreadUtils.java | UTF-8 | 1,622 | 2.75 | 3 | [] | no_license | package com.taobao.brand.bear.utils;
import org.springframework.util.CollectionUtils;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;
/**
* @author jinshuan.li
*/
public class ThreadUtils {
public static ExecutorService executorService = ThreadPoolUtils.createThreadPool(70, "batch_process");
/**
* 多线程执行任务并且等待完成
*
* @param tasks
* @throws InterruptedException
* @throws ExecutionException
*/
public static <T> List<T> runWaitCompleteTask(List<Callable<T>> tasks, Long timeout, TimeUnit timeUnit)
throws Exception {
if (CollectionUtils.isEmpty(tasks)) {
return new ArrayList<T>();
}
CompletionService<T> completionService = new ExecutorCompletionService<T>(executorService);
for (Callable<T> runnable : tasks) {
completionService.submit(runnable);
}
Future<T> resultFuture = null;
List<T> result = new ArrayList<T>();
for (int i = 0; i < tasks.size(); i++) {
resultFuture = completionService.take();
result.add(resultFuture.get(timeout, timeUnit));
}
return result;
}
public static <T> Future<T> runAsync(Callable<T> task) {
return executorService.submit(task);
}
public static <T> Future<T> runAsync(ExecutorService executor, Callable<T> task) {
return executor.submit(task);
}
public static void sleep(long time) {
try {
Thread.sleep(time);
} catch (InterruptedException e) {
}
}
}
| true |
b83d1b7668fadc11ce1b8e74826c1946a77a7076 | Java | team2485/sdwidgets | /src/team2485/smartdashboard/extension/WebcamCardTracker.java | UTF-8 | 24,484 | 1.992188 | 2 | [] | no_license | package team2485.smartdashboard.extension;
import com.googlecode.javacv.CanvasFrame;
import com.googlecode.javacv.cpp.opencv_core;
import static com.googlecode.javacv.cpp.opencv_core.cvScalar;
import com.googlecode.javacv.cpp.opencv_imgproc;
import edu.wpi.first.smartdashboard.gui.*;
import edu.wpi.first.smartdashboard.properties.*;
import edu.wpi.first.wpijavacv.*;
import edu.wpi.first.wpilibj.networktables.NetworkTable;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;
import javax.imageio.ImageIO;
import javax.swing.*;
import team2485.smartdashboard.extension.util.*;
/**
* Webcam Image Processing Widget
* @author Bryce Matsumori
*/
public class WebcamCardTracker extends StaticWidget {
public static final String NAME = "Webcam Card Tracker";
private static final long SNAP_TIME = 2000;
private enum TrackState {
NONE(0), LEFT(1), RIGHT(2);
public final int id;
TrackState(int id) {
this.id = id;
}
}
// State
private boolean connected = false, process = true, showBinaryImage = false, showHsvTuner = false;
private int
hueMin = 39, hueMax = 108,
satMin = 111, satMax = 255,
vibMin = 98, vibMax = 255;
private TrackState trackingState = TrackState.NONE;
// SmartDashboard Properties
public final BooleanProperty processProperty = new BooleanProperty(this, "Process Images", process),
binaryImageProperty = new BooleanProperty(this, "Show Binary Image", showBinaryImage),
hsvTunerProperty = new BooleanProperty(this, "Show HSV Tuner", showHsvTuner);
public final IntegerProperty
hMinProp = new IntegerProperty(this, "Hue Min", hueMin),
hMaxProp = new IntegerProperty(this, "Hue Max", hueMax),
sMinProp = new IntegerProperty(this, "Saturation Min", satMin),
sMaxProp = new IntegerProperty(this, "Saturation Max", satMax),
vMinProp = new IntegerProperty(this, "Vibrance Min", vibMin),
vMaxProp = new IntegerProperty(this, "Vibrance Max", vibMax);
private NetworkTable table;
// Image Processing
private WPIWebcam cam;
private BufferedImage drawnImage;
private opencv_core.CvSize size = null;
private WPIContour[] contours;
private opencv_core.IplImage thresh, hsv, dilated;
private static opencv_core.CvScalar min, max;
private opencv_imgproc.IplConvKernel dilationElement;
// UI
private final JCheckBoxMenuItem binaryImageMenuItem = new JCheckBoxMenuItem("Show Binary Image", false), hsvTunerMenuItem = new JCheckBoxMenuItem("Show HSV Tuner", false), recordMenuItem = new JCheckBoxMenuItem("Record", false);
private final JMenu configMenu = new JMenu("Config");
private final JMenuItem configSaveItem = new JMenuItem("Save Current");
private CanvasFrame binaryPreview;
private HSVTuner hsvTuner;
private BufferedImage noneImage, leftImage, rightImage, placeholderImage;
private String errorMessage = "Connecting to webcam...";
private final SimpleDateFormat format = new SimpleDateFormat("yyyy-mm-dd HH-mm-ss");
private long lastUpdateTime = 0;
private boolean recording = false;
// Configuration
private static final File
SD_HOME = new File(new File(System.getProperty("user.home")), "SmartDashboard"),
WEBCAM_CONFIG_FILE = new File(SD_HOME, "webcamconfig.properties"),
SNAP_HOME = new File(SD_HOME, "Webcam"),
REC_LOCK = new File(SNAP_HOME, "recording");
private final Properties props = new Properties();
private final HashMap<String, HSVConfig> configs = new HashMap<>();
private class GCThread extends Thread {
boolean destroyed = false;
public GCThread() {
super("Webcam GC");
setDaemon(true);
}
@Override
public void run() {
while (!destroyed) {
try {
Thread.sleep(10000);
} catch (InterruptedException ex) { }
System.gc();
}
}
@Override
public void destroy() {
destroyed = true;
interrupt();
}
}
private final GCThread gcThread = new GCThread();
private class BGThread extends Thread {
boolean destroyed = false;
public BGThread() {
super("Webcam Background");
setDaemon(true);
}
@Override
public void run() {
WPIImage image;
while (!destroyed) {
if (cam == null) cam = new WPIWebcam();
try {
image = cam.getNewImage(5.0);
connected = true;
if (process) {
WPIImage img = processImage((WPIColorImage) image);
drawnImage = img.getBufferedImage();
img.dispose();
table.putNumber("targets", trackingState.id);
}
else drawnImage = image.getBufferedImage();
if (recording) {
long time = System.currentTimeMillis();
if (time - lastUpdateTime > SNAP_TIME) {
try {
ImageIO.write(drawnImage, "jpg", new File(SNAP_HOME, format.format(new Date()) + ".jpg"));
} catch (IOException ex) {
System.err.println("Could not save image.");
ex.printStackTrace();
}
lastUpdateTime = time;
}
}
image.dispose();
repaint();
} catch (final WPIWebcam.BadConnectionException e) {
connected = false;
errorMessage = "Could not connect to webcam.";
System.err.println("* Could not getNewImage: OpenCVFrameGrabber.BadConnectionException");
if (cam != null) cam.dispose();
cam = null;
drawnImage = null;
repaint();
try {
Thread.sleep(2000);
} catch (InterruptedException ex) { }
}
table.putBoolean("connected", connected);
}
}
@Override
public void destroy() {
destroyed = true;
}
}
private final BGThread bgThread = new BGThread();
public WebcamCardTracker() {
WPIExtensions.init();
// Try loading the HSV configurations
try {
props.load(new FileInputStream(WEBCAM_CONFIG_FILE));
for (String prop : props.stringPropertyNames()) {
configs.put(prop, HSVConfig.parse(props.getProperty(prop)));
}
} catch (IOException ex) {
System.err.println("Could not load webcam properties.");
}
}
@Override
public void init() {
table = NetworkTable.getTable("vision");
process = processProperty.getValue();
showBinaryImage = binaryImageProperty.getValue();
showHsvTuner = hsvTunerProperty.getValue();
showHideBinaryImage();
showHideHsvTuner();
hueMin = hMinProp.getValue();
hueMax = hMaxProp.getValue();
satMin = sMinProp.getValue();
satMax = sMaxProp.getValue();
vibMin = vMinProp.getValue();
vibMax = vMaxProp.getValue();
SNAP_HOME.mkdir();
if (REC_LOCK.exists()) {
recording = true;
recordMenuItem.setSelected(true);
}
try {
noneImage = ImageIO.read(getClass().getResourceAsStream("/team2485/smartdashboard/extension/res/hot-none.png"));
leftImage = ImageIO.read(getClass().getResourceAsStream("/team2485/smartdashboard/extension/res/hot-left.png"));
rightImage = ImageIO.read(getClass().getResourceAsStream("/team2485/smartdashboard/extension/res/hot-right.png"));
placeholderImage = ImageIO.read(getClass().getResourceAsStream("/team2485/smartdashboard/extension/res/axis.png"));
} catch (IOException e) { }
final Dimension minSize = new Dimension(320, 240);
setSize(minSize);
setPreferredSize(minSize);
setMinimumSize(minSize);
setMaximumSize(new Dimension(800, 600));
// <editor-fold defaultstate="collapsed" desc="Setup Menu Bar">
final WebcamCardTracker self = this;
final JMenuBar bar = new JMenuBar();
bar.setVisible(false);
this.addMouseListener(new MouseAdapter() {
@Override
public void mouseEntered(MouseEvent e) {
bar.setVisible(false);
}
});
this.addMouseMotionListener(new MouseAdapter() {
@Override
public void mouseMoved(MouseEvent e) {
if (e.getY() < 20) {
bar.setVisible(true);
}
}
});
bar.addMouseListener(new MouseAdapter() {
@Override
public void mouseExited(MouseEvent e) {
if (self.findComponentAt(e.getX(), e.getY()) != self)
bar.setVisible(false);
}
});
final JMenu debugMenu = new JMenu("Debug");
binaryImageMenuItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
showBinaryImage = binaryImageMenuItem.isSelected();
showHideBinaryImage();
binaryImageProperty.setValue(showBinaryImage);
}
});
hsvTunerMenuItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
showHsvTuner = hsvTunerMenuItem.isSelected();
showHideHsvTuner();
hsvTunerProperty.setValue(showHsvTuner);
}
});
recordMenuItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
toggleRecording();
}
});
debugMenu.add(binaryImageMenuItem);
debugMenu.add(hsvTunerMenuItem);
debugMenu.add(recordMenuItem);
configSaveItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
String name = JOptionPane.showInputDialog(null, "Enter configuration name.", "Webcam Processor", JOptionPane.PLAIN_MESSAGE);
if (name == null) return;
if (name.indexOf('=') != -1) {
JOptionPane.showMessageDialog(null, "Name cannot contain \"=\"!", "Webcam Processor", JOptionPane.ERROR_MESSAGE);
return;
}
final HSVConfig config = new HSVConfig(hueMin, hueMax, satMin, satMax, vibMin, vibMax);
configs.put(name, config);
constructConfigMenu();
props.setProperty(name, config.toString());
saveProperties();
}
});
constructConfigMenu();
bar.add(debugMenu);
bar.add(configMenu);
setLayout(new BorderLayout());
add(bar, BorderLayout.NORTH);
// </editor-fold>
bgThread.start();
gcThread.start();
revalidate();
repaint();
}
@Override
public void propertyChanged(Property property) {
if (property == processProperty) {
process = !property.hasValue() || (property.hasValue() && (Boolean)property.getValue()); // default or the value
}
else if (property == binaryImageProperty) {
showBinaryImage = !property.hasValue() || (property.hasValue() && (Boolean)property.getValue()); // default or the value
showHideBinaryImage();
}
else if (property == hsvTunerProperty) {
showHsvTuner = !property.hasValue() || (property.hasValue() && (Boolean)property.getValue()); // default or the value
showHideHsvTuner();
}
else if (property == hMinProp && hMinProp.hasValue()) {
hueMin = hMinProp.getValue();
if (hsvTuner != null) hsvTuner.setHMin(hueMin);
}
else if (property == hMaxProp && hMaxProp.hasValue()) {
hueMax = hMaxProp.getValue();
if (hsvTuner != null) hsvTuner.setHMax(hueMax);
}
else if (property == sMinProp && sMinProp.hasValue()) {
satMin = sMinProp.getValue();
if (hsvTuner != null) hsvTuner.setSMin(satMin);
}
else if (property == sMaxProp && sMaxProp.hasValue()) {
satMax = sMaxProp.getValue();
if (hsvTuner != null) hsvTuner.setSMax(satMax);
}
else if (property == vMinProp && vMinProp.hasValue()) {
vibMin = vMinProp.getValue();
if (hsvTuner != null) hsvTuner.setVMin(vibMin);
}
else if (property == vMaxProp && vMaxProp.hasValue()) {
vibMax = vMaxProp.getValue();
if (hsvTuner != null) hsvTuner.setVMax(vibMax);
}
}
@Override
public void disconnect() {
bgThread.destroy();
gcThread.destroy();
if (cam != null) cam.dispose();
super.disconnect();
}
@Override
protected void paintComponent(Graphics gg) {
Graphics2D g = (Graphics2D)gg;
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
final int width = getBounds().width,
height = getBounds().height;
if (connected && drawnImage != null) {
// Calculate scaling
final int imageWidth = drawnImage.getWidth(),
imageHeight = drawnImage.getHeight();
final double scale = Math.min((double)width / (double)imageWidth, (double)height / (double)imageHeight);
final int imageX = (int)(width - (scale * imageWidth)) / 2,
imageY = (int)(height - (scale * imageHeight)) / 2;
// Draw camera image
g.drawImage(drawnImage, imageX, imageY,
(int) ((width + scale * imageWidth) / 2), (int) (height + scale * imageHeight) / 2,
0, 0, imageWidth, imageHeight, null);
// Draw overlays
final int centerX = imageX + (int)((scale * imageWidth) * 0.5),
scaledImageHeight = (int)(scale * imageHeight);
g.setColor(new Color(255, 0, 0, 128));
g.drawLine(centerX + 2, imageY, centerX + 2, imageY + scaledImageHeight);
g.drawLine(centerX - 3, imageY, centerX - 3, imageY + scaledImageHeight);
g.setColor(new Color(0, 255, 0, 128));
g.drawLine(centerX + 60, imageY, centerX + 60, imageY + scaledImageHeight);
g.drawLine(centerX - 61, imageY, centerX - 61, imageY + scaledImageHeight);
g.setColor(new Color(0, 0, 255, 128));
g.drawLine(centerX + 110, imageY, centerX + 110, imageY + scaledImageHeight);
g.drawLine(centerX - 111, imageY, centerX - 111, imageY + scaledImageHeight);
if (process) {
// Draw hot image
BufferedImage hotImg = null;
switch (trackingState) {
case NONE: hotImg = noneImage; break;
case LEFT: hotImg = leftImage; break;
case RIGHT: hotImg = rightImage; break;
}
g.drawImage(hotImg, getWidth() / 2 - noneImage.getWidth() / 2, 0, null);
}
}
else {
// Calculate scaling
final double scale = Math.min(width / 320.0, height / 240.0);
final int
imageX = (int)(width - (scale * 320)) / 2,
imageY = (int)(height - (scale * 240)) / 2,
scaledImageWidth = (int)(scale * 320),
scaledImageHeight = (int)(scale * 240);
// Draw placeholder
g.setColor(new Color(255, 255, 255, 25));
g.fillRoundRect(imageX, imageY, scaledImageWidth - 1, scaledImageHeight - 1, 10, 10);
g.setColor(Color.white);
g.drawRoundRect(imageX, imageY, scaledImageWidth - 1, scaledImageHeight - 1, 10, 10);
g.drawImage(placeholderImage, imageX + scaledImageWidth / 2 - 36, imageY + scaledImageHeight / 2 - 54, null);
if (errorMessage != null) {
g.setFont(new Font("Ubuntu", Font.PLAIN, 14));
g.drawString(errorMessage,
imageX + scaledImageWidth / 2 - g.getFontMetrics().stringWidth(errorMessage) / 2,
imageY + scaledImageHeight - 10);
}
}
super.paintComponent(gg);
}
public WPIImage processImage(WPIColorImage rawImage) {
// Refresh IplImage sizes if necessary
if (size == null || size.width() != rawImage.getWidth() || size.height() != rawImage.getHeight()) {
if (size != null) size.deallocate();
if (thresh != null) thresh.deallocate();
if (hsv != null) hsv.deallocate();
if (dilationElement != null) dilationElement.deallocate();
size = opencv_core.cvSize(rawImage.getWidth(), rawImage.getHeight());
thresh = opencv_core.IplImage.create(size, 8, 1);
hsv = opencv_core.IplImage.create(size, 8, 3);
dilated = opencv_core.IplImage.create(size, 8, 1);
dilationElement = opencv_imgproc.cvCreateStructuringElementEx(
3, 3, 0, 0,
opencv_imgproc.CV_SHAPE_ELLIPSE, null);
}
min = cvScalar(hueMin, satMin, vibMin, 0);
max = cvScalar(hueMax, satMax, vibMax, 255);
// Get the raw IplImage
opencv_core.IplImage input = rawImage.getIplImage();
// Convert to HSV color space
opencv_imgproc.cvCvtColor(input, hsv, opencv_imgproc.CV_RGB2HSV);
// Find the green areas
opencv_core.cvInRangeS(hsv, min, max, thresh);
// Expand the edges for accuracy
opencv_imgproc.cvDilate(thresh, dilated, dilationElement, 2);
if (showBinaryImage && binaryPreview != null)
binaryPreview.showImage(dilated.getBufferedImage());
// Find the contours!
WPIBinaryImage binWpi = WPIExtensions.makeWPIBinaryImage(dilated);
contours = WPIExtensions.findConvexContours(binWpi);
double leftArea = 0, rightArea = 0;
for (WPIContour c : contours) {
double area = opencv_imgproc.cvContourArea(c.getCVSeq(), opencv_core.CV_WHOLE_SEQ, 0);
if (area < 600) continue; // eliminate noise
final int rectCenterX = c.getX() + c.getWidth() / 2;
if (rectCenterX < dilated.width() / 2 && area > leftArea) {
leftArea = area;
}
else if (area > rightArea) {
rightArea = area;
}
}
if (leftArea > 0 && leftArea > rightArea) {
trackingState = TrackState.LEFT;
}
else if (rightArea > 0 && rightArea > leftArea) {
trackingState = TrackState.RIGHT;
}
else {
trackingState = TrackState.NONE;
}
WPIExtensions.releaseMemory();
return rawImage;
}
private void constructConfigMenu() {
configMenu.removeAll();
configMenu.add(configSaveItem);
configMenu.add(new JPopupMenu.Separator());
if (configs.isEmpty()) {
final JMenuItem noConfigItem = new JMenuItem("(no configs)");
noConfigItem.setEnabled(false);
configMenu.add(noConfigItem);
}
else {
Iterator<Map.Entry<String, HSVConfig>> iterator = configs.entrySet().iterator();
while (iterator.hasNext()) {
final Map.Entry<String, HSVConfig> next = iterator.next();
final HSVConfig config = next.getValue();
final JMenuItem configItem = new JMenuItem(next.getKey());
configItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
hMinProp.setValue(config.hMin);
hMaxProp.setValue(config.hMax);
sMinProp.setValue(config.sMin);
sMaxProp.setValue(config.sMax);
vMinProp.setValue(config.vMin);
vMaxProp.setValue(config.vMax);
JOptionPane.showMessageDialog(null,
String.format("%s\nH: %d - %d\nS: %d - %d\nV: %d - %d", next.getKey(), config.hMin, config.hMax, config.sMin, config.sMax, config.vMin, config.vMax),
"Webcam Processor", JOptionPane.INFORMATION_MESSAGE);
}
});
configMenu.add(configItem);
configMenu.revalidate();
}
}
}
private void saveProperties() {
try {
WEBCAM_CONFIG_FILE.createNewFile();
props.store(new FileOutputStream(WEBCAM_CONFIG_FILE), "Webcam Config");
} catch (IOException ex) {
System.err.println("Error saving webcam config file.");
ex.printStackTrace();
}
}
private void showHideBinaryImage() {
if (showBinaryImage) {
if (binaryPreview == null) {
binaryPreview = new CanvasFrame("Binary Preview");
binaryPreview.setAlwaysOnTop(true);
binaryPreview.setSize(320, 240);
}
binaryPreview.setVisible(true);
}
else if (binaryPreview != null) {
binaryPreview.setVisible(false);
}
binaryImageMenuItem.setSelected(showBinaryImage);
}
private void showHideHsvTuner() {
if (showHsvTuner) {
if (hsvTuner == null) {
hsvTuner = new HSVTuner(new HSVTuner.HSVTunerChangeListener() {
@Override
public void hMinChanged(int newValue) {
hueMin = newValue;
hMinProp.setValue(newValue);
}
@Override
public void hMaxChanged(int newValue) {
hueMax = newValue;
hMaxProp.setValue(newValue);
}
@Override
public void sMinChanged(int newValue) {
satMin = newValue;
sMinProp.setValue(newValue);
}
@Override
public void sMaxChanged(int newValue) {
satMax = newValue;
sMaxProp.setValue(newValue);
}
@Override
public void vMinChanged(int newValue) {
vibMin = newValue;
vMinProp.setValue(newValue);
}
@Override
public void vMaxChanged(int newValue) {
vibMax = newValue;
vMaxProp.setValue(newValue);
}
}, hueMin, hueMax, satMin, satMax, vibMin, vibMax);
}
hsvTuner.setVisible(true);
}
else if (hsvTuner != null) {
hsvTuner.setVisible(false);
}
hsvTunerMenuItem.setSelected(showHsvTuner);
}
private void toggleRecording() {
recording = !recording;
if (recording) {
try {
REC_LOCK.createNewFile();
} catch (IOException e) {
System.err.println("Could not create recording lock.");
e.printStackTrace();
}
}
else {
REC_LOCK.delete();
}
}
}
| true |
e380458be892d78ab11ac76f7c6c9a14973bed08 | Java | paranjay11/OOAD | /ParkingLot/ParkingLotDesign/src/parkingLotDesign/ParkingLot.java | UTF-8 | 2,539 | 2.875 | 3 | [] | no_license | package parkingLotDesign;
import java.util.ArrayList;
import java.util.HashMap;
import parkingLotDesign.Constants.ParkingSpotType;
import parkingLotDesign.Constants.ParkingStatus;
import parkingLotDesign.Constants.PaymentStatus;
public class ParkingLot{
static private ParkingLot Instance;
static private ArrayList<ParkingFloor> floors;
private static HashMap<Long,ParkingTicket> customers;
// private static ArrayList<Display> floorsDisplay;
private ParkingLot(){
floors=new ArrayList<ParkingFloor>();
customers=new HashMap<Long,ParkingTicket>();
// floorsDisplay=new ArrayList<Display>();
}
public static ParkingLot getParkingLotInstance() {
if(Instance==null) {
Instance=new ParkingLot();
}
return Instance;
}
public void addFloor(ParkingFloor parkingFloor){
floors.add(parkingFloor);
// floorsDisplay.add(parkingFloor.getDisplay());
}
public void removeFloor(ParkingFloor parkingFloor){
floors.remove(parkingFloor);
}
public static boolean isAvailable(ParkingSpotType parkingSpotType){
for(int i=0;i<floors.size();i++){
ParkingFloor temp=floors.get(i);
if(temp.isParkingSpotAvailable(parkingSpotType)) {
return true;
}
}
return false;
}
public static Long issueParkingTicket(Account account,Long initTime) {
Cell cell=null;
Long ticketId=null;
ParkingTicket ticket;
ParkingSpotType parkingSpotType=account.getParkingSpotType();
int i;
for(i=0;i<floors.size();i++){
ParkingFloor temp=floors.get(i);
if(temp.isParkingSpotAvailable(parkingSpotType)) {
cell=temp.getCell(parkingSpotType);
break;
}
}
if(cell!=null) {
System.out.println("Updating the matrix......");
((ParkingFloor)floors.get(i)).updateMatrix(cell, ParkingStatus.OCCUPIED);
ticket=new ParkingTicket(ParkingStatus.OCCUPIED,account.getVehicleId(),cell,initTime,i);
ticketId=ticket.getParkingTicketId();
customers.put(ticketId,ticket);
}
return ticketId;
}
public static boolean CheckOut(Long ticketId, PaymentMethod paymentMethod) {
System.out.println("Checking out initiated...." );
ParkingTicket ticket=customers.get(ticketId);
System.out.println("tickeId = "+ ticketId);
Cell cell=ticket.getCell();
boolean ticketStatus=false;
if(paymentMethod.pay()) {
System.out.println("Payment received.....");
((ParkingFloor)floors.get(ticket.getParkingFloor())).updateMatrix(cell, ParkingStatus.FREE);
ticket.setPaymentStatus(PaymentStatus.FREE);
ticketStatus = true;
customers.remove(ticketId);
}
return ticketStatus;
}
} | true |
5fbc3ad09464cad55ae54afe41228793d9b9f2de | Java | saveripal/Yahtzee | /scoringCategories/LargeStraight.java | UTF-8 | 978 | 3.5 | 4 | [] | no_license |
/**
* Scoring category for a "large straight". A hand with N dice satisfies this category only if
* there are N distinct consecutive values. For a hand that satisfies this category, the score
* is a fixed value specified in the constructor; otherwise, the score is zero.
*
* @author Saveri Pal
*
*/
public class LargeStraight extends XXStraights
{
/**
*
* Constructs a LargeStraight category with the given display name and score.
* @param name category name
* @param points points to be awarded if given hand satisfies criteria
*/
public LargeStraight(java.lang.String name, int points)
{
super(name, points);
}
@Override
/**
* Determines if a given hand contains N consecutive values
*/
public boolean isSatisfiedBy(Hand hand)
{
// number if dice an the given hand
int n = hand.getNumDice();
int count = countConsec(hand);
if (count == (n))
{
return true;
}
return false;
}
}
| true |
736cbb81a812e45995015db95b0e5aaaadb3de2f | Java | bookere90/Light_Pattern_Tester | /app/src/main/java/android/booker/light_module/MainActivity.java | UTF-8 | 1,444 | 2.484375 | 2 | [] | no_license | package android.booker.light_module;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import org.w3c.dom.Text;
public class MainActivity extends AppCompatActivity {
private Button flashButton;
private EditText frequencyInput;
private GetTime timeObject;
// Event listener for FlashButton
private View.OnClickListener FlashButtonOnClickListener = new View.OnClickListener() {
@Override
public void onClick(View v) {
FlashButtonClicked();
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
frequencyInput = findViewById(R.id.frequencyInputEditText);
flashButton = findViewById(R.id.FlashButton);
flashButton.setOnClickListener(FlashButtonOnClickListener);
}
private void FlashButtonClicked(){
// gets the frequency that the user input into the EditText box
int frequency = Integer.parseInt(frequencyInput.getText().toString());
// gets the time one second ahead of the start time
int stopTime = timeObject.GetCurrentSecond() + 1;
while(frequency > 0){
if(stopTime != timeObject.GetCurrentSecond()){
frequency--;
}
}
}
}
| true |
bbfbf2a378a471510d5b4baf55a1f5dcd1db19e4 | Java | linzhongshou/app | /src/main/java/cn/linzs/app/common/shiro/cache/RedisCache.java | UTF-8 | 2,123 | 2.578125 | 3 | [] | no_license | package cn.linzs.app.common.shiro.cache;
import org.apache.shiro.cache.Cache;
import org.apache.shiro.cache.CacheException;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import java.util.Collection;
import java.util.Set;
/**
* @Author linzs
* @Date 2018-01-26 15:35
* @Description
*/
public class RedisCache<K, V> implements Cache<K, V> {
private RedisTemplate<K, V> redisTemplate;
private HashOperations<String, K, V> hashOperations;
private final static String REDIS_KEY = "SHIRO_KEY_COMMMMMM";
public RedisCache(RedisTemplate redisTemplate) {
this.redisTemplate = redisTemplate;
this.hashOperations = redisTemplate.opsForHash();
}
@Override
public V get(K k) throws CacheException {
try {
if(k != null) {
return hashOperations.get(REDIS_KEY, k);
} else {
return null;
}
} catch (Throwable e) {
throw new CacheException(e);
}
}
@Override
public V put(K k, V v) throws CacheException {
try {
hashOperations.put(REDIS_KEY, k, v);
return v;
} catch (Throwable e) {
throw new CacheException(e);
}
}
@Override
public V remove(K k) throws CacheException {
try {
V v = get(k);
hashOperations.delete(REDIS_KEY, k);
return v;
} catch (Throwable e) {
throw new CacheException(e);
}
}
@Override
public void clear() throws CacheException {
try {
hashOperations.delete(REDIS_KEY, hashOperations.keys(REDIS_KEY));
} catch (Throwable e) {
throw new CacheException(e);
}
}
@Override
public int size() {
return hashOperations.keys(REDIS_KEY).size();
}
@Override
public Set<K> keys() {
return hashOperations.keys(REDIS_KEY);
}
@Override
public Collection<V> values() {
return hashOperations.entries(REDIS_KEY).values();
}
}
| true |
3f005839f64a545a95eb048bc1a9cc7f446128b4 | Java | adcaine/inputTest | /app/src/main/java/com/allancaine/inputtest/ResourceFinder.java | UTF-8 | 1,295 | 2.390625 | 2 | [] | no_license | package com.allancaine.inputtest;
import android.content.Context;
import java.util.ArrayList;
/**
* Created by allancaine on 2015-07-01.
*/
public class ResourceFinder {
private ArrayList<Page> mPageResources;
private Context mContext;
private static ResourceFinder sResourceFinder;
public static ResourceFinder get(Context context){
if(sResourceFinder == null){
sResourceFinder = new ResourceFinder(context);
}
return sResourceFinder;
}
private ResourceFinder(Context c){
mContext = c.getApplicationContext();
mPageResources = new ArrayList<>();
mPageResources.add(new Page(mContext.getString(R.string.basic_input_title),
R.layout.basic_input_layout));
mPageResources.add(new Page(mContext.getString(R.string.password_input_title),
R.layout.password_input_layout));
mPageResources.add(new Page(mContext.getString(R.string.date_time_phone_title),
R.layout.date_time_phone_layout));
}
public Page getResource(int position){
return mPageResources.get(position);
}
public ArrayList<Page> getPageResources(){
return mPageResources;
}
public int size(){
return mPageResources.size();
}
}
| true |
5e201ef88d276fa3c8f143afddcbd8827bb4cdca | Java | Shahnovski/autoshop-server | /src/main/java/com/example/autoshopserver/car/comment/CommentDTO.java | UTF-8 | 423 | 1.679688 | 2 | [] | no_license | package com.example.autoshopserver.car.comment;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@NoArgsConstructor
@AllArgsConstructor
public class CommentDTO {
private Long id;
private String commentText;
private Long carId;
private Long userId;
private String userUsername;
private Long receiverCommentId;
private String receiverCommentText;
}
| true |
fa8163aca83641cec9496f78caa7a78101d8af6c | Java | Stason1o/Java-SpringBoot-App | /src/test/java/com/sbogdanschi/springboot/controller/AdminActionsControllerTest.java | UTF-8 | 3,348 | 2.046875 | 2 | [] | no_license | package com.sbogdanschi.springboot.controller;
import com.sbogdanschi.springboot.entity.Role;
import com.sbogdanschi.springboot.entity.User;
import com.sbogdanschi.springboot.service.RoleService;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.web.servlet.View;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import static com.sbogdanschi.springboot.util.PageUrl.Admin.*;
import static com.sbogdanschi.springboot.util.SecurityContextInitializationHelper.getAuthentication;
import static com.sbogdanschi.springboot.util.TestDataUtil.*;
import static org.mockito.Mockito.*;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.view;
import static org.springframework.test.web.servlet.setup.MockMvcBuilders.standaloneSetup;
@RunWith(SpringJUnit4ClassRunner.class)
public class AdminActionsControllerTest {
@Mock
private RoleService roleService;
@Mock
private AdminActionsApi adminService;
@Mock
private View mockView;
@InjectMocks
private AdminActionsController adminActionsController;
private MockMvc mockMvc;
@Before
public void setUp() throws Exception {
mockMvc = standaloneSetup(adminActionsController).setSingleView(mockView).build();
User user = buildValidUser();
UsernamePasswordAuthenticationToken token = (UsernamePasswordAuthenticationToken) getAuthentication(user);
SecurityContextHolder.getContext().setAuthentication(token);
}
@Test
public void testGetUserListPage() throws Exception {
List<User> users = buildUserList();
ResponseEntity<List<User>> responseEntity = new ResponseEntity<List<User>>(users, HttpStatus.OK);
Set<Role> roles = buildRoleList();
when(roleService.findAll()).thenReturn(new ArrayList<>(roles));
when(adminService.getListOfUsers()).thenReturn(responseEntity);
mockMvc.perform(get(ADMIN_PAGE + USER_MANAGEMENT + USERS))
.andExpect(status().isOk())
.andExpect(view().name("user-list"));
verify(roleService).findAll();
verify(adminService, times(1)).getListOfUsers();
verifyNoMoreInteractions(roleService, adminService);
}
@Test
public void testGetUserManagementPage() throws Exception {
mockMvc.perform(get(ADMIN_PAGE + USER_MANAGEMENT))
.andExpect(status().isOk())
.andExpect(view().name("user-management"));
}
@Test
public void testGetSearchPage() throws Exception {
mockMvc.perform(get(ADMIN_PAGE + SEARCH))
.andExpect(status().isOk())
.andExpect(view().name("search"));
}
} | true |
b2438552fef3f0aa63f622ea038a07455623e241 | Java | korut94/pcd-actors | /src/test/java/it/unipd/math/pcd/actors/StackTest/PushMessage.java | UTF-8 | 351 | 2.3125 | 2 | [
"MIT"
] | permissive | package it.unipd.math.pcd.actors.StackTest;
import it.unipd.math.pcd.actors.Message;
/**
* Created by amantova on 21/12/15.
*/
public class PushMessage implements Message
{
private int payload_ = 0;
public PushMessage( int payload )
{
payload_ = payload;
}
public int extract()
{
return payload_;
}
}
| true |
fc6b8d8bc5fdc7209685e6567b3109a175bd8e4e | Java | olszewskimichal/selenium-jupiter | /src/main/java/io/github/bonigarcia/handler/AppiumDriverHandler.java | UTF-8 | 2,890 | 2.046875 | 2 | [
"Apache-2.0"
] | permissive | /*
* (C) Copyright 2017 Boni Garcia (http://bonigarcia.github.io/)
*
* 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 io.github.bonigarcia.handler;
import static java.lang.invoke.MethodHandles.lookup;
import static org.slf4j.LoggerFactory.getLogger;
import java.lang.reflect.Parameter;
import java.net.URL;
import java.util.Optional;
import org.openqa.selenium.Capabilities;
import org.openqa.selenium.WebDriver;
import org.slf4j.Logger;
import io.appium.java_client.android.AndroidDriver;
import io.appium.java_client.service.local.AppiumDriverLocalService;
import io.github.bonigarcia.AnnotationsReader;
/**
* Resolver for ChromeDriver.
*
* @author Boni Garcia (boni.gg@gmail.com)
* @since 1.2.0
*/
public class AppiumDriverHandler {
final Logger log = getLogger(lookup().lookupClass());
static AppiumDriverHandler instance;
private AppiumDriverLocalService appiumDriverLocalService;
public static synchronized AppiumDriverHandler getInstance() {
if (instance == null) {
instance = new AppiumDriverHandler();
}
return instance;
}
public WebDriver resolve(Parameter parameter,
Optional<Object> testInstance) {
WebDriver webDriver = null;
Optional<Capabilities> capabilities = AnnotationsReader.getInstance()
.getCapabilities(parameter, testInstance);
Optional<URL> url = AnnotationsReader.getInstance().getUrl(parameter,
testInstance);
if (capabilities.isPresent()) {
URL appiumServerUrl;
if (url.isPresent()) {
appiumServerUrl = url.get();
} else {
appiumDriverLocalService = AppiumDriverLocalService
.buildDefaultService();
appiumDriverLocalService.start();
appiumServerUrl = appiumDriverLocalService.getUrl();
}
webDriver = new AndroidDriver<>(appiumServerUrl,
capabilities.get());
} else {
log.warn(
"Was not possible to instantiate AppiumDriver: Capabilites not present");
}
return webDriver;
}
public void closeLocalServiceIfNecessary() {
if (appiumDriverLocalService != null) {
appiumDriverLocalService.stop();
appiumDriverLocalService = null;
}
}
}
| true |
4c36a96b79ba95a615e5230b2d843b875d7451c2 | Java | MariusMsw/BullStock | /src/main/java/com/mariusmihai/banchelors/BullStock/repositories/TokensRepository.java | UTF-8 | 853 | 2.03125 | 2 | [] | no_license | package com.mariusmihai.banchelors.BullStock.repositories;
import com.mariusmihai.banchelors.BullStock.models.UserTokens;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import java.util.List;
import java.util.Optional;
@Repository
public interface TokensRepository extends CrudRepository<UserTokens, Long> {
List<UserTokens> findAllByUserId(int userId);
Optional<UserTokens> findByAccessToken(String accessToken);
void deleteByAccessToken(String accessToken);
@Modifying
@Query("delete from UserTokens ut where ut.user.id = :userId")
Integer deleteAllByUserId(@Param("userId") int userId);
}
| true |
926de69bce07aa42480d54af3a22b05e07bcb3c4 | Java | jdsllk7/Calculus-Prime | /app/src/main/java/com/example/jdslk/calculusprime/MiddleMan_Interface.java | UTF-8 | 119 | 1.640625 | 2 | [] | no_license | package com.example.jdslk.calculusprime;
public interface MiddleMan_Interface {
void data_carrier(String data);
}
| true |
468a727910920dc4d78de903e8d28f9d6dfae784 | Java | gamsung0388/java-2021-05-21 | /basic01/J20210412_4_Scanner.java | UTF-8 | 3,160 | 4.125 | 4 | [] | no_license | package basic01;
import java.util.Scanner;
public class J20210412_4_Scanner {
public static void main(String[] args) {
// 사용자에게 입력받기
// Scanner sc = new Scanner(System.in);
// System.out.println("정수를 입력하세요.");
// int a = sc.nextInt();
// System.out.println("입력받은 값은: "+ a);
//반지름을 입력받아 원의 넓이 구하기
// Scanner sc = new Scanner(System.in);
// System.out.println("반지름을 입력하세요");
// double r = sc.nextDouble();
// //Math.PI: 원주율
// System.out.printf("원의 넓이는 %.2f 입니다\n",r*r*Math.PI); //static은 눕습니다.
//문자열을 입력받을 때
// Scanner sc = new Scanner(System.in);
// 클래스(구조체) 변수
// System.out.print("이름은?");
// String name = sc.next();
// System.out.println("당신의 이름은 " + name);
// 메소드
//한줄을 읽어들이는 메소드(enter값을 기준으로 읽기
//공백허용
// Scanner sc = new Scanner(System.in); //키보드로 불러들이겠다는 scanf
// System.out.print("이름");
// String name = sc.nextLine();
// System.out.println("이름은 "+name);
//
//실습)나이와 이메일을 입력받아 출력.
// Scanner sc = new Scanner(System.in);
// System.out.print("나이는?");
// int age = sc.nextInt();
// System.out.print("이메일?");
// String email = sc.next(); //문자열(공백,엔터기준)
// sc.nextLine(); //엔터처리 (버퍼를 비우기 위해서
// System.out.print("이름은?");
// String name = sc.nextLine(); //엔터를 기준으로 문자열 읽기
//
// //enter 기준으로 한라인을 통제로 불러들여 읽힘.
// System.out.println("이름은 " + name + " 나이는 " + age + "살 " + "이메일은 " + email);
//실습)반, 이름, 파이썬,c,자바 정수를 입력받아
//총점과 평균을 구하라.
//스캐너
// Scanner sc = new Scanner(System.in);
// //반,이름 정의
// System.out.print("어떤 반이십니까? 이름은 어떻게되시죠? ");
// String clase = sc.next();
// String name = sc.nextLine();
// //점수들 정의
// System.out.print("파이썬, C , 자바 점수를 입력하세요 ");
// int python = sc.nextInt();
// int c = sc.nextInt();
// int java = sc.nextInt();
// //총점,평균 정의
// int sum = python + c + java;
// double avg = (double)sum/3; //자동형변환
//
// //출력
// System.out.println("------------------------------------------------------");
// System.out.println(clase + "반의 "+ name + "님의 점수는 파이썬은 "+ python + "점 C는 " + c + "점 자바는 " + java + "점으로 입력받았습니다." );
// System.out.printf("그럼으로 총점은 %d점 평균은 %.2f 점 입니다.",sum,avg);
// double avg = 123.456789;
//math round 이용
// System.out.println(avg * 100);
// System.out.println(Math.round(avg * 100));
// System.out.println((double)Math.round(avg * 100)/100);
//format 메소드 이용
// System.out.println("포맷메소드: "+String.format("%.2f", avg));
}
}
| true |
2858f0de47579b7b12298afbf6ae44a7795643dd | Java | diegotpereira/Supermercado-Master-Rest | /Supermercado-Master-Rest/BackEnd-Supermercado/src/main/java/co/edu/javeriana/myapp/server/myappserver/model/VentaRepository.java | UTF-8 | 194 | 1.570313 | 2 | [] | no_license | package co.edu.javeriana.myapp.server.myappserver.model;
import org.springframework.data.repository.CrudRepository;
public interface VentaRepository extends CrudRepository<Venta, Long>{
}
| true |
49f74519f11d9a6d39d16d657a09004c2a744acd | Java | caalvaro/ConcurrentComputing | /Lab7 - Problemas Clássicos em Java/ProdutoresConsumidores.java | UTF-8 | 5,960 | 3.578125 | 4 | [] | no_license | /* Disciplina: Computacao Concorrente */
/* Prof.: Silvana Rossetto */
/* Codigo: Leitores e escritores usando monitores em Java */
/* -------------------------------------------------------------------*/
//classe da estrutura de dados (recurso) compartilhado entre as threads
class Buffer {
private Integer buffer[];
private int bufferSize;
//construtor
Buffer() {
this.buffer = new Integer[Main.sharedAreaSize];
this.bufferSize = 0; // quantidade de elementos não nulos
for (int i = 0; i < buffer.length; i++) {
this.buffer[i] = null; // inicia um buffer vazio
}
}
//operacao de leitura sobre o recurso compartilhado
public synchronized void printBuffer() {
System.out.print("[ ");
for (int i = 0; i < buffer.length - 1; i++) {
if (this.buffer[i] == null) {
System.out.print("--, ");
} else {
System.out.print(buffer[i] + ", ");
}
}
if (this.buffer[buffer.length - 1] == null) {
System.out.println(" -- ]");
} else {
System.out.println(buffer[buffer.length - 1] + " ]");
}
}
//operacao de leitura sobre o recurso compartilhado
public int getBufferSize() {
return this.bufferSize;
}
//operacao de leitura sobre o recurso compartilhado
public synchronized Integer getElement(int index) {
return this.buffer[index];
}
//operacao de escrita sobre o recurso compartilhado
public synchronized Integer insertElement(int index, int value) {
// a função só insere um elemento na posição se ela estiver vazia
if (this.buffer[index] == null) {
this.buffer[index] = value;
this.bufferSize++;
}
return this.buffer[index];
}
//operacao de escrita sobre o recurso compartilhado
public synchronized Integer removeElement(int index) {
Integer removedElement = null;
// se a posição estiver vazia, não remove o elemento e retorna nulo
if (this.buffer[index] != null) {
removedElement = this.buffer[index];
this.buffer[index] = null;
this.bufferSize--;
}
return removedElement;
}
}
// Monitor
class ProducerConsumer {
private int in, out;
private Buffer buffer;
// Construtor
ProducerConsumer(Buffer buffer) {
this.in = 0; // posição da próxima produção
this.out = 0; // posição do próximo consumo
this.buffer = buffer;
}
// O consumidor consome o buffer
public synchronized void consume(int id) {
try {
System.out.println("Consumidor "+id+" quer consumir");
// se o buffer não tiver elementos para serem consumidos, a thread se bloqueia
while (this.buffer.getBufferSize() == 0) {
System.out.println ("Consumidor "+id+" se bloqueou. Buffer está vazio");
wait(); //bloqueia pela condicao logica da aplicacao
}
this.buffer.removeElement(this.out);
this.buffer.printBuffer();
System.out.println("Consumidor "+id+" consumiu na posição "+this.out);
this.out = (this.out + 1) % Main.sharedAreaSize;
this.notify();
} catch (InterruptedException e) { }
}
// Produtor produz elementos
public synchronized void produce(int id) {
try {
System.out.println("Produtor "+id+" quer produzir");
// se o buffer estiver cheio, a thread se bloqueia
while(this.buffer.getBufferSize() == Main.sharedAreaSize) {
System.out.println("Produtor "+id+" se bloqueou. Buffer está cheio");
wait(); //bloqueia pela condicao logica da aplicacao
}
this.buffer.insertElement(this.in, id);
this.buffer.printBuffer();
System.out.println("Produtor "+id+" terminou de produzir na posição "+this.in);
this.in = (this.in + 1) % Main.sharedAreaSize;
this.notify();
} catch (InterruptedException e) { }
}
}
//--------------------------------------------------------
// Consumidor
class Consumer extends Thread {
int id; //identificador da thread
int delay; //atraso bobo
ProducerConsumer monitor; //objeto monitor para coordenar a lógica de execução das threads
// Construtor
Consumer(int id, int delayTime, ProducerConsumer monitor) {
this.id = id;
this.delay = delayTime;
this.monitor = monitor;
}
// Método executado pela thread
public void run() {
try {
for (;;) {
this.monitor.consume(this.id);
sleep(this.delay);
}
} catch (InterruptedException e) { return; }
}
}
//--------------------------------------------------------
// Produtor
class Producer extends Thread {
int id; //identificador da thread
int delay; //atraso bobo...
ProducerConsumer monitor; //objeto monitor para coordenar a lógica de execução das threads
// Construtor
Producer(int id, int delayTime, ProducerConsumer monitor) {
this.id = id;
this.delay = delayTime;
this.monitor = monitor;
}
// Método executado pela thread
public void run() {
try {
for (;;) {
this.monitor.produce(this.id);
sleep(this.delay); //atraso bobo...
}
} catch (InterruptedException e) { return; }
}
}
//--------------------------------------------------------
// Classe principal
class Main {
static final int NumberOfConsumers = 2;
static final int NumberOfProducers = 5;
static final int sharedAreaSize = 5;
public static void main (String[] args) {
int i;
Buffer buffer = new Buffer();
ProducerConsumer monitor = new ProducerConsumer(buffer); // Monitor (objeto compartilhado entre produtores e consumidores)
Consumer[] consumer = new Consumer[NumberOfConsumers]; // Threads consumidores
Producer[] producer = new Producer[NumberOfProducers]; // Threads produtores
for (i = 0; i < NumberOfConsumers; i++) {
consumer[i] = new Consumer(i+1, (i+1)*500, monitor);
consumer[i].start();
}
for (i = 0; i < NumberOfProducers; i++) {
producer[i] = new Producer(i+1, (i+1)*500, monitor);
producer[i].start();
}
}
}
| true |
492059a175b431a741fe584ef93a08ff07e4dc8b | Java | morristech/Candid | /java/defpackage/akp$2.java | UTF-8 | 581 | 1.835938 | 2 | [] | no_license | package defpackage;
import java.util.concurrent.CountDownLatch;
/* compiled from: Fabric */
class akp$2 implements aks {
final CountDownLatch a = new CountDownLatch(this.b);
final /* synthetic */ int b;
final /* synthetic */ akp c;
akp$2(akp akp, int i) {
this.c = akp;
this.b = i;
}
public void a(Object o) {
this.a.countDown();
if (this.a.getCount() == 0) {
this.c.n.set(true);
this.c.i.a(this.c);
}
}
public void a(Exception exception) {
this.c.i.a(exception);
}
}
| true |
3101f2e1808cb678dba35d52015eeef07a1ffde5 | Java | reverseengineeringer/com.yelp.android | /src/com/yelp/android/appdata/webrequests/x.java | UTF-8 | 1,019 | 1.679688 | 2 | [] | no_license | package com.yelp.android.appdata.webrequests;
import android.text.TextUtils;
import com.yelp.android.appdata.webrequests.core.b;
import com.yelp.android.serializable.BusinessCategorySuggest;
import com.yelp.parcelgen.JsonUtil;
import java.util.List;
import org.json.JSONException;
import org.json.JSONObject;
public class x
extends b<Void, Void, List<BusinessCategorySuggest>>
{
public x(String paramString1, String paramString2, ApiRequest.b paramb)
{
super(ApiRequest.RequestType.GET, "business/category_suggest", paramb);
a("term", paramString1);
if (!TextUtils.isEmpty(paramString2)) {
a("country_code", paramString2);
}
}
public List<BusinessCategorySuggest> a(JSONObject paramJSONObject)
throws JSONException
{
return JsonUtil.parseJsonList(paramJSONObject.getJSONArray("suggestions"), BusinessCategorySuggest.CREATOR);
}
}
/* Location:
* Qualified Name: com.yelp.android.appdata.webrequests.x
* Java Class Version: 6 (50.0)
* JD-Core Version: 0.7.1
*/ | true |
3c9b9caa7832933f331b93b5075e126906e0332d | Java | cej8/risc-project-copy | /riscApp/app/src/main/java/edu/duke/ece651/risc/gui/GUISpectate.java | UTF-8 | 11,746 | 2.578125 | 3 | [] | no_license | package edu.duke.ece651.risc.gui;
import android.app.Activity;
import android.content.Intent;
import android.os.Handler;
import android.util.Log;
import java.io.IOException;
import edu.duke.ece651.risc.client.ClientInputInterface;
import edu.duke.ece651.risc.client.ClientOutputInterface;
import edu.duke.ece651.risc.shared.Board;
import edu.duke.ece651.risc.shared.ConfirmationMessage;
import edu.duke.ece651.risc.shared.Connection;
import edu.duke.ece651.risc.shared.Constants;
import edu.duke.ece651.risc.shared.HumanPlayer;
import edu.duke.ece651.risc.shared.StringMessage;
public class GUISpectate extends Thread {
private ParentActivity parentActivity;
private boolean response;
private Connection connection;
private boolean alive;
private Board board;
private boolean gotBoard;
private Activity activity;
private ClientInputInterface clientInput;
private ClientOutputInterface clientOutput;
private double TURN_WAIT_MINUTES = Constants.TURN_WAIT_MINUTES;
private double START_WAIT_MINUTES = Constants.START_WAIT_MINUTES+.1;
private double LOGIN_WAIT_MINUTES = Constants.LOGIN_WAIT_MINUTES;
private boolean isPlaying = true;
private String winnerPrompt=null;
private Handler handler;
public GUISpectate(Handler h,Activity act,ClientInputInterface input,ClientOutputInterface output){
this.response = ParentActivity.getSpectate();
this.parentActivity = new ParentActivity();
this.connection = ParentActivity.getConnection();
this.alive = ParentActivity.getAlive();
this.activity = act;
this.clientInput = input;
this.clientOutput = output;
this.handler = h;
}
public void serverDisplayBoard(){
try {
if (alive != isPlaying) {
isPlaying = alive;
//Query for spectating
//If no then kill connection
connection.sendObject(new ConfirmationMessage(response));
if (!response) {
connection.closeAll();
clientInput.close();
}
}
// Next server sends board
board = (Board) (connection.receiveObject());
// ParentActivity parentActivity = new ParentActivity();
parentActivity.setBoard(board);
gotBoard = true;
} catch (Exception e) {
e.printStackTrace();
connection.closeAll();
clientInput.close();
handler.post(new Runnable() {
@Override
public void run() {
Intent intent = new Intent(activity,ConfirmLoginActivity.class);
activity.startActivity(intent);
}
});
return;
}
}
public void setWinner(String prompt){
this.winnerPrompt=prompt;
}
public String getWinner(){
return this.winnerPrompt;
}
public void checkAlive(){
try {
parentActivity.setPlayer((HumanPlayer)connection.receiveObject());
String turn = receiveAndDisplayString();
parentActivity.setStartTime(System.currentTimeMillis());
parentActivity.setMaxTime((long) (connection.getSocket().getSoTimeout()));//(long) (connection.getSocket().getSoTimeout());
//Catch case for issues in testing, should never really happen
if (ParentActivity.getMaxTime() == 0) {
parentActivity.setMaxTime((long) (TURN_WAIT_MINUTES * 60 * 1000)); //= (long) (TURN_WAIT_MINUTES * 60 * 1000);
}
// Start of each turn will have continue message if game still going
// Otherwise is winner message
StringMessage startMessage = (StringMessage) (connection.receiveObject());
String start = startMessage.unpacker();
if (!start.equals("Continue")) {
// If not continue then someone won --> print and exit
setWinner(start);
return;
}
// Next is alive status for player
ConfirmationMessage isAlive = (ConfirmationMessage) (connection.receiveObject());
// If null then something wrong
if (isAlive == null) {
return;
}
// Get primitive
alive = isAlive.getMessage();
parentActivity.setAlive(alive);
} catch (Exception e) {
e.printStackTrace();
connection.closeAll();
clientInput.close();
handler.post(new Runnable() {
@Override
public void run() {
Intent intent = new Intent(activity,ConfirmLoginActivity.class);
activity.startActivity(intent);
}
});
return;
}
}
public String receiveAndDisplayString() throws IOException, ClassNotFoundException{
StringMessage message = (StringMessage) (connection.receiveObject());
String str = message.unpacker();
return str;
}
public void allSpectate(){
try {
parentActivity.setPlayer((HumanPlayer)connection.receiveObject());
String turn = receiveAndDisplayString();
parentActivity.setStartTime(System.currentTimeMillis());
parentActivity.setMaxTime((long) (connection.getSocket().getSoTimeout()));//(long) (connection.getSocket().getSoTimeout());
//Catch case for issues in testing, should never really happen
if (ParentActivity.getMaxTime() == 0) {
parentActivity.setMaxTime((long) (TURN_WAIT_MINUTES * 60 * 1000)); //= (long) (TURN_WAIT_MINUTES * 60 * 1000);
}
// Start of each turn will have continue message if game still going
// Otherwise is winner message
StringMessage startMessage = (StringMessage) (connection.receiveObject());
String start = startMessage.unpacker();
if (!start.equals("Continue")) {
// If not continue then someone won --> print and exit
// clientOutput.displayString(start); // help text on map
setWinner(start);
return;
}
// Next is alive status for player
ConfirmationMessage isAlive = (ConfirmationMessage) (connection.receiveObject());
// If null then something wrong
if (isAlive == null) {
return;
}
// Get primitive
alive = isAlive.getMessage();
parentActivity.setAlive(alive);
if (alive != isPlaying) {
isPlaying = alive;
//Query for spectating
//If no then kill connection
connection.sendObject(new ConfirmationMessage(response));
if (!response) {
connection.closeAll();
clientInput.close();
handler.post(new Runnable() {
@Override
public void run() {
Intent intent = new Intent(activity,ConfirmLoginActivity.class);
activity.startActivity(intent);
}
});
}
}
while (true) {
// Next server sends board
board = (Board) (connection.receiveObject());
parentActivity.setBoard(board);
gotBoard = true;
String response = receiveAndDisplayString();
if (response.matches("^Fail:.*$")) {
continue;
}
if (response.matches("^Success:.*$")) {
break;
}
}
} catch (Exception e) {
e.printStackTrace();
connection.closeAll();
clientInput.close();
handler.post(new Runnable() {
@Override
public void run() {
Intent intent = new Intent(activity,ConfirmLoginActivity.class);
activity.startActivity(intent);
}
});
return;
}
}
public void recieveBoard(){
try {
// Next server sends board
board = (Board) (connection.receiveObject());
// ParentActivity parentActivity = new ParentActivity();
parentActivity.setBoard(board);
gotBoard = true;
// while (true) {
String response = receiveAndDisplayString();
if (response.matches("^Fail:.*$")) {
// continue;
}
if (response.matches("^Success:.*$")) {
// break;
}
} catch (Exception e) {
e.printStackTrace();
connection.closeAll();
clientInput.close();
handler.post(new Runnable() {
@Override
public void run() {
Intent intent = new Intent(activity,ConfirmLoginActivity.class);
activity.startActivity(intent);
}
});
return;
}
}
public void playGame() {
try {
String response = receiveAndDisplayString();
if (response.matches("^Fail:.*$")) {
}
if (response.matches("^Success:.*$")) {
}
} catch (Exception e) {
e.printStackTrace();
connection.closeAll();
clientInput.close();
handler.post(new Runnable() {
@Override
public void run() {
Intent intent = new Intent(activity,ConfirmLoginActivity.class);
activity.startActivity(intent);
}
});
return;
}
}
@Override
public void run(){
if (ParentActivity.getSpectateFirstCall()){
parentActivity.setSpectateFirstCall(false);
serverDisplayBoard();
playGame();
handler.post(new Runnable() {
@Override
public void run() {
if(getWinner()!=null){
//game over someone has won
Intent end = new Intent(activity, EndGameActivity.class);
end.putExtra("WINNER", getWinner());
activity.startActivity(end);
} else {
Intent firstUnits = new Intent(activity, SpectateActivity.class);
activity.startActivity(firstUnits);
}
}
});
} else {
allSpectate();
handler.post(new Runnable() {
@Override
public void run() {
if(getWinner()!=null){
//game over someone has won
Intent end = new Intent(activity, EndGameActivity.class);
end.putExtra("WINNER", getWinner());
activity.startActivity(end);
} else {
Intent firstUnits = new Intent(activity, SpectateActivity.class);
activity.startActivity(firstUnits);
}
}
});
}
}
}
| true |
2a84a8aead7f142fe25686a61d168e20d45e546a | Java | rpatel1291/Project | /FORK/src/project/Process.java | UTF-8 | 8,056 | 2.90625 | 3 | [] | no_license | package project;
import java.util.regex.*;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.io.PrintWriter;
import javax.swing.JOptionPane;
public class Process {
/*
* Global variables:
* Final String: USER_AGENT, ORIGINAL_FILE, FIRST_PROCESS
* String Array: restaurant
* BufferedReader reader
* PrintWriter output, output2
*
*/
private static final String USER_AGENT="Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_4) AppleWebKit/600.7.12 "
+ "(KHTML, like Gecko) Version/8.0.7 Safari/600.7.12";
private static final String ORIGINAL_FILE ="./src/project/InputWebPage.txt";
private static final String FIRST_PROCESS ="./src/project/FirstProcess.txt";
private static String[] restaurants = {
"http://www.allmenus.com/ny/new-york/248742-johns/menu/",
"http://www.allmenus.com/ny/new-york/47374-a-taste-of-seafood/menu/",
"http://www.allmenus.com/ny/new-york/3035-le-marais/menu/",
"http://www.allmenus.com/ny/new-york/249747-petite-abeille/menu/",
"http://www.allmenus.com/ga/atlanta-decatur/281304-fortune-cookie/menu/",
"http://www.allmenus.com/ga/atlanta/278792-goodfellas-pizza-and-wings/menu/",
"http://www.allmenus.com/ga/atlanta/308971-jacks-pizza--wings/menu/",
"http://www.allmenus.com/ca/southeast/83168-la-pizza-loca/menu/",
"http://www.allmenus.com/ca/los-angeles/271002-guelaguetza-restaurant/menu/"
};
private BufferedReader reader;
private PrintWriter output, output2;
/**
* Constructor that takes in no parameters and calls constructor that takes in a String array parameter
*/
public Process(){
this(restaurants);
}//Process with no parameters
/**
* Constructor that takes in one String array parameter that is a URL to a restaurant's menu
* @param webaddress
*/
public Process(String[] webaddress){
for(int i = 0; i < webaddress.length; i++){
try{
reader = read(webaddress[i]);
output = new PrintWriter(ORIGINAL_FILE);
output2 = new PrintWriter(FIRST_PROCESS);
readWhole(reader, output);
BufferedReader readAgain = new BufferedReader(new FileReader(ORIGINAL_FILE));
firstProcess(readAgain, output2);
}
catch (Exception e){
JOptionPane.showMessageDialog(null, "Error");
}
}
}//Process with 1 String parameter
/**
* This method takes in two parameters one of type BufferedReader and the other type PrintWriter.
* The BufferedReader is the collection of HTML tags from the input URL.
* The PrintWriter is the output file in which the content within the tags will be saved.
* @param original
* @param output
*/
public static void firstProcess(BufferedReader original, PrintWriter output){
/*
* The different type of content needed for the database are distributed throughout the different tags.
* Each content has a specific HTML syntax to matching
* After each line is properly identified it is saved to a text file.
*/
String beforeHTMLTag = "\\s*<\\w+\\s?[^>]*>";
String afterHTMLTag = "</\\w+[^>]*>";
Pattern restaurantName = Pattern.compile("<(h1)[^>]+>(.*?)</\\1>");
Pattern restaurantAddress = Pattern.compile("<(span)\\s(class=).*\\s(itemprop=\"streetAddress\")>(.*?)</\\1>");
Pattern restaurantCity = Pattern.compile("<(span)\\s(class=).*\\s(itemprop=\"addressLocality\")>(.*?)</\\1>");
Pattern restaurantState = Pattern.compile("<(span)\\s(class=).*\\s(itemprop=\"addressRegion\")>(.*?)</\\1>");
Pattern restaurantZip = Pattern.compile("<(span)\\s(class=).*\\s(itemprop=\"postalCode\")>(.*?)</\\1>");
Pattern cuisine = Pattern.compile("<(ul)>(.*?)</\\1>");
Pattern menuCategory = Pattern.compile("<(h3)>(.*?)</\\1>");
Pattern categoryDescription = Pattern.compile("<(p)>(.*?)</\\1>");
Pattern menuItem = Pattern.compile("<(span)\\s*(class=\"name\")>(.*?)</\\1>");
Pattern itemPrice = Pattern.compile("<(span)\\s*(class=\"price\")>(.*?)</\\1>");
Pattern itemDescription = Pattern.compile("<(p)\\s*(class=\"description\")>(.*?)</\\1>");
try{
String line = original.readLine();
while(line != null){
Matcher matchRestName = restaurantName.matcher(line);
Matcher matchRestAdd = restaurantAddress.matcher(line);
Matcher matchRestCity = restaurantCity.matcher(line);
Matcher matchRestState = restaurantState.matcher(line);
Matcher matchRestZip = restaurantZip.matcher(line);
Matcher matchCuisine = cuisine.matcher(line);
Matcher matchMenuCat = menuCategory.matcher(line);
Matcher matchCatDescr = categoryDescription.matcher(line);
Matcher matchMenuItem = menuItem.matcher(line);
Matcher matchItemPrice = itemPrice.matcher(line);
Matcher matchItemDescr = itemDescription.matcher(line);
if(matchRestName.find()){
String Name = line.replaceAll(beforeHTMLTag, " ");
Name = Name.replaceAll(afterHTMLTag, "\n");
output.println(Name.toString());
}
if(matchRestAdd.find()){
String tag = line.replaceAll(beforeHTMLTag, " ");
tag = tag.replaceAll(afterHTMLTag, "\n");
output.println(tag.toString());
}
if(matchRestCity.find()){
String tag = line.replaceAll(beforeHTMLTag, " ");
tag = tag.replaceAll(afterHTMLTag, "\n");
output.println(tag.toString());
}
if(matchRestState.find()){
String tag = line.replaceAll(beforeHTMLTag, " ");
tag = tag.replaceAll(afterHTMLTag, "\n");
output.println(tag.toString());
}
if(matchRestZip.find()){
String tag = line.replaceAll(beforeHTMLTag, " ");
tag = tag.replaceAll(afterHTMLTag, "\n");
output.println(tag.toString());
}
if(matchCuisine.find()){
String tag = line.replaceAll(beforeHTMLTag, "");
tag = tag.replaceAll(afterHTMLTag, "\n");
output.println(tag.toString());
}
if(matchMenuCat.find()){
String tag = line.replaceAll(beforeHTMLTag, "Menu Category ");
tag = tag.replaceAll(afterHTMLTag, "\n");
output.println(tag.toString());
}
if(matchCatDescr.find()){
String tag = line.replaceAll(beforeHTMLTag, " ");
tag = tag.replaceAll(afterHTMLTag, "\n");
output.println(tag.toString());
}
if(matchMenuItem.find()){
String tag = line.replaceAll(beforeHTMLTag, "Item ");
tag = tag.replaceAll(afterHTMLTag, "\n");
output.println(tag.toString());
}
if(matchItemPrice.find()){
String tag = line.replaceAll(beforeHTMLTag, "Price: ");
tag = tag.replaceAll(afterHTMLTag, "\n");
output.println(tag.toString());
}
if(matchItemDescr.find()){
String tag = line.replaceAll(beforeHTMLTag, "Description ");
tag = tag.replaceAll(afterHTMLTag, "\n");
output.println(tag.toString());
}
line = original.readLine();
}
}
catch(Exception error){
System.out.println("error");
}
}//firstProcess
/**
* This method takes in two parameters one of type BufferedReader and the other type PrintWriter.
* The output will save the HTML tags with content.
* @param reader
* @param output
*/
public static void readWhole(BufferedReader reader, PrintWriter output){
try{
String line = reader.readLine();
while(line != null){
output.println(line);
line = reader.readLine();
}
}
catch(Exception error){
JOptionPane.showMessageDialog(null, "Sorry.");
}
}//readWhole
/**
* This method connects to the URL
* @param sURL
* @return
* @throws Exception
*/
public static InputStream getURLInputStream(String sURL) throws Exception {
URLConnection oConnection = (new URL(sURL)).openConnection();
oConnection.setRequestProperty("User-Agent", USER_AGENT);
return oConnection.getInputStream();
} // getURLInputStream
/**
* This method reads the web content
* @param url
* @return
* @throws Exception
*/
public static BufferedReader read(String url) throws Exception {
InputStream content = (InputStream)getURLInputStream(url);
return new BufferedReader (new InputStreamReader(content));
} // read
}
| true |
1ef1a8dcf4ac5031656c33272c8d3dc6e7bd4087 | Java | pchachoo/Stratego_Game | /ComputerMemory.java | UTF-8 | 1,064 | 3.328125 | 3 | [] | no_license | /*********************************************************/
import java.util.LinkedList;
public class ComputerMemory {
char pieceRank=' ';
char Player=' ';
//linked list to store all available moves for that piece
LinkedList<int[]> MovesForPiece= new LinkedList<int[]>();
public ComputerMemory()
{ setpieceRank('0');
setPlayer('X');
}
public ComputerMemory(char c, char d)
{
setpieceRank(c);
setPlayer(d);
}
public void setpieceRank(char rank)
{
if(rank== 'S' || rank=='B' || rank=='F' || ((rank>=1)&&(rank<=9)))
pieceRank=rank;
else pieceRank='0';
}
public void setPlayer(char p)
{
if(p== 'X' || p=='O')
Player=p;
else Player=' ';
}
public char getpieceRank()
{return pieceRank;}
public char getPlayer()
{return Player; }
public ComputerMemory clone()
{return new ComputerMemory(this.getpieceRank(), this.getPlayer());}
public void Die()//frees tile if if piece is dead
{ setpieceRank('0');
setPlayer(' ');
}
}
| true |
34cbfbe6fca2477f7106652df687066fa9cb6bef | Java | SergeiShemshur/shop | /src/main/java/shop/servlet/ProductServlet.java | UTF-8 | 851 | 2.53125 | 3 | [] | no_license | package shop.servlet;
import shop.db.dao.ProductDao;
import shop.model.Product;
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 java.io.IOException;
import java.util.List;
/*@WebServlet(urlPatterns = "/products")*/
public class ProductServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
ProductDao dao = new ProductDao();
List<Product> all = dao.findAll();
StringBuilder sb = new StringBuilder();
for (Product product : all)
sb.append(product.toString()).append("\n");
resp.getWriter().print(sb.toString());
}
}
| true |
59e0447b9ce5200c9c59ea9a481b3c8a77a23a40 | Java | akash-07/class-notes-sem-6 | /Parser/src/lexer.java | UTF-8 | 953 | 2.609375 | 3 | [] | no_license | import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Created by @kash on 2/28/2018.
*/
public class lexer {
Map<String, Character> token_map = new HashMap<>();
lexer(){
token_map.put("if", 'i');
token_map.put("then", 't');
token_map.put("else", 'e');
token_map.put("a", 'a');
token_map.put("if", 'i');
token_map.put("true",'b');
token_map.put("false",'b');
}
public List<Character> getTokens(String inp){
List<Character> tokens = new ArrayList<>();
String[] split_inp = inp.split("\\W+");
for(String tok:split_inp){
if(token_map.get(tok) != null) {
tokens.add(token_map.get(tok));
System.out.println(tokens);
}
else{
tokens.add('@');
}
}
tokens.add('$');
return tokens;
}
}
| true |
73129644e6f781d9da6d2cfd4f29e766682f005a | Java | voidException/oxfffServer | /gloveback/src/main/java/org/geilove/controller/WeiBoController.java | UTF-8 | 27,386 | 2.25 | 2 | [] | no_license | package org.geilove.controller;
/*
*
* 我的页面使用这个接口,已废弃
*
* */
import org.geilove.pojo.Tweet;
import org.geilove.requestParam.PublishTweetParam;
import org.geilove.response.CommonRsp;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
//import org.springframework.stereotype.Controller;
//import org.springframework.web.bind.annotation.RequestBody;
//import org.springframework.web.bind.annotation.RequestMapping;
//import org.springframework.web.bind.annotation.ResponseBody;
//import org.geilove.pojo.Tweet;
//import org.geilove.service.MainService;
//import org.geilove.service.RegisterLoginService;
//import org.geilove.sqlpojo.OtherPartHelpPojo;
//import org.geilove.requestParam.WeiboParam;
//import java.util.List;
//import java.util.ArrayList;
//import java.util.Collections;
//import java.util.Map;
//import java.util.HashMap;
//import javax.annotation.Resource;
//import javax.servlet.http.HttpServletRequest;
//import org.geilove.response.*;
//import org.geilove.vo.WeiBo;
//import org.geilove.vo.Tuiwen;
@Deprecated
//@Controller
//@RequestMapping("/userpage")
public class WeiBoController {
// @Resource
// private MainService mainService;
// @Resource
// private RegisterLoginService rlService;
//@RequestMapping(value="/weibos/gettweetbyuserid")//用户查看对方主页的推文
// public @ResponseBody TweetsListRsp getTweetByUserID(@RequestBody WeiboParam tweetListParam,HttpServletRequest request){
// TweetsListRsp tweetsListRsp=new TweetsListRsp();
// Long userID=tweetListParam.getUserID();
// Integer page=tweetListParam.getPage();
// Integer pageSize=tweetListParam.getPageSize();
// List<Tweet>tweetlist=new ArrayList<Tweet>();//存放被转发的推文
// //这个是用来在sql-where-in中循环传参数用的。MainService中的getTweetByDiffIDs
// List<Long> paramslist=new ArrayList<Long>(); //这个是存放被转发推文id的地方
// List<Long> useridList=new ArrayList<Long>(); //这个是存放发布用户
// List<Long> zhuanfaUseridList=new ArrayList<Long>(); //存放被转发的推文中的用户id
//
// Map<String,Object> map=new HashMap<String,Object>();//存放查询的参数,传给Mybatis
//
// map.put("userID", userID);
// map.put("page", page);
// map.put("pageSize", pageSize);
// map.put("lastUpdate", tweetListParam.getLastUpdate());
// map.put("lastItemstart", tweetListParam.getLastItemstart());
// map.put("flag", tweetListParam.getFlag()); //1 是刷新,2是loadMore
// map.put("symbol",tweetListParam.getSymbol());
// List<Tweet> tweets=mainService.getTweetList(map);//首先取得推文,不带转发
//
// /*1.先获取这组推文包含的用户id集合和被转发的推文主键id集合*/
// if(tweets.size()!=0){
// if(tweetListParam.getFlag()==1){ //1刷新是升序排序的,所以需要翻转,loadMore不需要
// Collections.reverse(tweets);
// }
// /*这里应该循环为图片补全完整地址*/
// for(int i=0;i<tweets.size();i++){
// if(tweets.get(i).getTagid()==2){//如果等于2,则是转发的推文
// //取得所有要二次查询的推文的id号,因为他们大多数情况下是不一样的,也有可能一样的,所以用list
// paramslist.add(tweets.get(i).getSourcemsgid());//所有需要二次查询数据库获得转发中的推文ID放在这里
// }
// //这些是用户的id,根据这些可以找到用户的昵称头像等信息
// useridList.add(tweets.get(i).getUseridtweet());
// }
// }else{ //很可能用户没有关注任何人,所以微博是空的
// tweetsListRsp.setData(null);
// tweetsListRsp.setMsg("数据为空");
// tweetsListRsp.setRetcode(2002);
// return tweetsListRsp;
// }
//
// /*2.获取推文中需要展示的用户信息*/
// List<OtherPartHelpPojo> userPartProfile=new ArrayList<OtherPartHelpPojo>();
// if(useridList.size()!=0){
// //System.out.println(useridList.size());
//
// userPartProfile=mainService.getProfileByUserIDs(useridList); //如果能到这一步说明useridList肯定是非空的
// }
// /*3.获取被转发的推文*/
// if(paramslist.size()!=0){ //这个必须做判断,因为微博可能是全部原创的
// tweetlist=mainService.getTweetByDiffIDs(paramslist); //paramslist是所有需要二次查询的推文id组成的列表
// /*这里应该循环为图片补全完整地址*/
// }else{ //说明不含被转发的微博,那么直接组装微博返回就可以了
// /*5.合并推文和用户信息tweets 和 userPartProfile 到 lsWb*/
// List<WeiBo> lsWb=new ArrayList<WeiBo>();
// for(int k=0;k<tweets.size();k++){
// //System.out.println(tweets.size());
// //System.out.println(userPartProfile.size());
//
// WeiBo wb=new WeiBo();//WeiBo中有两个数据域,一个是推文领一个是被转发的推文
// for(int l=0;l<userPartProfile.size();l++){
// Tuiwen tw=new Tuiwen();
// tw.setTweet(tweets.get(k)); //把tweet放入推文中
// if(tweets.get(k).getUseridtweet()==userPartProfile.get(l).getUserid()){
// /*其它部分放入到推文*/
// tw.setPhotoupload((Byte)userPartProfile.get(l).getPhotoupload());
// tw.setSelfintroduce(userPartProfile.get(l).getSelfintroduce()); //用户的简介加入到Tuiwen中
// tw.setUsernickname(userPartProfile.get(l).getUsernickname()); //用户的昵称加入到Tuiwen中去
// tw.setUserphoto(userPartProfile.get(l).getUserphoto()); //用户的头像地址
// }
// wb.setTuiwen(tw); //推文被放入微博
// }
// lsWb.add(wb); //微博放入到微博列表中
// }
// tweetsListRsp.setData(lsWb);
// tweetsListRsp.setMsg("成功了");
// tweetsListRsp.setRetcode(2000);
//
// return tweetsListRsp;
// }
// /*4.获取被转发推文中的有关用户的信息*/
// if(tweetlist.size()!=0){ //能走到这一步,说明含有被转发的微博
// for(int j=0;j<tweetlist.size();j++){
// zhuanfaUseridList.add(tweetlist.get(j).getUseridtweet());
// }
// }
// List<OtherPartHelpPojo> zhuanfaUserPartProfile=new ArrayList<OtherPartHelpPojo>();
//
// if(zhuanfaUseridList.size()!=0){
// zhuanfaUserPartProfile=mainService.getProfileByUserIDs(zhuanfaUseridList);
// }
// /*能走到这一步,说明是一组微博并且有若干被转发的微博在里面*/
// /*5.合并推文和用户信息tweets 和 userPartProfile 到 lsWb*/
// List<WeiBo> lsWb=new ArrayList<WeiBo>();
// for(int k=0;k<tweets.size();k++){
// WeiBo wb=new WeiBo();//WeiBo中有两个数据域,一个是推文领一个是被转发的推文
// for(int l=0;l<userPartProfile.size();l++){
// Tuiwen tw=new Tuiwen();
// tw.setTweet(tweets.get(k)); //把tweet放入推文中
// if(tweets.get(k).getUseridtweet()==userPartProfile.get(l).getUserid()){
// /*其它部分放入到推文*/
// tw.setPhotoupload((Byte)userPartProfile.get(l).getPhotoupload());
// tw.setSelfintroduce(userPartProfile.get(l).getSelfintroduce()); //用户的简介加入到Tuiwen中
// tw.setUsernickname(userPartProfile.get(l).getUsernickname()); //用户的昵称加入到Tuiwen中去
// tw.setUserphoto(userPartProfile.get(l).getUserphoto()); //用户的头像地址
// }
// wb.setTuiwen(tw); //推文被放入微博
// }
// lsWb.add(wb); //微博放入到微博列表中
// }
// /* 合并被转发推文和用户信息tweetlist 和zhuanfaUserPartProfile到lsTw*/
// List<Tuiwen> lsTw=new ArrayList<Tuiwen>();
// for(int n=0;n<tweetlist.size();n++){
// for(int m=0;m<zhuanfaUserPartProfile.size();m++){
// Tuiwen tw=new Tuiwen();
// tw.setTweet(tweetlist.get(n));
// if(tweetlist.get(n).getUseridtweet()==zhuanfaUserPartProfile.get(m).getUserid()){
// tw.setPhotoupload(zhuanfaUserPartProfile.get(m).getPhotoupload());
// tw.setSelfintroduce(zhuanfaUserPartProfile.get(m).getSelfintroduce());
// tw.setUsernickname(zhuanfaUserPartProfile.get(m).getUsernickname());
// tw.setUserphoto(zhuanfaUserPartProfile.get(m).getUserphoto());
// }
// lsTw.add(tw); //推文放入到推文列表中
// }
// }
// /*7.合并lsTw 到 lsWb*/
// for(int p=0;p<lsWb.size();p++){ //微博数一定多于转发的微博数量
// for(int q=0;q<lsTw.size();q++){
// if(lsWb.get(p).getTuiwen().getTweet().getSourcemsgid()==lsTw.get(q).getTweet().getTweetid()){
// lsWb.get(p).setZhuanfaTuiwen(lsTw.get(q));
// }
// }
// }
//
// /* 8.返回tweetsListRsp*/
// tweetsListRsp.setData(lsWb);
// tweetsListRsp.setMsg("成功了");
// tweetsListRsp.setRetcode(2000);
//
// return tweetsListRsp;
// }
// @RequestMapping(value="/gettweetbyuserid")//比如查看用户自己发布、转发的推文
// public @ResponseBody TweetsListRsp getTweetByUserID(@RequestBody TweetListParam tweetListParam,HttpServletRequest request){
// TweetsListRsp tweetsListRsp=new TweetsListRsp();
// String token=tweetListParam.getToken(); //获取登录凭证
// String useridStr=token.substring(32); //获取userID
// //System.out.println(useridStr);
// Long userID=Long.valueOf(useridStr).longValue();
// Integer page=tweetListParam.getPage();
// Integer pageSize=tweetListParam.getPageSize();
// List<Tweet>tweetlist=new ArrayList<Tweet>();//存放被转发的推文
// //这个是用来在sql-where-in中循环传参数用的。MainService中的getTweetByDiffIDs
// List<Long> paramslist=new ArrayList<Long>(); //这个是存放被转发推文id的地方
// List<Long> useridList=new ArrayList<Long>(); //这个是存放发布用户
// List<Long> zhuanfaUseridList=new ArrayList<Long>(); //存放被转发的推文中的用户id
//
// Map<String,Object> map=new HashMap<String,Object>();//存放查询的参数,传给Mybatis
//
// map.put("userID", userID);
// map.put("page", page);
// map.put("pageSize", pageSize);
// map.put("lastUpdate", tweetListParam.getLastUpdate());
// map.put("lastItemstart", tweetListParam.getLastItemstart());
// map.put("flag", tweetListParam.getFlag()); //1 是刷新,2是loadMore
// map.put("symbol",tweetListParam.getSymbol());
// List<Tweet> tweets=mainService.getTweetList(map);//首先取得推文,不带转发
//
// /*1.先获取这组推文包含的用户id集合和被转发的推文主键id集合*/
// if(tweets.size()!=0){
// if(tweetListParam.getFlag()==1){ //1刷新是升序排序的,所以需要翻转,loadMore不需要
// Collections.reverse(tweets);
// }
// /*这里应该循环为图片补全完整地址*/
// for(int i=0;i<tweets.size();i++){
// if(tweets.get(i).getTagid()==2){//如果等于2,则是转发的推文
// //取得所有要二次查询的推文的id号,因为他们大多数情况下是不一样的,也有可能一样的,所以用list
// paramslist.add(tweets.get(i).getSourcemsgid());//所有需要二次查询数据库获得转发中的推文ID放在这里
// }
// //这些是用户的id,根据这些可以找到用户的昵称头像等信息
// useridList.add(tweets.get(i).getUseridtweet());
// }
// }else{ //很可能用户没有关注任何人,所以微博是空的
// tweetsListRsp.setData(null);
// tweetsListRsp.setMsg("数据为空");
// tweetsListRsp.setRetcode(2002);
// return tweetsListRsp;
// }
//
// /*2.获取推文中需要展示的用户信息*/
// List<OtherPartHelpPojo> userPartProfile=new ArrayList<OtherPartHelpPojo>();
// if(useridList.size()!=0){
// //System.out.println(useridList.size());
//
// userPartProfile=mainService.getProfileByUserIDs(useridList); //如果能到这一步说明useridList肯定是非空的
// }
// /*3.获取被转发的推文*/
// if(paramslist.size()!=0){ //这个必须做判断,因为微博可能是全部原创的
// tweetlist=mainService.getTweetByDiffIDs(paramslist); //paramslist是所有需要二次查询的推文id组成的列表
// /*这里应该循环为图片补全完整地址*/
// }else{ //说明不含被转发的微博,那么直接组装微博返回就可以了
// /*5.合并推文和用户信息tweets 和 userPartProfile 到 lsWb*/
// List<WeiBo> lsWb=new ArrayList<WeiBo>();
// for(int k=0;k<tweets.size();k++){
// //System.out.println(tweets.size());
// //System.out.println(userPartProfile.size());
//
// WeiBo wb=new WeiBo();//WeiBo中有两个数据域,一个是推文领一个是被转发的推文
// for(int l=0;l<userPartProfile.size();l++){
// Tuiwen tw=new Tuiwen();
// tw.setTweet(tweets.get(k)); //把tweet放入推文中
// if(tweets.get(k).getUseridtweet()==userPartProfile.get(l).getUserid()){
// /*其它部分放入到推文*/
// tw.setPhotoupload((Byte)userPartProfile.get(l).getPhotoupload());
// tw.setSelfintroduce(userPartProfile.get(l).getSelfintroduce()); //用户的简介加入到Tuiwen中
// tw.setUsernickname(userPartProfile.get(l).getUsernickname()); //用户的昵称加入到Tuiwen中去
// tw.setUserphoto(userPartProfile.get(l).getUserphoto()); //用户的头像地址
// }
// wb.setTuiwen(tw); //推文被放入微博
// }
// lsWb.add(wb); //微博放入到微博列表中
// }
// tweetsListRsp.setData(lsWb);
// tweetsListRsp.setMsg("成功了");
// tweetsListRsp.setRetcode(2000);
//
// return tweetsListRsp;
// }
// /*4.获取被转发推文中的有关用户的信息*/
// if(tweetlist.size()!=0){ //能走到这一步,说明含有被转发的微博
// for(int j=0;j<tweetlist.size();j++){
// zhuanfaUseridList.add(tweetlist.get(j).getUseridtweet());
// }
// }
// List<OtherPartHelpPojo> zhuanfaUserPartProfile=new ArrayList<OtherPartHelpPojo>();
//
// if(zhuanfaUseridList.size()!=0){
// zhuanfaUserPartProfile=mainService.getProfileByUserIDs(zhuanfaUseridList);
// }
// /*能走到这一步,说明是一组微博并且有若干被转发的微博在里面*/
// /*5.合并推文和用户信息tweets 和 userPartProfile 到 lsWb*/
// List<WeiBo> lsWb=new ArrayList<WeiBo>();
// for(int k=0;k<tweets.size();k++){
// WeiBo wb=new WeiBo();//WeiBo中有两个数据域,一个是推文领一个是被转发的推文
// for(int l=0;l<userPartProfile.size();l++){
// Tuiwen tw=new Tuiwen();
// tw.setTweet(tweets.get(k)); //把tweet放入推文中
// if(tweets.get(k).getUseridtweet()==userPartProfile.get(l).getUserid()){
// /*其它部分放入到推文*/
// tw.setPhotoupload((Byte)userPartProfile.get(l).getPhotoupload());
// tw.setSelfintroduce(userPartProfile.get(l).getSelfintroduce()); //用户的简介加入到Tuiwen中
// tw.setUsernickname(userPartProfile.get(l).getUsernickname()); //用户的昵称加入到Tuiwen中去
// tw.setUserphoto(userPartProfile.get(l).getUserphoto()); //用户的头像地址
// }
// wb.setTuiwen(tw); //推文被放入微博
// }
// lsWb.add(wb); //微博放入到微博列表中
// }
// /* 合并被转发推文和用户信息tweetlist 和zhuanfaUserPartProfile到lsTw*/
// List<Tuiwen> lsTw=new ArrayList<Tuiwen>();
// for(int n=0;n<tweetlist.size();n++){
// for(int m=0;m<zhuanfaUserPartProfile.size();m++){
// Tuiwen tw=new Tuiwen();
// tw.setTweet(tweetlist.get(n));
// if(tweetlist.get(n).getUseridtweet()==zhuanfaUserPartProfile.get(m).getUserid()){
// tw.setPhotoupload(zhuanfaUserPartProfile.get(m).getPhotoupload());
// tw.setSelfintroduce(zhuanfaUserPartProfile.get(m).getSelfintroduce());
// tw.setUsernickname(zhuanfaUserPartProfile.get(m).getUsernickname());
// tw.setUserphoto(zhuanfaUserPartProfile.get(m).getUserphoto());
// }
// lsTw.add(tw); //推文放入到推文列表中
// }
// }
// /*7.合并lsTw 到 lsWb*/
// for(int p=0;p<lsWb.size();p++){ //微博数一定多于转发的微博数量
// for(int q=0;q<lsTw.size();q++){
// if(lsWb.get(p).getTuiwen().getTweet().getSourcemsgid()==lsTw.get(q).getTweet().getTweetid()){
// lsWb.get(p).setZhuanfaTuiwen(lsTw.get(q));
// }
// }
// }
//
// /* 8.返回tweetsListRsp*/
// tweetsListRsp.setData(lsWb);
// tweetsListRsp.setMsg("成功了");
// tweetsListRsp.setRetcode(2000);
//
// return tweetsListRsp;
// }
//
//
// /*
// * 推文主页接口,先获取这个用户关注的人的id(按照关注时间排序),然后用这组id获取推文(按照时间排序)20条,
// * 如果是刷新还是这个接口,app端清空数据,
// * 如果是加载更多应该换一个接口。
// */
// @RequestMapping(value="/gettuiwenlists")
// public @ResponseBody TweetsListRsp getTweetLists(@RequestBody WeiBoListParam tweetListParam ){
// TweetsListRsp tweetsListRsp=new TweetsListRsp();
// String token=tweetListParam.getToken(); //获取登录凭证
// String useridStr=token.substring(32); //获取userID
// Long userID=Long.valueOf(useridStr).longValue();
// Integer page=tweetListParam.getPage();
// Integer pageSize=tweetListParam.getPageSize();
// Integer flag=tweetListParam.getFlag();
// String lastUpdate=tweetListParam.getLastUpdate();
// String lastItemstart=tweetListParam.getLastItemstart();
//
// List<Tweet>tweetlist=new ArrayList<Tweet>();//存放被转发的推文
// //这个是用来在sql-where-in中循环传参数用的。MainService中的getTweetByDiffIDs
// List<Long> paramslist=new ArrayList<Long>(); //这个是存放被转发推文id的地方
// List<Long> useridList=new ArrayList<Long>(); //这个是存放发布用户
// List<Long> zhuanfaUseridList=new ArrayList<Long>(); //存放被转发的推文中的用户id
//
// Map<String,Object> map=new HashMap<String,Object>();//存放查询的参数,传给Mybatis
// map.put("userID", userID);
// map.put("page", 0); //这里的page、pageSize要去掉,应该给maps用
// map.put("pageSize", 1000);
// /*-1.先获取这个人关注的列表集合List<Long>,其实应该获取所有的关注的人*/
// List<Long> lsids=mainService.getWatcherIds(map); //这个map只用到了userID
// if(lsids.isEmpty()|| lsids==null){
// tweetsListRsp.setData(null);
// tweetsListRsp.setMsg("用户没有关注人");
// tweetsListRsp.setRetcode(2001);
// return tweetsListRsp;
// }
// /*0.然后用这个userid集合获取一组推文,*/
// Map<String,Object> maps=new HashMap<String,Object>();
// maps.put("page", page);
// maps.put("pageSize", pageSize);
// maps.put("list", lsids); //列表参数
// maps.put("flag",flag);
// maps.put("lastUpdate", lastUpdate);
// maps.put("lastItemstart", lastItemstart);
// List<Tweet> tweets=mainService.getWeiBoList(maps);//首先取得推文,不带转发,这里应该传入map参数
//
// /*1.先获取这组推文包含的用户id集合和被转发的推文主键id集合*/
// if(tweets.size()!=0){
// if(tweetListParam.getFlag()==1){ //1刷新是升序排序的,所以需要翻转,loadMore不需要
// Collections.reverse(tweets);
// }
// for(int i=0;i<tweets.size();i++){
// if(tweets.get(i).getTagid()==2){//如果等于2,则是转发的推文
// //取得所有要二次查询的推文的id号,因为他们大多数情况下是不一样的,也有可能一样的,所以用list
// paramslist.add(tweets.get(i).getSourcemsgid());//所有需要二次查询数据库获得转发中的推文ID放在这里
// }
// //这些是用户的id,根据这些可以找到用户的昵称头像等信息
// useridList.add(tweets.get(i).getUseridtweet());
// }
// }else{ //很可能用户没有关注任何人,所以微博是空的
// tweetsListRsp.setData(null);
// tweetsListRsp.setMsg("数据为空");
// tweetsListRsp.setRetcode(2002);
// return tweetsListRsp;
// }
//
// /*2.获取推文中需要展示的用户信息*/
// List<OtherPartHelpPojo> userPartProfile=new ArrayList<OtherPartHelpPojo>();
// if(useridList.size()!=0){
// //System.out.println(useridList.size());
//
// userPartProfile=mainService.getProfileByUserIDs(useridList); //如果能到这一步说明useridList肯定是非空的
// }
// /*3.获取被转发的推文*/
// if(paramslist.size()!=0){ //这个必须做判断,因为微博可能是全部原创的
// tweetlist=mainService.getTweetByDiffIDs(paramslist); //paramslist是所有需要二次查询的推文id组成的列表
// }else{ //说明不含被转发的微博,那么直接组装微博返回就可以了
// /*5.合并推文和用户信息tweets 和 userPartProfile 到 lsWb*/
// List<WeiBo> lsWb=new ArrayList<WeiBo>();
// for(int k=0;k<tweets.size();k++){
// //System.out.println(tweets.size());
// //System.out.println(userPartProfile.size());
//
// WeiBo wb=new WeiBo();//WeiBo中有两个数据域,一个是推文领一个是被转发的推文
// for(int l=0;l<userPartProfile.size();l++){
// Tuiwen tw=new Tuiwen();
// tw.setTweet(tweets.get(k)); //把tweet放入推文中
// if(tweets.get(k).getUseridtweet()==userPartProfile.get(l).getUserid()){
// /*其它部分放入到推文*/
// tw.setPhotoupload((Byte)userPartProfile.get(l).getPhotoupload());
// tw.setSelfintroduce(userPartProfile.get(l).getSelfintroduce()); //用户的简介加入到Tuiwen中
// tw.setUsernickname(userPartProfile.get(l).getUsernickname()); //用户的昵称加入到Tuiwen中去
// tw.setUserphoto(userPartProfile.get(l).getUserphoto()); //用户的头像地址
// }
// wb.setTuiwen(tw); //推文被放入微博
// }
// lsWb.add(wb); //微博放入到微博列表中
// }
// tweetsListRsp.setData(lsWb);
// tweetsListRsp.setMsg("成功了");
// tweetsListRsp.setRetcode(2000);
//
// return tweetsListRsp;
// }
// /*4.获取被转发推文中的有关用户的信息*/
// if(tweetlist.size()!=0){ //能走到这一步,说明含有被转发的微博
// for(int j=0;j<tweetlist.size();j++){
// zhuanfaUseridList.add(tweetlist.get(j).getUseridtweet());
// }
// }
// List<OtherPartHelpPojo> zhuanfaUserPartProfile=new ArrayList<OtherPartHelpPojo>();
//
// if(zhuanfaUseridList.size()!=0){
// zhuanfaUserPartProfile=mainService.getProfileByUserIDs(zhuanfaUseridList);
// }
// /*能走到这一步,说明是一组微博并且有若干被转发的微博在里面*/
// /*5.合并推文和用户信息tweets 和 userPartProfile 到 lsWb*/
// List<WeiBo> lsWb=new ArrayList<WeiBo>();
// for(int k=0;k<tweets.size();k++){
// WeiBo wb=new WeiBo();//WeiBo中有两个数据域,一个是推文领一个是被转发的推文
// for(int l=0;l<userPartProfile.size();l++){
// Tuiwen tw=new Tuiwen();
// tw.setTweet(tweets.get(k)); //把tweet放入推文中
// if(tweets.get(k).getUseridtweet()==userPartProfile.get(l).getUserid()){
// /*其它部分放入到推文*/
// tw.setPhotoupload((Byte)userPartProfile.get(l).getPhotoupload());
// tw.setSelfintroduce(userPartProfile.get(l).getSelfintroduce()); //用户的简介加入到Tuiwen中
// tw.setUsernickname(userPartProfile.get(l).getUsernickname()); //用户的昵称加入到Tuiwen中去
// tw.setUserphoto(userPartProfile.get(l).getUserphoto()); //用户的头像地址
// }
// wb.setTuiwen(tw); //推文被放入微博
// }
// lsWb.add(wb); //微博放入到微博列表中
// }
// /* 合并被转发推文和用户信息tweetlist 和zhuanfaUserPartProfile到lsTw*/
// List<Tuiwen> lsTw=new ArrayList<Tuiwen>();
// for(int n=0;n<tweetlist.size();n++){
// for(int m=0;m<zhuanfaUserPartProfile.size();m++){
// Tuiwen tw=new Tuiwen();
// tw.setTweet(tweetlist.get(n));
// if(tweetlist.get(n).getUseridtweet()==zhuanfaUserPartProfile.get(m).getUserid()){
// tw.setPhotoupload(zhuanfaUserPartProfile.get(m).getPhotoupload());
// tw.setSelfintroduce(zhuanfaUserPartProfile.get(m).getSelfintroduce());
// tw.setUsernickname(zhuanfaUserPartProfile.get(m).getUsernickname());
// tw.setUserphoto(zhuanfaUserPartProfile.get(m).getUserphoto());
// }
// lsTw.add(tw); //推文放入到推文列表中
// }
// }
// /*7.合并lsTw 到 lsWb*/
// for(int p=0;p<lsWb.size();p++){ //微博数一定多于转发的微博数量
// for(int q=0;q<lsTw.size();q++){
// if(lsWb.get(p).getTuiwen().getTweet().getSourcemsgid()==lsTw.get(q).getTweet().getTweetid()){
// lsWb.get(p).setZhuanfaTuiwen(lsTw.get(q));
// }
// }
// }
//
// /* 8.返回tweetsListRsp*/
// tweetsListRsp.setData(lsWb);
// tweetsListRsp.setMsg("成功了");
// tweetsListRsp.setRetcode(2000);
//
// return tweetsListRsp;
// }
/*这是一条推文的转发列表,本质上也是一组推文。不需要取得原推文内容,如果转发时输入为空,默认存储为“转发推文” */
// @RequestMapping(value="/listZhuanfa")
// public @ResponseBody TweetsListRsp getZhuanfaList(@RequestBody ZhuangfaListParam zhuanfaListParam){
// String proofs=zhuanfaListParam.getProof(); //登录凭证,暂时不用
// Long tweetid =zhuanfaListParam.getTweetid();
// Integer page=zhuanfaListParam.getPage();
// Integer pageSize=zhuanfaListParam.getPageSize();
// //这里应该验证proof的有效性
// Map<String,Object> map=new HashMap<String,Object>();
// map.put("tweetid", tweetid);
// map.put("page", page);
// map.put("pageSize", pageSize);
// TweetsListRsp tweetsListRsp=new TweetsListRsp();
// List<Tweet> tweets=mainService.getZhuanfaTweetList(map); //首先取得推文,不带头像,不带转发的推文
// if(tweets==null || tweets.size() ==0 ){
//
// tweetsListRsp.setMsg("用户没有发表推文哦");
// tweetsListRsp.setRetcode(2001);
// }else{
//
// tweetsListRsp.setMsg("获取数据成功");
// tweetsListRsp.setRetcode(2000);
// }
// return tweetsListRsp;
// }
/*这是发布一条推文,--已废弃,发布推文在FileUploadController里面*/
//@Deprecated
//@RequestMapping(value="/publishTweet")
//public @ResponseBody
//CommonRsp publishTweet(@RequestBody PublishTweetParam publishTweetParam){
// String proof=publishTweetParam.getProof();
// String userEmail=publishTweetParam.getUserEmail();
// String userPassword=publishTweetParam.getUserPassword();
// String tweetContent=publishTweetParam.getTweetContent();
// CommonRsp rsp=new CommonRsp();
//
// //这里应该验证请求凭证Proof的有效性,先省略
// Tweet tweet=new Tweet();
// tweet.setMsgcontent(tweetContent); //其它用默认的
// Integer response=mainService.addTweet(tweet);
// if(response==0){
// rsp.setMsg("发布推文失败了");
// rsp.setRetcode(2003);
// }else{
// rsp.setMsg("发布成功");
// rsp.setRetcode(2000);
// }
// return rsp;
//}
}
| true |
ac94c5862c32a885d7e61fa146a98fbd41fbd271 | Java | akraievoy/elw | /server/src/main/java/elw/dao/ctx/CtxTask.java | UTF-8 | 4,996 | 2.40625 | 2 | [] | no_license | package elw.dao.ctx;
import elw.vo.*;
import elw.vo.Class;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.SortedMap;
/**
* Parameter Object, storing the full Class/Task/Version context.
*/
public class CtxTask extends CtxStudent {
public final IndexEntry indexEntry;
public final TaskType tType;
public final Task task;
public final Version ver;
public final Iterable<CtxSlot> slots;
public CtxTask(
Enrollment enr,
Course course,
Group group,
Student student,
IndexEntry indexEntry,
Task task,
TaskType tType,
Version ver
) {
super(enr, course, group, student);
this.indexEntry = indexEntry;
this.tType = tType;
this.task = task;
this.ver = ver;
this.slots = new Iterable<CtxSlot>() {
public Iterator<CtxSlot> iterator() {
final Iterator<Map.Entry<String, FileSlot>> slotIterator =
CtxTask.this.tType.getFileSlots().entrySet().iterator();
return new Iterator<CtxSlot>() {
public boolean hasNext() {
return slotIterator.hasNext();
}
public CtxSlot next() {
return slot(slotIterator.next().getValue());
}
public void remove() {
slotIterator.remove();
}
};
}
};
}
protected static String safeClassKey(
final SortedMap<String, Class> classMap,
final String classKey
) {
final SortedMap<String, Class> tailMap =
classMap.tailMap(classKey);
if (!tailMap.isEmpty()) {
return tailMap.firstKey();
}
return classMap.lastKey();
}
public static Class classForKey(
final SortedMap<String, Class> classMap,
final String classKey
) {
return classMap.get(safeClassKey(classMap, classKey));
}
public CtxSlot slot(final String slotId) {
final FileSlot slot = tType.getFileSlots().get(slotId);
// LATER these checks somehow duplicate Ctx resolution code
// maybe a custom exception here would fit better
if (slot == null) {
throw new IllegalStateException(
"slot '" + slotId + "' not found: " + String.valueOf(this)
);
}
return slot(slot);
}
public CtxSlot slot(final FileSlot slot) {
final CtxSlot ctxSlot = new CtxSlot(
enr, group, student, course,
indexEntry, task, tType, ver,
slot
);
return propagateTZCache(ctxSlot);
}
public Class openClass() {
return classForKey(
enr.getClasses(),
indexEntry.getClassFrom()
);
}
public long openMillis() {
final Class classOpen = openClass();
return classOpen.getFromDateTime().getMillis();
}
public boolean open() {
long now = System.currentTimeMillis();
return openMillis() <= now;
}
// some tasks consist completely or partially of shared versions
// solutions to which may queried or uploaded by students
public CtxTask overrideToShared(Version sharedVersion) {
if (!sharedVersion.isShared()) {
throw new IllegalStateException("overriding to non-shared version");
}
final CtxTask ctxTask = new CtxTask(
enr, course, group,
student,
indexEntry, task, tType,
sharedVersion
);
return propagateTZCache(ctxTask);
}
public static interface StateForSlot {
State getState(FileSlot slot);
}
public boolean writable(
final FileSlot slot,
final StateForSlot stateForSlot
) {
if (!slot.isWritable()) {
return false;
}
final List<String> writeApprovals =
slot.getWriteApprovals();
for (String writeApproval : writeApprovals) {
final FileSlot approvalSlot =
tType.getFileSlots().get(writeApproval);
if (State.APPROVED != stateForSlot.getState(approvalSlot)) {
return false;
}
}
return true;
}
public boolean readable(FileSlot slot, StateForSlot stateForSlot) {
final List<String> readApprovals =
slot.getReadApprovals();
for (String readApproval : readApprovals) {
final FileSlot approvalSlot =
tType.getFileSlots().get(readApproval);
if (State.APPROVED != stateForSlot.getState(approvalSlot)) {
return false;
}
}
return true;
}
}
| true |
9d9e3e698733882a69dfdbcf2b3ebcf966c252f8 | Java | sandeepgoyal194/CheersOnDemand | /app/src/main/java/com/cheersondemand/model/AuthenticationResponse.java | UTF-8 | 1,819 | 2.140625 | 2 | [] | no_license | package com.cheersondemand.model;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
import java.util.List;
/**
* Created by GAURAV on 5/30/2018.
*/
public class AuthenticationResponse {
@SerializedName("success")
@Expose
private Boolean success;
@SerializedName("message")
@Expose
private String message;
@SerializedName("error_description")
@Expose
private String errorDescription;
@SerializedName("error")
@Expose
private String error;
@SerializedName("data")
@Expose
private Data data;
@SerializedName("meta")
@Expose
private List<Object> meta = null;
@SerializedName("errors")
@Expose
private List<Object> errors = null;
public Boolean getSuccess() {
return success;
}
public void setSuccess(Boolean success) {
this.success = success;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public Data getData() {
return data;
}
public void setData(Data data) {
this.data = data;
}
public List<Object> getMeta() {
return meta;
}
public void setMeta(List<Object> meta) {
this.meta = meta;
}
public List<Object> getErrors() {
return errors;
}
public void setErrors(List<Object> errors) {
this.errors = errors;
}
public String getErrorDescription() {
return errorDescription;
}
public void setErrorDescription(String errorDescription) {
this.errorDescription = errorDescription;
}
public String getError() {
return error;
}
public void setError(String error) {
this.error = error;
}
}
| true |
22e9f196cb42a374750b9d45f667995513ec2926 | Java | hradio/timeshiftplayer-example | /timeshiftsampleapp/src/main/java/eu/hradio/timeshiftsample/RetainedFragment.java | UTF-8 | 10,499 | 1.726563 | 2 | [
"Apache-2.0"
] | permissive | package eu.hradio.timeshiftsample;
import android.app.PendingIntent;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.IBinder;
import android.support.v4.app.Fragment;
import android.util.Log;
import org.omri.radio.Radio;
import org.omri.radioservice.RadioService;
import org.omri.radioservice.RadioServiceType;
import org.omri.radioservice.metadata.Textual;
import org.omri.radioservice.metadata.TextualDabDynamicLabel;
import org.omri.radioservice.metadata.TextualDabDynamicLabelPlusItem;
import org.omri.radioservice.metadata.TextualType;
import org.omri.radioservice.metadata.Visual;
import org.omri.tuner.ReceptionQuality;
import org.omri.tuner.Tuner;
import org.omri.tuner.TunerListener;
import org.omri.tuner.TunerStatus;
import java.io.IOException;
import eu.hradio.core.audiotrackservice.AudiotrackService;
import eu.hradio.timeshiftplayer.SkipItem;
import eu.hradio.timeshiftplayer.TimeshiftListener;
import eu.hradio.timeshiftplayer.TimeshiftPlayer;
import eu.hradio.timeshiftplayer.TimeshiftPlayerFactory;
import static eu.hradio.timeshiftsample.BuildConfig.DEBUG;
public class RetainedFragment extends Fragment implements TunerListener, TimeshiftListener {
private static final String TAG = "RetainedFragment";
private TimeshiftPlayer mTimeshiftPlayer = null;
private RadioService mRunningSrv = null;
private boolean mAudiotrackServiceBound = false;
private transient AudiotrackService.AudioTrackBinder mAudiotrackService = null;
private PendingIntent mNotificationIntent = null;
private ServiceConnection mSrvCon = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
if(BuildConfig.DEBUG)Log.d(TAG, "onServiceConnected AudioTrackService");
if(service instanceof AudiotrackService.AudioTrackBinder) {
mAudiotrackServiceBound = true;
mAudiotrackService = (AudiotrackService.AudioTrackBinder) service;
if(mNotificationIntent != null) {
mAudiotrackService.getNotification().setContentIntent(mNotificationIntent);
}
}
}
@Override
public void onServiceDisconnected(ComponentName name) {
if(BuildConfig.DEBUG)Log.d(TAG, "onServiceDisconnected AudioTrackService");
mAudiotrackServiceBound = false;
mAudiotrackService = null;
}
};
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if(BuildConfig.DEBUG) Log.d(TAG, "onCreate");
setRetainInstance(true);
Bundle argsbundle = getArguments();
if(argsbundle != null) {
mNotificationIntent = argsbundle.getParcelable(MainActivity.NOTIFICATION_INTENT_ID);
}
}
private RetainedStateCallback mRetCb = null;
@Override
public void onAttach(Context context) {
super.onAttach(context);
if(BuildConfig.DEBUG) Log.d(TAG, "onAttach");
mRetCb = (RetainedStateCallback)context;
if(mTimeshiftPlayer != null) {
mRetCb.onNewTimeshiftPlayer(mTimeshiftPlayer);
}
if(getActivity() != null) {
Intent aTrackIntent = new Intent(getActivity(), eu.hradio.core.audiotrackservice.AudiotrackService.class);
getActivity().startService(aTrackIntent);
getActivity().bindService(aTrackIntent, mSrvCon, 0);
}
}
@Override
public void onDetach() {
super.onDetach();
if(BuildConfig.DEBUG) Log.d(TAG, "onDetach, isRemoving: " + isRemoving() + " : isStateSaved: " + isStateSaved());
if(mAudiotrackServiceBound && mAudiotrackService != null) {
if(getActivity() != null) {
getActivity().unbindService(mSrvCon);
}
}
}
@Override
public void onDestroy() {
super.onDestroy();
if(BuildConfig.DEBUG) Log.d(TAG, "onDestroy, isRemoving: " + isRemoving() + ", isStateSaved: " + isStateSaved() + ", Activity: " + (getActivity() != null ? "okay" : "null"));
if(mTimeshiftPlayer != null) {
mTimeshiftPlayer.stop(true);
mTimeshiftPlayer.removeAudioDataListener(mAudiotrackService.getAudioDataListener());
}
if(mAudiotrackServiceBound && mAudiotrackService != null) {
if(BuildConfig.DEBUG)Log.d(TAG, "Dismissing notification, Activity: " + (getActivity() != null ? "okay" : "null"));
mAudiotrackService.getNotification().dismissNotification();
if(getActivity() != null) {
getActivity().unbindService(mSrvCon);
getActivity().stopService(new Intent(getActivity(), eu.hradio.core.audiotrackservice.AudiotrackService.class));
//set here because onDetach will be called before onServiceDisconnected() from ServiceConnection
mAudiotrackServiceBound = false;
}
}
}
TimeshiftPlayer getTimeshiftPlayer() {
return mTimeshiftPlayer;
}
void setNotificationIntent(PendingIntent intent) {
if(mAudiotrackServiceBound && mAudiotrackService != null) {
mAudiotrackService.getNotification().setContentIntent(intent);
}
}
void setNotificatinLargeIcon(Bitmap largeIcon) {
if(mAudiotrackServiceBound && mAudiotrackService != null) {
mAudiotrackService.getNotification().setLargeIcon(largeIcon);
}
}
void shutdown() {
if(BuildConfig.DEBUG)Log.d(TAG, "Shutting down");
if(mTimeshiftPlayer != null) {
mTimeshiftPlayer.stop(true);
mTimeshiftPlayer.removeAudioDataListener(mAudiotrackService.getAudioDataListener());
}
if(BuildConfig.DEBUG)Log.d(TAG, "Dismissing notification, Activity: " + (getActivity() != null ? "okay" : "null"));
mAudiotrackService.getNotification().dismissNotification();
if(getActivity() != null) {
getActivity().unbindService(mSrvCon);
getActivity().stopService(new Intent(getActivity(), eu.hradio.core.audiotrackservice.AudiotrackService.class));
}
}
/**/
@Override
public void radioServiceStarted(Tuner tuner, RadioService radioService) {
if(BuildConfig.DEBUG) Log.d(TAG, "radioServiceStarted: " + radioService.getServiceLabel());
if(mRunningSrv != null) {
/*
if(mRunningSrv.equalsRadioService(radioService)) {
if(DEBUG)Log.d(TAG, "Same service started, switching Service: " + mRunningSrv.getServiceLabel() + " from " + mRunningSrv.getRadioServiceType().toString() + " to " + radioService.getRadioServiceType().toString());
if(mTimeshiftPlayer != null) {
if(DEBUG)Log.d(TAG, "TimeshiftPlayer already running....");
((TimeshiftPlayerPcmAu)mTimeshiftPlayer).setNewService(radioService);
Radio.getInstance().stopRadioService(mRunningSrv);
mRunningSrv = radioService;
return;
}
}
*/
Radio.getInstance().stopRadioService(mRunningSrv);
}
mRunningSrv = radioService;
if(mTimeshiftPlayer != null) {
mTimeshiftPlayer.removeListener(this);
mTimeshiftPlayer.stop(true);
if(mAudiotrackServiceBound) {
if(mAudiotrackService != null) {
mTimeshiftPlayer.removeAudioDataListener(mAudiotrackService.getAudioDataListener());
}
}
mTimeshiftPlayer = null;
}
try {
//For ShoutCast IP services a PCM TimeshiftPlayer is needed
if(radioService.getRadioServiceType() == RadioServiceType.RADIOSERVICE_TYPE_IP) {
mTimeshiftPlayer = TimeshiftPlayerFactory.createPcmPlayer(getActivity(), radioService);
} else {
mTimeshiftPlayer = TimeshiftPlayerFactory.create(getActivity(), radioService);
}
if(mTimeshiftPlayer != null) {
mTimeshiftPlayer.addListener(this);
mRetCb.onNewTimeshiftPlayer(mTimeshiftPlayer);
mTimeshiftPlayer.setPlayWhenReady();
if(mAudiotrackServiceBound && mAudiotrackService != null) {
mTimeshiftPlayer.addAudioDataListener(mAudiotrackService.getAudioDataListener());
Bitmap logoBmp = null;
if(!radioService.getLogos().isEmpty()) {
for(Visual logo : radioService.getLogos()) {
if(logo.getVisualHeight() > 32 && logo.getVisualHeight() == logo.getVisualHeight()) {
if(DEBUG)Log.d(TAG, "Setting NotificationIcon with: " + logo.getVisualWidth() + "x" + logo.getVisualHeight());
logoBmp = BitmapFactory.decodeByteArray(logo.getVisualData(), 0, logo.getVisualData().length);
break;
}
}
}
mAudiotrackService.getNotification().setLargeIcon(logoBmp);
mAudiotrackService.getNotification().setNotificationText("");
mAudiotrackService.getNotification().setNotificationTitle(radioService.getServiceLabel());
}
}
} catch(IOException ioE) {
ioE.printStackTrace();
}
}
@Override
public void radioServiceStopped(Tuner tuner, RadioService radioService) {
if(BuildConfig.DEBUG) Log.d(TAG, "radioServiceStopped: " + radioService.getServiceLabel());
if(mAudiotrackServiceBound && mAudiotrackService != null) {
//
}
}
@Override
public void tunerStatusChanged(Tuner tuner, TunerStatus tunerStatus) {
}
@Override
public void tunerScanStarted(Tuner tuner) {
}
@Override
public void tunerScanProgress(Tuner tuner, int i) {
}
@Override
public void tunerScanFinished(Tuner tuner) {
}
@Override
public void tunerScanServiceFound(Tuner tuner, RadioService radioService) {
}
@Override
public void tunerReceptionStatistics(Tuner tuner, boolean b, ReceptionQuality receptionQuality) {
}
@Override
public void tunerRawData(Tuner tuner, byte[] bytes) {
}
/* TimeshiftListener impl*/
@Override
public void progress(long l, long l1) {
}
@Override
public void sbtRealTime(long l, long l1, long l2, long l3) {
}
@Override
public void started() {
}
@Override
public void paused() {
}
@Override
public void stopped() {
}
@Override
public void textual(Textual textual) {
if(textual.getType() == TextualType.METADATA_TEXTUAL_TYPE_DAB_DLS && ((TextualDabDynamicLabel)textual).hasTags()) {
TextualDabDynamicLabel dl = (TextualDabDynamicLabel)textual;
String itemArtist = null;
String itemTitle = null;
for(TextualDabDynamicLabelPlusItem dlItem : dl.getDlPlusItems()) {
switch (dlItem.getDynamicLabelPlusContentType()) {
case ITEM_TITLE:
itemTitle = dlItem.getDlPlusContentText();
break;
case ITEM_ARTIST:
itemArtist = dlItem.getDlPlusContentText();
break;
}
}
if(itemArtist != null && itemTitle != null) {
mAudiotrackService.getNotification().setNotificationText(itemArtist + "\n" + itemTitle);
}
}
}
@Override
public void visual(Visual visual) {
}
@Override
public void skipItemAdded(SkipItem skipItem) {
}
@Override
public void skipItemRemoved(SkipItem skipItem) {
}
/**/
public interface RetainedStateCallback {
void onNewTimeshiftPlayer(TimeshiftPlayer player);
}
}
| true |
5d15412bc32358dda2341784e5b18643471240ba | Java | hellodanielting/document-search-and-summarisation | /src/inforet/util/LineWrapper.java | UTF-8 | 731 | 3.40625 | 3 | [] | no_license | package inforet.util;
/**
* Created by johnuiterwyk on 9/10/2014.
*/
public class LineWrapper {
/***
* prints a string to the console, with automatic line wrapping at a certain number of characters
* This is based on the following stack overflow post:
* http://stackoverflow.com/questions/4212675/
*
* @param line
*/
public static void printWrappedLine(String line, int maxChar)
{
line = line.replace("\n"," ");
StringBuilder sb = new StringBuilder(line);
int i = 0;
while (i + maxChar < sb.length() && (i = sb.lastIndexOf(" ", i + maxChar)) != -1) {
sb.replace(i, i + 1, "\n");
}
System.out.println(sb.toString());
}
}
| true |
18b97f09c21184fc118794e70dd07e7fbc24d7ae | Java | jayasri-dev15/Drools | /Greetings/src/main/java/com/sample/Test.java | UTF-8 | 805 | 2.125 | 2 | [] | no_license | package com.sample;
import org.kie.api.KieServices;
import org.kie.api.runtime.KieContainer;
import org.kie.api.runtime.KieSession;
public class Test {
public static void main(String[] args)
{
// TODO Auto-generated method stub
try {
// TODO Auto-generated method stub
KieServices ks = KieServices.Factory.get();
KieContainer kContainer = ks.getKieClasspathContainer();
KieSession kSession = kContainer.newKieSession("ksession-rules");
Person persons=new Person();
persons.setName("Jayasri");
persons.setTime(9);
kSession.insert(persons);
kSession.fireAllRules();
System.out.println(persons.getMessage());
}
catch (Throwable t) {
t.printStackTrace();
}
}
}
| true |