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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
8591c741d30e64bd0345b30415d266e4de4caa9b
|
Java
|
AlexhahahaDrag/drag_blog
|
/drag_base/src/main/java/com/alex/dragblog/base/validator/contraint/IdValidator.java
|
UTF-8
| 859
| 2.28125
| 2
|
[] |
no_license
|
package com.alex.dragblog.base.validator.contraint;
import com.alex.dragblog.base.global.Constants;
import com.alex.dragblog.base.validator.annotion.IdValid;
import com.alex.dragblog.utils.StringUtils;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
/**
*description:
*author: alex
*createDate: 2020/7/4 15:52
*version: 1.0.0
*/
public class IdValidator implements ConstraintValidator<IdValid, String> {
@Override
public void initialize(IdValid constraintAnnotation) {
}
@Override
public boolean isValid(String value, ConstraintValidatorContext constraintValidatorContext) {
if (value == null || StringUtils.isBlank(value) || StringUtils.isEmpty(value.trim()) || value.length() != Constants.THIRTY_TWO)
return false;
return true;
}
}
| true
|
4ab29faf2124c9e05d20ac250b2598b032209c37
|
Java
|
AlexFome/Planster
|
/app/src/main/java/com/fome/planster/AlarmManager.java
|
UTF-8
| 1,397
| 2.265625
| 2
|
[] |
no_license
|
package com.fome.planster;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import com.fome.planster.models.Task;
import com.google.gson.Gson;
import static android.content.Context.ALARM_SERVICE;
/**
* Created by Alex on 12.04.2017.
*/
public class AlarmManager {
static String FILTER = "com.fome.planster";
static android.app.AlarmManager alarmManager;
static Context context;
static Gson gson;
public static void init (Context c) {
context = c;
alarmManager = (android.app.AlarmManager) context.getSystemService(ALARM_SERVICE);
gson = new Gson();
}
public static void setAlarm (Task task) {
Intent intent = new Intent(FILTER);
intent.putExtra("task", gson.toJson(task));
PendingIntent alarmIntent = PendingIntent.getBroadcast(context, task.getId(), intent, PendingIntent.FLAG_UPDATE_CURRENT);
alarmManager.set(android.app.AlarmManager.RTC_WAKEUP,
task.getStartDate().getTime() - (task.getNotificateBefore() * 1000 * 60) + 5,
alarmIntent);
}
public static void removeAlarm (Task task) {
Intent intent = new Intent(FILTER);
PendingIntent alarmIntent = PendingIntent.getBroadcast(context, task.getId(), intent, PendingIntent.FLAG_UPDATE_CURRENT);
alarmManager.cancel(alarmIntent);
}
}
| true
|
05834ef948c960b646c0f5d9b51d9d017b435b98
|
Java
|
tectronics/gullivers-travels-ae
|
/GulliverTravelsProject/src/com/unical/ae/gullivertravels/client/gui/customer/YouTubePanel.java
|
UTF-8
| 1,322
| 2.484375
| 2
|
[] |
no_license
|
package com.unical.ae.gullivertravels.client.gui.customer;
import com.bramosystems.oss.player.core.client.AbstractMediaPlayer;
import com.bramosystems.oss.player.core.client.PluginNotFoundException;
import com.bramosystems.oss.player.core.client.PluginVersionException;
import com.bramosystems.oss.player.youtube.client.YouTubePlayer;
import com.extjs.gxt.ui.client.widget.ContentPanel;
import com.google.gwt.user.client.Window;
public class YouTubePanel extends ContentPanel{
public YouTubePanel() {
// TODO Auto-generated constructor stub
AbstractMediaPlayer player = null;
try
{
// create the player, specifing URL of media
player = new YouTubePlayer("http://www.youtube.com/v/DfDisSBO6gY", "427px", "320px");
add(player); // add player to panel.
}
catch (final PluginVersionException e)
{
// required Flash plugin version is not available,
// alert user possibly providing a link to the plugin download page.
Window.alert(".. some nice message telling the user to download plugin first ..");
}
catch (final PluginNotFoundException e)
{
// catch PluginNotFoundException and display a friendly notice.
Window.alert("Plugin not found");
}
}
}
| true
|
fa47b584f7822dac70168eb9a33647155cf207f8
|
Java
|
datamaskin/ruckus
|
/test/stats/updateprocessor/mlb/UpdateProcessorTest.java
|
UTF-8
| 123,488
| 1.84375
| 2
|
[] |
no_license
|
package stats.updateprocessor.mlb;
import com.avaje.ebean.Ebean;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import common.GlobalConstants;
import dao.IContestDao;
import dao.ISportsDao;
import models.sports.*;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;
import org.w3c.dom.Document;
import org.xml.sax.InputSource;
import play.Logger;
import stats.updateprocessor.FantasyPointAthleteUpdateEvent;
import stats.updateprocessor.FantasyPointUpdateEvent;
import utilities.BaseTest;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPathFactory;
import java.io.IOException;
import java.io.StringReader;
import java.math.BigDecimal;
import java.util.*;
import static org.junit.Assert.*;
/**
* Created by dmaclean on 6/17/14.
*/
public class UpdateProcessorTest extends BaseTest {
// private MLBFantasyPointTranslator translator;
private UpdateProcessor updateProcessor;
private ISportsDao sportsDao;
private IContestDao contestDao;
private Team team;
private Team team2;
private Athlete athlete1;
private Athlete athlete2;
private SportEvent sportEvent;
private AthleteSportEventInfo athleteSportEventInfo;
private AthleteSportEventInfo athleteSportEventInfo2;
private ArrayList<Team> teams;
private static DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
private static XPathFactory xpathFactory = XPathFactory.newInstance();
@Before
public void setUp() {
ApplicationContext context = new FileSystemXmlApplicationContext("test/spring-test.xml");
sportsDao = context.getBean("sportsDao", ISportsDao.class);
contestDao = context.getBean("contestDao", IContestDao.class);
// translator = new MLBFantasyPointTranslator((ScoringRulesManager) context.getBean("ScoringRulesManager"));
updateProcessor = context.getBean("MLBStatsUpdateProcessor", UpdateProcessor.class);
team = new Team(League.MLB, "Boston", "Red Sox", "BOS", 1);
sportsDao.saveTeam(team);
team2 = new Team(League.MLB, "New York", "Yankees", "NYY", 2);
sportsDao.saveTeam(team2);
teams = new ArrayList<>();
teams.add(team);
teams.add(team2);
// Ebean.save(new ScoringRule(GlobalConstants.SCORING_MLB_SINGLE_LABEL, League.MLB, GlobalConstants.SCORING_MLB_SINGLE_FACTOR));
// Ebean.save(new ScoringRule(GlobalConstants.SCORING_MLB_DOUBLE_LABEL, League.MLB, GlobalConstants.SCORING_MLB_DOUBLE_FACTOR));
// Ebean.save(new ScoringRule(GlobalConstants.SCORING_MLB_TRIPLE_LABEL, League.MLB, GlobalConstants.SCORING_MLB_TRIPLE_FACTOR));
// Ebean.save(new ScoringRule(GlobalConstants.SCORING_MLB_HOMERUN_LABEL, League.MLB, GlobalConstants.SCORING_MLB_HOMERUN_FACTOR));
// Ebean.save(new ScoringRule(GlobalConstants.SCORING_MLB_RUN_BATTED_IN_LABEL, League.MLB, GlobalConstants.SCORING_MLB_RUN_BATTED_IN_FACTOR));
// Ebean.save(new ScoringRule(GlobalConstants.SCORING_MLB_RUN_LABEL, League.MLB, GlobalConstants.SCORING_MLB_RUN_FACTOR));
// Ebean.save(new ScoringRule(GlobalConstants.SCORING_MLB_WALK_LABEL, League.MLB, GlobalConstants.SCORING_MLB_WALK_FACTOR));
// Ebean.save(new ScoringRule(GlobalConstants.SCORING_MLB_HIT_BY_PITCH_LABEL, League.MLB, GlobalConstants.SCORING_MLB_HIT_BY_PITCH_FACTOR));
// Ebean.save(new ScoringRule(GlobalConstants.SCORING_MLB_STOLEN_BASE_LABEL, League.MLB, GlobalConstants.SCORING_MLB_STOLEN_BASE_FACTOR));
// Ebean.save(new ScoringRule(GlobalConstants.SCORING_MLB_CAUGHT_STEALING_LABEL, League.MLB, GlobalConstants.SCORING_MLB_CAUGHT_STEALING_FACTOR));
//
// Ebean.save(new ScoringRule(GlobalConstants.SCORING_MLB_INNING_PITCHED_LABEL, League.MLB, GlobalConstants.SCORING_MLB_INNING_PITCHED_FACTOR));
// Ebean.save(new ScoringRule(GlobalConstants.SCORING_MLB_STRIKEOUT_LABEL, League.MLB, GlobalConstants.SCORING_MLB_STRIKEOUT_FACTOR));
// Ebean.save(new ScoringRule(GlobalConstants.SCORING_MLB_WIN_LABEL, League.MLB, GlobalConstants.SCORING_MLB_WIN_FACTOR));
// Ebean.save(new ScoringRule(GlobalConstants.SCORING_MLB_EARNED_RUN_LABEL, League.MLB, GlobalConstants.SCORING_MLB_EARNED_RUN_FACTOR));
// Ebean.save(new ScoringRule(GlobalConstants.SCORING_MLB_PITCHER_HIT_LABEL, League.MLB, GlobalConstants.SCORING_MLB_PITCHER_HIT_FACTOR));
// Ebean.save(new ScoringRule(GlobalConstants.SCORING_MLB_PITCHER_WALK_LABEL, League.MLB, GlobalConstants.SCORING_MLB_PITCHER_WALK_FACTOR));
// Ebean.save(new ScoringRule(GlobalConstants.SCORING_MLB_PITCHER_HIT_BY_PITCH_LABEL, League.MLB, GlobalConstants.SCORING_MLB_PITCHER_HIT_BY_PITCH_FACTOR));
// Ebean.save(new ScoringRule(GlobalConstants.SCORING_MLB_COMPLETE_GAME_LABEL, League.MLB, GlobalConstants.SCORING_MLB_COMPLETE_GAME_FACTOR));
}
@After
public void tearDown() {
updateProcessor = null;
teams = null;
team = null;
athlete1 = null;
athlete2 = null;
sportEvent = null;
athleteSportEventInfo = null;
athleteSportEventInfo2 = null;
}
@Test
public void testUpdateIndicators_FinalBoxScore() {
team = new Team(League.MLB, "Los Angeles", "Dodgers", "LAD", 243);
sportsDao.saveTeam(team);
team2 = new Team(League.MLB, "San Francisco", "Giants", "SFG", 250);
sportsDao.saveTeam(team2);
athlete1 = new Athlete(184104, "Adrian", "Gonzalez", team, "1");
athlete1.setPositions(Arrays.asList(Position.BS_FIRST_BASE));
sportsDao.saveAthlete(athlete1);
athlete2 = new Athlete(202716, "Matt", "Cain", team2, "2");
athlete2.setPositions(Arrays.asList(Position.BS_PITCHER));
sportsDao.saveAthlete(athlete2);
Athlete athleteHanleyRamirez = new Athlete(201879, "Hanley", "Ramirez", team, "2");
athleteHanleyRamirez.setPositions(Arrays.asList(Position.BS_SHORT_STOP));
sportsDao.saveAthlete(athleteHanleyRamirez);
Athlete athleteCarlCrawford = new Athlete(12345, "Carl", "Crawford", team, "2");
athleteCarlCrawford.setPositions(Arrays.asList(Position.BS_OUTFIELD));
sportsDao.saveAthlete(athleteCarlCrawford);
Athlete athleteBusterPosey = new Athlete(6789, "Buster", "Posey", team2, "2");
athleteBusterPosey.setPositions(Arrays.asList(Position.BS_CATCHER));
sportsDao.saveAthlete(athleteBusterPosey);
sportEvent = new SportEvent(1284165, League.MLB, new Date(), "{}", "{}", 9, false, 2014, -1, 1);
sportEvent.setTeams(teams);
sportsDao.saveSportEvent(sportEvent);
athleteSportEventInfo = new AthleteSportEventInfo(sportEvent, athlete1, new BigDecimal("0.00"), "[]", "[]");
athleteSportEventInfo.setIndicator(GlobalConstants.INDICATOR_SCORING_OPPORTUNITY);
sportsDao.saveAthleteSportEventInfo(athleteSportEventInfo);
athleteSportEventInfo2 = new AthleteSportEventInfo(sportEvent, athlete2, new BigDecimal("0.00"), "[]", "[]");
athleteSportEventInfo2.setIndicator(GlobalConstants.INDICATOR_SCORING_OPPORTUNITY);
sportsDao.saveAthleteSportEventInfo(athleteSportEventInfo2);
AthleteSportEventInfo athleteSportEventInfoRamirez = new AthleteSportEventInfo(sportEvent, athleteHanleyRamirez, new BigDecimal("0.00"), "[]", "[]");
athleteSportEventInfoRamirez.setIndicator(GlobalConstants.INDICATOR_SCORING_OPPORTUNITY);
sportsDao.saveAthleteSportEventInfo(athleteSportEventInfoRamirez);
AthleteSportEventInfo athleteSportEventInfoCrawford = new AthleteSportEventInfo(sportEvent, athleteCarlCrawford, new BigDecimal("0.00"), "[]", "[]");
athleteSportEventInfoCrawford.setIndicator(GlobalConstants.INDICATOR_SCORING_OPPORTUNITY);
sportsDao.saveAthleteSportEventInfo(athleteSportEventInfoCrawford);
AthleteSportEventInfo athleteSportEventInfoPosey = new AthleteSportEventInfo(sportEvent, athleteBusterPosey, new BigDecimal("0.00"), "[]", "[]");
athleteSportEventInfoPosey.setIndicator(GlobalConstants.INDICATOR_SCORING_OPPORTUNITY);
sportsDao.saveAthleteSportEventInfo(athleteSportEventInfoPosey);
String data = "<MLB-event>\n" +
"<gamecode code=\"330912119\" global-id=\"1284165\"/>\n" +
" <gamestate>\n" +
" <game status=\"Final\" status-id=\"1\" reason=\"\" inning=\"1\" balls=\"0\" strikes=\"0\" outs=\"2\" segment-number=\"1\" segment-division=\"0\" active-state=\"true\" restart=\"false\" pitch-sequence=\"\"/>\n" +
" <batter id=\"7054\" global-id=\"184104\" first-name=\"Adrian\" last-name=\"Gonzalez\" batting-slot=\"4\" hand=\"L\"/>\n" +
" <pitcher id=\"7495\" global-id=\"202716\" first-name=\"Matt\" last-name=\"Cain\" hand=\"R\"/>\n" +
" <runner id=\"7488\" global-id=\"201879\" first-name=\"Hanley\" last-name=\"Ramirez\" base=\"1\"/>\n" +
" </gamestate>\n" +
" <home-team>\n" +
"<team-name name=\"Dodgers\" alias=\"LAD\"/>\n" +
"<team-city city=\"Los Angeles\"/>\n" +
"<team-code id=\"19\" global-id=\"243\"/>\n" +
" <record wins=\"85\" losses=\"60\" ties=\"0\" pct=\".586\"/>\n" +
" <innings>\n" +
" <inning number=\"1\" score=\"0\"/>\n" +
" </innings>\n" +
" <current-pitcher id=\"7257\" global-id=\"202781\" first-name=\"Zack\" last-name=\"Greinke\" hand=\"R\" wins=\"14\" losses=\"3\"/>\n" +
" <next-up-batter id=\"7710\" global-id=\"226249\" first-name=\"Andre\" last-name=\"Ethier\" hand=\"L\"/>\n" +
" <next-up-batter-two id=\"6698\" global-id=\"8757\" first-name=\"Juan\" last-name=\"Uribe\" hand=\"R\"/>\n" +
" <next-up-batter-three id=\"8373\" global-id=\"225850\" first-name=\"A.J.\" last-name=\"Ellis\" hand=\"R\"/>\n" +
" <due-up due=\"false\"/>\n" +
" </home-team>\n" +
" <home-score type=\"runs\" type-id=\"1\" number=\"1\"/>\n" +
" <home-score type=\"hits\" type-id=\"2\" number=\"1\"/>\n" +
" <home-score type=\"errors\" type-id=\"3\" number=\"0\"/>\n" +
" <visiting-team>\n" +
"<team-name name=\"Giants\" alias=\"SF\"/>\n" +
"<team-city city=\"San Francisco\"/>\n" +
"<team-code id=\"26\" global-id=\"250\"/>\n" +
" <record wins=\"66\" losses=\"80\" ties=\"0\" pct=\".452\"/>\n" +
" <innings>\n" +
" <inning number=\"1\" score=\"0\"/>\n" +
" </innings>\n" +
" <current-pitcher id=\"7495\" global-id=\"202716\" first-name=\"Matt\" last-name=\"Cain\" hand=\"R\" wins=\"8\" losses=\"9\"/>\n" +
" <next-up-batter id=\"7963\" global-id=\"262071\" first-name=\"Hunter\" last-name=\"Pence\" hand=\"R\"/>\n" +
" <next-up-batter-two id=\"8326\" global-id=\"254551\" first-name=\"Pablo\" last-name=\"Sandoval\" hand=\"S\"/>\n" +
" <next-up-batter-three id=\"8945\" global-id=\"454517\" first-name=\"Brandon\" last-name=\"Crawford\" hand=\"L\"/>\n" +
" <due-up due=\"true\"/>\n" +
" </visiting-team>\n" +
" <visiting-score type=\"runs\" type-id=\"1\" number=\"0\"/>\n" +
" <visiting-score type=\"hits\" type-id=\"2\" number=\"0\"/>\n" +
" <visiting-score type=\"errors\" type-id=\"3\" number=\"0\"/>\n" +
" <event-details>\n" +
" <event sequence=\"25\" id=\"4\" code=\"1\" name=\"Single\" balls=\"0\" strikes=\"1\" outs-bef=\"2\" outs-aft=\"2\" rbi=\"0\" segment-number=\"1\" segment-division=\"Bottom\" dir=\"M\" dist=\"157\" bat-type=\"G\" scored=\"false\" base-sit-bef=\"0\" base-sit-aft=\"1\" vis-score=\"0\" home-score=\"0\" team-id=\"19\" team-global-id=\"0\" team-city=\"Los Angeles\" team-name=\"Dodgers\" team-alias=\"LAD\"/>\n" +
" <batter id=\"7488\" global-id=\"201879\" first-name=\"Hanley\" last-name=\"Ramirez\" batting-slot=\"3\" hand=\"R\" end-base=\"1\"/>\n" +
" <pitcher id=\"7495\" global-id=\"202716\" first-name=\"Matt\" last-name=\"Cain\" hand=\"R\"/>\n" +
" <pitch sequence=\"Foul,InPlay\"/>\n" +
" <description text=\"H.Ramirez singled to center.\"/>\n" +
" </event-details>\n" +
"</MLB-event>";
try {
InputSource source = new InputSource(new StringReader(data));
DocumentBuilder documentBuilder = dbFactory.newDocumentBuilder();
Document doc = documentBuilder.parse(source);
FantasyPointUpdateEvent fantasyPointUpdateEvent = new FantasyPointUpdateEvent();
fantasyPointUpdateEvent.setSportEvent(sportEvent);
updateProcessor.updateIndicators(fantasyPointUpdateEvent, doc);
for(Map.Entry<Integer, Integer> entry : fantasyPointUpdateEvent.getIndicators().entrySet()) {
assertEquals(entry.getValue().intValue(), GlobalConstants.INDICATOR_TEAM_OFF_FIELD);
}
int[] ids = {
athleteSportEventInfo.getId(),
athleteSportEventInfo2.getId(),
athleteSportEventInfoCrawford.getId(),
athleteSportEventInfoPosey.getId(),
athleteSportEventInfoRamirez.getId()
};
for(int i=0; i<ids.length; i++) {
AthleteSportEventInfo athleteSportEventInfo1 = sportsDao.findAthleteSportEventInfo(ids[i]);
assertEquals(athleteSportEventInfo1.getIndicator(), GlobalConstants.INDICATOR_TEAM_OFF_FIELD);
}
}
catch(Exception e) {
fail(e.getMessage());
}
}
@Test
public void testUpdateTimeline_BatterOut() {
}
@Test
public void testNoFantasyPointImpact() {
Athlete angelPagan = new Athlete(200060, "Angel", "Pagan", team, "1");
sportsDao.saveAthlete(angelPagan);
Athlete zachGreinke = new Athlete(202781, "Zach", "Greinke", team, "2");
sportsDao.saveAthlete(zachGreinke);
Athlete mattCain = new Athlete(1234, "Matt", "Cain", team, "12");
sportsDao.saveAthlete(mattCain);
sportEvent = new SportEvent(1284165, League.MLB, new Date(), "test", "test", 9, false, 2014, -1, 1);
sportEvent.setTeams(teams);
Ebean.save(sportEvent);
athleteSportEventInfo = new AthleteSportEventInfo(sportEvent, angelPagan, new BigDecimal("0.00"), "{}", "[]");
sportsDao.saveAthleteSportEventInfo(athleteSportEventInfo);
AthleteSportEventInfo athleteSportEventInfoZachGreinke = new AthleteSportEventInfo(sportEvent, zachGreinke, new BigDecimal("0.00"), "{}", "[]");
sportsDao.saveAthleteSportEventInfo(athleteSportEventInfoZachGreinke);
AthleteSportEventInfo athleteSportEventInfoMattCain = new AthleteSportEventInfo(sportEvent, mattCain, new BigDecimal("0.00"), "{}", "[]");
sportsDao.saveAthleteSportEventInfo(athleteSportEventInfoMattCain);
String data = "<MLB-event>\n" +
"<gamecode code=\"330912119\" global-id=\"1284165\"/>\n" +
" <gamestate>\n" +
" <game status=\"In-Progress\" status-id=\"1\" reason=\"\" inning=\"1\" balls=\"1\" strikes=\"0\" outs=\"0\" segment-number=\"1\" segment-division=\"1\" active-state=\"true\" restart=\"false\" pitch-sequence=\"Ball,\"/>\n" +
" <batter id=\"7717\" global-id=\"200060\" first-name=\"Angel\" last-name=\"Pagan\" batting-slot=\"1\" hand=\"S\"/>\n" +
" <pitcher id=\"7257\" global-id=\"202781\" first-name=\"Zack\" last-name=\"Greinke\" hand=\"R\"/>\n" +
" </gamestate>\n" +
" <home-team>\n" +
"<team-name name=\"Dodgers\" alias=\"LAD\"/>\n" +
"<team-city city=\"Los Angeles\"/>\n" +
"<team-code id=\"19\" global-id=\"243\"/>\n" +
" <record wins=\"85\" losses=\"60\" ties=\"0\" pct=\".586\"/>\n" +
" <innings>\n" +
" </innings>\n" +
" <current-pitcher id=\"7257\" global-id=\"202781\" first-name=\"Zack\" last-name=\"Greinke\" hand=\"R\" wins=\"14\" losses=\"3\"/>\n" +
" <next-up-batter id=\"9341\" global-id=\"659910\" first-name=\"Yasiel\" last-name=\"Puig\" hand=\"R\"/>\n" +
" <next-up-batter-two id=\"6870\" global-id=\"75597\" first-name=\"Carl\" last-name=\"Crawford\" hand=\"L\"/>\n" +
" <next-up-batter-three id=\"7488\" global-id=\"201879\" first-name=\"Hanley\" last-name=\"Ramirez\" hand=\"R\"/>\n" +
" <due-up due=\"true\"/>\n" +
" </home-team>\n" +
" <home-score type=\"runs\" type-id=\"1\" number=\"0\"/>\n" +
" <home-score type=\"hits\" type-id=\"2\" number=\"0\"/>\n" +
" <home-score type=\"errors\" type-id=\"3\" number=\"0\"/>\n" +
" <visiting-team>\n" +
"<team-name name=\"Giants\" alias=\"SF\"/>\n" +
"<team-city city=\"San Francisco\"/>\n" +
"<team-code id=\"26\" global-id=\"250\"/>\n" +
" <record wins=\"66\" losses=\"80\" ties=\"0\" pct=\".452\"/>\n" +
" <innings>\n" +
" <inning number=\"1\" score=\"0\"/>\n" +
" </innings>\n" +
" <current-pitcher id=\"7495\" global-id=\"202716\" first-name=\"Matt\" last-name=\"Cain\" hand=\"R\" wins=\"8\" losses=\"9\"/>\n" +
" <next-up-batter id=\"6966\" global-id=\"168575\" first-name=\"Marco\" last-name=\"Scutaro\" hand=\"R\"/>\n" +
" <next-up-batter-two id=\"8795\" global-id=\"327177\" first-name=\"Brandon\" last-name=\"Belt\" hand=\"L\"/>\n" +
" <next-up-batter-three id=\"8578\" global-id=\"454353\" first-name=\"Buster\" last-name=\"Posey\" hand=\"R\"/>\n" +
" <due-up due=\"false\"/>\n" +
" </visiting-team>\n" +
" <visiting-score type=\"runs\" type-id=\"1\" number=\"0\"/>\n" +
" <visiting-score type=\"hits\" type-id=\"2\" number=\"0\"/>\n" +
" <visiting-score type=\"errors\" type-id=\"3\" number=\"0\"/>\n" +
"</MLB-event>";
FantasyPointUpdateEvent event = updateProcessor.process(data);
assertTrue(event == null);
// assertTrue(event.getIndicators().get(200060) == GlobalConstants.INDICATOR_SCORING_OPPORTUNITY);
// assertTrue(event.getIndicators().get(202781) == GlobalConstants.INDICATOR_SCORING_OPPORTUNITY);
// assertTrue(event.getIndicators().get(1234) == GlobalConstants.INDICATOR_TEAM_OFF_FIELD);
// assertTrue("Expected map to be empty", events.isEmpty());
// fail("Re-evaluate");
}
@Test
public void testParseBoxScores() {
startHazelcast();
team = new Team(League.MLB, "Los Angeles", "Dodgers", "LAD", 243);
sportsDao.saveTeam(team);
team2 = new Team(League.MLB, "San Francisco", "Giants", "SFG", 250);
sportsDao.saveTeam(team2);
athlete1 = new Athlete(184104, "Adrian", "Gonzalez", team, "1");
athlete1.setPositions(Arrays.asList(Position.BS_FIRST_BASE));
sportsDao.saveAthlete(athlete1);
athlete2 = new Athlete(202716, "Matt", "Cain", team2, "2");
athlete2.setPositions(Arrays.asList(Position.BS_PITCHER));
sportsDao.saveAthlete(athlete2);
Athlete athleteHanleyRamirez = new Athlete(201879, "Hanley", "Ramirez", team, "2");
athleteHanleyRamirez.setPositions(Arrays.asList(Position.BS_SHORT_STOP));
sportsDao.saveAthlete(athleteHanleyRamirez);
Athlete athleteCarlCrawford = new Athlete(12345, "Carl", "Crawford", team, "2");
athleteCarlCrawford.setPositions(Arrays.asList(Position.BS_OUTFIELD));
sportsDao.saveAthlete(athleteCarlCrawford);
Athlete athleteBusterPosey = new Athlete(6789, "Buster", "Posey", team2, "2");
athleteBusterPosey.setPositions(Arrays.asList(Position.BS_CATCHER));
sportsDao.saveAthlete(athleteBusterPosey);
sportEvent = new SportEvent(1284165, League.MLB, new Date(), "{}", "{}", 9, false, 2014, -1, 1);
sportEvent.setTeams(teams);
sportsDao.saveSportEvent(sportEvent);
athleteSportEventInfo = new AthleteSportEventInfo(sportEvent, athlete1, new BigDecimal("0.00"), "{}", "[]");
sportsDao.saveAthleteSportEventInfo(athleteSportEventInfo);
athleteSportEventInfo2 = new AthleteSportEventInfo(sportEvent, athlete2, new BigDecimal("0.00"), "{}", "[]");
sportsDao.saveAthleteSportEventInfo(athleteSportEventInfo2);
AthleteSportEventInfo athleteSportEventInfoRamirez = new AthleteSportEventInfo(sportEvent, athleteHanleyRamirez, new BigDecimal("0.00"), "{}", "[]");
sportsDao.saveAthleteSportEventInfo(athleteSportEventInfoRamirez);
AthleteSportEventInfo athleteSportEventInfoCrawford = new AthleteSportEventInfo(sportEvent, athleteCarlCrawford, new BigDecimal("0.00"), "{}", "[]");
sportsDao.saveAthleteSportEventInfo(athleteSportEventInfoCrawford);
AthleteSportEventInfo athleteSportEventInfoPosey = new AthleteSportEventInfo(sportEvent, athleteBusterPosey, new BigDecimal("0.00"), "{}", "[]");
sportsDao.saveAthleteSportEventInfo(athleteSportEventInfoPosey);
String data = "<MLB-event>\n" +
"<gamecode code=\"330912119\" global-id=\"1284165\"/>\n" +
" <gamestate>\n" +
" <game status=\"In-Progress\" status-id=\"1\" reason=\"\" inning=\"1\" balls=\"0\" strikes=\"0\" outs=\"2\" segment-number=\"1\" segment-division=\"0\" active-state=\"true\" restart=\"false\" pitch-sequence=\"\"/>\n" +
" <batter id=\"7054\" global-id=\"184104\" first-name=\"Adrian\" last-name=\"Gonzalez\" batting-slot=\"4\" hand=\"L\"/>\n" +
" <pitcher id=\"7495\" global-id=\"202716\" first-name=\"Matt\" last-name=\"Cain\" hand=\"R\"/>\n" +
" <runner id=\"7488\" global-id=\"201879\" first-name=\"Hanley\" last-name=\"Ramirez\" base=\"1\"/>\n" +
" </gamestate>\n" +
" <home-team>\n" +
"<team-name name=\"Dodgers\" alias=\"LAD\"/>\n" +
"<team-city city=\"Los Angeles\"/>\n" +
"<team-code id=\"19\" global-id=\"243\"/>\n" +
" <record wins=\"85\" losses=\"60\" ties=\"0\" pct=\".586\"/>\n" +
" <innings>\n" +
" <inning number=\"1\" score=\"0\"/>\n" +
" </innings>\n" +
" <current-pitcher id=\"7257\" global-id=\"202781\" first-name=\"Zack\" last-name=\"Greinke\" hand=\"R\" wins=\"14\" losses=\"3\"/>\n" +
" <next-up-batter id=\"7710\" global-id=\"226249\" first-name=\"Andre\" last-name=\"Ethier\" hand=\"L\"/>\n" +
" <next-up-batter-two id=\"6698\" global-id=\"8757\" first-name=\"Juan\" last-name=\"Uribe\" hand=\"R\"/>\n" +
" <next-up-batter-three id=\"8373\" global-id=\"225850\" first-name=\"A.J.\" last-name=\"Ellis\" hand=\"R\"/>\n" +
" <due-up due=\"false\"/>\n" +
" </home-team>\n" +
" <home-score type=\"runs\" type-id=\"1\" number=\"1\"/>\n" +
" <home-score type=\"hits\" type-id=\"2\" number=\"1\"/>\n" +
" <home-score type=\"errors\" type-id=\"3\" number=\"0\"/>\n" +
" <visiting-team>\n" +
"<team-name name=\"Giants\" alias=\"SF\"/>\n" +
"<team-city city=\"San Francisco\"/>\n" +
"<team-code id=\"26\" global-id=\"250\"/>\n" +
" <record wins=\"66\" losses=\"80\" ties=\"0\" pct=\".452\"/>\n" +
" <innings>\n" +
" <inning number=\"1\" score=\"0\"/>\n" +
" </innings>\n" +
" <current-pitcher id=\"7495\" global-id=\"202716\" first-name=\"Matt\" last-name=\"Cain\" hand=\"R\" wins=\"8\" losses=\"9\"/>\n" +
" <next-up-batter id=\"7963\" global-id=\"262071\" first-name=\"Hunter\" last-name=\"Pence\" hand=\"R\"/>\n" +
" <next-up-batter-two id=\"8326\" global-id=\"254551\" first-name=\"Pablo\" last-name=\"Sandoval\" hand=\"S\"/>\n" +
" <next-up-batter-three id=\"8945\" global-id=\"454517\" first-name=\"Brandon\" last-name=\"Crawford\" hand=\"L\"/>\n" +
" <due-up due=\"true\"/>\n" +
" </visiting-team>\n" +
" <visiting-score type=\"runs\" type-id=\"1\" number=\"0\"/>\n" +
" <visiting-score type=\"hits\" type-id=\"2\" number=\"0\"/>\n" +
" <visiting-score type=\"errors\" type-id=\"3\" number=\"0\"/>\n" +
" <event-details>\n" +
" <event sequence=\"25\" id=\"4\" code=\"1\" name=\"Single\" balls=\"0\" strikes=\"1\" outs-bef=\"2\" outs-aft=\"2\" rbi=\"0\" segment-number=\"1\" segment-division=\"Bottom\" dir=\"M\" dist=\"157\" bat-type=\"G\" scored=\"false\" base-sit-bef=\"0\" base-sit-aft=\"1\" vis-score=\"0\" home-score=\"0\" team-id=\"19\" team-global-id=\"0\" team-city=\"Los Angeles\" team-name=\"Dodgers\" team-alias=\"LAD\"/>\n" +
" <batter id=\"7488\" global-id=\"201879\" first-name=\"Hanley\" last-name=\"Ramirez\" batting-slot=\"3\" hand=\"R\" end-base=\"1\"/>\n" +
" <pitcher id=\"7495\" global-id=\"202716\" first-name=\"Matt\" last-name=\"Cain\" hand=\"R\"/>\n" +
" <pitch sequence=\"Foul,InPlay\"/>\n" +
" <description text=\"H.Ramirez singled to center.\"/>\n" +
" </event-details>\n" +
"<baseball-mlb-boxscore-home-team-stats>\n" +
"<baseball-mlb-boxscore-team-stats>\n" +
"<at-bats at-bats=\"3\"/>\n" +
"<runs runs=\"0\"/>\n" +
"<hits hits=\"1\"/>\n" +
"<runs-batted-in runs-batted-in=\"0\"/>\n" +
"<total-bases total-bases=\"1\"/>\n" +
"<walks walks=\"0\"/>\n" +
"<strike-outs strike-outs=\"0\"/>\n" +
"<runners-left-on-base runners=\"0\"/>\n" +
"<double-plays number=\"0\"/>\n" +
"<triple-plays number=\"0\"/>\n" +
"<total-innings total=\"1\"/>\n" +
"</baseball-mlb-boxscore-team-stats>\n" +
"</baseball-mlb-boxscore-home-team-stats>\n" +
"<baseball-mlb-boxscore-visiting-team-stats>\n" +
"<baseball-mlb-boxscore-team-stats>\n" +
"<at-bats at-bats=\"3\"/>\n" +
"<runs runs=\"0\"/>\n" +
"<hits hits=\"0\"/>\n" +
"<runs-batted-in runs-batted-in=\"0\"/>\n" +
"<total-bases total-bases=\"0\"/>\n" +
"<walks walks=\"1\"/>\n" +
"<strike-outs strike-outs=\"0\"/>\n" +
"<runners-left-on-base runners=\"1\"/>\n" +
"<double-plays number=\"0\"/>\n" +
"<triple-plays number=\"0\"/>\n" +
"<total-innings total=\"1\"/>\n" +
"</baseball-mlb-boxscore-team-stats>\n" +
"</baseball-mlb-boxscore-visiting-team-stats>\n" +
"<baseball-mlb-boxscore-home-team-batting-lineup>\n" +
"<baseball-mlb-boxscore-batting-lineup>\n" +
"<name first-name=\"Hanley\" last-name=\"Ramirez\"/>\n" +
"<player-code id=\"7488\" global-id=\"201879\" uniform=\"13\"/>\n" +
"<player-position position=\"SS\" id=\"6\"/>\n" +
"<batting-hand hand=\"R\"/>\n" +
"<batting-slot slot=\"3\"/>\n" +
"<at-bats at-bats=\"1\" season=\"282\"/>\n" +
"<runs runs=\"0\" season=\"57\"/>\n" +
"<hits hits=\"1\" season=\"97\"/>\n" +
"<doubles doubles=\"0\" season=\"25\"/>\n" +
"<triples triples=\"0\" season=\"2\"/>\n" +
"<home-runs home-runs=\"0\" season=\"18\"/>\n" +
"<stolen-bases stolen-bases=\"0\" season=\"10\"/>\n" +
"<caught-stealing caught-stealing=\"0\" season=\"2\"/>\n" +
"<runs-batted-in runs-batted-in=\"0\" season=\"53\"/>\n" +
"<total-bases total-bases=\"1\" season=\"180\"/>\n" +
"<walks walks=\"0\" season=\"22\"/>\n" +
"<strike-outs strike-outs=\"0\" season=\"47\"/>\n" +
"<left-on-base number=\"0\"/>\n" +
"<plate-appearances number=\"1\" season=\"308\"/>\n" +
"<hit-by-pitch number=\"0\" season=\"2\"/>\n" +
"<ground-into-double-play number=\"0\" season=\"5\"/>\n" +
"<sacrifice-flies number=\"0\" season=\"2\"/>\n" +
"<sacrifice-hits number=\"0\" season=\"0\"/>\n" +
"<batting-average average=\".344\"/>\n" +
"<on-base-percentage percentage=\".393\"/>\n" +
"<slugging-percentage percentage=\".638\"/>\n" +
"<started-game started-game=\"true\"/>\n" +
"<entered-game inning=\"1\"/>\n" +
"<slot-index number=\"1\"/>\n" +
"<picked-off number=\"0\" season=\"0\"/>\n" +
"</baseball-mlb-boxscore-batting-lineup>\n" +
"</baseball-mlb-boxscore-home-team-batting-lineup>\n" +
"<baseball-mlb-boxscore-visiting-team-batting-lineup>\n" +
"</baseball-mlb-boxscore-visiting-team-batting-lineup>\n" +
"<baseball-mlb-boxscore-home-team-pitching-lineup>\n" +
"</baseball-mlb-boxscore-home-team-pitching-lineup>\n" +
"<baseball-mlb-boxscore-visiting-team-pitching-lineup>\n" +
"<baseball-mlb-boxscore-pitching-lineup>\n" +
"<name first-name=\"Matt\" last-name=\"Cain\"/>\n" +
"<player-code id=\"7495\" global-id=\"202716\" uniform=\"18\"/>\n" +
"<throwing-hand hand=\"R\"/>\n" +
"<sequence number=\"1\"/>\n" +
"<wins number=\"8\"/>\n" +
"<losses number=\"9\"/>\n" +
"<saves saves=\"0\"/>\n" +
"<innings-pitched innings=\"0.2\" season=\"163.1\"/>\n" +
"<games-pitched games=\"28\" starts=\"28\"/>\n" +
"<hits hits=\"1\" season=\"140\"/>\n" +
"<runs runs=\"0\" season=\"80\"/>\n" +
"<earned-runs earned-runs=\"0\" season=\"79\"/>\n" +
"<home-runs-allowed home-runs=\"0\" season=\"21\"/>\n" +
"<walks walks=\"0\" season=\"51\"/>\n" +
"<strike-outs strike-outs=\"0\" season=\"143\"/>\n" +
"<pitch-count count=\"7\"/>\n" +
"<balls balls=\"2\"/>\n" +
"<strikes strikes=\"5\"/>\n" +
"<batters-faced batters-faced=\"3\" season=\"675\"/>\n" +
"<opponent-at-bats at-bats=\"3\" season=\"614\"/>\n" +
"<ground-balls number=\"1\" season=\"178\"/>\n" +
"<fly-balls number=\"2\" season=\"179\"/>\n" +
"<inherited-runners runners=\"0\"/>\n" +
"<inherited-stranded stranded=\"0\"/>\n" +
"<hit-batsmen number=\"0\" season=\"4\"/>\n" +
"<balks number=\"0\" season=\"0\"/>\n" +
"<wild-pitches number=\"0\" season=\"1\"/>\n" +
"<earned-run-average average=\"4.35\"/>\n" +
"<opponent-batting-average average=\".228\"/>\n" +
"<entered-game inning=\"1\"/>\n" +
"<doubles number=\"0\" season=\"30\"/>\n" +
"<triples number=\"0\" season=\"5\"/>\n" +
"<gidp number=\"0\" season=\"8\"/>\n" +
"<stolen-bases number=\"0\" season=\"14\"/>\n" +
"<pickoffs number=\"0\" season=\"0\"/>\n" +
"<walks-and-hits-per-inning average=\"1.17\"/>\n" +
"</baseball-mlb-boxscore-pitching-lineup>\n" +
"</baseball-mlb-boxscore-visiting-team-pitching-lineup>\n" +
"</MLB-event>";
FantasyPointUpdateEvent event = updateProcessor.process(data);
assertTrue(event.getCurrentUnitOfTime() == 1);
assertTrue(event.getSportEvent().getUnitsRemaining() == 8);
assertTrue(event.getEventDescription().equals("H.Ramirez singled to center."));
assertTrue(event.getAwayScore() == 0);
assertTrue(event.getHomeScore() == 1);
ObjectMapper mapper = new ObjectMapper();
TypeReference<Map<String, Object>> typeReference = new TypeReference<Map<String, Object>>() {};
TypeReference<List<Map<String, Object>>> listTypeReference = new TypeReference<List<Map<String, Object>>>() {};
try {
Map<String, Object> scoreData = mapper.readValue(event.getSportEvent().getShortDescription(), typeReference);
assertTrue((Integer) scoreData.get("homeScore") == 1);
assertTrue((Integer) scoreData.get("awayScore") == 0);
} catch (IOException e) {
Logger.error("Unable to parse the SportEvent short description for " + sportEvent.getId() + ": " + e.getMessage());
}
/*
* Indicators
*/
assertTrue(event.getIndicators().get(184104) == GlobalConstants.INDICATOR_SCORING_OPPORTUNITY);
assertTrue(event.getIndicators().get(202716) == GlobalConstants.INDICATOR_SCORING_OPPORTUNITY);
assertTrue(event.getIndicators().get(201879) == GlobalConstants.INDICATOR_SCORING_OPPORTUNITY);
assertTrue(event.getIndicators().get(12345) == GlobalConstants.INDICATOR_TEAM_ON_FIELD);
assertTrue(event.getIndicators().get(6789) == GlobalConstants.INDICATOR_TEAM_OFF_FIELD);
assertTrue(sportsDao.findAthleteSportEventInfo(athleteSportEventInfo.getId()).getIndicator() == GlobalConstants.INDICATOR_SCORING_OPPORTUNITY);
assertTrue(sportsDao.findAthleteSportEventInfo(athleteSportEventInfo2.getId()).getIndicator() == GlobalConstants.INDICATOR_SCORING_OPPORTUNITY);
assertTrue(sportsDao.findAthleteSportEventInfo(athleteSportEventInfoRamirez.getId()).getIndicator() == GlobalConstants.INDICATOR_SCORING_OPPORTUNITY);
assertTrue(sportsDao.findAthleteSportEventInfo(athleteSportEventInfoCrawford.getId()).getIndicator() == GlobalConstants.INDICATOR_TEAM_ON_FIELD);
assertTrue(sportsDao.findAthleteSportEventInfo(athleteSportEventInfoPosey.getId()).getIndicator() == GlobalConstants.INDICATOR_TEAM_OFF_FIELD);
assertTrue(event.getFantasyPointAthleteUpdateEventList().size() == 2);
/*
* Pitcher
*/
FantasyPointAthleteUpdateEvent fantasyPointAthleteUpdateEvent = event.getFantasyPointAthleteUpdateEventList().get(0);
assertTrue(fantasyPointAthleteUpdateEvent.getFantasyPointDelta().compareTo(new BigDecimal("-0.6")) == 0);
assertTrue(fantasyPointAthleteUpdateEvent.getFantasyPoints().compareTo(new BigDecimal("0.9")) == 0);
String timeline = fantasyPointAthleteUpdateEvent.getTimeline();
try {
List<Map<String, Object>> timelineList = mapper.readValue(timeline, listTypeReference);
assertTrue(timelineList.size() == 1);
Map<String, Object> timelineValues = timelineList.get(0);
assertTrue(timelineValues.get("timestamp") instanceof Long);
assertTrue(timelineValues.get("description").equals("H.Ramirez singled to center."));
assertTrue(timelineValues.get("fpChange").equals("-0.6"));
assertTrue((Integer) timelineValues.get("athleteSportEventInfoId") == fantasyPointAthleteUpdateEvent.getAthleteSportEventInfo().getId());
}
catch(Exception e) {
fail(e.getMessage());
}
String boxscore = fantasyPointAthleteUpdateEvent.getBoxscore();
try {
List<Map<String, Object>> boxScoreList = mapper.readValue(boxscore, listTypeReference);
assertTrue(boxScoreList.size() == 8);
for(Map<String, Object> boxScoreEntry: boxScoreList) {
if(boxScoreEntry.get("name").equals(GlobalConstants.SCORING_MLB_INNING_PITCHED_LABEL)) {
assertTrue(boxScoreEntry.get("abbr").equals(GlobalConstants.SCORING_MLB_INNINGS_PITCHED_ABBR));
assertTrue((Double) boxScoreEntry.get("amount") == 0.2);
assertTrue((Double) boxScoreEntry.get("fpp") == 1.5);
}
else if(boxScoreEntry.get("name").equals(GlobalConstants.SCORING_MLB_STRIKEOUT_LABEL)) {
assertTrue((Integer) boxScoreEntry.get("amount") == 0);
assertTrue((Double) boxScoreEntry.get("fpp") == 0);
}
else if(boxScoreEntry.get("name").equals(GlobalConstants.SCORING_MLB_EARNED_RUN_LABEL)) {
assertTrue((Integer) boxScoreEntry.get("amount") == 0);
assertTrue((Double) boxScoreEntry.get("fpp") == 0);
}
else if(boxScoreEntry.get("name").equals(GlobalConstants.SCORING_MLB_PITCHER_HIT_LABEL)) {
assertTrue((Integer) boxScoreEntry.get("amount") == 1);
assertTrue((Double) boxScoreEntry.get("fpp") == -0.6);
}
else if(boxScoreEntry.get("name").equals(GlobalConstants.SCORING_MLB_PITCHER_WALK_LABEL)) {
assertTrue((Integer) boxScoreEntry.get("amount") == 0);
assertTrue((Double) boxScoreEntry.get("fpp") == 0);
}
else if(boxScoreEntry.get("name").equals(GlobalConstants.SCORING_MLB_PITCHER_HIT_BY_PITCH_LABEL)) {
assertTrue((Integer) boxScoreEntry.get("amount") == 0);
assertTrue((Double) boxScoreEntry.get("fpp") == 0);
}
else if(boxScoreEntry.get("name").equals(GlobalConstants.SCORING_MLB_WIN_LABEL)) {
assertTrue((Integer) boxScoreEntry.get("amount") == 0);
assertTrue((Double) boxScoreEntry.get("fpp") == 0);
}
else if(boxScoreEntry.get("name").equals(GlobalConstants.SCORING_MLB_COMPLETE_GAME_LABEL)) {
assertTrue((Integer) boxScoreEntry.get("amount") == 0);
assertTrue((Double) boxScoreEntry.get("fpp") == 0);
}
}
// assertTrue(boxScoreValues.get(GlobalConstants.SCORING_MLB_INNING_PITCHED_LABEL).compareTo(new BigDecimal("0.2")) == 0);
// assertTrue(boxScoreValues.get(GlobalConstants.SCORING_MLB_STRIKEOUT_LABEL).intValue() == 0);
// assertTrue(boxScoreValues.get(GlobalConstants.SCORING_MLB_EARNED_RUN_LABEL).intValue() == 0);
// assertTrue(boxScoreValues.get(GlobalConstants.SCORING_MLB_PITCHER_HIT_LABEL).intValue() == 1);
// assertTrue(boxScoreValues.get(GlobalConstants.SCORING_MLB_PITCHER_WALK_LABEL).intValue() == 0);
// assertTrue(boxScoreValues.get(GlobalConstants.SCORING_MLB_PITCHER_HIT_BY_PITCH_LABEL).intValue() == 0);
// assertTrue(boxScoreValues.get(GlobalConstants.SCORING_MLB_WIN_LABEL).intValue() == 0);
// assertTrue(boxScoreValues.get(GlobalConstants.SCORING_MLB_COMPLETE_GAME_LABEL).intValue() == 0);
}
catch(Exception e) {
fail(e.getMessage());
}
/*
* Batter
*/
fantasyPointAthleteUpdateEvent = event.getFantasyPointAthleteUpdateEventList().get(1);
assertTrue(fantasyPointAthleteUpdateEvent.getFantasyPointDelta().compareTo(new BigDecimal("3")) == 0);
assertTrue(fantasyPointAthleteUpdateEvent.getFantasyPoints().compareTo(new BigDecimal("3")) == 0);
timeline = fantasyPointAthleteUpdateEvent.getTimeline();
try {
List<Map<String, Object>> timelineList = mapper.readValue(timeline, listTypeReference);
assertTrue(timelineList.size() == 1);
Map<String, Object> timelineValues = timelineList.get(0);
assertTrue(timelineValues.get("timestamp") instanceof Long);
assertTrue(timelineValues.get("description").equals("H.Ramirez singled to center."));
assertTrue(timelineValues.get("fpChange").equals("+3.0"));
assertTrue((Integer) timelineValues.get("athleteSportEventInfoId") == fantasyPointAthleteUpdateEvent.getAthleteSportEventInfo().getId());
}
catch(Exception e) {
fail(e.getMessage());
}
boxscore = fantasyPointAthleteUpdateEvent.getBoxscore();
try {
List<Map<String, Object>> boxScoreList = mapper.readValue(boxscore, listTypeReference);
assertTrue(boxScoreList.size() == 10);
for(Map<String, Object> boxScoreEntry: boxScoreList) {
if(boxScoreEntry.get("name").equals(GlobalConstants.SCORING_MLB_DOUBLE_LABEL)) {
assertTrue((Integer) boxScoreEntry.get("amount") == 0);
assertTrue((Double) boxScoreEntry.get("fpp") == 0);
}
else if(boxScoreEntry.get("name").equals(GlobalConstants.SCORING_MLB_TRIPLE_LABEL)) {
assertTrue((Integer) boxScoreEntry.get("amount") == 0);
assertTrue((Double) boxScoreEntry.get("fpp") == 0);
}
else if(boxScoreEntry.get("name").equals(GlobalConstants.SCORING_MLB_HOMERUN_LABEL)) {
assertTrue((Integer) boxScoreEntry.get("amount") == 0);
assertTrue((Double) boxScoreEntry.get("fpp") == 0);
}
else if(boxScoreEntry.get("name").equals(GlobalConstants.SCORING_MLB_SINGLE_LABEL)) {
assertTrue((Integer) boxScoreEntry.get("amount") == 1);
assertTrue((Double) boxScoreEntry.get("fpp") == 3);
}
else if(boxScoreEntry.get("name").equals(GlobalConstants.SCORING_MLB_RUN_BATTED_IN_LABEL)) {
assertTrue((Integer) boxScoreEntry.get("amount") == 0);
assertTrue((Double) boxScoreEntry.get("fpp") == 0);
}
else if(boxScoreEntry.get("name").equals(GlobalConstants.SCORING_MLB_RUN_LABEL)) {
assertTrue((Integer) boxScoreEntry.get("amount") == 0);
assertTrue((Double) boxScoreEntry.get("fpp") == 0);
}
else if(boxScoreEntry.get("name").equals(GlobalConstants.SCORING_MLB_WALK_LABEL)) {
assertTrue((Integer) boxScoreEntry.get("amount") == 0);
assertTrue((Double) boxScoreEntry.get("fpp") == 0);
}
else if(boxScoreEntry.get("name").equals(GlobalConstants.SCORING_MLB_HIT_BY_PITCH_LABEL)) {
assertTrue((Integer) boxScoreEntry.get("amount") == 0);
assertTrue((Double) boxScoreEntry.get("fpp") == 0);
}
else if(boxScoreEntry.get("name").equals(GlobalConstants.SCORING_MLB_STOLEN_BASE_LABEL)) {
assertTrue((Integer) boxScoreEntry.get("amount") == 0);
assertTrue((Double) boxScoreEntry.get("fpp") == 0);
}
else if(boxScoreEntry.get("name").equals(GlobalConstants.SCORING_MLB_CAUGHT_STEALING_LABEL)) {
assertTrue((Integer) boxScoreEntry.get("amount") == 0);
assertTrue((Double) boxScoreEntry.get("fpp") == 0);
}
}
// Map<String, BigDecimal> boxScoreValues = boxScoreList.get(0);
// assertTrue(boxScoreValues.get(GlobalConstants.SCORING_MLB_DOUBLE_LABEL) == 0);
// assertTrue(boxScoreValues.get(GlobalConstants.SCORING_MLB_TRIPLE_LABEL) == 0);
// assertTrue(boxScoreValues.get(GlobalConstants.SCORING_MLB_HOMERUN_LABEL) == 0);
// assertTrue(boxScoreValues.get(GlobalConstants.SCORING_MLB_HIT_LABEL) == 1);
// assertTrue(boxScoreValues.get(GlobalConstants.SCORING_MLB_SINGLE_LABEL) == 1);
// assertTrue(boxScoreValues.get(GlobalConstants.SCORING_MLB_RUN_BATTED_IN_LABEL) == 0);
// assertTrue(boxScoreValues.get(GlobalConstants.SCORING_MLB_RUN_LABEL) == 0);
// assertTrue(boxScoreValues.get(GlobalConstants.SCORING_MLB_WALK_LABEL) == 0);
// assertTrue(boxScoreValues.get(GlobalConstants.SCORING_MLB_HIT_BY_PITCH_LABEL) == 0);
// assertTrue(boxScoreValues.get(GlobalConstants.SCORING_MLB_STOLEN_BASE_LABEL) == 0);
// assertTrue(boxScoreValues.get(GlobalConstants.SCORING_MLB_CAUGHT_STEALING_LABEL) == 0);
}
catch(Exception e) {
fail(e.getMessage());
}
//
// SportEvent updatedSportEvent = SportEvent.findByStatsId(sportEvent.getStatProviderId());
// assertTrue(String.format("Units remaining is %s, expected 8", updatedSportEvent.getUnitsRemaining()), updatedSportEvent.getUnitsRemaining() == 8);
//
// assertTrue(events.size() == 2);
// assertTrue(events.get(0).getAthleteId() == 201879
// && events.get(0).getFantasyPoints().doubleValue() == 3.0
// && events.get(0).getLatestDelta().doubleValue() == 3.0
// && events.get(0).getAwayScore() == 0
// && events.get(0).getHomeScore() == 0);
// assertTrue(events.get(1).getAthleteId() == 202716
// && events.get(1).getFantasyPoints().doubleValue() == 0.885
// && events.get(1).getLatestDelta().doubleValue() == 0.885
// && events.get(0).getAwayScore() == 0
// && events.get(0).getHomeScore() == 0);
}
// @Test
public void testProcessMessage_NoEventDetails() {
String statData = "<MLB-event>\n" +
"<gamecode code=\"330912119\" global-id=\"1284165\"/>\n" +
" <gamestate>\n" +
" <game status=\"In-Progress\" status-id=\"1\" reason=\"\" inning=\"1\" balls=\"1\" strikes=\"0\" outs=\"0\" segment-number=\"1\" segment-division=\"1\" active-state=\"true\" restart=\"false\" pitch-sequence=\"Ball,\"/>\n" +
" <batter id=\"7717\" global-id=\"200060\" first-name=\"Angel\" last-name=\"Pagan\" batting-slot=\"1\" hand=\"S\"/>\n" +
" <pitcher id=\"7257\" global-id=\"202781\" first-name=\"Zack\" last-name=\"Greinke\" hand=\"R\"/>\n" +
" </gamestate>\n" +
" <home-team>\n" +
"<team-name name=\"Dodgers\" alias=\"LAD\"/>\n" +
"<team-city city=\"Los Angeles\"/>\n" +
"<team-code id=\"19\" global-id=\"243\"/>\n" +
" <record wins=\"85\" losses=\"60\" ties=\"0\" pct=\".586\"/>\n" +
" <innings>\n" +
" </innings>\n" +
" <current-pitcher id=\"7257\" global-id=\"202781\" first-name=\"Zack\" last-name=\"Greinke\" hand=\"R\" wins=\"14\" losses=\"3\"/>\n" +
" <next-up-batter id=\"9341\" global-id=\"659910\" first-name=\"Yasiel\" last-name=\"Puig\" hand=\"R\"/>\n" +
" <next-up-batter-two id=\"6870\" global-id=\"75597\" first-name=\"Carl\" last-name=\"Crawford\" hand=\"L\"/>\n" +
" <next-up-batter-three id=\"7488\" global-id=\"201879\" first-name=\"Hanley\" last-name=\"Ramirez\" hand=\"R\"/>\n" +
" <due-up due=\"true\"/>\n" +
" </home-team>\n" +
" <home-score type=\"runs\" type-id=\"1\" number=\"0\"/>\n" +
" <home-score type=\"hits\" type-id=\"2\" number=\"0\"/>\n" +
" <home-score type=\"errors\" type-id=\"3\" number=\"0\"/>\n" +
" <visiting-team>\n" +
"<team-name name=\"Giants\" alias=\"SF\"/>\n" +
"<team-city city=\"San Francisco\"/>\n" +
"<team-code id=\"26\" global-id=\"250\"/>\n" +
" <record wins=\"66\" losses=\"80\" ties=\"0\" pct=\".452\"/>\n" +
" <innings>\n" +
" <inning number=\"1\" score=\"0\"/>\n" +
" </innings>\n" +
" <current-pitcher id=\"7495\" global-id=\"202716\" first-name=\"Matt\" last-name=\"Cain\" hand=\"R\" wins=\"8\" losses=\"9\"/>\n" +
" <next-up-batter id=\"6966\" global-id=\"168575\" first-name=\"Marco\" last-name=\"Scutaro\" hand=\"R\"/>\n" +
" <next-up-batter-two id=\"8795\" global-id=\"327177\" first-name=\"Brandon\" last-name=\"Belt\" hand=\"L\"/>\n" +
" <next-up-batter-three id=\"8578\" global-id=\"454353\" first-name=\"Buster\" last-name=\"Posey\" hand=\"R\"/>\n" +
" <due-up due=\"false\"/>\n" +
" </visiting-team>\n" +
" <visiting-score type=\"runs\" type-id=\"1\" number=\"0\"/>\n" +
" <visiting-score type=\"hits\" type-id=\"2\" number=\"0\"/>\n" +
" <visiting-score type=\"errors\" type-id=\"3\" number=\"0\"/>\n" +
"</MLB-event>";
// List<FantasyPointUpdateEvent> events = updateProcessor.process(statData);
//
// assertTrue(events.isEmpty());
fail("Re-evaluate");
}
// @Test
public void testProcessMessage_EventDetails_NonRelevantEvent() {
String statData = "<MLB-event>\n" +
" <gamecode code=\"330912119\" global-id=\"1284165\"/>\n" +
" <gamestate>\n" +
" <game status=\"In-Progress\" status-id=\"2\" reason=\"\" inning=\"10\" balls=\"\" strikes=\"\" outs=\"\" segment-number=\"10\" segment-division=\"0\" active-state=\"false\" restart=\"false\" pitch-sequence=\"\"/>\n" +
" <batter id=\"\" global-id=\"\" first-name=\"\" last-name=\"\" batting-slot=\"\"/>\n" +
" <pitcher id=\"\" global-id=\"\" first-name=\"\" last-name=\"\"/>\n" +
" </gamestate>\n" +
" <double-header double-header=\"false\"/>\n" +
" <double-header-game-number number=\"0\"/>\n" +
" <gametype id=\"1\" type=\"Regular Season\"/>\n" +
" <league id=\"2\" league=\"NL\"/>\n" +
" <stadium name=\"Dodger Stadium\" city=\"Los Angeles\" state=\"California\"/>\n" +
"\t\t<event-details>\n" +
"\t\t <event sequence=\"3\" id=\"1\" code=\"96\" name=\"Lineup Change\" balls=\"0\" strikes=\"0\" outs-bef=\"0\" outs-aft=\"0\" segment-number=\"\" segment-division=\"\" dir=\"\" dist=\"\" bat-type=\"\" scored=\"false\" base-sit-bef=\"0\" base-sit-aft=\"0\" vis-score=\"0\" home-score=\"0\" team-id=\"26\" team-global-id=\"250\" team-city=\"San Francisco\" team-name=\"Giants\" team-alias=\"SF\">\n" +
"\t\t\t <player id=\"7717\" global-id=\"200060\" first-name=\"Angel\" last-name=\"Pagan\" batting-slot=\"1\" pos-id=\"8\" pos-name=\"CF\"/>\n" +
"\t\t </event>\n" +
"\t\t</event-details>\n" +
" </MLB-event>";
// List<FantasyPointUpdateEvent> events = updateProcessor.process(statData);
//
// assertTrue(events.isEmpty());
fail("Re-evaluate");
}
// @Test
public void testProcessMessage_EventDetails_RelevantEvent() {
startHazelcast();
athlete1 = new Athlete(200060, "Player1", "test", team, "1");
Ebean.save(athlete1);
sportEvent = new SportEvent(1284165, League.MLB, new Date(), "test", "test", 9, false, 2014, -1, 1);
sportEvent.setTeams(teams);
Ebean.save(sportEvent);
athleteSportEventInfo = new AthleteSportEventInfo(sportEvent, athlete1, new BigDecimal("0.00"), "{}", "[]");
Ebean.save(athleteSportEventInfo);
String statData = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
"<MLB-event>\n" +
" <gamecode code=\"330912119\" global-id=\"1284165\"/>\n" +
" <gamestate>\n" +
" <game status=\"In-Progress\" status-id=\"2\" reason=\"\" inning=\"10\" balls=\"\" strikes=\"\" outs=\"\" segment-number=\"10\" segment-division=\"0\" active-state=\"false\" restart=\"false\" pitch-sequence=\"\"/>\n" +
" <batter id=\"\" global-id=\"\" first-name=\"\" last-name=\"\" batting-slot=\"\"/>\n" +
" <pitcher id=\"\" global-id=\"\" first-name=\"\" last-name=\"\"/>\n" +
" </gamestate>\n" +
" <double-header double-header=\"false\"/>\n" +
" <double-header-game-number number=\"0\"/>\n" +
" <gametype id=\"1\" type=\"Regular Season\"/>\n" +
" <league id=\"2\" league=\"NL\"/>\n" +
" <stadium name=\"Dodger Stadium\" city=\"Los Angeles\" state=\"California\"/>\n" +
" <home-team>\n" +
"<team-name name=\"Dodgers\" alias=\"LAD\"/>\n" +
"<team-city city=\"Los Angeles\"/>\n" +
"<team-code id=\"19\" global-id=\"243\"/>\n" +
" <record wins=\"85\" losses=\"60\" ties=\"0\" pct=\".586\"/>\n" +
" <innings>\n" +
" <inning number=\"1\" score=\"0\"/>\n" +
" </innings>\n" +
" <current-pitcher id=\"7257\" global-id=\"202781\" first-name=\"Zack\" last-name=\"Greinke\" hand=\"R\" wins=\"14\" losses=\"3\"/>\n" +
" <next-up-batter id=\"7710\" global-id=\"226249\" first-name=\"Andre\" last-name=\"Ethier\" hand=\"L\"/>\n" +
" <next-up-batter-two id=\"6698\" global-id=\"8757\" first-name=\"Juan\" last-name=\"Uribe\" hand=\"R\"/>\n" +
" <next-up-batter-three id=\"8373\" global-id=\"225850\" first-name=\"A.J.\" last-name=\"Ellis\" hand=\"R\"/>\n" +
" <due-up due=\"false\"/>\n" +
" </home-team>\n" +
" <home-score type=\"runs\" type-id=\"1\" number=\"2\"/>\n" +
" <home-score type=\"hits\" type-id=\"2\" number=\"1\"/>\n" +
" <home-score type=\"errors\" type-id=\"3\" number=\"0\"/>\n" +
" <visiting-team>\n" +
"<team-name name=\"Giants\" alias=\"SF\"/>\n" +
"<team-city city=\"San Francisco\"/>\n" +
"<team-code id=\"26\" global-id=\"250\"/>\n" +
" <record wins=\"66\" losses=\"80\" ties=\"0\" pct=\".452\"/>\n" +
" <innings>\n" +
" <inning number=\"1\" score=\"0\"/>\n" +
" </innings>\n" +
" <current-pitcher id=\"7495\" global-id=\"202716\" first-name=\"Matt\" last-name=\"Cain\" hand=\"R\" wins=\"8\" losses=\"9\"/>\n" +
" <next-up-batter id=\"7963\" global-id=\"262071\" first-name=\"Hunter\" last-name=\"Pence\" hand=\"R\"/>\n" +
" <next-up-batter-two id=\"8326\" global-id=\"254551\" first-name=\"Pablo\" last-name=\"Sandoval\" hand=\"S\"/>\n" +
" <next-up-batter-three id=\"8945\" global-id=\"454517\" first-name=\"Brandon\" last-name=\"Crawford\" hand=\"L\"/>\n" +
" <due-up due=\"true\"/>\n" +
" </visiting-team>\n" +
" <visiting-score type=\"runs\" type-id=\"1\" number=\"1\"/>\n" +
" <visiting-score type=\"hits\" type-id=\"2\" number=\"1\"/>\n" +
" <visiting-score type=\"errors\" type-id=\"3\" number=\"0\"/>\n" +
" <event-details>\n" +
" <event sequence=\"22\" id=\"14\" code=\"106\" name=\"Walk\" balls=\"4\" strikes=\"2\" outs-bef=\"1\" outs-aft=\"1\" segment-number=\"1\" segment-division=\"Top\" dir=\"\" dist=\"\" bat-type=\"\" scored=\"false\" base-sit-bef=\"0\" base-sit-aft=\"1\" vis-score=\"0\" home-score=\"0\" team-id=\"26\" team-global-id=\"250\" team-city=\"San Francisco\" team-name=\"Giants\" team-alias=\"SF\"/>\n" +
" <batter id=\"6966\" global-id=\"168575\" first-name=\"Marco\" last-name=\"Scutaro\" batting-slot=\"2\" end-base=\"1\"/>\n" +
" <pitcher id=\"7257\" global-id=\"202781\" first-name=\"Zack\" last-name=\"Greinke\"/>\n" +
" <pitch sequence=\"Strike,Foul,Ball,Ball,Ball,Foul,Foul,Foul,Ball\"/>\n" +
" <description text=\"M.Scutaro walked on a full count.\"/>\n" +
" </event-details>\n" +
" \n" +
" <baseball-mlb-boxscore-home-team-stats>\n" +
" <baseball-mlb-boxscore-team-stats>\n" +
" <at-bats at-bats=\"36\"/>\n" +
" <runs runs=\"3\"/>\n" +
" <hits hits=\"9\"/>\n" +
" <runs-batted-in runs-batted-in=\"3\"/>\n" +
" <total-bases total-bases=\"10\"/>\n" +
" <walks walks=\"2\"/>\n" +
" <strike-outs strike-outs=\"6\"/>\n" +
" <runners-left-on-base runners=\"9\"/>\n" +
" <double-plays number=\"2\"/>\n" +
" <triple-plays number=\"0\"/>\n" +
" <double-plays>\n" +
" <fielders>\n" +
" <fielder pos=\"C\" id=\"8373\" global-id=\"225850\" first-name=\"A.J.\" last-name=\"Ellis\"/>\n" +
" <fielder pos=\"SS\" id=\"6793\" global-id=\"75296\" first-name=\"Nick\" last-name=\"Punto\"/>\n" +
" </fielders>\n" +
" <description description=\"A.Ellis to Punto\"/>\n" +
" </double-plays>\n" +
" <double-plays>\n" +
" <fielders>\n" +
" <fielder pos=\"3B\" id=\"6698\" global-id=\"8757\" first-name=\"Juan\" last-name=\"Uribe\"/>\n" +
" <fielder pos=\"1B\" id=\"7054\" global-id=\"184104\" first-name=\"Adrian\" last-name=\"Gonzalez\"/>\n" +
" </fielders>\n" +
" <description description=\"Uribe to Ad.Gonzalez\"/>\n" +
" </double-plays>\n" +
" <passed-balls>\n" +
" <name first-name=\"Tim\" last-name=\"Federowicz\"/>\n" +
" <player-code id=\"9075\" global-id=\"454959\" uniform=\"18\"/>\n" +
" <game-total number=\"1\"/>\n" +
" </passed-balls>\n" +
" <total-innings total=\"10\"/>\n" +
" </baseball-mlb-boxscore-team-stats>\n" +
" </baseball-mlb-boxscore-home-team-stats>\n" +
" <baseball-mlb-boxscore-visiting-team-stats>\n" +
" <baseball-mlb-boxscore-team-stats>\n" +
" <at-bats at-bats=\"35\"/>\n" +
" <runs runs=\"2\"/>\n" +
" <hits hits=\"9\"/>\n" +
" <runs-batted-in runs-batted-in=\"2\"/>\n" +
" <total-bases total-bases=\"13\"/>\n" +
" <walks walks=\"5\"/>\n" +
" <strike-outs strike-outs=\"7\"/>\n" +
" <runners-left-on-base runners=\"9\"/>\n" +
" <double-plays number=\"0\"/>\n" +
" <triple-plays number=\"0\"/>\n" +
" <errors>\n" +
" <name first-name=\"Matt\" last-name=\"Cain\"/>\n" +
" <player-code id=\"7495\" global-id=\"202716\" uniform=\"18\"/>\n" +
" <game-total number=\"1\"/>\n" +
" <season-total number=\"1\"/>\n" +
" </errors>\n" +
" <total-innings total=\"10\"/>\n" +
" </baseball-mlb-boxscore-team-stats>\n" +
" </baseball-mlb-boxscore-visiting-team-stats>\n" +
" <baseball-mlb-boxscore-home-team-batting-lineup>\n" +
" </baseball-mlb-boxscore-home-team-batting-lineup>\n" +
" <baseball-mlb-boxscore-visiting-team-batting-lineup>\n" +
" <baseball-mlb-boxscore-batting-lineup>\n" +
" <name first-name=\"Angel\" last-name=\"Pagan\"/>\n" +
" <player-code id=\"7717\" global-id=\"200060\" uniform=\"16\"/>\n" +
" <player-position position=\"CF\" id=\"8\"/>\n" +
" <batting-slot slot=\"1\"/>\n" +
" <at-bats at-bats=\"5\" season=\"233\"/>\n" +
" <runs runs=\"0\" season=\"37\"/>\n" +
" <hits hits=\"2\" season=\"66\"/>\n" +
" <doubles doubles=\"0\" season=\"13\"/>\n" +
" <triples triples=\"0\" season=\"2\"/>\n" +
" <home-runs home-runs=\"0\" season=\"3\"/>\n" +
" <stolen-bases stolen-bases=\"1\" season=\"9\"/>\n" +
" <caught-stealing caught-stealing=\"0\" season=\"4\"/>\n" +
" <runs-batted-in runs-batted-in=\"0\" season=\"25\"/>\n" +
" <total-bases total-bases=\"2\" season=\"92\"/>\n" +
" <walks walks=\"0\" season=\"19\"/>\n" +
" <strike-outs strike-outs=\"0\" season=\"30\"/>\n" +
" <left-on-base number=\"1\"/>\n" +
" <plate-appearances number=\"5\" season=\"254\"/>\n" +
" <hit-by-pitch number=\"0\" season=\"0\"/>\n" +
" <ground-into-double-play number=\"0\" season=\"1\"/>\n" +
" <sacrifice-flies number=\"0\" season=\"2\"/>\n" +
" <sacrifice-hits number=\"0\" season=\"0\"/>\n" +
" <batting-average average=\".283\"/>\n" +
" <on-base-percentage percentage=\".335\"/>\n" +
" <slugging-percentage percentage=\".395\"/>\n" +
" <started-game started-game=\"true\"/>\n" +
" <entered-game inning=\"1\"/>\n" +
" <slot-index number=\"1\"/>\n" +
" <picked-off number=\"0\" season=\"0\"/>\n" +
" </baseball-mlb-boxscore-batting-lineup>\n" +
" </baseball-mlb-boxscore-visiting-team-batting-lineup>\n" +
"</MLB-event>\n";
// List<FantasyPointUpdateEvent> events = updateProcessor.process(statData);
//
// assertTrue(events.size() == 1);
//
// assertTrue(events.get(0).getAwayScore() == 1
// && events.get(0).getHomeScore() == 2);
//
// SportEvent updatedSportEvent = SportEvent.findByStatsId(sportEvent.getStatProviderId());
// assertTrue(String.format("unitsRemaining is %s, expected 0", updatedSportEvent.getUnitsRemaining()), updatedSportEvent.getUnitsRemaining() == 0);
fail("Re-evaluate");
}
// @Test
public void testProcessMessage_EventDetails_RelevantEvent_ExistingFantasyPoints() {
startHazelcast();
athlete1 = new Athlete(200060, "Player1", "test", team, "1");
Ebean.save(athlete1);
sportEvent = new SportEvent(1284165, League.MLB, new Date(), "test", "test", 9, false, 2014, -1, 1);
sportEvent.setTeams(teams);
Ebean.save(sportEvent);
athleteSportEventInfo = new AthleteSportEventInfo(sportEvent, athlete1, new BigDecimal("5.00"), "{}", "[]");
Ebean.save(athleteSportEventInfo);
String statData = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
"<MLB-event>\n" +
" <gamecode code=\"330912119\" global-id=\"1284165\"/>\n" +
" <gamestate>\n" +
" <game status=\"In-Progress\" status-id=\"2\" reason=\"\" inning=\"10\" balls=\"\" strikes=\"\" outs=\"\" segment-number=\"10\" segment-division=\"0\" active-state=\"false\" restart=\"false\" pitch-sequence=\"\"/>\n" +
" <batter id=\"\" global-id=\"\" first-name=\"\" last-name=\"\" batting-slot=\"\"/>\n" +
" <pitcher id=\"\" global-id=\"\" first-name=\"\" last-name=\"\"/>\n" +
" </gamestate>\n" +
" <double-header double-header=\"false\"/>\n" +
" <double-header-game-number number=\"0\"/>\n" +
" <gametype id=\"1\" type=\"Regular Season\"/>\n" +
" <league id=\"2\" league=\"NL\"/>\n" +
" <stadium name=\"Dodger Stadium\" city=\"Los Angeles\" state=\"California\"/>\n" +
" <home-team>\n" +
"<team-name name=\"Dodgers\" alias=\"LAD\"/>\n" +
"<team-city city=\"Los Angeles\"/>\n" +
"<team-code id=\"19\" global-id=\"243\"/>\n" +
" <record wins=\"85\" losses=\"60\" ties=\"0\" pct=\".586\"/>\n" +
" <innings>\n" +
" <inning number=\"1\" score=\"0\"/>\n" +
" </innings>\n" +
" <current-pitcher id=\"7257\" global-id=\"202781\" first-name=\"Zack\" last-name=\"Greinke\" hand=\"R\" wins=\"14\" losses=\"3\"/>\n" +
" <next-up-batter id=\"7710\" global-id=\"226249\" first-name=\"Andre\" last-name=\"Ethier\" hand=\"L\"/>\n" +
" <next-up-batter-two id=\"6698\" global-id=\"8757\" first-name=\"Juan\" last-name=\"Uribe\" hand=\"R\"/>\n" +
" <next-up-batter-three id=\"8373\" global-id=\"225850\" first-name=\"A.J.\" last-name=\"Ellis\" hand=\"R\"/>\n" +
" <due-up due=\"false\"/>\n" +
" </home-team>\n" +
" <home-score type=\"runs\" type-id=\"1\" number=\"2\"/>\n" +
" <home-score type=\"hits\" type-id=\"2\" number=\"1\"/>\n" +
" <home-score type=\"errors\" type-id=\"3\" number=\"0\"/>\n" +
" <visiting-team>\n" +
"<team-name name=\"Giants\" alias=\"SF\"/>\n" +
"<team-city city=\"San Francisco\"/>\n" +
"<team-code id=\"26\" global-id=\"250\"/>\n" +
" <record wins=\"66\" losses=\"80\" ties=\"0\" pct=\".452\"/>\n" +
" <innings>\n" +
" <inning number=\"1\" score=\"0\"/>\n" +
" </innings>\n" +
" <current-pitcher id=\"7495\" global-id=\"202716\" first-name=\"Matt\" last-name=\"Cain\" hand=\"R\" wins=\"8\" losses=\"9\"/>\n" +
" <next-up-batter id=\"7963\" global-id=\"262071\" first-name=\"Hunter\" last-name=\"Pence\" hand=\"R\"/>\n" +
" <next-up-batter-two id=\"8326\" global-id=\"254551\" first-name=\"Pablo\" last-name=\"Sandoval\" hand=\"S\"/>\n" +
" <next-up-batter-three id=\"8945\" global-id=\"454517\" first-name=\"Brandon\" last-name=\"Crawford\" hand=\"L\"/>\n" +
" <due-up due=\"true\"/>\n" +
" </visiting-team>\n" +
" <visiting-score type=\"runs\" type-id=\"1\" number=\"1\"/>\n" +
" <visiting-score type=\"hits\" type-id=\"2\" number=\"1\"/>\n" +
" <visiting-score type=\"errors\" type-id=\"3\" number=\"0\"/>\n" +
" <event-details>\n" +
" <event sequence=\"22\" id=\"14\" code=\"106\" name=\"Walk\" balls=\"4\" strikes=\"2\" outs-bef=\"1\" outs-aft=\"1\" segment-number=\"1\" segment-division=\"Top\" dir=\"\" dist=\"\" bat-type=\"\" scored=\"false\" base-sit-bef=\"0\" base-sit-aft=\"1\" vis-score=\"0\" home-score=\"0\" team-id=\"26\" team-global-id=\"250\" team-city=\"San Francisco\" team-name=\"Giants\" team-alias=\"SF\"/>\n" +
" <batter id=\"6966\" global-id=\"168575\" first-name=\"Marco\" last-name=\"Scutaro\" batting-slot=\"2\" end-base=\"1\"/>\n" +
" <pitcher id=\"7257\" global-id=\"202781\" first-name=\"Zack\" last-name=\"Greinke\"/>\n" +
" <pitch sequence=\"Strike,Foul,Ball,Ball,Ball,Foul,Foul,Foul,Ball\"/>\n" +
" <description text=\"M.Scutaro walked on a full count.\"/>\n" +
" </event-details>\n" +
" \n" +
" <baseball-mlb-boxscore-home-team-stats>\n" +
" <baseball-mlb-boxscore-team-stats>\n" +
" <at-bats at-bats=\"36\"/>\n" +
" <runs runs=\"3\"/>\n" +
" <hits hits=\"9\"/>\n" +
" <runs-batted-in runs-batted-in=\"3\"/>\n" +
" <total-bases total-bases=\"10\"/>\n" +
" <walks walks=\"2\"/>\n" +
" <strike-outs strike-outs=\"6\"/>\n" +
" <runners-left-on-base runners=\"9\"/>\n" +
" <double-plays number=\"2\"/>\n" +
" <triple-plays number=\"0\"/>\n" +
" <double-plays>\n" +
" <fielders>\n" +
" <fielder pos=\"C\" id=\"8373\" global-id=\"225850\" first-name=\"A.J.\" last-name=\"Ellis\"/>\n" +
" <fielder pos=\"SS\" id=\"6793\" global-id=\"75296\" first-name=\"Nick\" last-name=\"Punto\"/>\n" +
" </fielders>\n" +
" <description description=\"A.Ellis to Punto\"/>\n" +
" </double-plays>\n" +
" <double-plays>\n" +
" <fielders>\n" +
" <fielder pos=\"3B\" id=\"6698\" global-id=\"8757\" first-name=\"Juan\" last-name=\"Uribe\"/>\n" +
" <fielder pos=\"1B\" id=\"7054\" global-id=\"184104\" first-name=\"Adrian\" last-name=\"Gonzalez\"/>\n" +
" </fielders>\n" +
" <description description=\"Uribe to Ad.Gonzalez\"/>\n" +
" </double-plays>\n" +
" <passed-balls>\n" +
" <name first-name=\"Tim\" last-name=\"Federowicz\"/>\n" +
" <player-code id=\"9075\" global-id=\"454959\" uniform=\"18\"/>\n" +
" <game-total number=\"1\"/>\n" +
" </passed-balls>\n" +
" <total-innings total=\"10\"/>\n" +
" </baseball-mlb-boxscore-team-stats>\n" +
" </baseball-mlb-boxscore-home-team-stats>\n" +
" <baseball-mlb-boxscore-visiting-team-stats>\n" +
" <baseball-mlb-boxscore-team-stats>\n" +
" <at-bats at-bats=\"35\"/>\n" +
" <runs runs=\"2\"/>\n" +
" <hits hits=\"9\"/>\n" +
" <runs-batted-in runs-batted-in=\"2\"/>\n" +
" <total-bases total-bases=\"13\"/>\n" +
" <walks walks=\"5\"/>\n" +
" <strike-outs strike-outs=\"7\"/>\n" +
" <runners-left-on-base runners=\"9\"/>\n" +
" <double-plays number=\"0\"/>\n" +
" <triple-plays number=\"0\"/>\n" +
" <errors>\n" +
" <name first-name=\"Matt\" last-name=\"Cain\"/>\n" +
" <player-code id=\"7495\" global-id=\"202716\" uniform=\"18\"/>\n" +
" <game-total number=\"1\"/>\n" +
" <season-total number=\"1\"/>\n" +
" </errors>\n" +
" <total-innings total=\"10\"/>\n" +
" </baseball-mlb-boxscore-team-stats>\n" +
" </baseball-mlb-boxscore-visiting-team-stats>\n" +
" <baseball-mlb-boxscore-home-team-batting-lineup>\n" +
" </baseball-mlb-boxscore-home-team-batting-lineup>\n" +
" <baseball-mlb-boxscore-visiting-team-batting-lineup>\n" +
" <baseball-mlb-boxscore-batting-lineup>\n" +
" <name first-name=\"Angel\" last-name=\"Pagan\"/>\n" +
" <player-code id=\"7717\" global-id=\"200060\" uniform=\"16\"/>\n" +
" <player-position position=\"CF\" id=\"8\"/>\n" +
" <batting-slot slot=\"1\"/>\n" +
" <at-bats at-bats=\"5\" season=\"233\"/>\n" +
" <runs runs=\"0\" season=\"37\"/>\n" +
" <hits hits=\"2\" season=\"66\"/>\n" +
" <doubles doubles=\"0\" season=\"13\"/>\n" +
" <triples triples=\"0\" season=\"2\"/>\n" +
" <home-runs home-runs=\"0\" season=\"3\"/>\n" +
" <stolen-bases stolen-bases=\"1\" season=\"9\"/>\n" +
" <caught-stealing caught-stealing=\"0\" season=\"4\"/>\n" +
" <runs-batted-in runs-batted-in=\"0\" season=\"25\"/>\n" +
" <total-bases total-bases=\"2\" season=\"92\"/>\n" +
" <walks walks=\"0\" season=\"19\"/>\n" +
" <strike-outs strike-outs=\"0\" season=\"30\"/>\n" +
" <left-on-base number=\"1\"/>\n" +
" <plate-appearances number=\"5\" season=\"254\"/>\n" +
" <hit-by-pitch number=\"0\" season=\"0\"/>\n" +
" <ground-into-double-play number=\"0\" season=\"1\"/>\n" +
" <sacrifice-flies number=\"0\" season=\"2\"/>\n" +
" <sacrifice-hits number=\"0\" season=\"0\"/>\n" +
" <batting-average average=\".283\"/>\n" +
" <on-base-percentage percentage=\".335\"/>\n" +
" <slugging-percentage percentage=\".395\"/>\n" +
" <started-game started-game=\"true\"/>\n" +
" <entered-game inning=\"1\"/>\n" +
" <slot-index number=\"1\"/>\n" +
" <picked-off number=\"0\" season=\"0\"/>\n" +
" </baseball-mlb-boxscore-batting-lineup>\n" +
" </baseball-mlb-boxscore-visiting-team-batting-lineup>\n" +
"</MLB-event>\n";
// List<FantasyPointUpdateEvent> events = updateProcessor.process(statData);
//
// AthleteSportEventInfo athleteSportEventInfo1 = AthleteSportEventInfo.findByAthleteAndSportEvent(athlete1, sportEvent);
// try {
// TypeReference<List<Map<String, Object>>> typeReference = new TypeReference<List<Map<String, Object>>>() {};
// List<Map<String, Object>> data = mapper.readValue(athleteSportEventInfo1.getStats(), typeReference);
// assertTrue(data.get(0).get(JSON_FIELD_NAME).equals(GlobalConstants.SCORING_MLB_DOUBLE_LABEL));
// assertTrue((Integer) data.get(0).get(JSON_FIELD_AMOUNT) == 0);
// assertTrue((Double) data.get(0).get(JSON_FIELD_FPP) == 0.0);
// assertTrue(data.get(1).get(JSON_FIELD_NAME).equals(GlobalConstants.SCORING_MLB_TRIPLE_LABEL));
// assertTrue((Integer) data.get(1).get(JSON_FIELD_AMOUNT) == 0);
// assertTrue((Double) data.get(1).get(JSON_FIELD_FPP) == 0.0);
// assertTrue(data.get(2).get(JSON_FIELD_NAME).equals(GlobalConstants.SCORING_MLB_HOMERUN_LABEL));
// assertTrue((Integer) data.get(2).get(JSON_FIELD_AMOUNT) == 0);
// assertTrue((Double) data.get(2).get(JSON_FIELD_FPP) == 0.0);
// assertTrue(data.get(3).get(JSON_FIELD_NAME).equals(GlobalConstants.SCORING_MLB_SINGLE_LABEL));
// assertTrue((Integer) data.get(3).get(JSON_FIELD_AMOUNT) == 2);
// assertTrue((Double) data.get(3).get(JSON_FIELD_FPP) == 6.0);
// assertTrue(data.get(4).get(JSON_FIELD_NAME).equals(GlobalConstants.SCORING_MLB_RUN_BATTED_IN_LABEL));
// assertTrue((Integer) data.get(4).get(JSON_FIELD_AMOUNT) == 0);
// assertTrue((Double) data.get(4).get(JSON_FIELD_FPP) == 0.0);
// assertTrue(data.get(5).get(JSON_FIELD_NAME).equals(GlobalConstants.SCORING_MLB_RUN_LABEL));
// assertTrue((Integer) data.get(5).get(JSON_FIELD_AMOUNT) == 0);
// assertTrue((Double) data.get(5).get(JSON_FIELD_FPP) == 0.0);
// assertTrue(data.get(6).get(JSON_FIELD_NAME).equals(GlobalConstants.SCORING_MLB_WALK_LABEL));
// assertTrue((Integer) data.get(6).get(JSON_FIELD_AMOUNT) == 0);
// assertTrue((Double) data.get(6).get(JSON_FIELD_FPP) == 0.0);
// assertTrue(data.get(7).get(JSON_FIELD_NAME).equals(GlobalConstants.SCORING_MLB_HIT_BY_PITCH_LABEL));
// assertTrue((Integer) data.get(7).get(JSON_FIELD_AMOUNT) == 0);
// assertTrue((Double) data.get(7).get(JSON_FIELD_FPP) == 0.0);
// assertTrue(data.get(8).get(JSON_FIELD_NAME).equals(GlobalConstants.SCORING_MLB_STOLEN_BASE_LABEL));
// assertTrue((Integer) data.get(8).get(JSON_FIELD_AMOUNT) == 1);
// assertTrue((Double) data.get(8).get(JSON_FIELD_FPP) == 5.0);
// assertTrue(data.get(9).get(JSON_FIELD_NAME).equals(GlobalConstants.SCORING_MLB_CAUGHT_STEALING_LABEL));
// assertTrue((Integer) data.get(9).get(JSON_FIELD_AMOUNT) == 0);
// assertTrue((Double) data.get(9).get(JSON_FIELD_FPP) == 0.0);
//
// List<Map<String, Object>> timelineData = mapper.readValue(athleteSportEventInfo1.getTimeline(), typeReference);
// assertTrue(timelineData.size() == 1);
// assertTrue(timelineData.get(0).get("description").equals("M.Scutaro walked on a full count."));
// assertTrue(timelineData.get(0).get("fpChange").equals("+6.00"));
// assertTrue(!timelineData.get(0).get("timestamp").equals(""));
// } catch (IOException e) {
// fail(e.getMessage());
// }
//
// SportEvent updatedSportEvent = SportEvent.findByStatsId(sportEvent.getStatProviderId());
// assertTrue(String.format("unitsRemaining is %s, expected 0", updatedSportEvent.getUnitsRemaining()), updatedSportEvent.getUnitsRemaining() == 0);
//
// assertTrue(events.size() == 1);
// assertTrue(events.get(0).getAthleteId() == 200060 && events.get(0).getFantasyPoints().doubleValue() == 11.0 && events.get(0).getLatestDelta().doubleValue() == 6.0);
fail("Re-evaluate");
}
// @Test
public void testProcessMessage_EventDetails_RelevantEvent_Pitcher() {
startHazelcast();
athlete1 = new Athlete(253985, "JA", "Happ", team, "1");
Ebean.save(athlete1);
sportEvent = new SportEvent(1284165, League.MLB, new Date(), "test", "test", 9, false, 2014, -1, 1);
sportEvent.setTeams(teams);
Ebean.save(sportEvent);
athleteSportEventInfo = new AthleteSportEventInfo(sportEvent, athlete1, new BigDecimal("0.00"), "{}", "[]");
Ebean.save(athleteSportEventInfo);
String statData = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
"<MLB-event>\n" +
" <gamecode code=\"330912119\" global-id=\"1284165\"/>\n" +
" <gamestate>\n" +
" <game status=\"In-Progress\" status-id=\"2\" reason=\"\" inning=\"7\" balls=\"\" strikes=\"\" outs=\"\" segment-number=\"7\" segment-division=\"0\" active-state=\"false\" restart=\"false\" pitch-sequence=\"\"/>\n" +
" <batter id=\"\" global-id=\"\" first-name=\"\" last-name=\"\" batting-slot=\"\"/>\n" +
" <pitcher id=\"\" global-id=\"\" first-name=\"\" last-name=\"\"/>\n" +
" </gamestate>\n" +
" <double-header double-header=\"false\"/>\n" +
" <double-header-game-number number=\"0\"/>\n" +
" <gametype id=\"1\" type=\"Regular Season\"/>\n" +
" <league id=\"2\" league=\"NL\"/>\n" +
" <stadium name=\"Dodger Stadium\" city=\"Los Angeles\" state=\"California\"/>\n" +
" <home-team>\n" +
"<team-name name=\"Dodgers\" alias=\"LAD\"/>\n" +
"<team-city city=\"Los Angeles\"/>\n" +
"<team-code id=\"19\" global-id=\"243\"/>\n" +
" <record wins=\"85\" losses=\"60\" ties=\"0\" pct=\".586\"/>\n" +
" <innings>\n" +
" <inning number=\"1\" score=\"0\"/>\n" +
" </innings>\n" +
" <current-pitcher id=\"7257\" global-id=\"202781\" first-name=\"Zack\" last-name=\"Greinke\" hand=\"R\" wins=\"14\" losses=\"3\"/>\n" +
" <next-up-batter id=\"7710\" global-id=\"226249\" first-name=\"Andre\" last-name=\"Ethier\" hand=\"L\"/>\n" +
" <next-up-batter-two id=\"6698\" global-id=\"8757\" first-name=\"Juan\" last-name=\"Uribe\" hand=\"R\"/>\n" +
" <next-up-batter-three id=\"8373\" global-id=\"225850\" first-name=\"A.J.\" last-name=\"Ellis\" hand=\"R\"/>\n" +
" <due-up due=\"false\"/>\n" +
" </home-team>\n" +
" <home-score type=\"runs\" type-id=\"1\" number=\"2\"/>\n" +
" <home-score type=\"hits\" type-id=\"2\" number=\"1\"/>\n" +
" <home-score type=\"errors\" type-id=\"3\" number=\"0\"/>\n" +
" <visiting-team>\n" +
"<team-name name=\"Giants\" alias=\"SF\"/>\n" +
"<team-city city=\"San Francisco\"/>\n" +
"<team-code id=\"26\" global-id=\"250\"/>\n" +
" <record wins=\"66\" losses=\"80\" ties=\"0\" pct=\".452\"/>\n" +
" <innings>\n" +
" <inning number=\"1\" score=\"0\"/>\n" +
" </innings>\n" +
" <current-pitcher id=\"7495\" global-id=\"202716\" first-name=\"Matt\" last-name=\"Cain\" hand=\"R\" wins=\"8\" losses=\"9\"/>\n" +
" <next-up-batter id=\"7963\" global-id=\"262071\" first-name=\"Hunter\" last-name=\"Pence\" hand=\"R\"/>\n" +
" <next-up-batter-two id=\"8326\" global-id=\"254551\" first-name=\"Pablo\" last-name=\"Sandoval\" hand=\"S\"/>\n" +
" <next-up-batter-three id=\"8945\" global-id=\"454517\" first-name=\"Brandon\" last-name=\"Crawford\" hand=\"L\"/>\n" +
" <due-up due=\"true\"/>\n" +
" </visiting-team>\n" +
" <visiting-score type=\"runs\" type-id=\"1\" number=\"1\"/>\n" +
" <visiting-score type=\"hits\" type-id=\"2\" number=\"1\"/>\n" +
" <visiting-score type=\"errors\" type-id=\"3\" number=\"0\"/>\n" +
" <event-details>\n" +
" <event sequence=\"22\" id=\"14\" code=\"106\" name=\"Walk\" balls=\"4\" strikes=\"2\" outs-bef=\"1\" outs-aft=\"1\" segment-number=\"1\" segment-division=\"Top\" dir=\"\" dist=\"\" bat-type=\"\" scored=\"false\" base-sit-bef=\"0\" base-sit-aft=\"1\" vis-score=\"0\" home-score=\"0\" team-id=\"26\" team-global-id=\"250\" team-city=\"San Francisco\" team-name=\"Giants\" team-alias=\"SF\"/>\n" +
" <batter id=\"6966\" global-id=\"168575\" first-name=\"Marco\" last-name=\"Scutaro\" batting-slot=\"2\" end-base=\"1\"/>\n" +
" <pitcher id=\"7257\" global-id=\"202781\" first-name=\"Zack\" last-name=\"Greinke\"/>\n" +
" <pitch sequence=\"Strike,Foul,Ball,Ball,Ball,Foul,Foul,Foul,Ball\"/>\n" +
" <description text=\"M.Scutaro walked on a full count.\"/>\n" +
" </event-details>\n" +
" \n" +
" <baseball-mlb-boxscore-home-team-stats>\n" +
" <baseball-mlb-boxscore-team-stats>\n" +
" <at-bats at-bats=\"36\"/>\n" +
" <runs runs=\"3\"/>\n" +
" <hits hits=\"9\"/>\n" +
" <runs-batted-in runs-batted-in=\"3\"/>\n" +
" <total-bases total-bases=\"10\"/>\n" +
" <walks walks=\"2\"/>\n" +
" <strike-outs strike-outs=\"6\"/>\n" +
" <runners-left-on-base runners=\"9\"/>\n" +
" <double-plays number=\"2\"/>\n" +
" <triple-plays number=\"0\"/>\n" +
" <double-plays>\n" +
" <fielders>\n" +
" <fielder pos=\"C\" id=\"8373\" global-id=\"225850\" first-name=\"A.J.\" last-name=\"Ellis\"/>\n" +
" <fielder pos=\"SS\" id=\"6793\" global-id=\"75296\" first-name=\"Nick\" last-name=\"Punto\"/>\n" +
" </fielders>\n" +
" <description description=\"A.Ellis to Punto\"/>\n" +
" </double-plays>\n" +
" <double-plays>\n" +
" <fielders>\n" +
" <fielder pos=\"3B\" id=\"6698\" global-id=\"8757\" first-name=\"Juan\" last-name=\"Uribe\"/>\n" +
" <fielder pos=\"1B\" id=\"7054\" global-id=\"184104\" first-name=\"Adrian\" last-name=\"Gonzalez\"/>\n" +
" </fielders>\n" +
" <description description=\"Uribe to Ad.Gonzalez\"/>\n" +
" </double-plays>\n" +
" <passed-balls>\n" +
" <name first-name=\"Tim\" last-name=\"Federowicz\"/>\n" +
" <player-code id=\"9075\" global-id=\"454959\" uniform=\"18\"/>\n" +
" <game-total number=\"1\"/>\n" +
" </passed-balls>\n" +
" <total-innings total=\"7\"/>\n" +
" </baseball-mlb-boxscore-team-stats>\n" +
" </baseball-mlb-boxscore-home-team-stats>\n" +
" <baseball-mlb-boxscore-visiting-team-stats>\n" +
" <baseball-mlb-boxscore-team-stats>\n" +
" <at-bats at-bats=\"35\"/>\n" +
" <runs runs=\"2\"/>\n" +
" <hits hits=\"9\"/>\n" +
" <runs-batted-in runs-batted-in=\"2\"/>\n" +
" <total-bases total-bases=\"13\"/>\n" +
" <walks walks=\"5\"/>\n" +
" <strike-outs strike-outs=\"7\"/>\n" +
" <runners-left-on-base runners=\"9\"/>\n" +
" <double-plays number=\"0\"/>\n" +
" <triple-plays number=\"0\"/>\n" +
" <errors>\n" +
" <name first-name=\"Matt\" last-name=\"Cain\"/>\n" +
" <player-code id=\"7495\" global-id=\"202716\" uniform=\"18\"/>\n" +
" <game-total number=\"1\"/>\n" +
" <season-total number=\"1\"/>\n" +
" </errors>\n" +
" <total-innings total=\"7\"/>\n" +
" </baseball-mlb-boxscore-team-stats>\n" +
" </baseball-mlb-boxscore-visiting-team-stats>\n" +
" <baseball-mlb-boxscore-home-team-batting-lineup>\n" +
" </baseball-mlb-boxscore-home-team-batting-lineup>\n" +
"<baseball-mlb-boxscore-home-team-pitching-lineup>\n" +
"<baseball-mlb-boxscore-pitching-lineup>\n" +
"<name first-name=\"J.A.\" last-name=\"Happ\"/>\n" +
"<player-code id=\"8061\" global-id=\"253985\" uniform=\"48\"/>\n" +
"<throwing-hand hand=\"L\"/>\n" +
"<sequence number=\"1\"/>\n" +
"<wins number=\"4\"/>\n" +
"<losses number=\"5\"/>\n" +
"<saves saves=\"0\"/>\n" +
"<innings-pitched innings=\"0.2\" season=\"69.2\"/>\n" +
"<games-pitched games=\"15\" starts=\"15\"/>\n" +
"<hits hits=\"0\" season=\"68\"/>\n" +
"<runs runs=\"0\" season=\"44\"/>\n" +
"<earned-runs earned-runs=\"0\" season=\"39\"/>\n" +
"<home-runs-allowed home-runs=\"0\" season=\"7\"/>\n" +
"<walks walks=\"0\" season=\"36\"/>\n" +
"<strike-outs strike-outs=\"1\" season=\"56\"/>\n" +
"<pitch-count count=\"14\"/>\n" +
"<balls balls=\"4\"/>\n" +
"<strikes strikes=\"10\"/>\n" +
"<batters-faced batters-faced=\"2\" season=\"315\"/>\n" +
"<opponent-at-bats at-bats=\"2\" season=\"273\"/>\n" +
"<ground-balls number=\"0\" season=\"84\"/>\n" +
"<fly-balls number=\"1\" season=\"95\"/>\n" +
"<inherited-runners runners=\"0\"/>\n" +
"<inherited-stranded stranded=\"0\"/>\n" +
"<hit-batsmen number=\"0\" season=\"2\"/>\n" +
"<balks number=\"0\" season=\"0\"/>\n" +
"<wild-pitches number=\"0\" season=\"4\"/>\n" +
"<earned-run-average average=\"5.04\"/>\n" +
"<opponent-batting-average average=\".249\"/>\n" +
"<entered-game inning=\"1\"/>\n" +
"<doubles number=\"0\" season=\"15\"/>\n" +
"<triples number=\"0\" season=\"2\"/>\n" +
"<gidp number=\"0\" season=\"3\"/>\n" +
"<stolen-bases number=\"0\" season=\"9\"/>\n" +
"<pickoffs number=\"0\" season=\"0\"/>\n" +
"<walks-and-hits-per-inning average=\"1.51\"/>\n" +
"</baseball-mlb-boxscore-pitching-lineup>\n" +
"</baseball-mlb-boxscore-home-team-pitching-lineup>" +
"</MLB-event>\n";
// List<FantasyPointUpdateEvent> events = updateProcessor.process(statData);
//
// AthleteSportEventInfo athleteSportEventInfo1 = AthleteSportEventInfo.findByAthleteAndSportEvent(athlete1, sportEvent);
// try {
// TypeReference<List<Map<String, Object>>> typeReference = new TypeReference<List<Map<String, Object>>>() {};
// List<Map<String, Object>> data = mapper.readValue(athleteSportEventInfo1.getStats(), typeReference);
// assertTrue(data.get(0).get(JSON_FIELD_NAME).equals(GlobalConstants.SCORING_MLB_INNING_PITCHED_LABEL));
// assertTrue((Double) data.get(0).get(JSON_FIELD_AMOUNT) == 0.2);
// assertTrue((Double) data.get(0).get(JSON_FIELD_FPP) == 1.485);
// assertTrue(data.get(1).get(JSON_FIELD_NAME).equals(GlobalConstants.SCORING_MLB_STRIKEOUT_LABEL));
// assertTrue((Integer) data.get(1).get(JSON_FIELD_AMOUNT) == 1);
// assertTrue((Double) data.get(1).get(JSON_FIELD_FPP) == 2.0);
// assertTrue(data.get(2).get(JSON_FIELD_NAME).equals(GlobalConstants.SCORING_MLB_EARNED_RUN_LABEL));
// assertTrue((Integer) data.get(2).get(JSON_FIELD_AMOUNT) == 0);
// assertTrue((Double) data.get(2).get(JSON_FIELD_FPP) == 0.0);
// assertTrue(data.get(3).get(JSON_FIELD_NAME).equals(GlobalConstants.SCORING_MLB_PITCHER_HIT_LABEL));
// assertTrue((Integer) data.get(3).get(JSON_FIELD_AMOUNT) == 0);
// assertTrue((Double) data.get(3).get(JSON_FIELD_FPP) == 0.0);
// assertTrue(data.get(4).get(JSON_FIELD_NAME).equals(GlobalConstants.SCORING_MLB_PITCHER_WALK_LABEL));
// assertTrue((Integer) data.get(4).get(JSON_FIELD_AMOUNT) == 0);
// assertTrue((Double) data.get(4).get(JSON_FIELD_FPP) == 0.0);
// assertTrue(data.get(5).get(JSON_FIELD_NAME).equals(GlobalConstants.SCORING_MLB_PITCHER_HIT_BY_PITCH_LABEL));
// assertTrue((Integer) data.get(5).get(JSON_FIELD_AMOUNT) == 0);
// assertTrue((Double) data.get(5).get(JSON_FIELD_FPP) == 0.0);
//
//// TypeReference<List<Map<String, Object>>> typeReference = new TypeReference<List<Map<String, Object>>>() {};
// List<Map<String, Object>> timelineData = mapper.readValue(athleteSportEventInfo1.getTimeline(), typeReference);
//// assertTrue(athleteSportEventInfo1.timeline.equals("[\"+3.4850 - M.Scutaro walked on a full count.\"]"));
// assertTrue(timelineData.size() == 1);
// assertTrue(!timelineData.get(0).get("timestamp").equals(""));
// assertTrue(timelineData.get(0).get("description").equals("M.Scutaro walked on a full count."));
// assertTrue(timelineData.get(0).get("fpChange").equals("+3.4850"));
// assertTrue((Integer) timelineData.get(0).get("athleteSportEventInfoId") == athleteSportEventInfo1.getId());
// } catch (IOException e) {
// fail(e.getMessage());
// }
//
// SportEvent updatedSportEvent = SportEvent.findByStatsId(sportEvent.getStatProviderId());
// assertTrue(String.format("unitsRemaining is %s, expected 2", updatedSportEvent.getUnitsRemaining()), updatedSportEvent.getUnitsRemaining() == 2);
//
// assertTrue(events.size() == 1);
// assertTrue(events.get(0).getAthleteId() == 253985
// && events.get(0).getFantasyPoints().doubleValue() == 3.485
// && events.get(0).getLatestDelta().doubleValue() == 3.485
// && events.get(0).getHomeScore() == 2
// && events.get(0).getAwayScore() == 1);
fail("Re-evaluate");
}
@Test
public void testProcessMessage_LineupChange() {
startHazelcast();
athlete1 = new Athlete(253985, "JA", "Happ", team, "1");
Ebean.save(athlete1);
sportEvent = new SportEvent(1284165, League.MLB, new Date(), "test", "test", 9, false, 2014, -1, 1);
sportEvent.setTeams(teams);
Ebean.save(sportEvent);
athleteSportEventInfo = new AthleteSportEventInfo(sportEvent, athlete1, new BigDecimal("0.00"), "{}", "[]");
Ebean.save(athleteSportEventInfo);
String statData = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
"<MLB-event>\n" +
" <gamecode code=\"330912119\" global-id=\"1284165\"/>\n" +
" <gamestate>\n" +
" <game status=\"Final\" status-id=\"2\" reason=\"\" inning=\"7\" balls=\"\" strikes=\"\" outs=\"\" segment-number=\"7\" segment-division=\"0\" active-state=\"false\" restart=\"false\" pitch-sequence=\"\"/>\n" +
" <batter id=\"\" global-id=\"\" first-name=\"\" last-name=\"\" batting-slot=\"\"/>\n" +
" <pitcher id=\"\" global-id=\"\" first-name=\"\" last-name=\"\"/>\n" +
" </gamestate>\n" +
" <double-header double-header=\"false\"/>\n" +
" <double-header-game-number number=\"0\"/>\n" +
" <gametype id=\"1\" type=\"Regular Season\"/>\n" +
" <league id=\"2\" league=\"NL\"/>\n" +
" <stadium name=\"Dodger Stadium\" city=\"Los Angeles\" state=\"California\"/>\n" +
" <event-details>\n" +
" <event sequence=\"1\" id=\"1\" code=\"96\" name=\"Lineup Change\" balls=\"0\" strikes=\"0\" outs-bef=\"0\" outs-aft=\"0\" rbi=\"0\" segment-number=\"\" segment-division=\"\" dir=\"\" dist=\"\" bat-type=\"\" scored=\"false\" base-sit-bef=\"0\" base-sit-aft=\"0\" vis-score=\"0\" home-score=\"0\" team-id=\"3\" team-global-id=\"0\" team-city=\"Los Angeles\" team-name=\"Angels\" team-alias=\"LAA\"/>\n" +
" <player id=\"8968\" global-id=\"390597\" first-name=\"Collin\" last-name=\"Cowgill\" batting-slot=\"1\" pos-id=\"8\" pos-name=\"CF\"/>\n" +
" <pitch sequence=\"\"/>\n" +
" <description text=\"\"/>\n" +
" </event-details>" +
" <baseball-mlb-boxscore-home-team-stats>\n" +
" <baseball-mlb-boxscore-team-stats>\n" +
" <at-bats at-bats=\"36\"/>\n" +
" <runs runs=\"3\"/>\n" +
" <hits hits=\"9\"/>\n" +
" <runs-batted-in runs-batted-in=\"3\"/>\n" +
" <total-bases total-bases=\"10\"/>\n" +
" <walks walks=\"2\"/>\n" +
" <strike-outs strike-outs=\"6\"/>\n" +
" <runners-left-on-base runners=\"9\"/>\n" +
" <double-plays number=\"2\"/>\n" +
" <triple-plays number=\"0\"/>\n" +
" <double-plays>\n" +
" <fielders>\n" +
" <fielder pos=\"C\" id=\"8373\" global-id=\"225850\" first-name=\"A.J.\" last-name=\"Ellis\"/>\n" +
" <fielder pos=\"SS\" id=\"6793\" global-id=\"75296\" first-name=\"Nick\" last-name=\"Punto\"/>\n" +
" </fielders>\n" +
" <description description=\"A.Ellis to Punto\"/>\n" +
" </double-plays>\n" +
" <double-plays>\n" +
" <fielders>\n" +
" <fielder pos=\"3B\" id=\"6698\" global-id=\"8757\" first-name=\"Juan\" last-name=\"Uribe\"/>\n" +
" <fielder pos=\"1B\" id=\"7054\" global-id=\"184104\" first-name=\"Adrian\" last-name=\"Gonzalez\"/>\n" +
" </fielders>\n" +
" <description description=\"Uribe to Ad.Gonzalez\"/>\n" +
" </double-plays>\n" +
" <passed-balls>\n" +
" <name first-name=\"Tim\" last-name=\"Federowicz\"/>\n" +
" <player-code id=\"9075\" global-id=\"454959\" uniform=\"18\"/>\n" +
" <game-total number=\"1\"/>\n" +
" </passed-balls>\n" +
" <total-innings total=\"7\"/>\n" +
" </baseball-mlb-boxscore-team-stats>\n" +
" </baseball-mlb-boxscore-home-team-stats>\n" +
" <baseball-mlb-boxscore-visiting-team-stats>\n" +
" <baseball-mlb-boxscore-team-stats>\n" +
" <at-bats at-bats=\"35\"/>\n" +
" <runs runs=\"2\"/>\n" +
" <hits hits=\"9\"/>\n" +
" <runs-batted-in runs-batted-in=\"2\"/>\n" +
" <total-bases total-bases=\"13\"/>\n" +
" <walks walks=\"5\"/>\n" +
" <strike-outs strike-outs=\"7\"/>\n" +
" <runners-left-on-base runners=\"9\"/>\n" +
" <double-plays number=\"0\"/>\n" +
" <triple-plays number=\"0\"/>\n" +
" <errors>\n" +
" <name first-name=\"Matt\" last-name=\"Cain\"/>\n" +
" <player-code id=\"7495\" global-id=\"202716\" uniform=\"18\"/>\n" +
" <game-total number=\"1\"/>\n" +
" <season-total number=\"1\"/>\n" +
" </errors>\n" +
" <total-innings total=\"7\"/>\n" +
" </baseball-mlb-boxscore-team-stats>\n" +
" </baseball-mlb-boxscore-visiting-team-stats>\n" +
" <baseball-mlb-boxscore-home-team-batting-lineup>\n" +
" </baseball-mlb-boxscore-home-team-batting-lineup>\n" +
"<baseball-mlb-boxscore-home-team-pitching-lineup>\n" +
"<baseball-mlb-boxscore-pitching-lineup>\n" +
"<name first-name=\"J.A.\" last-name=\"Happ\"/>\n" +
"<player-code id=\"8061\" global-id=\"253985\" uniform=\"48\"/>\n" +
"<throwing-hand hand=\"L\"/>\n" +
"<sequence number=\"1\"/>\n" +
"<wins number=\"4\"/>\n" +
"<losses number=\"5\"/>\n" +
"<saves saves=\"0\"/>\n" +
"<innings-pitched innings=\"0.2\" season=\"69.2\"/>\n" +
"<games-pitched games=\"15\" starts=\"15\"/>\n" +
"<hits hits=\"0\" season=\"68\"/>\n" +
"<runs runs=\"0\" season=\"44\"/>\n" +
"<earned-runs earned-runs=\"0\" season=\"39\"/>\n" +
"<home-runs-allowed home-runs=\"0\" season=\"7\"/>\n" +
"<walks walks=\"0\" season=\"36\"/>\n" +
"<strike-outs strike-outs=\"1\" season=\"56\"/>\n" +
"<pitch-count count=\"14\"/>\n" +
"<balls balls=\"4\"/>\n" +
"<strikes strikes=\"10\"/>\n" +
"<batters-faced batters-faced=\"2\" season=\"315\"/>\n" +
"<opponent-at-bats at-bats=\"2\" season=\"273\"/>\n" +
"<ground-balls number=\"0\" season=\"84\"/>\n" +
"<fly-balls number=\"1\" season=\"95\"/>\n" +
"<inherited-runners runners=\"0\"/>\n" +
"<inherited-stranded stranded=\"0\"/>\n" +
"<hit-batsmen number=\"0\" season=\"2\"/>\n" +
"<balks number=\"0\" season=\"0\"/>\n" +
"<wild-pitches number=\"0\" season=\"4\"/>\n" +
"<earned-run-average average=\"5.04\"/>\n" +
"<opponent-batting-average average=\".249\"/>\n" +
"<entered-game inning=\"1\"/>\n" +
"<doubles number=\"0\" season=\"15\"/>\n" +
"<triples number=\"0\" season=\"2\"/>\n" +
"<gidp number=\"0\" season=\"3\"/>\n" +
"<stolen-bases number=\"0\" season=\"9\"/>\n" +
"<pickoffs number=\"0\" season=\"0\"/>\n" +
"<walks-and-hits-per-inning average=\"1.51\"/>\n" +
"</baseball-mlb-boxscore-pitching-lineup>\n" +
"</baseball-mlb-boxscore-home-team-pitching-lineup>" +
"</MLB-event>\n";
// List<FantasyPointUpdateEvent> events = updateProcessor.process(statData);
//
// assertTrue(events.isEmpty());
fail("Re-evaluate");
}
@Test
public void testProcessMessage_FinalBoxScore() {
startHazelcast();
athlete1 = new Athlete(253985, "JA", "Happ", team, "1");
Ebean.save(athlete1);
sportEvent = new SportEvent(1284165, League.MLB, new Date(), "test", "test", 9, false, 2014, -1, 1);
sportEvent.setTeams(teams);
Ebean.save(sportEvent);
athleteSportEventInfo = new AthleteSportEventInfo(sportEvent, athlete1, new BigDecimal("0.00"), "{}", "[]");
Ebean.save(athleteSportEventInfo);
String statData = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
"<MLB-event>\n" +
" <gamecode code=\"330912119\" global-id=\"1284165\"/>\n" +
" <gamestate>\n" +
" <game status=\"Final\" status-id=\"2\" reason=\"\" inning=\"9\" balls=\"\" strikes=\"\" outs=\"\" segment-number=\"9\" segment-division=\"0\" active-state=\"false\" restart=\"false\" pitch-sequence=\"\"/>\n" +
" <batter id=\"\" global-id=\"\" first-name=\"\" last-name=\"\" batting-slot=\"\"/>\n" +
" <pitcher id=\"\" global-id=\"\" first-name=\"\" last-name=\"\"/>\n" +
" </gamestate>" +
" <double-header double-header=\"false\"/>\n" +
" <double-header-game-number number=\"0\"/>\n" +
" <gametype id=\"1\" type=\"Regular Season\"/>\n" +
" <league id=\"2\" league=\"NL\"/>\n" +
" <stadium name=\"Dodger Stadium\" city=\"Los Angeles\" state=\"California\"/>\n" +
" <event-details>\n" +
" <event sequence=\"1\" id=\"1\" code=\"96\" name=\"Lineup Change\" balls=\"0\" strikes=\"0\" outs-bef=\"0\" outs-aft=\"0\" rbi=\"0\" segment-number=\"\" segment-division=\"\" dir=\"\" dist=\"\" bat-type=\"\" scored=\"false\" base-sit-bef=\"0\" base-sit-aft=\"0\" vis-score=\"0\" home-score=\"0\" team-id=\"3\" team-global-id=\"0\" team-city=\"Los Angeles\" team-name=\"Angels\" team-alias=\"LAA\"/>\n" +
" <player id=\"8968\" global-id=\"390597\" first-name=\"Collin\" last-name=\"Cowgill\" batting-slot=\"1\" pos-id=\"8\" pos-name=\"CF\"/>\n" +
" <pitch sequence=\"\"/>\n" +
" <description text=\"\"/>\n" +
" </event-details>" +
" <baseball-mlb-boxscore-home-team-stats>\n" +
" <baseball-mlb-boxscore-team-stats>\n" +
" <at-bats at-bats=\"36\"/>\n" +
" <runs runs=\"3\"/>\n" +
" <hits hits=\"9\"/>\n" +
" <runs-batted-in runs-batted-in=\"3\"/>\n" +
" <total-bases total-bases=\"10\"/>\n" +
" <walks walks=\"2\"/>\n" +
" <strike-outs strike-outs=\"6\"/>\n" +
" <runners-left-on-base runners=\"9\"/>\n" +
" <double-plays number=\"2\"/>\n" +
" <triple-plays number=\"0\"/>\n" +
" <double-plays>\n" +
" <fielders>\n" +
" <fielder pos=\"C\" id=\"8373\" global-id=\"225850\" first-name=\"A.J.\" last-name=\"Ellis\"/>\n" +
" <fielder pos=\"SS\" id=\"6793\" global-id=\"75296\" first-name=\"Nick\" last-name=\"Punto\"/>\n" +
" </fielders>\n" +
" <description description=\"A.Ellis to Punto\"/>\n" +
" </double-plays>\n" +
" <double-plays>\n" +
" <fielders>\n" +
" <fielder pos=\"3B\" id=\"6698\" global-id=\"8757\" first-name=\"Juan\" last-name=\"Uribe\"/>\n" +
" <fielder pos=\"1B\" id=\"7054\" global-id=\"184104\" first-name=\"Adrian\" last-name=\"Gonzalez\"/>\n" +
" </fielders>\n" +
" <description description=\"Uribe to Ad.Gonzalez\"/>\n" +
" </double-plays>\n" +
" <passed-balls>\n" +
" <name first-name=\"Tim\" last-name=\"Federowicz\"/>\n" +
" <player-code id=\"9075\" global-id=\"454959\" uniform=\"18\"/>\n" +
" <game-total number=\"1\"/>\n" +
" </passed-balls>\n" +
" <total-innings total=\"7\"/>\n" +
" </baseball-mlb-boxscore-team-stats>\n" +
" </baseball-mlb-boxscore-home-team-stats>\n" +
" <baseball-mlb-boxscore-visiting-team-stats>\n" +
" <baseball-mlb-boxscore-team-stats>\n" +
" <at-bats at-bats=\"35\"/>\n" +
" <runs runs=\"2\"/>\n" +
" <hits hits=\"9\"/>\n" +
" <runs-batted-in runs-batted-in=\"2\"/>\n" +
" <total-bases total-bases=\"13\"/>\n" +
" <walks walks=\"5\"/>\n" +
" <strike-outs strike-outs=\"7\"/>\n" +
" <runners-left-on-base runners=\"9\"/>\n" +
" <double-plays number=\"0\"/>\n" +
" <triple-plays number=\"0\"/>\n" +
" <errors>\n" +
" <name first-name=\"Matt\" last-name=\"Cain\"/>\n" +
" <player-code id=\"7495\" global-id=\"202716\" uniform=\"18\"/>\n" +
" <game-total number=\"1\"/>\n" +
" <season-total number=\"1\"/>\n" +
" </errors>\n" +
" <total-innings total=\"7\"/>\n" +
" </baseball-mlb-boxscore-team-stats>\n" +
" </baseball-mlb-boxscore-visiting-team-stats>\n" +
" <baseball-mlb-boxscore-home-team-batting-lineup>\n" +
" </baseball-mlb-boxscore-home-team-batting-lineup>\n" +
"<baseball-mlb-boxscore-home-team-pitching-lineup>\n" +
"<baseball-mlb-boxscore-pitching-lineup>\n" +
"<name first-name=\"J.A.\" last-name=\"Happ\"/>\n" +
"<player-code id=\"8061\" global-id=\"253985\" uniform=\"48\"/>\n" +
"<throwing-hand hand=\"L\"/>\n" +
"<sequence number=\"1\"/>\n" +
"<wins number=\"4\"/>\n" +
"<losses number=\"5\"/>\n" +
"<saves saves=\"0\"/>\n" +
"<innings-pitched innings=\"0.2\" season=\"69.2\"/>\n" +
"<games-pitched games=\"15\" starts=\"15\"/>\n" +
"<hits hits=\"0\" season=\"68\"/>\n" +
"<runs runs=\"0\" season=\"44\"/>\n" +
"<earned-runs earned-runs=\"0\" season=\"39\"/>\n" +
"<home-runs-allowed home-runs=\"0\" season=\"7\"/>\n" +
"<walks walks=\"0\" season=\"36\"/>\n" +
"<strike-outs strike-outs=\"1\" season=\"56\"/>\n" +
"<pitch-count count=\"14\"/>\n" +
"<balls balls=\"4\"/>\n" +
"<strikes strikes=\"10\"/>\n" +
"<batters-faced batters-faced=\"2\" season=\"315\"/>\n" +
"<opponent-at-bats at-bats=\"2\" season=\"273\"/>\n" +
"<ground-balls number=\"0\" season=\"84\"/>\n" +
"<fly-balls number=\"1\" season=\"95\"/>\n" +
"<inherited-runners runners=\"0\"/>\n" +
"<inherited-stranded stranded=\"0\"/>\n" +
"<hit-batsmen number=\"0\" season=\"2\"/>\n" +
"<balks number=\"0\" season=\"0\"/>\n" +
"<wild-pitches number=\"0\" season=\"4\"/>\n" +
"<earned-run-average average=\"5.04\"/>\n" +
"<opponent-batting-average average=\".249\"/>\n" +
"<entered-game inning=\"1\"/>\n" +
"<doubles number=\"0\" season=\"15\"/>\n" +
"<triples number=\"0\" season=\"2\"/>\n" +
"<gidp number=\"0\" season=\"3\"/>\n" +
"<stolen-bases number=\"0\" season=\"9\"/>\n" +
"<pickoffs number=\"0\" season=\"0\"/>\n" +
"<walks-and-hits-per-inning average=\"1.51\"/>\n" +
"</baseball-mlb-boxscore-pitching-lineup>\n" +
"</baseball-mlb-boxscore-home-team-pitching-lineup>" +
"</MLB-event>\n";
// List<FantasyPointUpdateEvent> events = updateProcessor.process(statData);
//
// SportEvent updatedSportEvent = SportEvent.findByStatsId(1284165);
// assertTrue(updatedSportEvent.isComplete());
//
// assertTrue(events.isEmpty());
fail("Re-evaluate");
}
@Test
public void testShouldProcessMessage_RosterMessage() {
DocumentBuilder documentBuilder;
try {
String statData = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
"<MLB-event>\n" +
" <gamecode code=\"330912119\" global-id=\"1284165\"/>\n" +
" <gamestate>\n" +
" <game status=\"Pre-Game\" status-id=\"0\" reason=\"\" inning=\"9\" balls=\"\" strikes=\"\" outs=\"\" segment-number=\"9\" segment-division=\"0\" active-state=\"false\" restart=\"false\" pitch-sequence=\"\"/>\n" +
" <batter id=\"\" global-id=\"\" first-name=\"\" last-name=\"\" batting-slot=\"\"/>\n" +
" <pitcher id=\"\" global-id=\"\" first-name=\"\" last-name=\"\"/>\n" +
" </gamestate>" +
" <double-header double-header=\"false\"/>\n" +
" <double-header-game-number number=\"0\"/>\n" +
" <gametype id=\"1\" type=\"Regular Season\"/>\n" +
" <league id=\"2\" league=\"NL\"/>\n" +
" <stadium name=\"Dodger Stadium\" city=\"Los Angeles\" state=\"California\"/>\n" +
"</MLB-event>\n";
InputSource source = new InputSource(new StringReader(statData));
documentBuilder = dbFactory.newDocumentBuilder();
Document doc = documentBuilder.parse(source);
assertTrue(!updateProcessor.shouldProcessMessage(doc));
}
catch(Exception e) {
fail(e.getMessage());
}
}
// @Test
public void testShouldProcessMessage_LineupMessage() {
DocumentBuilder documentBuilder;
try {
String statData = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
"<MLB-event>\n" +
" <gamecode code=\"330912119\" global-id=\"1284165\"/>\n" +
" <gamestate>\n" +
" <game status=\"Pre-Game\" status-id=\"0\" reason=\"\" inning=\"9\" balls=\"\" strikes=\"\" outs=\"\" segment-number=\"9\" segment-division=\"0\" active-state=\"false\" restart=\"false\" pitch-sequence=\"\"/>\n" +
" <batter id=\"\" global-id=\"\" first-name=\"\" last-name=\"\" batting-slot=\"\"/>\n" +
" <pitcher id=\"\" global-id=\"\" first-name=\"\" last-name=\"\"/>\n" +
" </gamestate>" +
" <double-header double-header=\"false\"/>\n" +
" <double-header-game-number number=\"0\"/>\n" +
" <gametype id=\"1\" type=\"Regular Season\"/>\n" +
" <league id=\"2\" league=\"NL\"/>\n" +
" <stadium name=\"Dodger Stadium\" city=\"Los Angeles\" state=\"California\"/>\n" +
" <event-details>\n" +
" <event sequence=\"16\" id=\"1\" code=\"97\" name=\"Lineup Change\" balls=\"0\" strikes=\"0\" outs-bef=\"0\" outs-aft=\"0\" rbi=\"0\" segment-number=\"\" segment-division=\"\" dir=\"\" dist=\"\" bat-type=\"\" scored=\"false\" base-sit-bef=\"0\" base-sit-aft=\"0\" vis-score=\"0\" home-score=\"0\" team-id=\"14\" team-global-id=\"0\" team-city=\"Toronto\" team-name=\"Blue Jays\" team-alias=\"Tor\"/>\n" +
" <player id=\"7835\" global-id=\"201169\" first-name=\"Rajai\" last-name=\"Davis\" batting-slot=\"6\" pos-id=\"10\" pos-name=\"DH\"/>\n" +
" <pitch sequence=\"\"/>\n" +
" <description text=\"\"/>\n" +
" </event-details>" +
"</MLB-event>\n";
InputSource source = new InputSource(new StringReader(statData));
documentBuilder = dbFactory.newDocumentBuilder();
Document doc = documentBuilder.parse(source);
assertTrue(!updateProcessor.shouldProcessMessage(doc));
}
catch(Exception e) {
fail(e.getMessage());
}
}
// @Test
public void testShouldProcessMessage_SinglePitchMessage() {
DocumentBuilder documentBuilder;
try {
String statData = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
"<MLB-event>\n" +
" <gamecode code=\"330912119\" global-id=\"1284165\"/>\n" +
" <gamestate>\n" +
" <game status=\"In-Progress\" status-id=\"2\" reason=\"\" inning=\"9\" balls=\"\" strikes=\"\" outs=\"\" segment-number=\"9\" segment-division=\"0\" active-state=\"false\" restart=\"false\" pitch-sequence=\"\"/>\n" +
" <batter id=\"\" global-id=\"\" first-name=\"\" last-name=\"\" batting-slot=\"\"/>\n" +
" <pitcher id=\"\" global-id=\"\" first-name=\"\" last-name=\"\"/>\n" +
" </gamestate>" +
" <double-header double-header=\"false\"/>\n" +
" <double-header-game-number number=\"0\"/>\n" +
" <gametype id=\"1\" type=\"Regular Season\"/>\n" +
" <league id=\"2\" league=\"NL\"/>\n" +
" <stadium name=\"Dodger Stadium\" city=\"Los Angeles\" state=\"California\"/>\n" +
" <event-details>\n" +
" <event sequence=\"1\" id=\"9\" code=\"96\" name=\"Pitches Only\" balls=\"0\" strikes=\"0\" outs-bef=\"0\" outs-aft=\"0\" rbi=\"0\" segment-number=\"\" segment-division=\"\" dir=\"\" dist=\"\" bat-type=\"\" scored=\"false\" base-sit-bef=\"0\" base-sit-aft=\"0\" vis-score=\"0\" home-score=\"0\" team-id=\"3\" team-global-id=\"0\" team-city=\"Los Angeles\" team-name=\"Angels\" team-alias=\"LAA\"/>\n" +
" <player id=\"8968\" global-id=\"390597\" first-name=\"Collin\" last-name=\"Cowgill\" batting-slot=\"1\" pos-id=\"8\" pos-name=\"CF\"/>\n" +
" <pitch sequence=\"\"/>\n" +
" <description text=\"\"/>\n" +
" </event-details>" +
"</MLB-event>\n";
InputSource source = new InputSource(new StringReader(statData));
documentBuilder = dbFactory.newDocumentBuilder();
Document doc = documentBuilder.parse(source);
assertTrue(!updateProcessor.shouldProcessMessage(doc));
}
catch(Exception e) {
fail(e.getMessage());
}
}
// @Test
public void testShouldProcessMessage_GameEventMessage() {
DocumentBuilder documentBuilder;
try {
String statData = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
"<MLB-event>\n" +
" <gamecode code=\"330912119\" global-id=\"1284165\"/>\n" +
" <gamestate>\n" +
" <game status=\"Final\" status-id=\"2\" reason=\"\" inning=\"9\" balls=\"\" strikes=\"\" outs=\"\" segment-number=\"9\" segment-division=\"0\" active-state=\"false\" restart=\"false\" pitch-sequence=\"\"/>\n" +
" <batter id=\"\" global-id=\"\" first-name=\"\" last-name=\"\" batting-slot=\"\"/>\n" +
" <pitcher id=\"\" global-id=\"\" first-name=\"\" last-name=\"\"/>\n" +
" </gamestate>" +
" <double-header double-header=\"false\"/>\n" +
" <double-header-game-number number=\"0\"/>\n" +
" <gametype id=\"1\" type=\"Regular Season\"/>\n" +
" <league id=\"2\" league=\"NL\"/>\n" +
" <stadium name=\"Dodger Stadium\" city=\"Los Angeles\" state=\"California\"/>\n" +
" <event-details>\n" +
" <event sequence=\"1\" id=\"1\" code=\"96\" name=\"Lineup Change\" balls=\"0\" strikes=\"0\" outs-bef=\"0\" outs-aft=\"0\" rbi=\"0\" segment-number=\"\" segment-division=\"\" dir=\"\" dist=\"\" bat-type=\"\" scored=\"false\" base-sit-bef=\"0\" base-sit-aft=\"0\" vis-score=\"0\" home-score=\"0\" team-id=\"3\" team-global-id=\"0\" team-city=\"Los Angeles\" team-name=\"Angels\" team-alias=\"LAA\"/>\n" +
" <player id=\"8968\" global-id=\"390597\" first-name=\"Collin\" last-name=\"Cowgill\" batting-slot=\"1\" pos-id=\"8\" pos-name=\"CF\"/>\n" +
" <pitch sequence=\"\"/>\n" +
" <description text=\"\"/>\n" +
" </event-details>" +
"</MLB-event>\n";
InputSource source = new InputSource(new StringReader(statData));
documentBuilder = dbFactory.newDocumentBuilder();
Document doc = documentBuilder.parse(source);
assertTrue(updateProcessor.shouldProcessMessage(doc));
}
catch(Exception e) {
fail(e.getMessage());
}
}
// @Test
public void testShouldProcessMessage_FinalBoxScoreMessage() {
DocumentBuilder documentBuilder;
try {
String statData = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
"<MLB-event>\n" +
" <gamecode code=\"330912119\" global-id=\"1284165\"/>\n" +
" <gamestate>\n" +
" <game status=\"Final\" status-id=\"2\" reason=\"\" inning=\"9\" balls=\"\" strikes=\"\" outs=\"\" segment-number=\"9\" segment-division=\"0\" active-state=\"false\" restart=\"false\" pitch-sequence=\"\"/>\n" +
" <batter id=\"\" global-id=\"\" first-name=\"\" last-name=\"\" batting-slot=\"\"/>\n" +
" <pitcher id=\"\" global-id=\"\" first-name=\"\" last-name=\"\"/>\n" +
" </gamestate>" +
" <double-header double-header=\"false\"/>\n" +
" <double-header-game-number number=\"0\"/>\n" +
" <gametype id=\"1\" type=\"Regular Season\"/>\n" +
" <league id=\"2\" league=\"NL\"/>\n" +
" <stadium name=\"Dodger Stadium\" city=\"Los Angeles\" state=\"California\"/>\n" +
" <event-details>\n" +
" <event sequence=\"1\" id=\"1\" code=\"96\" name=\"Lineup Change\" balls=\"0\" strikes=\"0\" outs-bef=\"0\" outs-aft=\"0\" rbi=\"0\" segment-number=\"\" segment-division=\"\" dir=\"\" dist=\"\" bat-type=\"\" scored=\"false\" base-sit-bef=\"0\" base-sit-aft=\"0\" vis-score=\"0\" home-score=\"0\" team-id=\"3\" team-global-id=\"0\" team-city=\"Los Angeles\" team-name=\"Angels\" team-alias=\"LAA\"/>\n" +
" <player id=\"8968\" global-id=\"390597\" first-name=\"Collin\" last-name=\"Cowgill\" batting-slot=\"1\" pos-id=\"8\" pos-name=\"CF\"/>\n" +
" <pitch sequence=\"\"/>\n" +
" <description text=\"\"/>\n" +
" </event-details>" +
"</MLB-event>\n";
InputSource source = new InputSource(new StringReader(statData));
documentBuilder = dbFactory.newDocumentBuilder();
Document doc = documentBuilder.parse(source);
assertTrue(updateProcessor.shouldProcessMessage(doc));
}
catch(Exception e) {
fail(e.getMessage());
}
}
}
| true
|
dd909d18aa134366fbad4ad5104e7da52afa2e53
|
Java
|
weileng11/BeautifulApp-master
|
/app/src/main/java/com/jogger/beautifulapp/function/model/FindNiceFriendModel.java
|
UTF-8
| 554
| 2.015625
| 2
|
[] |
no_license
|
package com.jogger.beautifulapp.function.model;
import com.jogger.beautifulapp.entity.AppNiceFriendData;
import com.jogger.beautifulapp.function.contract.FindNiceFriendContract;
import com.jogger.beautifulapp.http.HttpAction;
import com.jogger.beautifulapp.http.listener.OnHttpRequestListener;
public class FindNiceFriendModel implements FindNiceFriendContract.Model {
@Override
public void getFindNiceFriendDatas(OnHttpRequestListener<AppNiceFriendData> listener) {
HttpAction.getHttpAction().getFindNiceFriendDatas(listener);
}
}
| true
|
5c3d228154e80ba5cc20d6326b54d1c848e035cb
|
Java
|
JaydeepJK/JEditText
|
/src/main/java/com/jay/jedittext/JEditText.java
|
UTF-8
| 8,536
| 1.945313
| 2
|
[] |
no_license
|
package com.jay.jedittext;
import android.content.Context;
import android.content.res.TypedArray;
import android.os.Vibrator;
import android.speech.tts.TextToSpeech;
import android.text.Editable;
import android.text.InputType;
import android.text.TextWatcher;
import android.text.method.PasswordTransformationMethod;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.TextView;
import java.util.Locale;
public class JEditText extends FrameLayout implements OnTouchListener
{
private EditText m_etText;
private TextView m_tvErrorText;
private long m_vibrationPattern[] = { 0, 100 };
public Vibrator m_vibrator;
private Context m_context;
private Animation shake;
private static TextToSpeech tts;
private boolean mEnableTTS = false;
private boolean mEnableShakeAnimation = false;
// public CustomEditText(Context p_context, AttributeSet p_set)
// {
// super(p_context, p_set);
// }
public static TextToSpeech getTts() {
return tts;
}
public static void setTts(TextToSpeech tts) {
JEditText.tts = tts;
}
public JEditText(Context p_context, AttributeSet p_set)
{
super(p_context, p_set);
LayoutInflater m_inflater = LayoutInflater.from(p_context);
FrameLayout m_rlMainContainer = (FrameLayout) m_inflater.inflate(R.layout.error_edittext_layout, this, true);
m_context = p_context;
m_etText = (EditText) m_rlMainContainer.findViewById(R.id.eel_etEdittext);
m_tvErrorText = (TextView) m_rlMainContainer.findViewById(R.id.eel_tvErrorMessage);
//If TTS is not initialized, then initialize it
if(getTts() == null)
{
try
{
tts = new TextToSpeech(p_context,new TextToSpeech.OnInitListener() {
@Override
public void onInit(int status)
{
if(status != TextToSpeech.ERROR)
{
tts.setLanguage(Locale.UK);
Log.e("In constructor","TTS initialized");
}
}
});
setTts(tts);
}
catch (Throwable e)
{
e.printStackTrace();
}
}
else
{
Log.e("In constructor","getTts() is null");
}
// m_etText.setRawInputType(InputType.TYPE_TEXT_VARIATION_PASSWORD);
m_tvErrorText.setOnTouchListener(this);
// // This parses the attributeSet and filters out to the stuff we care about
// TypedArray typedArray = p_context.obtainStyledAttributes(R.styleable.custom_edittext);
// // Now we read let's say an int into our custom member variable.
// int attr = typedArray.getInt(R.styleable.myCustomComponents_myCustomAttribute, 0);
// // Make a public mutator so that others can set this attribute programatically
// setCustomAttribute(attr);
// // Remember to recycle the TypedArray (saved memory)
// typedArray.recycle();
// TypedArray m_attr = p_context.obtainStyledAttributes(p_set, R.styleable.custom_edittext, p_defStyle, 0);
TypedArray m_attr = p_context.obtainStyledAttributes(p_set, R.styleable.custom_edittext);
// String str = a.getString(R.styleable.custom_edittext_inputtype);
// int attr = m_attr.getInt(R.styleable.custom_edittext_inputtype, 0);
if (p_set != null)
{
TypedArray a = getContext().obtainStyledAttributes(p_set, R.styleable.custom_edittext, 0, 0);
// setHint(a.getString(index));
setDefaultInputType(a.getInt(R.styleable.custom_edittext_inputtype, 0x7f010094));
a.recycle();
}
final int m_count = m_attr.getIndexCount();
for (int i = 0; i < m_count; ++i)
{
int attr = m_attr.getIndex(i);
if(attr == R.styleable.custom_edittext_inputtype)
{
if (p_context.isRestricted())
{
throw new IllegalStateException("The " + getClass().getCanonicalName() + ":required attribute cannot " + "be used within a restricted context");
}
int m_defaultValue = 0;
final int m_required = m_attr.getInteger(0, m_defaultValue);
// DO SOMETHING
setDefaultInputType(m_required);
}
else if(attr == R.styleable.custom_edittext_hint)
{
String m_hint = "";
m_hint = m_attr.getString(1);
setHint(m_hint);
}
else if(attr == R.styleable.custom_edittext_enabletts)
{
mEnableTTS = m_attr.getBoolean(2,false);
}
else if(attr == R.styleable.custom_edittext_enableshakeanimation)
{
mEnableShakeAnimation = m_attr.getBoolean(3,false);
}
}
m_attr.recycle();
m_etText.addTextChangedListener(new TextWatcher()
{
@Override
public void onTextChanged(CharSequence p_s, int p_start, int p_before, int p_count)
{
if (p_s.length() > 0)
{
m_etText.setVisibility(View.VISIBLE);
m_tvErrorText.setVisibility(View.GONE);
}
}
@Override
public void beforeTextChanged(CharSequence p_s, int p_start, int p_count, int p_after)
{
}
@Override
public void afterTextChanged(Editable p_s)
{
}
});
}
/**
* Method to set the default inputtype of the edittext
*
* @param p_type
* The inputtype of the edittext
*/
public void setDefaultInputType(final int p_type)
{
if (p_type == Constants.TEXT)
{
m_etText.setInputType(InputType.TYPE_TEXT_VARIATION_NORMAL);
}
if (p_type == Constants.EMAIL_ADDRESS)
{
m_etText.setInputType(InputType.TYPE_TEXT_VARIATION_EMAIL_ADDRESS);
}
if (p_type == Constants.PASSWORD)
{
m_etText.setInputType(InputType.TYPE_TEXT_VARIATION_PASSWORD);
m_etText.setTransformationMethod(PasswordTransformationMethod.getInstance());
}
if (p_type == Constants.NUMBER)
{
m_etText.setInputType(InputType.TYPE_NUMBER_FLAG_DECIMAL);
}
if (p_type == Constants.PHONE)
{
m_etText.setInputType(InputType.TYPE_TEXT_VARIATION_PHONETIC);
}
}
/**
* Method to set hint in the Edittext
*
* @param p_hintMessage
* The hint message
*/
public void setHint(String p_hintMessage)
{
m_etText.setHint(p_hintMessage);
}
@Override
public boolean onTouch(View p_v, MotionEvent p_event)
{
if(p_v.getId() == R.id.eel_tvErrorMessage)
{
hideErrorMessage();
}
return true;
}
/**
* Method to hide the error message
*/
public void hideErrorMessage()
{
m_tvErrorText.setVisibility(View.GONE);
m_etText.setVisibility(View.VISIBLE);
//m_etText.setText("");
m_etText.requestFocus();
showKeyboard(m_context, m_etText);
}
/**
* Method to set error message in the Edittext
*
* @param p_error
* The error message to be displayed in the Edittext
*/
public void setError(String p_error)
{
// m_etText.setText("");
startVibrate();
m_tvErrorText.setVisibility(View.VISIBLE);
m_tvErrorText.setText(p_error);
m_etText.setVisibility(View.VISIBLE);
if(mEnableShakeAnimation)
{
shake = AnimationUtils.loadAnimation(m_context, R.anim.shakeanim);
m_tvErrorText.startAnimation(shake);
}
try
{
if(mEnableTTS && getTts() != null)
{
if(tts.isSpeaking())
{
tts.playSilence(300,TextToSpeech.QUEUE_ADD,null);
tts.speak(p_error, TextToSpeech.QUEUE_ADD, null);
}
else
{
tts.speak(p_error + ".", TextToSpeech.QUEUE_FLUSH, null);
}
}
}
catch (Throwable e)
{
e.printStackTrace();
}
}
/**
* Get text from the gender selector
*
* @return text from the gender selector
*/
public String getText()
{
return m_etText.getText().toString();
}
/**
* Method to vibrate the phone for a small duration
*/
public void startVibrate()
{
m_vibrator = (Vibrator) m_context.getSystemService(Context.VIBRATOR_SERVICE);
m_vibrator.vibrate(m_vibrationPattern, -1);
}
/**
* Show virtual keyboard.
*
* @param p_context
* activity context
* @param p_view
* view of the activity
*/
public static void showKeyboard(Context p_context, View p_view)
{
InputMethodManager imm = (InputMethodManager) p_context.getSystemService(Context.INPUT_METHOD_SERVICE);
imm.showSoftInput(p_view, InputMethodManager.SHOW_FORCED);
}
public boolean isTTSEnabled()
{
return mEnableTTS;
}
public void setTTSEnabled(boolean pEnableTTS)
{
this.mEnableTTS = pEnableTTS;
}
public boolean isShakeAnimationEnabled()
{
return mEnableShakeAnimation;
}
public void setShakeAnimationEnabled(boolean pEnableShakeAnimation)
{
this.mEnableShakeAnimation = pEnableShakeAnimation;
}
}
| true
|
ca1b5a8c1bdd347b195093fa517a0a0b8a7571d6
|
Java
|
macc704/TurtleCafe
|
/turtlecafe2/html4/chapter11/src/DrawThreeRectanglesMethod.java
|
SHIFT_JIS
| 839
| 3.640625
| 4
|
[] |
no_license
|
/*
* QFlp`R`vO
* i\bh̏j
* 쐬ҁFMegumiAraki
* 쐬F2007/06/09
* [AhXFgarnet@sfc.keio.ac.jp
*/
public class DrawThreeRectanglesMethod extends Turtle {
// N
public static void main(String[] args) {
Turtle.startTurtle(new DrawThreeRectanglesMethod());
}
// ^[g
public void start() {
// lp`R`
for (int i = 0; i < 3; i++) {
drawRectangle();// lp``
move();// ̕`ʒu܂ňړ
}
}
// lp``
void drawRectangle() {
for (int i = 0; i < 4; i++) {
fd(50);
rt(90);
}
}
// ̕`ʒu܂ňړ
void move() {
up();
rt(90);
fd(60);
lt(90);
down();
}
}
| true
|
9bc8e4f3ef4b8b9663d0ed3662eb2e0939f7621c
|
Java
|
abuzzz/KeywordDrivenFramework
|
/Utils/src/main/java/Helper/FactoryMethod.java
|
UTF-8
| 329
| 1.640625
| 2
|
[] |
no_license
|
package helper;
/*package Helper;
import org.testng.annotations.Factory;
import com.xavient.scripts.*;
public class FactoryMethod {
@Factory
public Object[] factoryMethod() {
Object[] obj = new Object[2];
obj[0] = new Test_custTestNG();
obj[1] = new NewTest();
return obj;
}
}
*/
| true
|
99160fcc68a38025340bd48a59bf0262cb5b4537
|
Java
|
fullmanchiu/xiaozhao
|
/app/src/main/java/com/bishe/qiuzhi/module/apply/presenter/ApplyPresenter.java
|
UTF-8
| 525
| 1.789063
| 2
|
[] |
no_license
|
package com.bishe.qiuzhi.module.apply.presenter;
import com.bishe.qiuzhi.module.apply.contract.ApplyContract;
import com.bishe.qiuzhi.net.Api;
public class ApplyPresenter implements ApplyContract.Presenter {
private ApplyContract.View mView;
@Override
public void attachView(ApplyContract.View view) {
mView = view;
}
@Override
public void detachView() {
mView = null;
}
@Override
public void getApplyList() {
Api.getApplyList(mView.onGetAppyList());
}
}
| true
|
c656c3c5fbad5934fa445ece9acc1da8e39906d4
|
Java
|
dario86/SWOWS
|
/swows/src/main/java/org/swows/producer/RangeFunction.java
|
UTF-8
| 2,508
| 2.40625
| 2
|
[] |
no_license
|
package org.swows.producer;
import java.math.BigInteger;
import java.util.Iterator;
import org.swows.vocabulary.Instance;
import org.swows.vocabulary.SPINX;
import com.hp.hpl.jena.datatypes.xsd.XSDDatatype;
import com.hp.hpl.jena.graph.Graph;
import com.hp.hpl.jena.graph.Node;
import com.hp.hpl.jena.graph.Triple;
public class RangeFunction extends GraphToSetFunction {
/**
* Instantiates a new range producer.
*
* @param conf the graph with dataflow definition
* @param confRoot the specific node in the graph representing the producer configuration
* @param map the map to access the other defined producers
* @see Producer
*/
public RangeFunction(Graph conf, Node confRoot, ProducerMap map) {
super(conf,confRoot,map);
}
@Override
public Iterator<Node> createIterator(Graph inputGraph) {
final BigInteger start, end;
Iterator<Triple> startIter =
inputGraph.find(Instance.GraphRoot.asNode(), SPINX.intervalStart.asNode(), Node.ANY);
if (startIter.hasNext()) {
Node startNode = startIter.next().getObject();
if (startNode.isLiteral() && startNode.getLiteralDatatype().equals(XSDDatatype.XSDinteger)) {
start = new BigInteger( startNode.getLiteralLexicalForm() );
} else
throw new ProducerException("Parameter intervalStart has wrong type. expected literal with " + XSDDatatype.XSDinteger.getURI() + " type");
} else
throw new ProducerException("Parameter intervalStart not found");
Iterator<Triple> endIter =
inputGraph.find(Instance.GraphRoot.asNode(), SPINX.intervalEnd.asNode(), Node.ANY);
if (endIter.hasNext()) {
Node endNode = endIter.next().getObject();
if (endNode.isLiteral() && endNode.getLiteralDatatype().equals(XSDDatatype.XSDinteger)) {
end = new BigInteger( endNode.getLiteralLexicalForm() );
} else
throw new ProducerException("Parameter intervalEnd has wrong type. expected literal with " + XSDDatatype.XSDinteger.getURI() + " type");
} else
throw new ProducerException("Parameter intervalEnd not found");
// final BigInteger start, end;
return new Iterator<Node>() {
private BigInteger index = start;
@Override
public boolean hasNext() {
return index.compareTo(end) <= 0;
}
@Override
public Node next() {
Node currNode = Node.createLiteral(index.toString(),XSDDatatype.XSDinteger);
index = index.add(BigInteger.ONE);
return currNode;
}
@Override
public void remove() {
throw new UnsupportedOperationException("Read-only Iterator");
}
};
}
}
| true
|
b0a5b5dd1ca92fb2ae691af959b96ee2fe0b99fc
|
Java
|
bdxtx/aaaa
|
/app/src/main/java/com/weiyu/sp/lsjy/course/CourseDetailModel.java
|
UTF-8
| 839
| 2
| 2
|
[] |
no_license
|
package com.weiyu.sp.lsjy.course;
import com.weiyu.sp.lsjy.base.BaseObjectBean;
import com.weiyu.sp.lsjy.bean.CourseDetailBean;
import com.weiyu.sp.lsjy.net.RetrofitClient;
import java.util.Map;
import io.reactivex.Flowable;
public class CourseDetailModel implements CourseDetailContract.Model {
@Override
public Flowable<BaseObjectBean<CourseDetailBean>> courseDetail(String courseId) {
return RetrofitClient.getInstance().getApi().courseDetail(courseId);
}
@Override
public Flowable<BaseObjectBean<String>> courseCollection(Map<String, String> map) {
return RetrofitClient.getInstance().getApi().courseCollection(map);
}
@Override
public Flowable<BaseObjectBean<String>> startStudy(String courseId) {
return RetrofitClient.getInstance().getApi().startStudy(courseId);
}
}
| true
|
56bbbb875b71adb270e50a664846b7dfe48a3c13
|
Java
|
MakoMitsuki/cs342-project4-group18
|
/MCAnswer.java
|
UTF-8
| 1,316
| 3.359375
| 3
|
[] |
no_license
|
import java.util.*;
import java.io.PrintWriter;
public abstract class MCAnswer extends Answer {
// protected boolean selected = false; removed in Project 3
protected String text = "";
protected double creditIfSelected = 0;
protected boolean selected;
protected MCAnswer(String Text, double CreditIfSelected) {
text = Text;
creditIfSelected = CreditIfSelected;
}
/* NEW */
public MCAnswer(Scanner s1)
{
// get points
creditIfSelected = s1.nextDouble();
//System.out.println(creditIfSelected);
// skip space
s1.skip(" ");
// get answer
text = s1.nextLine();
//System.out.println(text);
selected = false;
}
public void print()
{
System.out.print(text);
}
public String getCorrect()
{
return text;
}
/* REMOVED FROM PROJECT 3
* public double getCreditIfSelected()
{
return creditIfSelected;
}
*/
public void setSelected(boolean Selected)
{
selected = Selected;
}
/* NEW */
public double getCredit(Answer a)
{
//System.out.println("this is the credit if selected: " +creditIfSelected);
return selected ? creditIfSelected : 0.0;
}
public void save(PrintWriter pw)
{
pw.print(creditIfSelected);
pw.print(" ");
pw.println(text);
pw.flush();
}
}
| true
|
b3591e2514d3c003acedd66351e73af94882c91a
|
Java
|
kevin554/punto-medico-android
|
/app/src/main/java/com/bo/punto/medico/utils/FragmentListener.java
|
UTF-8
| 112
| 1.546875
| 2
|
[] |
no_license
|
package com.bo.punto.medico.utils;
public interface FragmentListener {
void onSwitchToNextFragment();
}
| true
|
2bdc0af22dec2ca93f999673a6e1e7936e0120d5
|
Java
|
thomaslee87/data-app
|
/data-analysis-v2/src/main/java/com/intellbi/config/PropertyFileUtil.java
|
UTF-8
| 1,574
| 2.59375
| 3
|
[] |
no_license
|
package com.intellbi.config;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.text.MessageFormat;
import java.util.Properties;
import com.intellbit.v2.exception.PropertyParseException;
public class PropertyFileUtil {
public static Properties loadProperties(File... locations) throws PropertyParseException {
Properties props = new Properties();
loadProperties(props, locations);
return props;
}
private static void loadProperties(Properties props, File... locations) throws PropertyParseException {
try {
for (File location : locations) {
Properties prop = new Properties();
if (location.isDirectory()) {
File[] files = location.listFiles();
loadProperties(props, files);
} else {
prop.load(new InputStreamReader(new FileInputStream(location),"utf-8"));
}
for (Object key : prop.keySet()) {
if(key == null || props.containsKey(key.toString()))
throw new PropertyParseException(MessageFormat.format("Property Key Duplication: {0}", key));
props.put(key, prop.get(key));
}
}
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
| true
|
8cf988de05102bc6a22f8c8fd69b4e2cceaf6a3c
|
Java
|
maarteneeckman/eurder
|
/src/main/java/com/switchfully/eurder/api/CustomerController.java
|
UTF-8
| 1,405
| 2.1875
| 2
|
[] |
no_license
|
package com.switchfully.eurder.api;
import com.switchfully.eurder.service.customer.CreateCustomerDto;
import com.switchfully.eurder.service.customer.CustomerDto;
import com.switchfully.eurder.service.customer.CustomerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;
import java.util.Collection;
import java.util.UUID;
@RestController
@RequestMapping(path = "customers")
public class CustomerController {
private final CustomerService customerService;
@Autowired
public CustomerController(CustomerService customerService) {
this.customerService = customerService;
}
@PostMapping(consumes = "application/json", produces = "application/json")
@ResponseStatus(HttpStatus.CREATED)
public CustomerDto createCustomer(@RequestBody CreateCustomerDto addCustomerDto) {
return customerService.createCustomer(addCustomerDto);
}
@GetMapping(produces = "application/json")
@ResponseStatus(HttpStatus.OK)
public Collection<CustomerDto> getAllCustomers() {
return customerService.getAllCustomers();
}
@GetMapping(path = "{id}", produces = "application/json")
@ResponseStatus(HttpStatus.OK)
public CustomerDto getCustomerById(@PathVariable UUID id) {
return customerService.getCustomerById(id);
}
}
| true
|
82fbce2e08d28224f42831a996b55aa17c4cfb80
|
Java
|
zsiddiqui2/ConnectFour
|
/ConnectFour/src/main/java/ch/hszt/connectfour/util/GameStarter.java
|
UTF-8
| 2,241
| 3.109375
| 3
|
[] |
no_license
|
/**
*
*/
package ch.hszt.connectfour.util;
import java.awt.Window;
import ch.hszt.connectfour.gui.GameFrame;
import ch.hszt.connectfour.gui.MainGameFrame;
import ch.hszt.connectfour.model.game.Game;
import ch.hszt.connectfour.model.game.Player;
/**
* Utility class to trigger relevant logic and actions on starting a {@link Game}.
* Provides different overloads of <code>GameStarter.launch</code> method to initiiate a {@link Game} with correct settings.
* @author Markus Vetsch
* @version 1.0, 14.11.2011
*/
public class GameStarter
{
/**
* The helper class can't be instantiated.
*/
private GameStarter()
{
}
/**
* Launches the specified {@link Game}.
* @param game - The {@link Game} to be launched.
* @return - The {@link GameFrame} for user interaction.
*/
public static GameFrame launch(Game game)
{
return launch(null, game);
}
/**
* Launches the specified {@link Game}.
* @param owner - The {@link Window} acting as owner for the {@link GameFrame} to be returned.
* @param game - The {@link Game} to be launched.
* @return The {@link GameFrame} for user interaction, that already provides access to the started {@link Game}.
*/
public static GameFrame launch(Window owner, Game game)
{
return new MainGameFrame(owner, game);
}
/**
* Launches a new {@link Game} with specified {@link Player} as participants.
* @param either - The either {@link Player}.
* @param other - The other {@link Player}.
* @return The {@link GameFrame} for user interaction, that already provides access to the started {@link Game}.
*/
public static GameFrame launch(Player either, Player other)
{
return launch(null, either, other);
}
/**
* Launches a new {@link Game} with specified {@link Player} as participants.
* @param owner - The {@link Window} acting as owner for the {@link GameFrame} to be returned.
* @param either - The either {@link Player}.
* @param other - The other {@link Player}.
* @return The {@link GameFrame} for user interaction, that already provides access to the started {@link Game}.
*/
public static GameFrame launch(Window owner, Player either, Player other)
{
Game game = new Game(either, other);
return new MainGameFrame(owner, game);
}
}
| true
|
cf54377eaa34c8f975988006ca4bc08ebcc784d2
|
Java
|
darkshadow88/Basic-Java-Programs
|
/Example2.java
|
UTF-8
| 285
| 3
| 3
|
[] |
no_license
|
/* my second java program
it used some variables.
*/
class Example2{
public static void main(String args[]){
int num;
num=100;
System.out.println("the number is: "+num);
num=num*2;
System.out.print("the value of num*2 is");
System.out.println(num);
}
}
| true
|
5ad9bf0a8c3add610319843abe2f7c8c1f38334b
|
Java
|
kai-zhu/the-teaching-machine-and-webwriter
|
/trunk/play/src/play/higraph/model/PLAYNode.java
|
UTF-8
| 891
| 2.40625
| 2
|
[] |
no_license
|
/**
* PLAYNode.java - play.higraph.model - PLAY
*
* Created on Feb 13, 2012 by Kai Zhu
*/
package play.higraph.model;
import play.higraph.view.PLAYNodeView;
import higraph.model.abstractTaggedClasses.AbstractTaggedNode;
/**
* @author Kai Zhu
*
*/
public class PLAYNode
extends
AbstractTaggedNode<PLAYTag,PLAYPayload, PLAYEdgeLabel, PLAYHigraph, PLAYWholeGraph, PLAYSubgraph, PLAYNode, PLAYEdge> {
private PLAYNodeView view;
public PLAYNode(PLAYWholeGraph wholeGraph, PLAYPayload payload) {
super(wholeGraph, payload);
}
protected PLAYNode(PLAYNode original, PLAYNode parent) {
super(original, parent);
}
@Override
protected PLAYNode getThis() {
return this;
}
public void setView(PLAYNodeView view){
this.view = view;
}
public PLAYNodeView getView(){
return this.view;
}
}
| true
|
85b6b08e9744c2e0f2b57260c244c099cd681b88
|
Java
|
IVyujie/GitTest
|
/src/reflect/MyInterface2.java
|
UTF-8
| 140
| 1.914063
| 2
|
[] |
no_license
|
package reflect;
/**
* @Author IVyujie
* @Date 2020/2/11 0011 11:32
*/
public interface MyInterface2
{
public void ImplMethod2();
}
| true
|
255289f8c33679f34b0e941692dbd5b7db38d480
|
Java
|
chujiuling/LissayApp-1
|
/LissayAppServer/src/com/seprojects/lissayappserver/Test.java
|
GB18030
| 515
| 2.34375
| 2
|
[] |
no_license
|
package com.seprojects.lissayappserver;
// ÿܶвһ
// û ʹ userID U00000001 ֻ12345678901 123ASD@01 ͺ123564
public class Test
{
public static void main(String[] args)
{
// TODO Զɵķ
// ҪĵϢ
CUser c = new CUser(); // 贴
String str = c.login("12345678901", "123ASD", "123564");
if (str == null)
{
System.out.println("success");
}
else
{
System.out.println(str);
}
}
}
| true
|
b5d22a57303733947cc2f8d63fe18f7ae15f1e35
|
Java
|
Akers/StuManager
|
/src/com/design/web/AddAdminAction.java
|
UTF-8
| 2,857
| 2.25
| 2
|
[
"Apache-2.0"
] |
permissive
|
package com.design.web;
import java.util.Map;
import javax.servlet.ServletContext;
import javax.swing.JOptionPane;
import org.apache.struts2.ServletActionContext;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import com.design.pojo.Admin;
import com.design.service.impl.AdminManagerImpl;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
public class AddAdminAction extends ActionSupport {
private String username;
private String password1;
private String password2;
private String question;
private String answer;
@SuppressWarnings("unchecked")
@Override
public String execute() throws Exception {
return SUCCESS;
}
@Override
public void validate() {
ActionContext ctx = ActionContext.getContext();
ServletContext sc = (ServletContext) ctx
.get(ServletActionContext.SERVLET_CONTEXT);
ApplicationContext appContext = WebApplicationContextUtils
.getRequiredWebApplicationContext(sc);
AdminManagerImpl ami = (AdminManagerImpl) appContext
.getBean("AdminManagerImpl");
Admin ad = ami.getAdmin(getUsername());
Admin admin = new Admin();
if (this.getUsername() == null || "".equals(this.getUsername().trim())) {
this.addFieldError("NoUsername", "用户名不能为空!");
} else if (this.getQuestion() == null
|| "".equals(this.getQuestion().trim())) {
this.addFieldError("NoQuestion", "密码问题不能为空!");
}else if(ad != null) {
this.addFieldError("existName", "用户已存在,请重新选择!");
}else if(this.getAnswer() == null
|| "".equals(this.getAnswer().trim())){
this.addFieldError("NoAnswer", "密码问题答案不能为空!");
} else if(!getPassword1().equals(getPassword2())) {
this.addFieldError("WrongPassword", "两次密码不相同!");
}else {
admin.setName(getUsername());
admin.setPassword((new MD5Digest()).md5crypt(getPassword1()));
// admin.setPassword(getPassword1());
admin.setQuestion(getQuestion());
admin.setAnswer(getAnswer());
admin.setSecurity(1);
ami.save(admin);
}
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getQuestion() {
return question;
}
public void setQuestion(String question) {
this.question = question;
}
public String getAnswer() {
return answer;
}
public void setAnswer(String answer) {
this.answer = answer;
}
public String getPassword1() {
return password1;
}
public void setPassword1(String password1) {
this.password1 = password1;
}
public String getPassword2() {
return password2;
}
public void setPassword2(String password2) {
this.password2 = password2;
}
}
| true
|
c8d0782bea3ecb0fa7bb82fd83a0cb8cff945739
|
Java
|
weijupeng/msb
|
/src/main/java/com/wjp/test/thread/productandcustomer/ConsumeTask.java
|
UTF-8
| 494
| 2.609375
| 3
|
[] |
no_license
|
package com.wjp.test.thread.productandcustomer;
/**
* @author wjp
* @date 2020/6/5 16:05
*/
public class ConsumeTask implements Runnable {
private PhoneFactory pf;
public ConsumeTask(PhoneFactory pf) {
this.pf = pf;
}
@Override
public void run() {
while (true) {
try {
Thread.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
pf.get();
}
}
}
| true
|
6700c56f904459b72ccd6f62fc322863bbba548d
|
Java
|
relentlesscoder/Leetcode
|
/src/org/wshuai/leetcode/SplitArrayIntoFibonacciSequence.java
|
UTF-8
| 1,263
| 3.453125
| 3
|
[] |
no_license
|
package org.wshuai.leetcode;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Wei on 11/05/2019.
* #0842 https://leetcode.com/problems/split-array-into-fibonacci-sequence/
*/
public class SplitArrayIntoFibonacciSequence {
public List<Integer> splitIntoFibonacci(String S) {
List<Integer> res = new ArrayList<>();
dfs(0, S.length(), S.toCharArray(), res);
return res;
}
private boolean dfs(int start, int n, char[] digits, List<Integer> res){
if(start == n){
return res.size() >= 3;
}
long cur = 0;
int size = res.size();
if(digits[start] == '0'){
if(size < 2 || res.get(size - 1) + res.get(size - 2) == 0){
res.add(0);
if(dfs(start + 1, n, digits, res)){
return true;
}
// only remove when all attempt failed
res.remove(res.size() - 1);
return false;
}else{
return false;
}
}
for(int i = start; i < n; i++){
cur = cur * 10 + (digits[i] - '0');
if(cur > Integer.MAX_VALUE){
break;
}
int next = (int)cur;
if(size < 2 || res.get(size - 1) + res.get(size - 2) == next){
res.add(next);
if(dfs(i + 1, n, digits, res)){
return true;
}
// only remove when all attempt failed
res.remove(res.size() - 1);
}
}
return false;
}
}
| true
|
8c8cb20d3a5f01b7ead87e31f435fda4015738de
|
Java
|
arcturus2/viz-engine
|
/modules/opengl-lwjgl/src/main/java/org/gephi/viz/engine/lwjgl/pipeline/indirect/IndirectNodeData.java
|
UTF-8
| 16,738
| 1.828125
| 2
|
[] |
no_license
|
package org.gephi.viz.engine.lwjgl.pipeline.indirect;
import java.nio.FloatBuffer;
import java.nio.IntBuffer;
import org.gephi.graph.api.Node;
import org.gephi.viz.engine.VizEngine;
import org.gephi.viz.engine.lwjgl.models.NodeDiskModel;
import org.gephi.viz.engine.pipeline.RenderingLayer;
import org.gephi.viz.engine.lwjgl.pipeline.common.AbstractNodeData;
import org.gephi.viz.engine.lwjgl.util.gl.GLBuffer;
import org.gephi.viz.engine.lwjgl.util.gl.GLBufferImmutable;
import org.gephi.viz.engine.pipeline.common.InstanceCounter;
import org.gephi.viz.engine.status.GraphRenderingOptions;
import org.gephi.viz.engine.status.GraphSelection;
import org.gephi.viz.engine.status.GraphSelectionNeighbours;
import org.gephi.viz.engine.structure.GraphIndexImpl;
import org.gephi.viz.engine.lwjgl.util.gl.GLBufferMutable;
import static org.gephi.viz.engine.util.gl.GLConstants.INDIRECT_DRAW_COMMAND_INTS_COUNT;
import org.gephi.viz.engine.lwjgl.util.gl.ManagedDirectBuffer;
import static org.gephi.viz.engine.util.gl.GLConstants.INDIRECT_DRAW_COMMAND_BYTES;
import static org.lwjgl.opengl.GL11.GL_FLOAT;
import static org.lwjgl.opengl.GL11.GL_UNSIGNED_INT;
import static org.lwjgl.opengl.GL20.glGenBuffers;
import org.lwjgl.system.MemoryStack;
/**
*
* @author Eduardo Ramos
*/
public class IndirectNodeData extends AbstractNodeData {
private final NodeDiskModel diskModel64;
private final NodeDiskModel diskModel32;
private final NodeDiskModel diskModel16;
private final NodeDiskModel diskModel8;
private final int circleVertexCount64;
private final int circleVertexCount32;
private final int circleVertexCount16;
private final int circleVertexCount8;
private final int firstVertex64;
private final int firstVertex32;
private final int firstVertex16;
private final int firstVertex8;
private final InstanceCounter instanceCounter = new InstanceCounter();
public IndirectNodeData() {
super(true);
diskModel64 = new NodeDiskModel(64);
diskModel32 = new NodeDiskModel(32);
diskModel16 = new NodeDiskModel(16);
diskModel8 = new NodeDiskModel(8);
circleVertexCount64 = diskModel64.getVertexCount();
circleVertexCount32 = diskModel32.getVertexCount();
circleVertexCount16 = diskModel16.getVertexCount();
circleVertexCount8 = diskModel8.getVertexCount();
firstVertex64 = 0;
firstVertex32 = circleVertexCount64;
firstVertex16 = firstVertex32 + circleVertexCount32;
firstVertex8 = firstVertex16 + circleVertexCount16;
}
private final int[] bufferName = new int[3];
private static final int VERT_BUFFER = 0;
private static final int ATTRIBS_BUFFER = 1;
private static final int INDIRECT_DRAW_BUFFER = 2;
public void init() {
initBuffers();
diskModel64.initGLPrograms();
}
public void update(VizEngine engine, GraphIndexImpl spatialIndex) {
updateData(
engine.getZoom(),
spatialIndex,
engine.getLookup().lookup(GraphRenderingOptions.class),
engine.getLookup().lookup(GraphSelection.class),
engine.getLookup().lookup(GraphSelectionNeighbours.class)
);
}
public void drawIndirect(RenderingLayer layer, VizEngine engine, float[] mvpFloats) {
final float[] backgroundColorFloats = engine.getBackgroundColor();
final int instanceCount;
final int instancesOffset;
final float colorLightenFactor;
if (layer == RenderingLayer.BACK) {
instanceCount = instanceCounter.unselectedCountToDraw * 2;
instancesOffset = 0;
colorLightenFactor = engine.getLookup().lookup(GraphRenderingOptions.class).getLightenNonSelectedFactor();
} else {
instanceCount = instanceCounter.selectedCountToDraw * 2;
instancesOffset = instanceCounter.unselectedCountToDraw * 2;
colorLightenFactor = 0;
}
if (instanceCount > 0) {
setupVertexArrayAttributes(engine);
commandsGLBuffer.bind();
diskModel64.drawIndirect(mvpFloats, backgroundColorFloats, colorLightenFactor, instanceCount, instancesOffset);
commandsGLBuffer.unbind();
unsetupVertexArrayAttributes();
}
}
private ManagedDirectBuffer attributesBuffer;
private ManagedDirectBuffer commandsBuffer;
private GLBuffer commandsGLBuffer;
private float[] attributesBufferBatch;
private int[] commandsBufferBatch;
private static final int BATCH_NODES_SIZE = 32768;
private void initBuffers() {
attributesBufferBatch = new float[ATTRIBS_STRIDE * BATCH_NODES_SIZE * 2];
commandsBufferBatch = new int[INDIRECT_DRAW_COMMAND_INTS_COUNT * BATCH_NODES_SIZE * 2];
glGenBuffers(bufferName);
final float[] circleVertexData = new float[diskModel64.getVertexData().length + diskModel32.getVertexData().length + diskModel16.getVertexData().length + diskModel8.getVertexData().length];
int offset = 0;
System.arraycopy(diskModel64.getVertexData(), 0, circleVertexData, offset, diskModel64.getVertexData().length);
offset += diskModel64.getVertexData().length;
System.arraycopy(diskModel32.getVertexData(), 0, circleVertexData, offset, diskModel32.getVertexData().length);
offset += diskModel32.getVertexData().length;
System.arraycopy(diskModel16.getVertexData(), 0, circleVertexData, offset, diskModel16.getVertexData().length);
offset += diskModel16.getVertexData().length;
System.arraycopy(diskModel8.getVertexData(), 0, circleVertexData, offset, diskModel8.getVertexData().length);
try (MemoryStack stack = MemoryStack.stackPush()) {
final FloatBuffer circleVertexBuffer = stack.floats(circleVertexData);
final int flags = 0;
vertexGLBuffer = new GLBufferImmutable(bufferName[VERT_BUFFER], GLBufferMutable.GL_BUFFER_TYPE_ARRAY);
vertexGLBuffer.bind();
vertexGLBuffer.init(circleVertexBuffer, flags);
vertexGLBuffer.unbind();
}
//Initialize for batch nodes size:
attributesGLBuffer = new GLBufferMutable(bufferName[ATTRIBS_BUFFER], GLBufferMutable.GL_BUFFER_TYPE_ARRAY);
attributesGLBuffer.bind();
attributesGLBuffer.init(ATTRIBS_STRIDE * Float.BYTES * BATCH_NODES_SIZE * 2, GLBufferMutable.GL_BUFFER_USAGE_DYNAMIC_DRAW);
attributesGLBuffer.unbind();
commandsGLBuffer = new GLBufferMutable(bufferName[INDIRECT_DRAW_BUFFER], GLBufferMutable.GL_BUFFER_TYPE_DRAW_INDIRECT);
commandsGLBuffer.bind();
commandsGLBuffer.init(INDIRECT_DRAW_COMMAND_BYTES * BATCH_NODES_SIZE * 2, GLBufferMutable.GL_BUFFER_USAGE_DYNAMIC_DRAW);
commandsGLBuffer.unbind();
attributesBuffer = new ManagedDirectBuffer(GL_FLOAT, ATTRIBS_STRIDE * BATCH_NODES_SIZE * 2);
commandsBuffer = new ManagedDirectBuffer(GL_UNSIGNED_INT, INDIRECT_DRAW_COMMAND_INTS_COUNT * BATCH_NODES_SIZE * 2);
}
public void updateBuffers() {
instanceCounter.promoteCountToDraw();
final FloatBuffer attributesBufferData = attributesBuffer.floatBuffer();
attributesBufferData.limit(instanceCounter.totalToDraw() * ATTRIBS_STRIDE * 2);
attributesGLBuffer.bind();
attributesGLBuffer.updateWithOrphaning(attributesBufferData);
attributesGLBuffer.unbind();
final IntBuffer commandsBufferData = commandsBuffer.intBuffer();
commandsBufferData.limit(instanceCounter.totalToDraw() * INDIRECT_DRAW_COMMAND_INTS_COUNT * 2);
commandsGLBuffer.bind();
commandsGLBuffer.updateWithOrphaning(commandsBufferData);
commandsGLBuffer.unbind();
//TODO: Persistent buffer if available?
}
private void updateData(final float zoom, final GraphIndexImpl spatialIndex, final GraphRenderingOptions renderingOptions, final GraphSelection selection, final GraphSelectionNeighbours neighboursSelection) {
//TODO: unify this copy-paste in nodes renderers...
if (!renderingOptions.isShowNodes()) {
instanceCounter.clearCount();
return;
}
spatialIndex.indexNodes();
//Selection:
final boolean someSelection = selection.getSelectedNodesCount() > 0;
final float lightenNonSelectedFactor = renderingOptions.getLightenNonSelectedFactor();
final boolean hideNonSelected = someSelection && (renderingOptions.isHideNonSelected() || lightenNonSelectedFactor >= 1);
final int totalNodes = spatialIndex.getNodeCount();
attributesBuffer.ensureCapacity(totalNodes * ATTRIBS_STRIDE * 2);
commandsBuffer.ensureCapacity(totalNodes * INDIRECT_DRAW_COMMAND_INTS_COUNT * 2);
final FloatBuffer attribs = attributesBuffer.floatBuffer();
final IntBuffer commands = commandsBuffer.intBuffer();
spatialIndex.getVisibleNodes(nodesCallback);
final Node[] visibleNodesArray = nodesCallback.getNodesArray();
final int visibleNodesCount = nodesCallback.getCount();
int newNodesCountUnselected = 0;
int newNodesCountSelected = 0;
int index = 0;
int commandIndex = 0;
int instanceId = 0;
final int stride = ATTRIBS_STRIDE * 2;
final int commandsStride = 8;
if (someSelection) {
if (hideNonSelected) {
for (int j = 0; j < visibleNodesCount; j++) {
final Node node = visibleNodesArray[j];
final boolean selected = selection.isNodeSelected(node) || neighboursSelection.isNodeSelected(node);
if (!selected) {
continue;
}
newNodesCountSelected++;
fillNodeAttributesData(attributesBufferBatch, node, index, someSelection, true);
fillNodeCommandData(node, zoom, commandIndex, instanceId);
if (index + stride == attributesBufferBatch.length) {
attribs.put(attributesBufferBatch, 0, attributesBufferBatch.length);
index = 0;
}
if (commandIndex + commandsStride == commandsBufferBatch.length) {
commands.put(commandsBufferBatch, 0, commandsBufferBatch.length);
commandIndex = 0;
}
index += stride;
commandIndex += commandsStride;
instanceId += 2;
}
} else {
//First non-selected (bottom):
for (int j = 0; j < visibleNodesCount; j++) {
final Node node = visibleNodesArray[j];
final boolean selected = selection.isNodeSelected(node) || neighboursSelection.isNodeSelected(node);
if (selected) {
continue;
}
newNodesCountUnselected++;
fillNodeAttributesData(attributesBufferBatch, node, index, someSelection, false);
fillNodeCommandData(node, zoom, commandIndex, instanceId);
if (index + stride == attributesBufferBatch.length) {
attribs.put(attributesBufferBatch, 0, attributesBufferBatch.length);
index = 0;
}
if (commandIndex + commandsStride == commandsBufferBatch.length) {
commands.put(commandsBufferBatch, 0, commandsBufferBatch.length);
commandIndex = 0;
}
index += stride;
commandIndex += commandsStride;
instanceId += 2;
}
//Then selected ones (up):
for (int j = 0; j < visibleNodesCount; j++) {
final Node node = visibleNodesArray[j];
final boolean selected = selection.isNodeSelected(node) || neighboursSelection.isNodeSelected(node);
if (!selected) {
continue;
}
newNodesCountSelected++;
fillNodeAttributesData(attributesBufferBatch, node, index, someSelection, true);
fillNodeCommandData(node, zoom, commandIndex, instanceId);
if (index + stride == attributesBufferBatch.length) {
attribs.put(attributesBufferBatch, 0, attributesBufferBatch.length);
index = 0;
}
if (commandIndex + commandsStride == commandsBufferBatch.length) {
commands.put(commandsBufferBatch, 0, commandsBufferBatch.length);
commandIndex = 0;
}
index += stride;
commandIndex += commandsStride;
instanceId += 2;
}
}
} else {
//Just all nodes, no selection active:
for (int j = 0; j < visibleNodesCount; j++) {
final Node node = visibleNodesArray[j];
newNodesCountSelected++;
fillNodeAttributesData(attributesBufferBatch, node, index, someSelection, true);
fillNodeCommandData(node, zoom, commandIndex, instanceId);
if (index + stride == attributesBufferBatch.length) {
attribs.put(attributesBufferBatch, 0, attributesBufferBatch.length);
index = 0;
}
if (commandIndex + commandsStride == commandsBufferBatch.length) {
commands.put(commandsBufferBatch, 0, commandsBufferBatch.length);
commandIndex = 0;
}
index += stride;
commandIndex += commandsStride;
instanceId += 2;
}
}
//Remaining:
if (index > 0) {
attribs.put(attributesBufferBatch, 0, index);
}
if (commandIndex > 0) {
commands.put(commandsBufferBatch, 0, commandIndex);
}
instanceCounter.unselectedCount = newNodesCountUnselected;
instanceCounter.selectedCount = newNodesCountSelected;
}
private void fillNodeCommandData(final Node node, final float zoom, final int index, final int instanceId) {
//Indirect Draw:
//Choose LOD:
final float observedSize = node.size() * zoom;
final int circleVertexCount;
final int firstVertex;
if (observedSize > OBSERVED_SIZE_LOD_THRESHOLD_64) {
circleVertexCount = circleVertexCount64;
firstVertex = firstVertex64;
} else if (observedSize > OBSERVED_SIZE_LOD_THRESHOLD_32) {
circleVertexCount = circleVertexCount32;
firstVertex = firstVertex32;
} else if (observedSize > OBSERVED_SIZE_LOD_THRESHOLD_16) {
circleVertexCount = circleVertexCount16;
firstVertex = firstVertex16;
} else {
circleVertexCount = circleVertexCount8;
firstVertex = firstVertex8;
}
//Outside circle:
commandsBufferBatch[index + 0] = circleVertexCount;//vertex count
commandsBufferBatch[index + 1] = 1;//instance count
commandsBufferBatch[index + 2] = firstVertex;//first vertex
commandsBufferBatch[index + 3] = instanceId;//base instance
//Inside circle:
commandsBufferBatch[index + 4] = circleVertexCount;//vertex count
commandsBufferBatch[index + 5] = 1;//instance count
commandsBufferBatch[index + 6] = firstVertex;//first vertex
commandsBufferBatch[index + 7] = instanceId + 1;//base instance
}
@Override
public void dispose() {
super.dispose();
attributesBufferBatch = null;
commandsBufferBatch = null;
if (attributesBuffer != null) {
attributesBuffer.destroy();
attributesBuffer = null;
}
if (commandsBuffer != null) {
commandsBuffer.destroy();
commandsBuffer = null;
}
}
}
| true
|
fbeac8b9eeb36997249a87f88aeac4db1d3b6ab0
|
Java
|
andrii-usov/PIPE
|
/pipe-gui/src/main/java/pipe/gui/PetriNetTab.java
|
UTF-8
| 9,911
| 2.296875
| 2
|
[
"MIT"
] |
permissive
|
package pipe.gui;
import pipe.constants.GUIConstants;
import pipe.controllers.SelectionManager;
import pipe.controllers.ZoomController;
import pipe.views.AbstractPetriNetViewComponent;
import pipe.views.PetriNetViewComponent;
import uk.ac.imperial.pipe.exceptions.PetriNetComponentException;
import uk.ac.imperial.pipe.models.petrinet.*;
import uk.ac.imperial.pipe.visitor.component.PetriNetComponentVisitor;
import javax.swing.*;
import javax.swing.event.MouseInputAdapter;
import java.awt.*;
import java.awt.print.PageFormat;
import java.awt.print.Printable;
import java.awt.print.PrinterException;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.File;
import java.util.HashMap;
import java.util.Map;
import java.util.Observable;
import java.util.Observer;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* The main canvas that the {@link pipe.views.PetriNetViewComponent}s appear on
* It is a tab in the main applicaiton
*/
public class PetriNetTab extends JLayeredPane implements Observer, Printable {
/**
* Class logger
*/
private static final Logger LOGGER = Logger.getLogger(PetriNetTab.class.getName());
/**
* Map of components in the tab with id -> component
*/
private final Map<String, PetriNetViewComponent> petriNetComponents = new HashMap<>();
/**
* Grid displayed on petri net tab
*/
private final Grid grid = new Grid();
/**
* Legacy file for the saving of the underlying Petri net
*/
@Deprecated
public File appFile;
/**
* Constructor
*
* Sets no layout manager to acheive an (x,y) layout
*/
public PetriNetTab() {
setLayout(null);
setOpaque(true);
setDoubleBuffered(true);
setAutoscrolls(true);
setBackground(GUIConstants.ELEMENT_FILL_COLOUR);
setCursor(Cursor.getPredefinedCursor(Cursor.CROSSHAIR_CURSOR));
}
/**
*
* Register the zoom listener to the Petri net tab
*
* @param zoomController zoom listener
*/
public void addZoomListener(ZoomController zoomController) {
zoomController.addPropertyChangeListener(new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent propertyChangeEvent) {
repaint();
}
});
}
/**
* Legacy update method
* @param o
* @param diffObj
*/
@Override
public void update(Observable o, Object diffObj) {
if (diffObj instanceof AbstractPetriNetViewComponent) {
AbstractPetriNetViewComponent<?> component = (AbstractPetriNetViewComponent<?>) diffObj;
addNewPetriNetComponent(component);
}
}
/**
* Adds the Petri net component to this canvas
* @param component to add to petri net view
*/
public void addNewPetriNetComponent(AbstractPetriNetViewComponent<?> component) {
add(component);
component.addToContainer(this);
}
/**
* Add the Petri net component to this canvas
* @param component
*/
public void add(AbstractPetriNetViewComponent<?> component) {
registerLocationChangeListener(component.getModel());
setLayer(component, DEFAULT_LAYER);
super.add(component);
petriNetComponents.put(component.getId(), component);
updatePreferredSize();
// repaint();
}
/**
* Update the preferred size of the canvas and grid that is displayed on it
*/
public void updatePreferredSize() {
Component[] components = getComponents();
Dimension d = new Dimension(0, 0);
for (Component component : components) {
if (component.getClass() == SelectionManager.class) {
continue;
}
Rectangle r = component.getBounds();
int x = r.x + r.width + 20;
int y = r.y + r.height + 20;
if (x > d.width) {
d.width = x;
}
if (y > d.height) {
d.height = y;
}
}
setPreferredSize(d);
Container parent = getParent();
if (parent != null) {
parent.validate();
}
}
/**
*
* Registeres a location listener on the Petri net component
*
* @param component
*/
private void registerLocationChangeListener(PetriNetComponent component) {
PetriNetComponentVisitor changeListener = new ChangeListener();
try {
component.accept(changeListener);
} catch (PetriNetComponentException e) {
LOGGER.log(Level.SEVERE, e.getMessage());
}
}
/**
* Prints the Petri net tab
* @param g
* @param pageFormat
* @param pageIndex
* @return
* @throws PrinterException
*/
@Override
public int print(Graphics g, PageFormat pageFormat, int pageIndex) throws PrinterException {
if (pageIndex > 0) {
return Printable.NO_SUCH_PAGE;
}
Graphics2D g2D = (Graphics2D) g;
g2D.translate(pageFormat.getImageableX(), pageFormat.getImageableY());
g2D.scale(0.5, 0.5);
print(g2D);
return Printable.PAGE_EXISTS;
}
/**
* Paints the underlying grid on the canvas
* @param g
*/
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
if (grid.isEnabled()) {
grid.updateSize(this);
grid.drawGrid(g);
}
}
/**
* Set the cursor type. Options are:
* - arrow
* - crosshair
* - move
* @param type cursor type
*/
//TODO These should be an enum
public void setCursorType(String type) {
if (type.equals("arrow")) {
setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
} else if (type.equals("crosshair")) {
setCursor(Cursor.getPredefinedCursor(Cursor.CROSSHAIR_CURSOR));
} else if (type.equals("move")) {
setCursor(Cursor.getPredefinedCursor(Cursor.MOVE_CURSOR));
}
}
/**
* Set meta down. Since there is no documentation for this the functionality
* has been depricated and it no longer does anything
* @param down
*/
@Deprecated
public void setMetaDown(boolean down) {
//TODO: DELETE
}
/**
* Updates the canvas boundary when dragging is taking place
* @param dragStart
* @param dragEnd
*/
public void drag(Point dragStart, Point dragEnd) {
if (dragStart == null) {
return;
}
JViewport viewer = (JViewport) getParent();
Point offScreen = viewer.getViewPosition();
if (dragStart.x > dragEnd.x) {
offScreen.translate(viewer.getWidth(), 0);
}
if (dragStart.y > dragEnd.y) {
offScreen.translate(0, viewer.getHeight());
}
offScreen.translate(dragStart.x - dragEnd.x, dragStart.y - dragEnd.y);
Rectangle r = new Rectangle(offScreen.x, offScreen.y, 1, 1);
scrollRectToVisible(r);
}
/**
* Remove the component with this id from the canvas
* @param id
*/
public void deletePetriNetComponent(String id) {
PetriNetViewComponent component = petriNetComponents.get(id);
if (component != null) {
component.delete();
remove((Component) component);
}
validate();
repaint();
}
/**
*
* @return Grid displayed on the canvas
*/
public Grid getGrid() {
return grid;
}
/**
*
* @param handler specifies how the canvas should behave to mouse events
*/
public void setMouseHandler(MouseInputAdapter handler) {
addMouseListener(handler);
addMouseMotionListener(handler);
addMouseWheelListener(handler);
}
/**
* Used to set the bounds of the canvas so that it will expand if components go out of bound
*/
private class ChangeListener implements PlaceVisitor, TransitionVisitor {
/**
* Listens to (x,y) changes in components and updates the canvas width
* if a place/transition goes out of the current bounds
*/
private PropertyChangeListener updateListener = new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent evt) {
String name = evt.getPropertyName();
if (name.equals(Connectable.X_CHANGE_MESSAGE)) {
int x = (int) evt.getNewValue();
if (x > getWidth()) {
updatePreferredSize();
}
}
if (name.equals(Connectable.Y_CHANGE_MESSAGE)) {
int y = (int) evt.getNewValue();
if (y > getHeight()) {
updatePreferredSize();
}
}
}
};
/**
* Add the update listener to the place
* @param place
*/
@Override
public void visit(Place place) {
place.addPropertyChangeListener(updateListener);
}
/**
* Add the update listener to the transition
* @param transition
*/
@Override
public void visit(Transition transition) {
transition.addPropertyChangeListener(updateListener);
}
}
}
| true
|
e1cc3661768902bd5cfa37b33bcfc901f715dd8c
|
Java
|
funing90919/springboot-demos
|
/src/test/java/top/os/fun/SpringbootDemosApplicationTests.java
|
UTF-8
| 3,816
| 2.46875
| 2
|
[] |
no_license
|
package top.os.fun;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.test.context.junit4.SpringRunner;
import top.os.base.uitl.DateUtils;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;
import java.util.Date;
@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringbootDemosApplicationTests {
@Autowired
private JavaMailSenderImpl mailSerder;
@Value("${spring.mail.username}")
private String mailFrom;
@Test
public void simpleMail() {
SimpleMailMessage mail = new SimpleMailMessage();
mail.setFrom(mailFrom);
mail.setTo(new String[] {"funing90919@163.com", "785385019@qq.com"});
mail.setSubject("春节放假通知");
mail.setText("哈哈,骗你的!--本邮件发自SpringBoot单元测试" + this.getClass());
mailSerder.send(mail);
}
@Test
public void comlexMail() throws MessagingException {
// 1.创建复杂消息
MimeMessage mimeMessage = mailSerder.createMimeMessage();
// 2.组装邮件
MimeMessageHelper mail = new MimeMessageHelper(mimeMessage, true);
mail.setFrom(mailFrom);
mail.setTo(new String[] {"funing90919@163.com", "785385019@qq.com"});
mail.setSubject("春节放假通知");
mail.setText("<b style='color: red;'>哈哈,骗你的!</b>--本邮件发自SpringBoot单元测试" + this.getClass(), true);
// 上传附件
mail.addAttachment("aa.png", new File("C:\\Users\\Jacky\\Pictures\\PIC\\21.png"));
mailSerder.send(mimeMessage);
}
@Test
public void dateUtilsTest() {
Date parse1 = DateUtils.parse("2018", DateUtils.DateFormatter.YYYY);
Date parse2 = DateUtils.parse("2018-12", DateUtils.DateFormatter.YYYY_MM);
Date parse3 = DateUtils.parse("2018-12-12", DateUtils.DateFormatter.YYYY_MM_DD);
Date parse4 = DateUtils.parse("2018-12-12 00:11:22", DateUtils.DateFormatter.YYYY_MM_DD_HH_MM_SS);
System.err.println(parse1);
System.err.println(parse2);
System.err.println(parse3);
System.err.println(parse4);
String format1 = DateUtils.format(new Date(), DateUtils.DateFormatter.YYYY);
String format2 = DateUtils.format(new Date(), DateUtils.DateFormatter.YYYY_MM);
String format3 = DateUtils.format(new Date(), DateUtils.DateFormatter.YYMM_STR);
String format4 = DateUtils.format(new Date(), DateUtils.DateFormatter.YYYYMM_STR);
String format5 = DateUtils.format(new Date(), DateUtils.DateFormatter.YYYY_MM_DD);
String format6 = DateUtils.format(new Date(), DateUtils.DateFormatter.YYMMDD_STR);
String format7 = DateUtils.format(new Date(), DateUtils.DateFormatter.YYYYMMDD_STR);
String format8 = DateUtils.format(new Date(), DateUtils.DateFormatter.YYYY_MM_DD_HH_MM_SS);
String format9 = DateUtils.format(new Date(), DateUtils.DateFormatter.YYMMDDHHMMSS_STR);
String format10 = DateUtils.format(new Date(), DateUtils.DateFormatter.YYYYMMDDHHMMSS_STR);
String format11 = DateUtils.format(new Date(), DateUtils.DateFormatter.YYMMDDHHMMSSSSS_STR);
String format12 = DateUtils.format(new Date(), DateUtils.DateFormatter.YYYYMMDDHHMMSSSSS_STR);
System.err.println(format1);
System.err.println(format2);
System.err.println(format3);
System.err.println(format4);
System.err.println(format5);
System.err.println(format6);
System.err.println(format7);
System.err.println(format8);
System.err.println(format9);
System.err.println(format10);
System.err.println(format11);
System.err.println(format12);
}
}
| true
|
d163cf37305863dda74865b16d245ceae992b15b
|
Java
|
YourLeg1/lyz
|
/greendaostudy/src/main/java/demo04/com/greendaostudy/app/MyApp.java
|
UTF-8
| 968
| 2.359375
| 2
|
[] |
no_license
|
package demo04.com.greendaostudy.app;
import android.app.Application;
import android.database.sqlite.SQLiteDatabase;
import demo04.com.greendaostudy.gen.DaoMaster;
import demo04.com.greendaostudy.gen.DaoSession;
/**
* Created by 小可爱 on 2017/11/6.
*/
//类的用途 :单例设计模式
public class MyApp extends Application{
private static MyApp mInstance;
private DaoSession daoSession;
@Override
public void onCreate() {
super.onCreate();
mInstance = this;
setDb();
}
public static MyApp getmInstance(){
return mInstance;
}
private void setDb() {
DaoMaster.DevOpenHelper helper = new DaoMaster.DevOpenHelper(this, "bw.dbb", null);
SQLiteDatabase database = helper.getWritableDatabase();
DaoMaster daoMaster = new DaoMaster(database);
daoSession = daoMaster.newSession();
}
public DaoSession getDaoSessio(){
return daoSession;
}
}
| true
|
9a0a855ff325da872d6e67521f7e728a25028fb2
|
Java
|
oswardlx/demogo
|
/src/main/java/com/example/util/test/DataUtil.java
|
UTF-8
| 326
| 2.078125
| 2
|
[] |
no_license
|
package com.example.util.test;
import org.springframework.util.StringUtils;
public class DataUtil {
public static String [] separatePath(String path){
if(StringUtils.isEmpty(path)){
return null;
}
String[] sep = path.split("\\.");
return new String[]{sep[0],sep[1]};
}
}
| true
|
6438edf6d90a9be89417f14eb671be9e777f8099
|
Java
|
adrianhryn/Flower_shop
|
/flower/CountryOfOrigin.java
|
UTF-8
| 276
| 2.625
| 3
|
[] |
no_license
|
package flower;
import lombok.Getter;
import lombok.Setter;
@Getter
public enum CountryOfOrigin {
UKRAINE("Ukraine"), SPAIN("Spain"), ITALY("Italy");
private String country;
CountryOfOrigin(String country){
this.country = country;
}
}
| true
|
14c4b2208b17b4dec3050c57b7eecc0190438335
|
Java
|
GGuinea/pkiapp
|
/src/main/java/pkiapp/DataBaseServlet.java
|
UTF-8
| 1,875
| 2.453125
| 2
|
[] |
no_license
|
package pkiapp;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
public class DataBaseServlet extends HttpServlet {
private static final long serialVersionUID = -4751096228274971485L;
private static Connection getConnection() throws URISyntaxException, SQLException {
URI dbUri = new URI(
"postgres://cufyfhbntvbmps:b36f62b672799e429f35145edaf4580617a16e2a05131167271cc380cef277d7@ec2-54-247-94-127.eu-west-1.compute.amazonaws.com:5432/d76jkk36ue2tp4");
String username = dbUri.getUserInfo()
.split(":")[0];
String password = dbUri.getUserInfo()
.split(":")[1];
String dbUrl = "jdbc:postgresql://" + dbUri.getHost() + dbUri.getPath();
return DriverManager.getConnection(dbUrl, username, password);
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
try {
List<String> tableList = new ArrayList<>();
DatabaseMetaData dvmd = getConnection().getMetaData();
String[] types = {"TABLE"};
ResultSet resultSet = dvmd.getTables(null, null, "%", types);
while(resultSet.next()) {
tableList.add(resultSet.getString("TABLE_NAME"));
}
req.setAttribute("tableList", tableList);
RequestDispatcher view = req.getRequestDispatcher("tableList.jsp");
view.forward(req, resp);
} catch (SQLException e) {
e.printStackTrace();
} catch (URISyntaxException e) {
e.printStackTrace();
}
}
}
| true
|
587590cb11ae31ab74ff19b5d6c86fecf6d96ebe
|
Java
|
javabcde/Tom-Im
|
/src/main/java/protocol/PacketCodec.java
|
UTF-8
| 6,978
| 2.015625
| 2
|
[] |
no_license
|
package protocol;
import static protocol.command.Command.BUSSINESS_CODEC;
import static protocol.command.Command.CREATE_GROUP_REQUEST;
import static protocol.command.Command.CREATE_GROUP_RESPONSE;
import static protocol.command.Command.GROUP_MESSAGE_REQUEST;
import static protocol.command.Command.GROUP_MESSAGE_RESPONSE;
import static protocol.command.Command.HEARTBEAT_REQUEST;
import static protocol.command.Command.HEARTBEAT_RESPONSE;
import static protocol.command.Command.JOIN_GROUP_REQUEST;
import static protocol.command.Command.JOIN_GROUP_RESPONSE;
import static protocol.command.Command.LIST_GROUP_MEMBERS_REQUEST;
import static protocol.command.Command.LIST_GROUP_MEMBERS_RESPONSE;
import static protocol.command.Command.LOGIN_REQUEST;
import static protocol.command.Command.LOGIN_RESPONSE;
import static protocol.command.Command.LOGOUT_REQUEST;
import static protocol.command.Command.LOGOUT_RESPONSE;
import static protocol.command.Command.MESSAGE_REQUEST;
import static protocol.command.Command.MESSAGE_RESPONSE;
import static protocol.command.Command.QUIT_GROUP_REQUEST;
import static protocol.command.Command.QUIT_GROUP_RESPONSE;
import codec.BussinessCodec;
import io.netty.buffer.ByteBuf;
import java.util.HashMap;
import java.util.Map;
import protocol.requestPacket.CreateGroupRequestPacket;
import protocol.requestPacket.GroupMessageRequestPacket;
import protocol.requestPacket.HeartBeatRequestPacket;
import protocol.requestPacket.JoinGroupRequestPacket;
import protocol.requestPacket.ListGroupMembersRequestPacket;
import protocol.requestPacket.LoginRequestPacket;
import protocol.requestPacket.LogoutRequestPacket;
import protocol.requestPacket.MessageRequestPacket;
import protocol.requestPacket.QuitGroupRequestPacket;
import protocol.responsePacket.CreateGroupResponsePacket;
import protocol.responsePacket.GroupMessageResponsePacket;
import protocol.responsePacket.HeartBeatResponsePacket;
import protocol.responsePacket.JoinGroupResponsePacket;
import protocol.responsePacket.ListGroupMembersResponsePacket;
import protocol.responsePacket.LoginResponsePacket;
import protocol.responsePacket.LogoutResponsePacket;
import protocol.responsePacket.MessageResponsePacket;
import protocol.responsePacket.QuitGroupResponsePacket;
import protocol.serialize.Serializer;
import protocol.serialize.impl.JSONSerializer;
/**
* <pre>
* **********************************************************************
* Protocol
* +-------+----------+------------+----------+---------+---------------+
* | | | | | | |
* | 4 | 1 | 1 | 1 | 4 | N |
* +--------------------------------------------------------------------+
* | | | | | | |
* | magic | version | serializer | command | length | body |
* | | | | | | |
* +-------+----------+------------+----------+---------+---------------+
* 消息头11个字节定长
* = 4 // 魔数,magic = (int) 0x12345678
* + 1 // 版本号,通常情况下时预留字段,用于协议升级的时候用到.
* + 1 // 序列化算法,如何把Java对象转换二进制数据已经二进制数据如何转换回Java对象
* + 1 // 指令
* + 4 // 数据部分的长度,int类型
* </pre>
*
* @author james mu
* @date 18-12-3 下午2:32
*/
public class PacketCodec {
public static final int MAGIC_NUMBER = 0x12345678;
public static final PacketCodec INSTANCE = new PacketCodec();
private final Map<Byte, Class<? extends Packet>> packetTypeMap;
private final Map<Byte, Serializer> serializerMap;
private PacketCodec() {
packetTypeMap = new HashMap<>();
packetTypeMap.put(LOGIN_REQUEST, LoginRequestPacket.class);
packetTypeMap.put(LOGIN_RESPONSE, LoginResponsePacket.class);
packetTypeMap.put(MESSAGE_REQUEST, MessageRequestPacket.class);
packetTypeMap.put(MESSAGE_RESPONSE, MessageResponsePacket.class);
packetTypeMap.put(LOGOUT_REQUEST, LogoutRequestPacket.class);
packetTypeMap.put(LOGOUT_RESPONSE, LogoutResponsePacket.class);
packetTypeMap.put(CREATE_GROUP_REQUEST, CreateGroupRequestPacket.class);
packetTypeMap.put(CREATE_GROUP_RESPONSE, CreateGroupResponsePacket.class);
packetTypeMap.put(JOIN_GROUP_REQUEST, JoinGroupRequestPacket.class);
packetTypeMap.put(JOIN_GROUP_RESPONSE, JoinGroupResponsePacket.class);
packetTypeMap.put(QUIT_GROUP_REQUEST, QuitGroupRequestPacket.class);
packetTypeMap.put(QUIT_GROUP_RESPONSE, QuitGroupResponsePacket.class);
packetTypeMap.put(LIST_GROUP_MEMBERS_REQUEST, ListGroupMembersRequestPacket.class);
packetTypeMap.put(LIST_GROUP_MEMBERS_RESPONSE, ListGroupMembersResponsePacket.class);
packetTypeMap.put(GROUP_MESSAGE_REQUEST, GroupMessageRequestPacket.class);
packetTypeMap.put(GROUP_MESSAGE_RESPONSE, GroupMessageResponsePacket.class);
packetTypeMap.put(HEARTBEAT_REQUEST, HeartBeatRequestPacket.class);
packetTypeMap.put(HEARTBEAT_RESPONSE, HeartBeatResponsePacket.class);
packetTypeMap.put(BUSSINESS_CODEC, BussinessCodec.class);
serializerMap = new HashMap<>();
Serializer serializer = new JSONSerializer();
//todo 以后加上谷歌的那个序列化
serializerMap.put(serializer.getSerializerAlgorithm(), serializer);
}
public void encode(ByteBuf byteBuf, Packet packet) {
// 1. 序列化 java 对象
byte[] bytes = Serializer.DEFAULT.serialize(packet);
// 2. 实际编码过程
byteBuf.writeInt(MAGIC_NUMBER);
byteBuf.writeByte(packet.getVersion());
byteBuf.writeByte(Serializer.DEFAULT.getSerializerAlgorithm());
byteBuf.writeByte(packet.getCommand());
byteBuf.writeInt(bytes.length);
byteBuf.writeBytes(bytes);
}
public Packet decode(ByteBuf byteBuf) {
// 跳过 magic number
byteBuf.skipBytes(4);
// 跳过版本号
byteBuf.skipBytes(1);
// 序列化算法
byte serializeAlgorithm = byteBuf.readByte();
// 指令
byte command = byteBuf.readByte();
// 数据包长度
int length = byteBuf.readInt();
byte[] bytes = new byte[length];
byteBuf.readBytes(bytes);
Class<? extends Packet> requestType = getRequestType(command);
Serializer serializer = getSerializer(serializeAlgorithm);
if (requestType != null && serializer != null) {
return serializer.deserialize(requestType, bytes);
}
return null;
}
private Serializer getSerializer(byte serializeAlgorithm) {
return serializerMap.get(serializeAlgorithm);
}
private Class<? extends Packet> getRequestType(byte command) {
return packetTypeMap.get(command);
}
}
| true
|
89467bf9b6728232eb13c716cb6b2d5e07a279b1
|
Java
|
z521598/design
|
/src/baidu/command/Invoker.java
|
UTF-8
| 478
| 2.546875
| 3
|
[] |
no_license
|
package baidu.command;
import java.util.List;
/**
* Created by Administrator on 2017/3/7.
*/
// 调用者,发起者
public class Invoker {
private Command command;// 可以多条
private List<Command> commands;
public Invoker(List<Command> commands) {
this.commands = commands;
}
// 多条可以批处理
public void call() {
for (int i = 0; i < commands.size(); i++) {
commands.get(0).execute();
}
}
}
| true
|
a4ad1fe1371b2bf00729bd6f7151feb92a4a96fb
|
Java
|
fxcjj/swing
|
/src/main/java/com/vic/fuck/LoginUI.java
|
UTF-8
| 545
| 2.375
| 2
|
[] |
no_license
|
package com.vic.fuck;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.WindowConstants;
public class LoginUI {
public static void main(String[] args) {
JFrame jf = new JFrame("User login");
//关闭窗口,程序退出
jf.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
//创建内容面板,默认使用流式布局
JPanel panel = new JPanel();
//something
jf.setContentPane(panel);
jf.pack();
jf.setLocationRelativeTo(null);
jf.setVisible(true);
}
}
| true
|
41b830aeb0b8123fbfba1d280166c6fcda63d76d
|
Java
|
reach-u/kov48
|
/src/main/java/com/reach_u/kov48/conf/SwaggerConf.java
|
UTF-8
| 1,513
| 1.890625
| 2
|
[] |
no_license
|
package com.reach_u.kov48.conf;
import com.google.common.collect.Lists;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ParameterBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.schema.ModelRef;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
@Configuration
@EnableSwagger2
public class SwaggerConf {
@Value("${bgm.swagger.base.path:}")
private String basePath;
@Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2).select()
.apis(RequestHandlerSelectors.basePackage("com.reach_u.kov48.rest.controller"))
.paths(PathSelectors.any()).build()
.pathMapping(basePath)
.globalOperationParameters(
Lists.newArrayList(new ParameterBuilder()
.name("apikey")
.description("Person ID code")
.modelRef(new ModelRef("string"))
.parameterType("header")
.required(true)
.build()));
}
}
| true
|
5d31c797702bbef033e0c573ef203146b7929ac6
|
Java
|
JanKonarski/perspective
|
/src/main/java/perspective/Configuration.java
|
UTF-8
| 519
| 2.609375
| 3
|
[] |
no_license
|
package perspective;
/**
*
* @author Jan Konarski
*/
public class Configuration {
public int windowWidth = 1280;
public int windowHeight = 800;
public int cameraFocalLength = 50;
//TODO: image background color
//TODO: image line color
public int parse(String stringValue) throws IllegalArgumentException{
int value = Integer.parseInt(stringValue);
if(value < 1)
throw new IllegalArgumentException("Value couldn't be negative value");
return value;
}
}
| true
|
ba27af897ab705408d807b9c3331edd136c3f019
|
Java
|
manav13x/SpringPrograms
|
/manav-spring/emplyoee-spring-data-app-testing/src/main/java/com/verizon/emp/dao/EmplyoeeRepository.java
|
UTF-8
| 800
| 2.078125
| 2
|
[] |
no_license
|
package com.verizon.emp.dao;
import java.time.LocalDate;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.format.annotation.DateTimeFormat.ISO;
import org.springframework.stereotype.Repository;
import com.verizon.emp.model.Emplyoee;
@Repository
public interface EmplyoeeRepository extends JpaRepository<Emplyoee, Long> {
boolean existsByMobileNumber(String mobileNumber);
boolean existsByEmailId(String Emplyoee);
Emplyoee findByMobileNumber(String mobileNumber);
Emplyoee findByEmailId(String emailId);
List<Emplyoee> findAllByLastName(String lastName);
List<Emplyoee> findAllByDept(String dept);
List<Emplyoee> findAllByDateOfBirth(LocalDate dateOfBirth);
}
| true
|
54c8c293ac431d1f59f665f737578b7a72952e43
|
Java
|
a569433273/newkepu
|
/src/com/liu/newkepu/dao/Impl/CuxiaozhengceDaoImpl.java
|
UTF-8
| 808
| 2.109375
| 2
|
[] |
no_license
|
package com.liu.newkepu.dao.Impl;
import com.liu.newkepu.dao.CuxiaozhengceDao;
import com.liu.newkepu.model.Cuxiaozhengce;
import org.hibernate.Query;
import org.hibernate.SessionFactory;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.util.List;
@Component("CuxiaozhengceDao")
public class CuxiaozhengceDaoImpl implements CuxiaozhengceDao {
@Resource
private SessionFactory sessionFactory;
@Override
public List<Cuxiaozhengce> findByhybsandother(int hybs, String from, String arrival) {
Query query = sessionFactory.getCurrentSession().createQuery("from Cuxiaozhengce c where c.cxzc_hybs='" + hybs + "' and c.cxzc_isstar='1'and c.cxzc_from='" + from + "' and c.cxzc_arrival='" + arrival + "'");
return query.list();
}
}
| true
|
d57ebfa471deffb0da99afa9dd6ce5cf8fd6dcf9
|
Java
|
ngnganh2207/Module-2.-T-ng-H-p-BT
|
/Bai6.KeThua.TuTest/src/test/Test2.java
|
UTF-8
| 127
| 1.75
| 2
|
[] |
no_license
|
package test;
public class Test2 extends Test1 {
@Override
public String hello(){
return "xin chào";
}
}
| true
|
7834db361289f92e442be8bf7b5e2d29b3fd43a6
|
Java
|
xunfeng324/Mybatis
|
/mybatis/src/main/java/com/jt/pojo/User.java
|
UTF-8
| 401
| 1.835938
| 2
|
[] |
no_license
|
package com.jt.pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;
@Data
@Accessors(chain = true)//链式加载
@NoArgsConstructor//无参构造
@AllArgsConstructor//有残构造
public class User {
private Integer id;
private String name;
private Integer age;
private String sex;
//222
//123
}
| true
|
7e99868297277b99a09770b4df0b8db09f7ecd2f
|
Java
|
trinodb/trino
|
/lib/trino-filesystem/src/main/java/io/trino/filesystem/tracing/TracingInputFile.java
|
UTF-8
| 3,714
| 1.9375
| 2
|
[
"Apache-2.0"
] |
permissive
|
/*
* 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.trino.filesystem.tracing;
import io.opentelemetry.api.trace.Span;
import io.opentelemetry.api.trace.Tracer;
import io.trino.filesystem.Location;
import io.trino.filesystem.TrinoInput;
import io.trino.filesystem.TrinoInputFile;
import io.trino.filesystem.TrinoInputStream;
import java.io.IOException;
import java.time.Instant;
import java.util.Optional;
import static io.trino.filesystem.tracing.Tracing.attribute;
import static io.trino.filesystem.tracing.Tracing.withTracing;
import static java.util.Objects.requireNonNull;
final class TracingInputFile
implements TrinoInputFile
{
private final Tracer tracer;
private final TrinoInputFile delegate;
private final Optional<Long> length;
public TracingInputFile(Tracer tracer, TrinoInputFile delegate, Optional<Long> length)
{
this.tracer = requireNonNull(tracer, "tracer is null");
this.delegate = requireNonNull(delegate, "delegate is null");
this.length = requireNonNull(length, "length is null");
}
@Override
public TrinoInput newInput()
throws IOException
{
Span span = tracer.spanBuilder("InputFile.newInput")
.setAttribute(FileSystemAttributes.FILE_LOCATION, toString())
.setAllAttributes(attribute(FileSystemAttributes.FILE_SIZE, length))
.startSpan();
return withTracing(span, () -> new TracingInput(tracer, delegate.newInput(), location(), length));
}
@Override
public TrinoInputStream newStream()
throws IOException
{
Span span = tracer.spanBuilder("InputFile.newStream")
.setAttribute(FileSystemAttributes.FILE_LOCATION, toString())
.setAllAttributes(attribute(FileSystemAttributes.FILE_SIZE, length))
.startSpan();
return withTracing(span, delegate::newStream);
}
@Override
public long length()
throws IOException
{
// skip tracing if length is cached, but delegate anyway
if (length.isPresent()) {
return delegate.length();
}
Span span = tracer.spanBuilder("InputFile.length")
.setAttribute(FileSystemAttributes.FILE_LOCATION, toString())
.startSpan();
return withTracing(span, delegate::length);
}
@Override
public Instant lastModified()
throws IOException
{
Span span = tracer.spanBuilder("InputFile.lastModified")
.setAttribute(FileSystemAttributes.FILE_LOCATION, toString())
.startSpan();
return withTracing(span, delegate::lastModified);
}
@Override
public boolean exists()
throws IOException
{
Span span = tracer.spanBuilder("InputFile.exists")
.setAttribute(FileSystemAttributes.FILE_LOCATION, toString())
.startSpan();
return withTracing(span, delegate::exists);
}
@Override
public Location location()
{
return delegate.location();
}
@Override
public String toString()
{
return location().toString();
}
}
| true
|
060746a04b881b3b1230fc2025429412faa4c8dd
|
Java
|
retosjalisco/mujerjalisco
|
/MujerJaliscoAndroid/app/src/main/java/com/dotstudio/mujerjalisco/CustomListAdapter.java
|
UTF-8
| 2,667
| 2.1875
| 2
|
[] |
no_license
|
package com.dotstudio.mujerjalisco;
import android.app.Activity;
import android.content.ClipData;
import android.content.Context;
import android.support.v4.widget.ViewDragHelper;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import org.w3c.dom.Text;
import java.security.acl.LastOwnerException;
import java.util.ArrayList;
public class CustomListAdapter extends BaseAdapter {
private ArrayList<ItemGet> listData;
Context context;
public ImageLoader imageLoader;
public CustomListAdapter(Context context, ArrayList<ItemGet> listData) {
this.listData = listData;
this.context = context;
imageLoader=new ImageLoader(context.getApplicationContext());
}
@Override
public int getCount() { return listData.size(); }
@Override
public Object getItem(int position) { return listData.get(position); }
@Override
public long getItemId(int position) { return position; }
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if(convertView == null) {
LayoutInflater mInflater = (LayoutInflater) context
.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
convertView = mInflater.inflate(R.layout.comunidadrow, null);
holder = new ViewHolder();
holder.titulotxt = (TextView) convertView.findViewById(R.id.textView13);
holder.descripciontxt = (TextView) convertView.findViewById(R.id.textView14);
holder.fechatxt = (TextView) convertView.findViewById(R.id.textView15);
holder.nocomentariostxt = (TextView) convertView.findViewById(R.id.textView16);
holder.foto = (ImageView) convertView.findViewById(R.id.imageView3);
convertView.setTag(holder);
}
else {
holder = (ViewHolder) convertView.getTag();
}
holder.titulotxt.setText(listData.get(position).getTitulo());
holder.descripciontxt.setText(listData.get(position).getSubtitulo());
holder.fechatxt.setText(listData.get(position).getFecha());
holder.nocomentariostxt.setText("Comentarios:2");
String path = listData.get(position).getImagen();
imageLoader.DisplayImage(path, holder.foto);
return convertView;
}
static class ViewHolder {
TextView titulotxt;
TextView descripciontxt;
TextView fechatxt;
TextView nocomentariostxt;
ImageView foto;
}
}
| true
|
6284b304a07994d354f2faf20b7e0ff22ac70f44
|
Java
|
zhulaoqi/Backend_development
|
/Spring_demo/src/main/Service/testService.java
|
UTF-8
| 82
| 1.71875
| 2
|
[] |
no_license
|
package main.Service;
public interface testService {
void findService();
}
| true
|
a7b3d5cded871bd765619bdd415b1f9ebe3530a4
|
Java
|
yarslvhomelinux/SpringCourse
|
/BookShopSpring/src/main/java/org/bookshop/app/services/UserRepository.java
|
UTF-8
| 755
| 2.484375
| 2
|
[] |
no_license
|
package org.bookshop.app.services;
import org.bookshop.web.dto.User;
import org.springframework.stereotype.Repository;
import java.util.ArrayList;
import java.util.List;
@Repository
public class UserRepository implements ProjectRepository<User> {
List<User> userList = new ArrayList<>();
@Override
public List<User> retreiveAll() {
return userList;
}
@Override
public void store(User user) {
userList.add(user);
}
@Override
public boolean removeItemById(Integer bookIdToRemove) {
for (User user : userList) {
if (user.getId().equals(bookIdToRemove)) {
userList.remove(user);
return true;
}
}
return false;
}
}
| true
|
fcfa2cbed8cb90f3b3147ebfc08b5be32e81f44c
|
Java
|
ThisWillGoWell/home-control-server
|
/src/main/java/home/system/SystemParent.java
|
UTF-8
| 4,848
| 2.5625
| 3
|
[] |
no_license
|
package home.system;
import home.controller.*;
import home.controller.subscriber.Publisher;
import home.controller.subscriber.Subscriber;
import home.controller.subscriber.SubscriberManager;
import home.parcel.Parcel;
import home.parcel.SystemException;
import home.controller.PS.GenericPS;
import java.util.concurrent.ConcurrentLinkedQueue;
/**
* Created by Willi on 9/26/2016.
*/
public abstract class SystemParent implements Runnable, Subscriber, Publisher {
protected Engine engine;
private long updateInterval;
protected String systemIdentifer;
private Thread thread;
protected ConcurrentLinkedQueue<Parcel> updateQueue;
public SystemParent(String name){
this(name, null);
}
public SystemParent(String name, Engine e)
{
this(name, e,-1);
}
public SystemParent(String name, Engine e, long updateInterval)
{
this.updateInterval = updateInterval;
this.engine = e;
this.systemIdentifer = name;
SubscriberManager.register(this);
thread = new Thread(this);
this.updateQueue = new ConcurrentLinkedQueue();
}
private void registerSubscriber(Parcel p) throws SystemException {
Logger.log(this, "registering subscriber " + p.toString(), Logger.LOG_LEVEL_INFO);
p.put(GenericPS.OP_KEY, "get");
switch (p.getString("type")){
case GenericPS.SUB_ALERT_TYPE:
SubscriberManager.listen(p.getSubscriber(GenericPS.SUBSCRIBER_KEY), this);
break;
case GenericPS.SUB_CHANGE_TYPE:
SubscriberManager.subscribe(p.getSubscriber(GenericPS.SUBSCRIBER_KEY), this, p);
break;
default:
throw SystemException.WHAT_NOT_SUPPORTED(p);
}
}
public void start(){
thread.start();
}
private void deregisterSubscriber(Subscriber s){
SubscriberManager.unsubscribe(s, this);
}
/*
Command: Replacement for /set and /get
All calls will be routed though this command interface and
use the dict to extrace the operation: "op"
*/
public Parcel command(Parcel p){
/*
take care of any high level command here,
Only one currently in use is register for websocket listener
*/
Parcel response = null;
Logger.log(this,p);
try {
switch (p.getString(GenericPS.OP_KEY)){
default:
return process(p);
case GenericPS.SUB_COMMAND:
registerSubscriber(p);
response= Parcel.RESPONSE_PARCEL("register success");
break;
case GenericPS.DEREGISTER_COMMAND:
deregisterSubscriber(p.getSubscriber("subscriber"));
response = Parcel.RESPONSE_PARCEL("deregister success");
break;
case GenericPS.UPDATE_COMMAND:
update();
response = Parcel.RESPONSE_PARCEL("updated");
break;
case GenericPS.HELLO_COMMAND:
response = Parcel.RESPONSE_PARCEL("hi");
break;
}
} catch (SystemException e) {
Logger.log(this, e);
return Parcel.RESPONSE_PARCEL_ERROR(e);
}finally {
SubscriberManager.checkUpdate(this);
}
Logger.log(this, response);
return response;
}
public abstract Parcel process(Parcel p) throws SystemException;
public Engine getEngine() {
return engine;
}
/**
* init is called before the first update after thread has been started
* @throws SystemException
*/
public void init() throws SystemException {
}
public void stop(){
thread.interrupt();
}
public void run(){
try {
init();
if(updateInterval != -1) {
while (true) {
update();
SubscriberManager.checkUpdate(this);
if(updateInterval <= 0){
break;
}
Thread.sleep(updateInterval);
}
}
}
catch (InterruptedException e) {
Logger.log(this, e);
} catch (SystemException e) {
e.printStackTrace();
}
}
/**
* Run this on subscription alert
* @param p
*/
public void subscriptionAlert(Parcel p){
}
/**
*
* @return
*/
public String getSystemIdentifer() {
return systemIdentifer;
}
@Override
public String getPublisherIdentifer() {
return getSystemIdentifer();
}
public void update() throws SystemException {
}
}
| true
|
e80e608e80ae6512f109781a69f1dc84dee76b0a
|
Java
|
lenik/stack
|
/ape/execution/ape-engine/src/main/java/com/bee32/ape/engine/identity/mem/MemoryActivitiDatabase.java
|
UTF-8
| 4,731
| 2.421875
| 2
|
[] |
no_license
|
package com.bee32.ape.engine.identity.mem;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import org.activiti.engine.identity.Group;
import org.activiti.engine.identity.User;
import org.activiti.engine.impl.persistence.entity.GroupEntity;
import org.activiti.engine.impl.persistence.entity.UserEntity;
import com.bee32.ape.engine.identity.ActivitiGroupType;
public class MemoryActivitiDatabase {
private Map<String, UserEntity> userMap = new HashMap<>();
private Map<String, GroupEntity> groupMap = new HashMap<>();
private Map<String, Set<String>> userGroups = new HashMap<>();
private Map<String, Set<String>> groupUsers = new HashMap<>();
public UserEntity getUser(String userId) {
return userMap.get(userId);
}
public GroupEntity getGroup(String groupId) {
return groupMap.get(groupId);
}
public Collection<UserEntity> getUsers() {
return userMap.values();
}
public Collection<GroupEntity> getGroups() {
return groupMap.values();
}
public synchronized void addUser(UserEntity user) {
if (user == null)
throw new NullPointerException("user");
String userId = user.getId();
if (userId == null)
throw new NullPointerException("userId");
UserEntity existing = userMap.get(userId);
if (existing != null)
throw new IllegalStateException("User is already existed: " + userId);
userMap.put(userId, user);
}
public synchronized void addGroup(GroupEntity group) {
if (group == null)
throw new NullPointerException("group");
String groupId = group.getId();
if (groupId == null)
throw new NullPointerException("groupId");
GroupEntity existing = groupMap.get(groupId);
if (existing != null)
throw new IllegalStateException("Group is already existed: " + groupId);
groupMap.put(groupId, group);
}
public synchronized void removeUserById(String userId) {
if (userId == null)
throw new NullPointerException("userId");
userMap.remove(userId);
userGroups.remove(userId);
for (Set<String> set : groupUsers.values())
set.remove(userId);
}
public synchronized void removeGroupById(String groupId) {
if (groupId == null)
throw new NullPointerException("groupId");
groupMap.remove(groupId);
groupUsers.remove(groupId);
for (Set<String> set : userGroups.values())
set.remove(groupId);
}
public synchronized Set<String> getGroupIdSet(String userId) {
if (userId == null)
throw new NullPointerException("userId");
Set<String> groups = userGroups.get(userId);
if (groups == null)
userGroups.put(userId, groups = new HashSet<>());
return groups;
}
public synchronized Set<String> getMemberIdSet(String groupId) {
if (groupId == null)
throw new NullPointerException("groupId");
Set<String> members = groupUsers.get(groupId);
if (members == null)
groupUsers.put(groupId, members = new HashSet<>());
return members;
}
public synchronized void addMembership(Group group, User user) {
if (group == null)
throw new NullPointerException("group");
if (user == null)
throw new NullPointerException("user");
addMembership(group.getId(), user.getId());
}
public synchronized void addMembership(String groupId, String userId) {
if (userId == null)
throw new NullPointerException("userId");
if (groupId == null)
throw new NullPointerException("groupId");
getGroupIdSet(userId).add(groupId);
getMemberIdSet(groupId).add(userId);
}
public GroupEntity ADMIN_GROUP = createGroup(ActivitiGroupType.SECURITY_ROLE_ADMIN, "APE Administrators");
public GroupEntity USER_GROUP = createGroup(ActivitiGroupType.SECURITY_ROLE_USER, "APE Users");
{
addGroup(ADMIN_GROUP);
addGroup(USER_GROUP);
}
static GroupEntity createGroup(String id, String name) {
GroupEntity group = new GroupEntity(id);
group.setName(name);
group.setType(ActivitiGroupType.SECURITY_ROLE);
return group;
}
static UserEntity createUser(String id, String firstName, String lastName, String password) {
UserEntity user = new UserEntity(id);
user.setFirstName(firstName);
user.setLastName(lastName);
user.setPassword(password);
return user;
}
}
| true
|
edb810ad3b88ed764cfe86eec5c0be01d076d2de
|
Java
|
huankai/hk-core
|
/hk-core-poi/src/main/java/com/hk/commons/poi/excel/model/ReadParam.java
|
UTF-8
| 1,488
| 2.171875
| 2
|
[] |
no_license
|
package com.hk.commons.poi.excel.model;
import java.util.List;
import java.util.Map;
import com.hk.commons.poi.excel.read.interceptor.ValidationInterceptor;
import com.hk.commons.poi.excel.read.validation.Validationable;
import lombok.Builder;
import lombok.Data;
/**
* 读取 Excel参数
*
* @author kevin
* @date 2018年1月10日下午5:17:49
*/
@Data
@Builder
public class ReadParam<T> {
/**
* 標題行
*/
private int titleRow;
/**
* 数据开始行
*/
@Builder.Default
private int dataStartRow = 1;
/**
* <pre>
* 是否解析所有工作表
* 如果设置为 true,自定义的 sheetStartIndex 与 sheetMaxIndex 将被覆盖
* </pre>
*/
private boolean parseAll;
/**
* 开始读取的sheet位置
*/
private int sheetStartIndex;
/**
* 上传表格需要读取的sheet最大的索引
*/
private int sheetMaxIndex;
/**
* 是否输出公式结果值
*/
private boolean outputFormulaValues;
/**
* 是否过滤单元格首尾空字符串
*/
@Builder.Default
private boolean trim = true;
/**
* <pre>
* 是否忽略换行符号
* </pre>
*/
private boolean ignoreLineBreak;
/**
* 列与属性映射
*/
private Map<Integer, String> columnProperties;
/**
* BeanClazz
*/
private Class<T> beanClazz;
/**
* 验证拦截器
*/
@Builder.Default
private ValidationInterceptor<T> interceptor = ValidationInterceptor.INSTANCE;
/**
* 验证器
*/
private List<Validationable<T>> validationList;
}
| true
|
bb4b437ca27d044e8cbb2ff112fb634adb5fbfec
|
Java
|
mohitrajvardhan17/java1.8.0_151
|
/sun/util/locale/provider/SPILocaleProviderAdapter.java
|
UTF-8
| 21,965
| 2.078125
| 2
|
[] |
no_license
|
package sun.util.locale.provider;
import java.security.AccessController;
import java.security.PrivilegedActionException;
import java.security.PrivilegedExceptionAction;
import java.text.BreakIterator;
import java.text.Collator;
import java.text.DateFormat;
import java.text.DateFormatSymbols;
import java.text.DecimalFormatSymbols;
import java.text.NumberFormat;
import java.text.spi.BreakIteratorProvider;
import java.text.spi.CollatorProvider;
import java.text.spi.DateFormatProvider;
import java.text.spi.DateFormatSymbolsProvider;
import java.text.spi.DecimalFormatSymbolsProvider;
import java.text.spi.NumberFormatProvider;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.ServiceLoader;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.spi.CalendarDataProvider;
import java.util.spi.CalendarNameProvider;
import java.util.spi.CurrencyNameProvider;
import java.util.spi.LocaleNameProvider;
import java.util.spi.LocaleServiceProvider;
import java.util.spi.TimeZoneNameProvider;
public class SPILocaleProviderAdapter
extends AuxLocaleProviderAdapter
{
public SPILocaleProviderAdapter() {}
public LocaleProviderAdapter.Type getAdapterType()
{
return LocaleProviderAdapter.Type.SPI;
}
protected <P extends LocaleServiceProvider> P findInstalledProvider(final Class<P> paramClass)
{
try
{
(LocaleServiceProvider)AccessController.doPrivileged(new PrivilegedExceptionAction()
{
public P run()
{
LocaleServiceProvider localLocaleServiceProvider1 = null;
Iterator localIterator = ServiceLoader.loadInstalled(paramClass).iterator();
while (localIterator.hasNext())
{
LocaleServiceProvider localLocaleServiceProvider2 = (LocaleServiceProvider)localIterator.next();
if (localLocaleServiceProvider1 == null) {
try
{
localLocaleServiceProvider1 = (LocaleServiceProvider)Class.forName(SPILocaleProviderAdapter.class.getCanonicalName() + "$" + paramClass.getSimpleName() + "Delegate").newInstance();
}
catch (ClassNotFoundException|InstantiationException|IllegalAccessException localClassNotFoundException)
{
LocaleServiceProviderPool.config(SPILocaleProviderAdapter.class, localClassNotFoundException.toString());
return null;
}
}
((SPILocaleProviderAdapter.Delegate)localLocaleServiceProvider1).addImpl(localLocaleServiceProvider2);
}
return localLocaleServiceProvider1;
}
});
}
catch (PrivilegedActionException localPrivilegedActionException)
{
LocaleServiceProviderPool.config(SPILocaleProviderAdapter.class, localPrivilegedActionException.toString());
}
return null;
}
private static <P extends LocaleServiceProvider> P getImpl(Map<Locale, P> paramMap, Locale paramLocale)
{
Iterator localIterator = LocaleServiceProviderPool.getLookupLocales(paramLocale).iterator();
while (localIterator.hasNext())
{
Locale localLocale = (Locale)localIterator.next();
LocaleServiceProvider localLocaleServiceProvider = (LocaleServiceProvider)paramMap.get(localLocale);
if (localLocaleServiceProvider != null) {
return localLocaleServiceProvider;
}
}
return null;
}
static class BreakIteratorProviderDelegate
extends BreakIteratorProvider
implements SPILocaleProviderAdapter.Delegate<BreakIteratorProvider>
{
private ConcurrentMap<Locale, BreakIteratorProvider> map = new ConcurrentHashMap();
BreakIteratorProviderDelegate() {}
public void addImpl(BreakIteratorProvider paramBreakIteratorProvider)
{
for (Locale localLocale : paramBreakIteratorProvider.getAvailableLocales()) {
map.putIfAbsent(localLocale, paramBreakIteratorProvider);
}
}
public BreakIteratorProvider getImpl(Locale paramLocale)
{
return (BreakIteratorProvider)SPILocaleProviderAdapter.getImpl(map, paramLocale);
}
public Locale[] getAvailableLocales()
{
return (Locale[])map.keySet().toArray(new Locale[0]);
}
public boolean isSupportedLocale(Locale paramLocale)
{
return map.containsKey(paramLocale);
}
public BreakIterator getWordInstance(Locale paramLocale)
{
BreakIteratorProvider localBreakIteratorProvider = getImpl(paramLocale);
assert (localBreakIteratorProvider != null);
return localBreakIteratorProvider.getWordInstance(paramLocale);
}
public BreakIterator getLineInstance(Locale paramLocale)
{
BreakIteratorProvider localBreakIteratorProvider = getImpl(paramLocale);
assert (localBreakIteratorProvider != null);
return localBreakIteratorProvider.getLineInstance(paramLocale);
}
public BreakIterator getCharacterInstance(Locale paramLocale)
{
BreakIteratorProvider localBreakIteratorProvider = getImpl(paramLocale);
assert (localBreakIteratorProvider != null);
return localBreakIteratorProvider.getCharacterInstance(paramLocale);
}
public BreakIterator getSentenceInstance(Locale paramLocale)
{
BreakIteratorProvider localBreakIteratorProvider = getImpl(paramLocale);
assert (localBreakIteratorProvider != null);
return localBreakIteratorProvider.getSentenceInstance(paramLocale);
}
}
static class CalendarDataProviderDelegate
extends CalendarDataProvider
implements SPILocaleProviderAdapter.Delegate<CalendarDataProvider>
{
private ConcurrentMap<Locale, CalendarDataProvider> map = new ConcurrentHashMap();
CalendarDataProviderDelegate() {}
public void addImpl(CalendarDataProvider paramCalendarDataProvider)
{
for (Locale localLocale : paramCalendarDataProvider.getAvailableLocales()) {
map.putIfAbsent(localLocale, paramCalendarDataProvider);
}
}
public CalendarDataProvider getImpl(Locale paramLocale)
{
return (CalendarDataProvider)SPILocaleProviderAdapter.getImpl(map, paramLocale);
}
public Locale[] getAvailableLocales()
{
return (Locale[])map.keySet().toArray(new Locale[0]);
}
public boolean isSupportedLocale(Locale paramLocale)
{
return map.containsKey(paramLocale);
}
public int getFirstDayOfWeek(Locale paramLocale)
{
CalendarDataProvider localCalendarDataProvider = getImpl(paramLocale);
assert (localCalendarDataProvider != null);
return localCalendarDataProvider.getFirstDayOfWeek(paramLocale);
}
public int getMinimalDaysInFirstWeek(Locale paramLocale)
{
CalendarDataProvider localCalendarDataProvider = getImpl(paramLocale);
assert (localCalendarDataProvider != null);
return localCalendarDataProvider.getMinimalDaysInFirstWeek(paramLocale);
}
}
static class CalendarNameProviderDelegate
extends CalendarNameProvider
implements SPILocaleProviderAdapter.Delegate<CalendarNameProvider>
{
private ConcurrentMap<Locale, CalendarNameProvider> map = new ConcurrentHashMap();
CalendarNameProviderDelegate() {}
public void addImpl(CalendarNameProvider paramCalendarNameProvider)
{
for (Locale localLocale : paramCalendarNameProvider.getAvailableLocales()) {
map.putIfAbsent(localLocale, paramCalendarNameProvider);
}
}
public CalendarNameProvider getImpl(Locale paramLocale)
{
return (CalendarNameProvider)SPILocaleProviderAdapter.getImpl(map, paramLocale);
}
public Locale[] getAvailableLocales()
{
return (Locale[])map.keySet().toArray(new Locale[0]);
}
public boolean isSupportedLocale(Locale paramLocale)
{
return map.containsKey(paramLocale);
}
public String getDisplayName(String paramString, int paramInt1, int paramInt2, int paramInt3, Locale paramLocale)
{
CalendarNameProvider localCalendarNameProvider = getImpl(paramLocale);
assert (localCalendarNameProvider != null);
return localCalendarNameProvider.getDisplayName(paramString, paramInt1, paramInt2, paramInt3, paramLocale);
}
public Map<String, Integer> getDisplayNames(String paramString, int paramInt1, int paramInt2, Locale paramLocale)
{
CalendarNameProvider localCalendarNameProvider = getImpl(paramLocale);
assert (localCalendarNameProvider != null);
return localCalendarNameProvider.getDisplayNames(paramString, paramInt1, paramInt2, paramLocale);
}
}
static class CollatorProviderDelegate
extends CollatorProvider
implements SPILocaleProviderAdapter.Delegate<CollatorProvider>
{
private ConcurrentMap<Locale, CollatorProvider> map = new ConcurrentHashMap();
CollatorProviderDelegate() {}
public void addImpl(CollatorProvider paramCollatorProvider)
{
for (Locale localLocale : paramCollatorProvider.getAvailableLocales()) {
map.putIfAbsent(localLocale, paramCollatorProvider);
}
}
public CollatorProvider getImpl(Locale paramLocale)
{
return (CollatorProvider)SPILocaleProviderAdapter.getImpl(map, paramLocale);
}
public Locale[] getAvailableLocales()
{
return (Locale[])map.keySet().toArray(new Locale[0]);
}
public boolean isSupportedLocale(Locale paramLocale)
{
return map.containsKey(paramLocale);
}
public Collator getInstance(Locale paramLocale)
{
CollatorProvider localCollatorProvider = getImpl(paramLocale);
assert (localCollatorProvider != null);
return localCollatorProvider.getInstance(paramLocale);
}
}
static class CurrencyNameProviderDelegate
extends CurrencyNameProvider
implements SPILocaleProviderAdapter.Delegate<CurrencyNameProvider>
{
private ConcurrentMap<Locale, CurrencyNameProvider> map = new ConcurrentHashMap();
CurrencyNameProviderDelegate() {}
public void addImpl(CurrencyNameProvider paramCurrencyNameProvider)
{
for (Locale localLocale : paramCurrencyNameProvider.getAvailableLocales()) {
map.putIfAbsent(localLocale, paramCurrencyNameProvider);
}
}
public CurrencyNameProvider getImpl(Locale paramLocale)
{
return (CurrencyNameProvider)SPILocaleProviderAdapter.getImpl(map, paramLocale);
}
public Locale[] getAvailableLocales()
{
return (Locale[])map.keySet().toArray(new Locale[0]);
}
public boolean isSupportedLocale(Locale paramLocale)
{
return map.containsKey(paramLocale);
}
public String getSymbol(String paramString, Locale paramLocale)
{
CurrencyNameProvider localCurrencyNameProvider = getImpl(paramLocale);
assert (localCurrencyNameProvider != null);
return localCurrencyNameProvider.getSymbol(paramString, paramLocale);
}
public String getDisplayName(String paramString, Locale paramLocale)
{
CurrencyNameProvider localCurrencyNameProvider = getImpl(paramLocale);
assert (localCurrencyNameProvider != null);
return localCurrencyNameProvider.getDisplayName(paramString, paramLocale);
}
}
static class DateFormatProviderDelegate
extends DateFormatProvider
implements SPILocaleProviderAdapter.Delegate<DateFormatProvider>
{
private ConcurrentMap<Locale, DateFormatProvider> map = new ConcurrentHashMap();
DateFormatProviderDelegate() {}
public void addImpl(DateFormatProvider paramDateFormatProvider)
{
for (Locale localLocale : paramDateFormatProvider.getAvailableLocales()) {
map.putIfAbsent(localLocale, paramDateFormatProvider);
}
}
public DateFormatProvider getImpl(Locale paramLocale)
{
return (DateFormatProvider)SPILocaleProviderAdapter.getImpl(map, paramLocale);
}
public Locale[] getAvailableLocales()
{
return (Locale[])map.keySet().toArray(new Locale[0]);
}
public boolean isSupportedLocale(Locale paramLocale)
{
return map.containsKey(paramLocale);
}
public DateFormat getTimeInstance(int paramInt, Locale paramLocale)
{
DateFormatProvider localDateFormatProvider = getImpl(paramLocale);
assert (localDateFormatProvider != null);
return localDateFormatProvider.getTimeInstance(paramInt, paramLocale);
}
public DateFormat getDateInstance(int paramInt, Locale paramLocale)
{
DateFormatProvider localDateFormatProvider = getImpl(paramLocale);
assert (localDateFormatProvider != null);
return localDateFormatProvider.getDateInstance(paramInt, paramLocale);
}
public DateFormat getDateTimeInstance(int paramInt1, int paramInt2, Locale paramLocale)
{
DateFormatProvider localDateFormatProvider = getImpl(paramLocale);
assert (localDateFormatProvider != null);
return localDateFormatProvider.getDateTimeInstance(paramInt1, paramInt2, paramLocale);
}
}
static class DateFormatSymbolsProviderDelegate
extends DateFormatSymbolsProvider
implements SPILocaleProviderAdapter.Delegate<DateFormatSymbolsProvider>
{
private ConcurrentMap<Locale, DateFormatSymbolsProvider> map = new ConcurrentHashMap();
DateFormatSymbolsProviderDelegate() {}
public void addImpl(DateFormatSymbolsProvider paramDateFormatSymbolsProvider)
{
for (Locale localLocale : paramDateFormatSymbolsProvider.getAvailableLocales()) {
map.putIfAbsent(localLocale, paramDateFormatSymbolsProvider);
}
}
public DateFormatSymbolsProvider getImpl(Locale paramLocale)
{
return (DateFormatSymbolsProvider)SPILocaleProviderAdapter.getImpl(map, paramLocale);
}
public Locale[] getAvailableLocales()
{
return (Locale[])map.keySet().toArray(new Locale[0]);
}
public boolean isSupportedLocale(Locale paramLocale)
{
return map.containsKey(paramLocale);
}
public DateFormatSymbols getInstance(Locale paramLocale)
{
DateFormatSymbolsProvider localDateFormatSymbolsProvider = getImpl(paramLocale);
assert (localDateFormatSymbolsProvider != null);
return localDateFormatSymbolsProvider.getInstance(paramLocale);
}
}
static class DecimalFormatSymbolsProviderDelegate
extends DecimalFormatSymbolsProvider
implements SPILocaleProviderAdapter.Delegate<DecimalFormatSymbolsProvider>
{
private ConcurrentMap<Locale, DecimalFormatSymbolsProvider> map = new ConcurrentHashMap();
DecimalFormatSymbolsProviderDelegate() {}
public void addImpl(DecimalFormatSymbolsProvider paramDecimalFormatSymbolsProvider)
{
for (Locale localLocale : paramDecimalFormatSymbolsProvider.getAvailableLocales()) {
map.putIfAbsent(localLocale, paramDecimalFormatSymbolsProvider);
}
}
public DecimalFormatSymbolsProvider getImpl(Locale paramLocale)
{
return (DecimalFormatSymbolsProvider)SPILocaleProviderAdapter.getImpl(map, paramLocale);
}
public Locale[] getAvailableLocales()
{
return (Locale[])map.keySet().toArray(new Locale[0]);
}
public boolean isSupportedLocale(Locale paramLocale)
{
return map.containsKey(paramLocale);
}
public DecimalFormatSymbols getInstance(Locale paramLocale)
{
DecimalFormatSymbolsProvider localDecimalFormatSymbolsProvider = getImpl(paramLocale);
assert (localDecimalFormatSymbolsProvider != null);
return localDecimalFormatSymbolsProvider.getInstance(paramLocale);
}
}
static abstract interface Delegate<P extends LocaleServiceProvider>
{
public abstract void addImpl(P paramP);
public abstract P getImpl(Locale paramLocale);
}
static class LocaleNameProviderDelegate
extends LocaleNameProvider
implements SPILocaleProviderAdapter.Delegate<LocaleNameProvider>
{
private ConcurrentMap<Locale, LocaleNameProvider> map = new ConcurrentHashMap();
LocaleNameProviderDelegate() {}
public void addImpl(LocaleNameProvider paramLocaleNameProvider)
{
for (Locale localLocale : paramLocaleNameProvider.getAvailableLocales()) {
map.putIfAbsent(localLocale, paramLocaleNameProvider);
}
}
public LocaleNameProvider getImpl(Locale paramLocale)
{
return (LocaleNameProvider)SPILocaleProviderAdapter.getImpl(map, paramLocale);
}
public Locale[] getAvailableLocales()
{
return (Locale[])map.keySet().toArray(new Locale[0]);
}
public boolean isSupportedLocale(Locale paramLocale)
{
return map.containsKey(paramLocale);
}
public String getDisplayLanguage(String paramString, Locale paramLocale)
{
LocaleNameProvider localLocaleNameProvider = getImpl(paramLocale);
assert (localLocaleNameProvider != null);
return localLocaleNameProvider.getDisplayLanguage(paramString, paramLocale);
}
public String getDisplayScript(String paramString, Locale paramLocale)
{
LocaleNameProvider localLocaleNameProvider = getImpl(paramLocale);
assert (localLocaleNameProvider != null);
return localLocaleNameProvider.getDisplayScript(paramString, paramLocale);
}
public String getDisplayCountry(String paramString, Locale paramLocale)
{
LocaleNameProvider localLocaleNameProvider = getImpl(paramLocale);
assert (localLocaleNameProvider != null);
return localLocaleNameProvider.getDisplayCountry(paramString, paramLocale);
}
public String getDisplayVariant(String paramString, Locale paramLocale)
{
LocaleNameProvider localLocaleNameProvider = getImpl(paramLocale);
assert (localLocaleNameProvider != null);
return localLocaleNameProvider.getDisplayVariant(paramString, paramLocale);
}
}
static class NumberFormatProviderDelegate
extends NumberFormatProvider
implements SPILocaleProviderAdapter.Delegate<NumberFormatProvider>
{
private ConcurrentMap<Locale, NumberFormatProvider> map = new ConcurrentHashMap();
NumberFormatProviderDelegate() {}
public void addImpl(NumberFormatProvider paramNumberFormatProvider)
{
for (Locale localLocale : paramNumberFormatProvider.getAvailableLocales()) {
map.putIfAbsent(localLocale, paramNumberFormatProvider);
}
}
public NumberFormatProvider getImpl(Locale paramLocale)
{
return (NumberFormatProvider)SPILocaleProviderAdapter.getImpl(map, paramLocale);
}
public Locale[] getAvailableLocales()
{
return (Locale[])map.keySet().toArray(new Locale[0]);
}
public boolean isSupportedLocale(Locale paramLocale)
{
return map.containsKey(paramLocale);
}
public NumberFormat getCurrencyInstance(Locale paramLocale)
{
NumberFormatProvider localNumberFormatProvider = getImpl(paramLocale);
assert (localNumberFormatProvider != null);
return localNumberFormatProvider.getCurrencyInstance(paramLocale);
}
public NumberFormat getIntegerInstance(Locale paramLocale)
{
NumberFormatProvider localNumberFormatProvider = getImpl(paramLocale);
assert (localNumberFormatProvider != null);
return localNumberFormatProvider.getIntegerInstance(paramLocale);
}
public NumberFormat getNumberInstance(Locale paramLocale)
{
NumberFormatProvider localNumberFormatProvider = getImpl(paramLocale);
assert (localNumberFormatProvider != null);
return localNumberFormatProvider.getNumberInstance(paramLocale);
}
public NumberFormat getPercentInstance(Locale paramLocale)
{
NumberFormatProvider localNumberFormatProvider = getImpl(paramLocale);
assert (localNumberFormatProvider != null);
return localNumberFormatProvider.getPercentInstance(paramLocale);
}
}
static class TimeZoneNameProviderDelegate
extends TimeZoneNameProvider
implements SPILocaleProviderAdapter.Delegate<TimeZoneNameProvider>
{
private ConcurrentMap<Locale, TimeZoneNameProvider> map = new ConcurrentHashMap();
TimeZoneNameProviderDelegate() {}
public void addImpl(TimeZoneNameProvider paramTimeZoneNameProvider)
{
for (Locale localLocale : paramTimeZoneNameProvider.getAvailableLocales()) {
map.putIfAbsent(localLocale, paramTimeZoneNameProvider);
}
}
public TimeZoneNameProvider getImpl(Locale paramLocale)
{
return (TimeZoneNameProvider)SPILocaleProviderAdapter.getImpl(map, paramLocale);
}
public Locale[] getAvailableLocales()
{
return (Locale[])map.keySet().toArray(new Locale[0]);
}
public boolean isSupportedLocale(Locale paramLocale)
{
return map.containsKey(paramLocale);
}
public String getDisplayName(String paramString, boolean paramBoolean, int paramInt, Locale paramLocale)
{
TimeZoneNameProvider localTimeZoneNameProvider = getImpl(paramLocale);
assert (localTimeZoneNameProvider != null);
return localTimeZoneNameProvider.getDisplayName(paramString, paramBoolean, paramInt, paramLocale);
}
public String getGenericDisplayName(String paramString, int paramInt, Locale paramLocale)
{
TimeZoneNameProvider localTimeZoneNameProvider = getImpl(paramLocale);
assert (localTimeZoneNameProvider != null);
return localTimeZoneNameProvider.getGenericDisplayName(paramString, paramInt, paramLocale);
}
}
}
/* Location: C:\Program Files (x86)\Java\jre1.8.0_151\lib\rt.jar!\sun\util\locale\provider\SPILocaleProviderAdapter.class
* Java compiler version: 8 (52.0)
* JD-Core Version: 0.7.1
*/
| true
|
79a9589c034874cf3a4590ca44cd0e80ab93047c
|
Java
|
mojo2405/Tickets
|
/app/src/main/java/il/co/myapp/tickets/data/AsyncLeadResponse.java
|
UTF-8
| 125
| 1.609375
| 2
|
[] |
no_license
|
package il.co.myapp.tickets.data;
public interface AsyncLeadResponse {
void NewLeadResponseReceived(String response);
}
| true
|
ddb5264d4854b5e95ef1a67129d52e0c63a5a705
|
Java
|
mknguyentran/ResourceSharing
|
/src/java/action/DeleteRequestAction.java
|
UTF-8
| 2,497
| 2.03125
| 2
|
[] |
no_license
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package action;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import dao.RequestDAO;
import dto.AccountDTO;
import java.util.Map;
import org.apache.log4j.Logger;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Result;
import utilities.Logging;
/**
*
* @author Mk
*/
public class DeleteRequestAction extends ActionSupport {
private static final Logger logger = Logger.getLogger(DeleteRequestAction.class);
private static final String USER_HISTORY = "searchRequestHistory";
private static final String LOGOUT = "logout";
private String searchResourceName, searchFromDate, searchToDate;
private int id;
public DeleteRequestAction() {
}
@Action(value = "invalidateRequest", results = {
@Result(name = USER_HISTORY, type = "redirectAction", location = USER_HISTORY)
,
@Result(name = LOGOUT, type = "redirect", location = LOGOUT)
})
public String execute() {
String result = LOGOUT;
Map session = ActionContext.getContext().getSession();
AccountDTO account = (AccountDTO) session.get("ACCOUNT");
Logging.logDebug(logger, "email", account.getEmail());
try {
if (account != null) {
RequestDAO rDAO = new RequestDAO();
if (rDAO.inactivateRequest(id, account.getEmail())) {
result = USER_HISTORY;
}
}
} catch (Exception e) {
Logging.logError(logger, e);
}
return result;
}
public String getSearchResourceName() {
return searchResourceName;
}
public void setSearchResourceName(String searchResourceName) {
this.searchResourceName = searchResourceName;
}
public String getSearchFromDate() {
return searchFromDate;
}
public void setSearchFromDate(String searchFromDate) {
this.searchFromDate = searchFromDate;
}
public String getSearchToDate() {
return searchToDate;
}
public void setSearchToDate(String searchToDate) {
this.searchToDate = searchToDate;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
}
| true
|
ac04d25007978399d617c9baa98d5b17ece79030
|
Java
|
kokabaskary/final_project
|
/src/test/java/framework/web_pages/LoginPage.java
|
UTF-8
| 384
| 1.960938
| 2
|
[] |
no_license
|
//package framework.web_pages;
//
//import framework.BasePage;
//import org.openqa.selenium.By;
//
//public class LoginPage extends BasePage {
//
//// private By pageHeader = By.xpath("//*[@id='content']/div/div/div[1]/span");
// private By pageHeader = By.xpath("//*[@class='container']");
//
// public String getPageHeader() {
//
// return getTextFromElement(pageHeader);
// }
//}
| true
|
652154bd606ebb0dc223a3a6afbb88599006d0f7
|
Java
|
NacolZero/TheRoadToGeek
|
/src/main/java/com/nacol/TheRoadToGeek/week_04/Symaphore/SemaphoreMain.java
|
UTF-8
| 2,431
| 3.515625
| 4
|
[] |
no_license
|
package com.nacol.TheRoadToGeek.week_04.Symaphore;
import java.util.concurrent.Semaphore;
public class SemaphoreMain {
public static void main(String[] args) throws InterruptedException {
// //箱子工人只能同时搬运4个箱子
// boxRun();
// //不讲武德,一次抢n个锁,释放n-1个锁,最终锁等于0,其他线程就傻逼一样的等。不讲武德。
// noSayAboutMartialArts();
// //测试的值,new Semaphore(n) 中的 n 并不是固定最大数量,仅仅是一个初始化值
// //会随着 acquire 小于 n, 随着 release 大于 n
// testRelease();
BoxFactory factory = new BoxFactory();
for (int i = 0; i < 1000; i++) {
Thread producer = new Thread(()->{
try {
factory.in();
} catch (InterruptedException e) {
e.printStackTrace();
}
});
producer.start();
}
for (int i = 0; i < 1000; i++) {
Thread consumer = new Thread(()->{
try {
factory.out();
} catch (InterruptedException e) {
e.printStackTrace();
}
});
consumer.start();
}
}
private static void testRelease() throws InterruptedException {
Semaphore semaphore = new Semaphore(0);
// semaphore.acquire();
System.out.println("1");
semaphore.release(5);
System.out.println("2");
semaphore.acquire(2);
System.out.println("3");
semaphore.acquire(2);
System.out.println("3");
}
private static void noSayAboutMartialArts() {
Rascal rascal = new Rascal();
for (int i = 0; i < 100; i++) {
new Thread(()->{
try {
rascal.doSemeThing();
} catch (InterruptedException e) {
e.printStackTrace();
}
}).start();
}
}
private static void boxRun() {
BoxWorker boxWorker = new BoxWorker();
for (int i = 0; i < 100; i++) {
new Thread(()->{
try {
boxWorker.doWork();
} catch (InterruptedException e) {
e.printStackTrace();
}
}).start();
}
}
}
| true
|
b67a4f8c48e6dbbb78320e848acff39cf6b489f3
|
Java
|
mlin2024/Doodl.e
|
/app/src/main/java/com/example/doodle/models/Doodle.java
|
UTF-8
| 3,233
| 2.21875
| 2
|
[
"Apache-2.0"
] |
permissive
|
package com.example.doodle.models;
import android.os.Parcelable;
import android.util.Log;
import android.view.View;
import androidx.annotation.NonNull;
import com.google.android.material.snackbar.Snackbar;
import com.parse.ParseClassName;
import com.parse.ParseFile;
import com.parse.ParseObject;
import com.parse.ParseUser;
import org.jetbrains.annotations.NotNull;
import java.util.Date;
@ParseClassName("Doodle")
public class Doodle extends ParseObject implements Parcelable {
public static final String TAG = "Doodle";
public static final String KEY_ARTIST = "artist";
public static final String KEY_IMAGE = "image";
public static final String KEY_PARENT = "parent";
public static final String KEY_TAIL_LENGTH = "tailLength";
public static final String KEY_ROOT = "root";
public static final String KEY_IN_GAME = "inGame";
@NonNull
@NotNull
@Override
public String toString() {
return getObjectId();
}
public ParseUser getArtist() {
return getParseUser(KEY_ARTIST);
}
public void setArtist(ParseUser user) {
put(KEY_ARTIST, user);
}
public ParseFile getImage() {
return getParseFile(KEY_IMAGE);
}
public void setImage(ParseFile image) {
put(KEY_IMAGE, image);
}
public Doodle getParent() {
return (Doodle) getParseObject(KEY_PARENT);
}
public void setParent(ParseObject parent) {
put(KEY_PARENT, parent);
}
public int getTailLength() {
return getInt(KEY_TAIL_LENGTH);
}
public void setTailLength(int tailLength) {
put(KEY_TAIL_LENGTH, tailLength);
}
public String getRoot() {
return getString(KEY_ROOT);
}
public void setRoot(String root) {
put(KEY_ROOT, root);
}
public String getInGame() {
if (containsKey(KEY_IN_GAME)) return getString(KEY_IN_GAME);
return null;
}
public void setInGame(String inGame) {
put(KEY_IN_GAME, inGame);
}
public String getTimestamp() {
Date createdAt = this.getCreatedAt();
int SECOND_MILLIS = 1000;
int MINUTE_MILLIS = 60 * SECOND_MILLIS;
int HOUR_MILLIS = 60 * MINUTE_MILLIS;
int DAY_MILLIS = 24 * HOUR_MILLIS;
try {
createdAt.getTime();
long time = createdAt.getTime();
long now = System.currentTimeMillis();
final long diff = now - time;
if (diff < MINUTE_MILLIS) {
return "just now";
} else if (diff < 2 * MINUTE_MILLIS) {
return "a minute ago";
} else if (diff < 50 * MINUTE_MILLIS) {
return diff / MINUTE_MILLIS + "m";
} else if (diff < 90 * MINUTE_MILLIS) {
return "an hour ago";
} else if (diff < 24 * HOUR_MILLIS) {
return diff / HOUR_MILLIS + "h";
} else if (diff < 48 * HOUR_MILLIS) {
return "yesterday";
} else {
return diff / DAY_MILLIS + "d";
}
} catch (Exception e) {
Log.i(TAG, "getTimestamp failed", e);
e.printStackTrace();
}
return "";
}
}
| true
|
121cbb7ec275ac1048fcb05cd91d5f332d883f03
|
Java
|
AimeeBaby/Android-DeviceManager
|
/DmSdk/DmSdkSample/app/src/main/java/com/nd/adhoc/dmsdk/demo/ui/adapter/HardwareAdapter.java
|
UTF-8
| 3,935
| 2.21875
| 2
|
[] |
no_license
|
package com.nd.adhoc.dmsdk.demo.ui.adapter;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.nd.adhoc.dmsdk.demo.R;
import com.nd.adhoc.dmsdk.demo.bean.HardWareSwitchBean;
import com.nd.adhoc.dmsdk.demo.ui.weget.GridDivider;
import java.util.ArrayList;
import java.util.List;
public class HardwareAdapter extends RecyclerView.Adapter<HardwareAdapter.HardWareSwitchHolder> {
private Context mContext;
private List<HardWareSwitchBean> mList;
private OnItemClickListener onItemClickListener;
public HardwareAdapter(Context context){
this.mContext= context;
mList=new ArrayList<HardWareSwitchBean>();
}
@NonNull
@Override
public HardwareAdapter.HardWareSwitchHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
return new HardWareSwitchHolder(LayoutInflater.from(this.mContext).inflate(R.layout.list_item_control,parent,false));
}
@Override
public void onBindViewHolder(@NonNull HardwareAdapter.HardWareSwitchHolder holder, final int position) {
Log.i(this.getClass().getName(),String.format("Get list=%d",mList.size()));
if(mList.size()>0 && mList.get(position) != null) {
holder.tvHardwareName.setText(mList.get(position).getName());
holder.tvHardWareStatus.setText(mList.get(position).getStatus()==0?"关":"开");
holder.itemView.setTag(position);
holder.itemView.setOnClickListener(itemClickListener);
if(mList.get(position).isDesiplaySave() && mList.get(position).getStatus()==0){
holder.ivHardWareStatus.setImageDrawable(mContext.getResources().getDrawable(R.drawable.icon_signal_gray));
holder.tvDevicePolicy.setVisibility(View.VISIBLE);
}else{
holder.ivHardWareStatus.setImageDrawable(mContext.getResources().getDrawable(R.drawable.icon_signal_green));
holder.tvDevicePolicy.setVisibility(View.GONE);
}
}
}
@Override
public int getItemCount() {
return mList.size();
}
class HardWareSwitchHolder extends RecyclerView.ViewHolder{
private TextView tvHardwareName;
private ImageView ivHardWare;
private TextView tvHardWareStatus;
private ImageView ivHardWareStatus;
private TextView tvDevicePolicy;
public HardWareSwitchHolder(View itemView) {
super(itemView);
tvHardwareName=(TextView) itemView.findViewById(R.id.tv_devicename_control);
ivHardWare=itemView.findViewById(R.id.iv_devicename_control);
tvHardWareStatus=itemView.findViewById(R.id.tv_devicestatus_control);
ivHardWareStatus=itemView.findViewById(R.id.iv_devicestatus_control);
tvDevicePolicy=itemView.findViewById(R.id.tv_devicepolicy_control);
}
}
public void setData(List list){
if(mList != null && mList.size()>0){
mList.clear();
}
if(list != null) {
mList.addAll(list);
}
}
public interface OnItemClickListener {
void onItemClick(View view , int position);
}
public OnItemClickListener getOnItemClickListener() {
return onItemClickListener;
}
public void setOnItemClickListener(OnItemClickListener onItemClickListener) {
this.onItemClickListener = onItemClickListener;
}
private View.OnClickListener itemClickListener=new View.OnClickListener() {
@Override
public void onClick(View v) {
onItemClickListener.onItemClick(v, (Integer) v.getTag());
}
};
}
| true
|
9314644aaa5db1e866268aed3c322c7b30721803
|
Java
|
dev-rui/Springboot
|
/src/main/java/com/example/springboot/modules/dao/CrawlerMapper.java
|
UTF-8
| 301
| 1.726563
| 2
|
[
"Apache-2.0"
] |
permissive
|
package com.example.springboot.modules.dao;
import com.example.springboot.modules.entity.CmsContentPO;
import org.apache.ibatis.annotations.Mapper;
/**
* @author heruihong
* @createTime 2022-01-05 16:07:38
*/
@Mapper
public interface CrawlerMapper {
int addCmsContent(CmsContentPO record);
}
| true
|
10f05cc18615599ccdde80f273e5b5842cf6f008
|
Java
|
Boba-Syu/cages-spring-boot
|
/src/main/java/cn/bobasyu/cagesspringboot/CagesSpringBootApplication.java
|
UTF-8
| 1,092
| 2.3125
| 2
|
[] |
no_license
|
package cn.bobasyu.cagesspringboot;
import cn.bobasyu.cagesspringboot.netty.TCPLinkServer;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
@MapperScan("cn.bobasyu.cagesspringboot.mapper")
public class CagesSpringBootApplication implements CommandLineRunner {
private final static Logger logger = LogManager.getLogger(CagesSpringBootApplication.class);
public static void main(String[] args) {
SpringApplication.run(CagesSpringBootApplication.class, args);
}
@Override
public void run(String... args) {
int port = 6666;
try {
TCPLinkServer.start(port);
logger.info("端口" + port + "启动成功");
} catch (Exception e) {
logger.info("端口" + port + "启动失败");
e.printStackTrace();
}
}
}
| true
|
971707d231e294de45e3ae870e89fcee54e6b312
|
Java
|
zhi-heart/yanerwu
|
/talent/src/main/java/com/yanerwu/talent/action/IndexAction.java
|
UTF-8
| 1,621
| 2.140625
| 2
|
[] |
no_license
|
package com.yanerwu.talent.action;
import com.yanerwu.common.BaseAction;
import com.yanerwu.common.Constants;
import com.yanerwu.talent.service.GoodsTopService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
/**
* @Author Zuz
* @Date 2017/8/11 11:39
* @Description
*/
@Controller
public class IndexAction extends BaseAction {
private Logger logger = LoggerFactory.getLogger(getClass());
@Autowired
private GoodsTopService goodsTopService;
/**
* 执行搜索
*
* @return
*/
@RequestMapping(value = "/index.html")
public String list() {
return "index";
}
/**
* 手动触发
*
* @return
*/
@RequestMapping(value = "/run.html")
public String run() {
new Thread(() -> {
long l = System.currentTimeMillis();
logger.info("手动触发 开始执行collectGoodsTop");
goodsTopService.collectGoodsTop(Constants.GOODS_TOP);
logger.info("手动触发 执行collectGoodsTop结束,耗时:{}毫秒", System.currentTimeMillis() - l);
logger.info("手动触发 collectConver");
l = System.currentTimeMillis();
goodsTopService.collectConver();
logger.info("手动触发 collectConver,耗时:{}毫秒", System.currentTimeMillis() - l);
}).start();
request.setAttribute("result", "手动触发成功!");
return "index";
}
}
| true
|
b9cb785e69b05c3d6c7d8c2f0ca7fc8e068d6755
|
Java
|
fofancy/voteme
|
/voteme-auth/src/main/java/com/fofancy/auth/security/UsernamePasswordLoginFilter.java
|
UTF-8
| 2,956
| 2.40625
| 2
|
[] |
no_license
|
package com.fofancy.auth.security;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fofancy.auth.model.UserLoginDto;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.logging.Logger;
public class UsernamePasswordLoginFilter extends AbstractAuthenticationProcessingFilter {
private AuthenticationSuccessHandler successHandler;
private AuthenticationFailureHandler failureHandler;
private static Logger log = Logger.getLogger(UsernamePasswordLoginFilter.class.getName());
public UsernamePasswordLoginFilter(
String defaultFilterProcessesUrl,
AuthenticationSuccessHandler successHandler,
AuthenticationFailureHandler failureHandler) {
super(defaultFilterProcessesUrl);
this.successHandler = successHandler;
this.failureHandler = failureHandler;
}
@Override
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException, IOException, ServletException {
log.info("Authentication attempting.");
ObjectMapper mapper = new ObjectMapper();
UserLoginDto userLoginDto = mapper.readValue(request.getReader(), UserLoginDto.class);
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(
userLoginDto.getUsername(), userLoginDto.getPassword()
);
return this.getAuthenticationManager().authenticate(token);
}
@Override
protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain, Authentication authResult) throws IOException, ServletException {
SecurityContextHolder.getContext().setAuthentication(authResult);
successHandler.onAuthenticationSuccess(request, response, authResult);
}
@Override
protected void unsuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response, AuthenticationException failed) throws IOException, ServletException {
SecurityContextHolder.clearContext();
failureHandler.onAuthenticationFailure(request, response, failed);
}
}
| true
|
9f14bc0c59f217ad00ed9d80921841bc8353fb30
|
Java
|
Aarvedahl/SchoolManagement
|
/src/main/java/io/github/aarvedahl/converters/CourseConverter.java
|
UTF-8
| 1,095
| 2.5625
| 3
|
[] |
no_license
|
package io.github.aarvedahl.converters;
import io.github.aarvedahl.backing.SchoolBean;
import io.github.aarvedahl.entities.Course;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;
@FacesConverter(forClass = Course.class)
public class CourseConverter implements Converter{
@Override
public Object getAsObject(FacesContext context, UIComponent uiComponent, String value) {
int id;
try {
id = Integer.parseInt(value);
} catch (NumberFormatException e) {
return "";
}
SchoolBean schoolBean = context.getApplication().evaluateExpressionGet(context, "#{schoolBean}", SchoolBean.class);
return schoolBean.getCourseEJB().find(id);
}
@Override
public String getAsString(FacesContext context, UIComponent component, Object value) {
if(value == null) return "";
if(!(value instanceof Course)) return "";
return Integer.toString(((Course) value).getCourseid());
}
}
| true
|
34481273b67fd770f94312b85a6f080461c4138f
|
Java
|
Nancy1301/The-Shelf
|
/app/src/main/java/com/example/android/theshelf/Issued_books_list.java
|
UTF-8
| 763
| 1.953125
| 2
|
[] |
no_license
|
package com.example.android.theshelf;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class Issued_books_list extends Activity {
private Button btn1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate( savedInstanceState );
setContentView( R.layout.issued_books_list );
setTitle( "Issued Book List" );
btn1 = (Button) findViewById( R.id.back );
btn1.setOnClickListener( new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent i =new Intent( Issued_books_list.this,Admin_Menu.class);
}
} );
}
}
| true
|
afe9e6235f78f5384f9abbb9fe65ce01cff28ba8
|
Java
|
hojohe/bit-java
|
/01_java-basic/src/day12/exam/ScissorsRockPaper.java
|
UTF-8
| 1,237
| 3.390625
| 3
|
[] |
no_license
|
package day12.exam;
import java.util.Random;
public class ScissorsRockPaper implements Game {
final static int SCISSOR = 1;
final static int ROCK = 2;
final static int PAPER = 3;
static int aGameScore;
Random r = new Random();
int me = r.nextInt(3) + 1;
public ScissorsRockPaper(int you) {}
public int startGame(int you) {
if (me == SCISSOR) {
if (you == ROCK) {
System.out.println("You win 가위 ");
aGameScore++;
return 1;
} else if (you == PAPER) {
System.out.println("You lose 가위");
return 0;
} else {
System.out.println("비겼습니다.가위 ");
return 0;
}
} else if (me == ROCK) {
if (you == PAPER) {
System.out.println("You win 바위");
aGameScore++;
return 1;
} else if (you == SCISSOR) {
System.out.println("You lose 바위");
return 0;
} else {
System.out.println("비겼습니다. 바위");
return 0;
}
} else if (me == PAPER) {
if (you == SCISSOR) {
System.out.println("You win 보");
aGameScore++;
return 1;
} else if (you == ROCK) {
System.out.println("You lose 보 ");
return 0;
} else {
System.out.println("비겼습니다.보");
return 0;
}
}
return 0;
}
}
| true
|
519facb11fada4a58d51a141e648aa0ea1da1887
|
Java
|
ahmed20142015/GithupSearch
|
/app/src/main/java/com/example/aelashry/githupsearch/activity/RepositoryActivity.java
|
UTF-8
| 2,771
| 2.046875
| 2
|
[] |
no_license
|
package com.example.aelashry.githupsearch.activity;
import android.app.ProgressDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.widget.LinearLayout;
import com.example.aelashry.githupsearch.DemoApplication;
import com.example.aelashry.githupsearch.R;
import com.example.aelashry.githupsearch.adapter.RepositoryAdapter;
import com.example.aelashry.githupsearch.di.component.ActivityComponent;
import com.example.aelashry.githupsearch.di.component.DaggerActivityComponent;
import com.example.aelashry.githupsearch.di.module.ActivityModule;
import com.example.aelashry.githupsearch.models.Item;
import com.example.aelashry.githupsearch.models.RepositoryResult;
import java.util.ArrayList;
import javax.inject.Inject;
public class RepositoryActivity extends AppCompatActivity implements RepositoryView {
ProgressDialog dialog;
RecyclerView repositoriesList;
@Inject
RepositoryPresenterImp presenterImp ;
private ActivityComponent activityComponent;
public ActivityComponent getActivityComponent() {
if (activityComponent == null) {
activityComponent = DaggerActivityComponent.builder()
.activityModule(new ActivityModule(this))
.applicationComponent(DemoApplication.get(this).getComponent())
.build();
}
return activityComponent;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getActivityComponent().inject(this);
repositoriesList = (RecyclerView) findViewById(R.id.repositories);
LinearLayoutManager layoutManager = new LinearLayoutManager(getApplicationContext());
repositoriesList.setHasFixedSize(true);
repositoriesList.setLayoutManager(layoutManager);
// presenterImp = new RepositoryPresenterImp();
presenterImp.setView(this);
presenterImp.RequestRepositories("android");
}
@Override
public void showLoader() {
dialog = new ProgressDialog(this);
dialog.setCancelable(false);
dialog.show();
}
@Override
public void hideLoader() {
if(dialog.isShowing() && dialog != null ){
dialog.dismiss();
}
}
@Override
public void setRepositories(ArrayList<Item> repositories) {
RepositoryAdapter adapter = new RepositoryAdapter(RepositoryActivity.this ,repositories);
repositoriesList.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
}
| true
|
9c400f9a8015d7dee21fd766cd3510449fb3d630
|
Java
|
kindArtcreator/kindArt
|
/kindArt-background/src/main/java/com/kindArt/manager/json/Json014/Json014Res.java
|
UTF-8
| 569
| 1.789063
| 2
|
[] |
no_license
|
package com.kindArt.manager.json.Json014;
import java.util.List;
public class Json014Res {
private ReturnObj returnObj;// 返回结果区域
private List<MyLiked> myLikedList;// 返回结果区域
public Json014Res() {
}
public ReturnObj getReturnObj() {
return returnObj;
}
public void setReturnObj(ReturnObj returnObj) {
this.returnObj = returnObj;
}
public List<MyLiked> getMyLikedList() {
return myLikedList;
}
public void setMyLikedList(List<MyLiked> myLikedList) {
this.myLikedList = myLikedList;
}
}
| true
|
359b90e77a1c4fb96d7fe5a321abdd025cccb7e6
|
Java
|
LEEJISU-dev/Java_codingTest
|
/6. 1차원 배열/3_2577_숫자의 개수/Main.java
|
UTF-8
| 589
| 3.4375
| 3
|
[] |
no_license
|
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
int a; // 입력받은 정수
int sum = 1; // 계산 결과
int count = 0; // 0-9까지의 수가 몇번 쓰였는지 카운트
Scanner sc = new Scanner(System.in);
for (int i = 0; i < 3; i++) {
a = sc.nextInt();
sum = sum * a;
}
for (int i = 0; i < 10; i++) {
for (int j = 0; j < Integer.toString(sum).length(); j++) {
if (Integer.toString(sum).charAt(j) == Integer.toString(i).charAt(0)) {
count++;
}
}
System.out.println(count);
count = 0;
}
}
}
| true
|
e3e42fc19824c5b303d59c3c33310a739634b0a7
|
Java
|
thinking123/yiqi-android-pro
|
/app/src/main/java/com/eshop/mvp/ui/activity/login/WelcomeActivity.java
|
UTF-8
| 1,280
| 1.90625
| 2
|
[] |
no_license
|
package com.eshop.mvp.ui.activity.login;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.widget.CheckBox;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.utils.ArmsUtils;
import com.eshop.R;
import com.eshop.app.base.BaseSupportActivity;
import com.eshop.mvp.utils.AppConstant;
import com.eshop.mvp.utils.SpUtils;
import butterknife.BindView;
import butterknife.OnClick;
public class WelcomeActivity extends BaseSupportActivity {
@BindView(R.id.cb_agree)
CheckBox cbAgree;
@Override
public void setupActivityComponent(@NonNull AppComponent appComponent) {
}
@Override
public int initView(@Nullable Bundle savedInstanceState) {
return R.layout.activity_welcome;
}
@Override
public void initData(@Nullable Bundle savedInstanceState) {
}
@OnClick(R.id.btn_complete)
public void onViewClicked() {
if (cbAgree.isChecked()) {
SpUtils.put(this, AppConstant.FIRST_OPEN, true);
startActivity(new Intent(this, LoginActivity.class));
finish();
} else {
ArmsUtils.snackbarText("请先同意权限声明");
}
}
}
| true
|
09c859a51f0cc36140d5fcb0b90ff4ed069f061b
|
Java
|
devlopper/ci.gouv.dgbf.system.useraccountrequest.client
|
/useraccountrequest-client-controller-impl/src/main/java/ci/gouv/dgbf/system/useraccountrequest/client/controller/impl/ProxyClassUniformResourceIdentifierStringProviderFunctionRunnableImpl.java
|
UTF-8
| 1,276
| 1.945313
| 2
|
[] |
no_license
|
package ci.gouv.dgbf.system.useraccountrequest.client.controller.impl;
import java.io.Serializable;
import org.cyk.utility.__kernel__.function.AbstractFunctionRunnableImpl;
import org.cyk.utility.client.controller.proxy.ProxyClassUniformResourceIdentifierStringProvider;
import ci.gouv.dgbf.system.usermanagement.server.representation.api.account.RoleRepresentation;
@Deprecated
public class ProxyClassUniformResourceIdentifierStringProviderFunctionRunnableImpl extends AbstractFunctionRunnableImpl<ProxyClassUniformResourceIdentifierStringProvider> implements Serializable {
private static final long serialVersionUID = 1L;
public ProxyClassUniformResourceIdentifierStringProviderFunctionRunnableImpl() {
setRunnable(new Runnable() {
@Override
public void run() {
if(RoleRepresentation.class.equals(getFunction().getClazz())) {
setOutput("http://localhost:8080/usermanagement/server");
//setOutput("http://192.168.99.100:8080");
}
//setOutput("http://mic-demande-compte-server:8080/");
//setOutput("http://localhost:8080/actor/server");
//System.out.println("Pro Var : "+System.getProperties());
//setOutput("http://localhost:8081");
//setOutput("http://mic-utilisateur-demande-server:8081/");
}
});
}
}
| true
|
647f076bea44e2cf89a024331a589181bcc2cae3
|
Java
|
RuslanLizogub/Base23
|
/src/week7/lesson13/BufferedReaderExmple.java
|
UTF-8
| 638
| 3.09375
| 3
|
[] |
no_license
|
package week7.lesson13;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
public class BufferedReaderExmple {
public static void main(String[] args) throws IOException {
Reader isr = new InputStreamReader(System.in);
BufferedReader d = new BufferedReader(isr);
// DataInputStream dis = new DataInputStream(System.in);
String a = d.readLine();
System.out.println("Вы напечатали: " + a);
System.out.println(d.read());
System.out.println(d.read());
System.out.println(d.read());
System.out.println(d.read());
}
}
| true
|
2dda450d47672d3bed7eaafa28fc7e0fd82bf006
|
Java
|
alzimmermsft/azure-sdk-for-java
|
/sdk/databox/azure-resourcemanager-databox/src/test/java/com/azure/resourcemanager/databox/generated/SkuInformationInnerTests.java
|
UTF-8
| 1,445
| 1.65625
| 2
|
[
"LGPL-2.1-or-later",
"BSD-3-Clause",
"MIT",
"Apache-2.0",
"LicenseRef-scancode-public-domain",
"BSD-2-Clause",
"LicenseRef-scancode-warranty-disclaimer",
"LicenseRef-scancode-unknown-license-reference",
"CC0-1.0",
"LicenseRef-scancode-generic-cla"
] |
permissive
|
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.
package com.azure.resourcemanager.databox.generated;
import com.azure.core.util.BinaryData;
import com.azure.resourcemanager.databox.fluent.models.SkuInformationInner;
public final class SkuInformationInnerTests {
@org.junit.jupiter.api.Test
public void testDeserialize() throws Exception {
SkuInformationInner model =
BinaryData
.fromString(
"{\"sku\":{\"name\":\"DataBoxDisk\",\"displayName\":\"xmzsbbzogg\",\"family\":\"rxwburv\"},\"enabled\":false,\"properties\":{\"dataLocationToServiceLocationMap\":[{\"dataLocation\":\"ydptkoen\",\"serviceLocation\":\"uknvudwti\"}],\"capacity\":{\"usable\":\"ldngkpoci\",\"maximum\":\"z\"},\"costs\":[{\"meterId\":\"gukgjnpiucgygevq\",\"meterType\":\"typmrbpizcdrqjsd\",\"multiplier\":98.3329583727786}],\"apiVersions\":[\"hxdeoejz\",\"cwif\",\"jttgzf\",\"ishc\"],\"disabledReason\":\"OfferType\",\"disabledReasonMessage\":\"jdeyeamdpha\",\"requiredFeature\":\"lpbuxwgipwhonowk\"}}")
.toObject(SkuInformationInner.class);
}
@org.junit.jupiter.api.Test
public void testSerialize() throws Exception {
SkuInformationInner model = new SkuInformationInner();
model = BinaryData.fromObject(model).toObject(SkuInformationInner.class);
}
}
| true
|
9b8fd89a04b9408510e5f584cafe7cdb43ade00d
|
Java
|
hsubtil/projet_info
|
/JEE2/JEE_2-web/src/main/java/fr/cpe/ICalculRestService.java
|
UTF-8
| 277
| 1.90625
| 2
|
[] |
no_license
|
package fr.cpe;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
@Path("/calcul")
public interface ICalculRestService {
@GET
@Produces("text/plain")
@Path("/")
String calcul(@QueryParam("a") int [] numbers);
}
| true
|
c6437eac5568216445eca1c2cc3101471358f5a1
|
Java
|
kenuiuc/easemob-im-server-sdk
|
/im-sdk-cli/src/main/java/com/easemob/im/cli/cmd/UpdateCmd.java
|
UTF-8
| 5,786
| 2.15625
| 2
|
[
"Apache-2.0"
] |
permissive
|
package com.easemob.im.cli.cmd;
import com.easemob.im.server.EMException;
import com.easemob.im.server.EMService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import picocli.CommandLine.ArgGroup;
import picocli.CommandLine.Command;
import picocli.CommandLine.Option;
import picocli.CommandLine.Parameters;
import reactor.core.publisher.Mono;
import java.util.Map;
@Component
@Command(name = "update", description = "Update a resource.", mixinStandardHelpOptions = true)
public class UpdateCmd {
@Autowired
private EMService service;
@Command(name = "user", description = "Update user info.", mixinStandardHelpOptions = true)
public void user(@Parameters(description = "the username") String username,
@Option(names = "--password", description = "update user password") String password) {
if (password != null) {
this.service.user().updateUserPassword(username, password)
.doOnSuccess(ignore -> System.out.println("done"))
.doOnError(err -> System.out.println("error: " + err.getMessage()))
.onErrorResume(EMException.class, ignore -> Mono.empty())
.block();
}
}
@Command(name = "group", description = "Update a group's settings.", mixinStandardHelpOptions = true)
public void group(@Parameters(description = "the group's id") String groupId,
@ArgGroup(multiplicity = "1", exclusive = false) GroupArgGroup argGroup) {
this.service.group().updateGroup(groupId, request -> {
request.setName(argGroup.name)
.setDescription(argGroup.description)
.setMaxMembers(argGroup.maxMembers)
.setCanMemberInviteOthers(argGroup.canMemberInvite)
.setNeedApproveToJoin(
argGroup.canMemberInvite == null ? null : !argGroup.canMemberInvite);
}).doOnSuccess(ignored -> System.out.println("done"))
.doOnError(err -> System.out.println("error: " + err.getMessage()))
.onErrorResume(EMException.class, ignore -> Mono.empty())
.block();
if (StringUtils.hasText(argGroup.owner)) {
this.service.group().updateGroupOwner(groupId, argGroup.owner)
.doOnSuccess(ignored -> System.out.println("done"))
.doOnError(err -> System.out.println("error: " + err.getMessage()))
.onErrorResume(EMException.class, ignore -> Mono.empty())
.block();
}
if (argGroup.announcement != null) {
this.service.group().updateGroupAnnouncement(groupId, argGroup.announcement)
.doOnSuccess(ignored -> System.out.println("done"))
.doOnError(err -> System.out.println("error: " + err.getMessage()))
.onErrorResume(EMException.class, ignore -> Mono.empty())
.block();
}
}
@Command(name = "room", description = "Update a room's settings.", mixinStandardHelpOptions = true)
public void room(@Parameters(description = "the room's id") String roomId,
@ArgGroup(multiplicity = "1", exclusive = false) RoomArgGroup argGroup) {
this.service.room().updateRoom(roomId, request -> {
if (argGroup.name != null) {
request.withName(argGroup.name);
}
if (argGroup.description != null) {
request.withDescription(argGroup.description);
}
if (argGroup.maxMembers != null) {
request.withMaxMembers(argGroup.maxMembers);
}
}).doOnSuccess(ignored -> System.out.println("done"))
.doOnError(err -> System.out.println("error: " + err.getMessage()))
.onErrorResume(EMException.class, ignore -> Mono.empty())
.block();
}
@Command(name = "metadata", description = "Update user metadata.", mixinStandardHelpOptions = true)
public void metadata(@Parameters(description = "the username") String username,
@Option(names = "--data", description = "set user metadata")
Map<String, String> dataMap) {
this.service.metadata().setMetadataToUser(username, dataMap)
.doOnSuccess(ignored -> System.out.println("done"))
.doOnError(err -> System.out.println("error: " + err.getMessage()))
.onErrorResume(EMException.class, ignore -> Mono.empty())
.block();
}
private static class GroupArgGroup {
@Option(names = {
"--owner"}, description = "the new owner's username, who must be member of this group")
String owner;
@Option(names = "--name", description = "the group's name")
String name;
@Option(names = "--description", description = "the group's description")
String description;
@Option(names = {"--announcement"}, description = "the announcement")
String announcement;
@Option(names = {"--max-members"}, description = "the max number of members")
Integer maxMembers;
@Option(names = {"--can-member-invite"}, description = "can member invite others to join")
Boolean canMemberInvite;
}
private static class RoomArgGroup {
@Option(names = "--name", description = "new room name")
String name;
@Option(names = {"--description"}, description = "the announcement")
String description;
@Option(names = {"--max-members"}, description = "the max number of members")
Integer maxMembers;
}
}
| true
|
5ae10b4485e4bd9bb34ad3a46b2b927f47940692
|
Java
|
MikeManalo1031/EzFacMan
|
/src/ParseSVGData/ParseSVGData.java
|
UTF-8
| 1,083
| 2.765625
| 3
|
[] |
no_license
|
package ParseSVGData;
import java.util.ArrayList;
import java.io.*;
/**
* Driver class to test parsing functionality
*
* @author Nick Killion
*/
public class ParseSVGData {
/**
* Creates SVGParser Object, to test parsing methods
*
* @param args the command line arguments
*/
public static void main(String[] args) {
// String filename = "C:\\Documents and Settings\\Nick\\Desktop\\capstone\\svgs\\603SFCB3.svg";
// String filename = "C:\\Documents and Settings\\Nick\\Desktop\\capstone\\svgs\\RHA09.svg";
String filename = "C:\\Documents and Settings\\Nick\\Desktop\\capstone\\svgs\\602PB.svg";
SVGParser parser = new SVGParser(filename);
RoomData rooms = parser.parse();
test(rooms.roomList);
}
/**
* Creates Test object, to test parsing
*
* @param rList ArrayList of Room objects
*/
public static void test(ArrayList<Room> rList) {
Test test = new Test(rList);
test.start();
}
}
| true
|
490f7ee5efb188b84c3aa98c7ee2bbd814b05618
|
Java
|
dphan26/clothing
|
/src/main/java/com/example/demo/CheckNumeric2.java
|
UTF-8
| 197
| 1.804688
| 2
|
[] |
no_license
|
package com.example.demo;
public class CheckNumeric2 {
public static void main(String[] args) {
}
public void speak() {
System.out.println("aaaaaaaaaaaa");
}
}
| true
|
3ac4f342122581dcd9707f41e22aab4149f6dfa1
|
Java
|
rahul-gade/True
|
/src/test/java/com/mop/qa/InvestmentManagement/TestDealFolder.java
|
UTF-8
| 1,263
| 1.976563
| 2
|
[] |
no_license
|
package com.mop.qa.InvestmentManagement;
import org.apache.log4j.Logger;
import org.testng.annotations.Test;
import com.mop.qa.testbase.TestBase;
public class TestDealFolder extends TestBase{
private static final Logger LOGGER = Logger.getLogger(TestHypothesisFull.class.getName());
@Test
public void testDealFolder() {
try {
System.out.println("Test --> "+this.getClass().getSimpleName());
String startURL = rds.getValue("INVMGMT", currentTest, "URL");
String uname = rds.getValue("INVMGMT", currentTest, "UserName");
String pwd = rds.getValue("INVMGMT", currentTest, "Password");
IM_Home home = new IM_Home(remoteDriver);
home.launchApp(remoteDriver, startURL, uname, pwd);
String project = rds.getValue("INVMGMT", currentTest, "projectName");
home.findLiveDeal(remoteDriver, project);
IM_DealSummaryPage summary = new IM_DealSummaryPage(remoteDriver);
String filePath = rds.getValue("INVMGMT", currentTest, "filePath");
String newFile = rds.getValue("INVMGMT", currentTest, "filePathX");
summary.validateFolders(remoteDriver, filePath);
summary.createFolder(remoteDriver);
summary.uploadFile(remoteDriver, newFile);
} catch (Exception e) {
LOGGER.info(e);
}
}
}
| true
|
5615c9e71fc30367de3b1fa60c8bd39675028b88
|
Java
|
linbarbell/vestwell
|
/src/main/java/vestwell/Chamber.java
|
UTF-8
| 2,154
| 3.0625
| 3
|
[] |
no_license
|
package vestwell;
import java.util.ArrayList;
import java.util.List;
import static vestwell.Constants.*;
public class Chamber {
private final String init;
public Chamber(String init) {
this.init = init;
}
public String[] animate(int speed) {
List<String> positions = new ArrayList<>();
List<List<Character>> particles = new ArrayList<>(init.length()); // list of particles at each position
boolean particlesRemain = false;
for (char c: init.toCharArray()) { // initialize the particles
List<Character> chars = new ArrayList<>();
if (c != EMPTY) {
chars.add(c);
particlesRemain = true;
}
particles.add(chars);
}
positions.add(getPosition(particles));
while (particlesRemain) { // while particles remain, calculate the new particle positions
List<List<Character>> newParticles = new ArrayList<>(init.length());
for (int i = 0; i < init.length(); i++) {
newParticles.add(new ArrayList<>());
}
for (int i = 0; i < init.length(); i++) {
List<Character> curr = particles.get(i);
if (curr == null || curr.isEmpty()) continue;
for (char particle : curr) {
int pos = particle == L ? i - speed : i + speed;
if (pos >= 0 && pos < init.length()) {
newParticles.get(pos).add(particle);
}
}
}
particles = newParticles;
positions.add(getPosition(particles));
particlesRemain = particles.stream().anyMatch(i -> !i.isEmpty());
}
return positions.toArray(new String[0]);
}
private String getPosition(List<List<Character>> particles) {
char[] position = new char[init.length()];
for (int i = 0; i < init.length(); i++) {
position[i] = particles.get(i).isEmpty() ? EMPTY : X;
}
return new String(position);
}
}
| true
|
2b2b6af727d7c530929e8ab7ca77dfeeaea2282a
|
Java
|
spacecrafts/spacecrafts
|
/legacy/src/se/jbee/game/any/gfx/Resource.java
|
UTF-8
| 117
| 1.796875
| 2
|
[] |
no_license
|
package se.jbee.game.any.gfx;
@FunctionalInterface
public interface Resource<T> {
T yield(Resources resources);
}
| true
|
04549bf40fa7a6fc4948c506615c90aed81625b3
|
Java
|
subramaniankumarappan/RuleInterceptor
|
/src/main/java/com/rules/data/dao/postgres/RuleMetadataPGDAO.java
|
UTF-8
| 7,650
| 2.265625
| 2
|
[] |
no_license
|
package com.rules.data.dao.postgres;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.rules.common.pojo.BaseVO;
import com.rules.common.pojo.Rule;
import com.rules.data.dao.AbstractDAO;
/**
* File : RuleMetadataPGDAO.java
* Description : This RuleMetadataPGDAO is the main class for Rule detail manipulations with
* postgres DB.
* Revision History :
* Version Date Author Reason
* 0.1 07-October-2016 595251 Initial version
*/
public class RuleMetadataPGDAO extends AbstractDAO{
private static final Logger logger = LoggerFactory.getLogger(RuleMetadataPGDAO.class);
public RuleMetadataPGDAO(Connection connection){
super(connection);
}
@Override
public boolean add(BaseVO baseVO) throws Exception {
String sql = "INSERT INTO rule_metadata (RULE_ID, RULE_NAME, RULE_DESCRIPTION, MICRO_SERVICE_NAME, ENABLED, PRE_POST_HOOK, EXEC_SEQ, RULE_TYPE, PROCEED_IND, CREATED_BY, CREATED_TIME, MODIFIED_BY, MODIFIED_TIME)"
+ " VALUES (nextval('public.SEQ_RM_RULE_ID'),?,?,?,?,?,?,?,?,'ADMIN',current_timestamp,'ADMIN',current_timestamp)";
PreparedStatement statement = null;
Rule rule = (Rule) baseVO;
boolean isAdded = false;
logger.info("RULE_METADATA - ADD ---> " +rule.toString());
try {
connection.setAutoCommit(false);
statement = connection.prepareStatement(sql);
statement.setString(1, rule.getRuleName());
statement.setString(2, rule.getRuleDescription());
statement.setString(3, rule.getMsName());
statement.setString(4, rule.getEnabled());
statement.setString(5, rule.getPrePostHook().equalsIgnoreCase("Pre Hook")? "PRE": "POST");
statement.setInt(6, Integer.parseInt(rule.getExecSeq()));
statement.setString(7, rule.getRuleType());
statement.setString(8, rule.getProceedInd());
isAdded = statement.execute();
getConnection().commit();
} catch (SQLException e) {
SQLException next = e.getNextException();
if (next != null) {
throw next;
}
throw e;
} finally {
if (statement != null) {
statement.close();
}
if (connection != null) {
//connection.close();
}
}
return isAdded;
}
@Override
public boolean update(BaseVO baseVO) throws Exception {
String sql = "UPDATE rule_metadata set RULE_NAME = ?, RULE_DESCRIPTION = ?, MICRO_SERVICE_NAME = ?, ENABLED = ?"
+ ", PRE_POST_HOOK = ?, EXEC_SEQ = ?, RULE_TYPE = ?, PROCEED_IND = ?, MODIFIED_BY = ?, MODIFIED_TIME = current_timestamp "
+ " Where RULE_ID = ? " ;
PreparedStatement statement = null;
Rule rule = (Rule) baseVO;
int isUpdated = 0;
logger.info("RULE_METADATA - UPDATE ---> " +rule.toString());
try {
connection.setAutoCommit(false);
statement = connection.prepareStatement(sql);
statement.setString(1, rule.getRuleName());
statement.setString(2, rule.getRuleDescription());
statement.setString(3, rule.getMsName());
statement.setString(4, rule.getEnabled());
statement.setString(5, rule.getPrePostHook().equalsIgnoreCase("Pre Hook")? "PRE": "POST");
statement.setInt(6, Integer.parseInt(rule.getExecSeq()));
statement.setString(7, rule.getRuleType());
statement.setString(8, rule.getProceedInd());
statement.setString(9, rule.getModifiedBy());
statement.setString(10, rule.getRuleId());
isUpdated = statement.executeUpdate();
getConnection().commit();
} catch (SQLException e) {
SQLException next = e.getNextException();
if (next != null) {
throw next;
}
throw e;
} finally {
if (statement != null) {
statement.close();
}
if (connection != null) {
//connection.close();
}
}
return (isUpdated == 0 ? false : true) ;
}
@Override
public boolean delete(BaseVO baseVO) throws Exception {
// TODO Auto-generated method stub
return false;
}
public List<Rule> getRules() throws Exception{
List ruleList = null;
String sql = "SELECT * FROM rule_metadata;";
Statement statement = null;
boolean isAdded = false;
logger.info("RULE_METADATA - GET ---> " );
try {
statement = connection.createStatement();
ResultSet rs = statement.executeQuery(sql);
ruleList = getRuleList(rs);
} catch (SQLException e) {
SQLException next = e.getNextException();
if (next != null) {
throw next;
}
throw e;
} finally {
if (statement != null) {
statement.close();
}
if (connection != null) {
connection.close();
}
}
System.out.println("RULE_METADATA - GET ---> ");
return ruleList;
}
public List<Rule> getRules(String microServiceName) throws Exception{
List ruleList = null;
String sql = "SELECT * FROM rule_metadata where MICRO_SERVICE_NAME = '"+microServiceName +"' and ENABLED = 'Y'"; //add order by EXEC_SEQ
Statement statement = null;
logger.info("RULE_METADATA - GET (MS)---> " );
try {
statement = connection.createStatement();
ResultSet rs = statement.executeQuery(sql);
ruleList = getRuleList(rs);
} catch (SQLException e) {
SQLException next = e.getNextException();
if (next != null) {
throw next;
}
throw e;
} finally {
if (statement != null) {
statement.close();
}
if (connection != null) {
connection.close();
}
}
System.out.println("RULE_METADATA - GET (MS) ---> ");
return ruleList;
}
public List<Rule> getRules(String microServiceName, String hookInd) throws Exception{
List ruleList = null;
String sql = "SELECT * FROM rule_metadata where MICRO_SERVICE_NAME = '"+microServiceName +"' and ENABLED = 'Y' " + " and PRE_POST_HOOK = '" +hookInd + "'"; //add order by EXEC_SEQ
Statement statement = null;
logger.info("RULE_METADATA - GET (MS, HI)---> " );
try {
statement = connection.createStatement();
ResultSet rs = statement.executeQuery(sql);
ruleList = getRuleList(rs);
} catch (SQLException e) {
SQLException next = e.getNextException();
if (next != null) {
throw next;
}
throw e;
} finally {
if (statement != null) {
statement.close();
}
if (connection != null) {
connection.close();
}
}
System.out.println("RULE_METADATA - GET (MS, HI) ---> ");
return ruleList;
}
private List <Rule> getRuleList(ResultSet rs) throws SQLException{
List ruleList = new ArrayList <Rule>();
Rule rule = null;
while(rs.next()){
rule = new Rule();
rule.setRuleId(rs.getInt("RULE_ID") +"");
rule.setRuleName(rs.getString("RULE_NAME"));
rule.setRuleDescription(rs.getString("RULE_DESCRIPTION"));
rule.setMsName(rs.getString("MICRO_SERVICE_NAME"));
rule.setEnabled(rs.getString("ENABLED"));
rule.setPrePostHook(rs.getString("PRE_POST_HOOK"));
rule.setExecSeq(rs.getString("EXEC_SEQ"));
rule.setRuleType(rs.getString("RULE_TYPE"));
rule.setProceedInd(rs.getString("PROCEED_IND"));
rule.setCreatedBy(rs.getString("CREATED_BY"));
rule.setCreatedTime(rs.getDate("CREATED_TIME"));
rule.setModifiedBy(rs.getString("MODIFIED_BY"));
rule.setModifiedTime(rs.getDate("CREATED_TIME"));
ruleList.add(rule);
}
return ruleList;
}
}
| true
|
35cda696bf3292880da3dd7db7d14e90001f1e5f
|
Java
|
LucasHenriqueLS/Bucket_Up
|
/Bucket_Up-main/src/main/java/model/Equipamento.java
|
UTF-8
| 2,131
| 2.21875
| 2
|
[] |
no_license
|
package main.java.model;
import java.util.*;
class Equipamento{
public Integer id;
public String hostname;
public String usuario_login;
public String senha_login;
public String ip;
public String port;
public String pastas;
public String agendamento;
public String id_user;
public Equipamento(String hostname, String usuario_login, String senha_login, String ip, String port,
String pastas, String agendamento, String id_user) {
this.hostname = hostname;
this.usuario_login = usuario_login;
this.senha_login = senha_login;
this.ip = ip;
this.port = port;
this.pastas = pastas;
this.agendamento = agendamento;
this.id_user = id_user;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getHostname() {
return hostname;
}
public void setHostname(String hostname) {
this.hostname = hostname;
}
public String getUsuario_login() {
return usuario_login;
}
public void setUsuario_login(String usuario_login) {
this.usuario_login = usuario_login;
}
public String getSenha_login() {
return senha_login;
}
public void setSenha_login(String senha_login) {
this.senha_login = senha_login;
}
public String getIp() {
return ip;
}
public void setIp(String ip) {
this.ip = ip;
}
public String getPort() {
return port;
}
public void setPort(String port) {
this.port = port;
}
public String getPastas() {
return pastas;
}
public void setPastas(String pastas) {
this.pastas = pastas;
}
public String getAgendamento() {
return agendamento;
}
public void setAgendamento(String agendamento) {
this.agendamento = agendamento;
}
public String getId_user() {
return id_user;
}
public void setId_user(String id_user) {
this.id_user = id_user;
}
}
| true
|
46a0cf70b7b2ecf6723da24a6866938955ba81d5
|
Java
|
icapk/ZYLC-2.0
|
/app/src/main/java/com/example/gte/sms_demo_12/mulu_list/Person.java
|
UTF-8
| 1,259
| 2.171875
| 2
|
[] |
no_license
|
package com.example.gte.sms_demo_12.mulu_list;
/**
* Created by GTE on 2016/11/22.
*/
import com.example.gte.sms_demo_12.Utils.pinyin_utils;
import com.example.gte.sms_demo_12.domain.Name;
public class Person {
//姓名
private String name;
private String mNumber;
private String pNumber;
private String mBeiZhu;
//拼音
private String pinyin;
//拼音首字母
private String headerWord;
public Person(String name,String pNumber,String beizhu) {
this.name = name;
this.pNumber = pNumber;
this.mBeiZhu = beizhu;
this.pinyin = pinyin_utils.getPinyin(name);
headerWord = pinyin.substring(0, 1);
}
public String getPinyin() {
return pinyin;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getHeaderWord() {
return headerWord;
}
public String getpNumber() {
return pNumber;
}
public void setpNumber(String pNumber) {
this.pNumber = pNumber;
}
public String getmBeiZhu() {
return mBeiZhu;
}
public void setmBeiZhu(String mBeiZhu) {
this.mBeiZhu = mBeiZhu;
}
}
| true
|
f0ad4232d77c50dcc9ccb64b224bcab85b170a36
|
Java
|
alinetenorio/GestaoAtividades
|
/src/Dados/UploadDownload/DownloadTarefa.java
|
UTF-8
| 3,972
| 2.9375
| 3
|
[] |
no_license
|
package Dados.UploadDownload;
import Dados.Repositorio.RepositorioTarefa;
import Negocio.entidade.Tarefa;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.text.SimpleDateFormat;
public class DownloadTarefa {
private final Tarefa[] listaTarefa;
private SimpleDateFormat sdf1;
private BufferedWriter arq;
public DownloadTarefa(RepositorioTarefa reposTarefa) {
this.listaTarefa = reposTarefa.returnListaTarefa();
sdf1= new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
}
public void main() {
try {
criarPastas();
limparArquivoPendente();
for (Tarefa listaTarefa1 : listaTarefa) {
if (listaTarefa1.getMarcaFinalizadoGerente() == true) {
criarObjetoEscritaFinalizada(listaTarefa1);
}
else {
criarObjetoEscritaPendente(listaTarefa1);
}
escreverArquivo(listaTarefa1);
arq.close();
}
}
catch(IOException e) {
System.out.println("ERRO: ao escrever o arquivo");
System.out.println(e.getMessage());
}
}
private void criarPastas() {
File diretorio1 = new File("ArquivoTXT/Tarefa/Finalizada");
File diretorio2 = new File("ArquivoTXT/Tarefa/Pendente");
diretorio1.mkdirs();
diretorio2.mkdirs();
}
private void limparArquivoPendente() throws IOException {
File file = new File("ArquivoTXT/Tarefa/Pendente");
File[] listaFile = file.listFiles();
for (File listaFile1 : listaFile) {
String nomeFuncionario = "ArquivoTXT/Tarefa/Pendente/" + listaFile1;
arq = new BufferedWriter(new FileWriter(nomeFuncionario, false));
arq.write("");
arq.close();
}
}
private void criarObjetoEscritaFinalizada(Tarefa tarefa) throws IOException {
String nomeFuncionario = "ArquivoTXT/Tarefa/Finalizada/Funcionario_" + tarefa.getResponsavel().getNome() + ".txt";
arq = new BufferedWriter(new FileWriter(nomeFuncionario, true));
}
private void criarObjetoEscritaPendente(Tarefa tarefa) throws IOException {
String nomeFuncionario = "ArquivoTXT/Tarefa/Pendente/Funcionario_" + tarefa.getResponsavel().getNome() + ".txt";
arq = new BufferedWriter(new FileWriter(nomeFuncionario, true));
}
private void escreverArquivo(Tarefa tarefa) throws IOException {
arq.write(tarefa.getResponsavel().getNome() + ";");
arq.write(tarefa.getResponsavel().getNumIdentidade() + "\n");
arq.write(tarefa.getDescricao() + ";");
arq.write(tarefa.getDataInicio() + ";");
arq.write(tarefa.getDataTermino() + ";");
arq.write(tarefa.getIndiceTimeline() + ";");
arq.write(tarefa.getMarcaFinalizadoFuncionario() + ";");
arq.write(tarefa.getMarcaFinalizadoGerente() + "\n");
for (int i = 0; i < 5; i++) {
if (tarefa.getTimelineTarefa()[i] == null) {
arq.write("null" + "\n");
}
else {
if (tarefa.getTimelineTarefa()[i].getDataMarcaFuncionario() == null) {
arq.write("null" + ";");
arq.write("null" + ";");
}
else{
arq.write(sdf1.format(tarefa.getTimelineTarefa()[i].getDataMarcaFuncionario()) + ";");
arq.write(sdf1.format(tarefa.getTimelineTarefa()[i].getDataMarcaGerente()) + ";");
}
arq.write(tarefa.getTimelineTarefa()[i].getTag() + ";");
arq.write(tarefa.getTimelineTarefa()[i].getNotaFuncionario() + ";");
arq.write(tarefa.getTimelineTarefa()[i].getNotaGerente() + "\n");
}
}
}
}
| true
|
2083416c2a5f4d99fb24c90b4db6ab5593b0a14e
|
Java
|
reverseengineeringer/com.yik.yak
|
/src/com/google/android/gms/common/api/Api$a.java
|
UTF-8
| 339
| 1.664063
| 2
|
[] |
no_license
|
package com.google.android.gms.common.api;
public abstract interface Api$a
{
public abstract void connect();
public abstract void disconnect();
public abstract boolean isConnected();
}
/* Location:
* Qualified Name: com.google.android.gms.common.api.Api.a
* Java Class Version: 6 (50.0)
* JD-Core Version: 0.7.1
*/
| true
|
718017df9ea02f3a6622e575454322f02fb13746
|
Java
|
samwarnick/catan
|
/src/server/commands/move/PlayMonopolyCommand.java
|
UTF-8
| 2,397
| 2.53125
| 3
|
[] |
no_license
|
package server.commands.move;
import java.io.IOException;
import com.fasterxml.jackson.databind.ObjectMapper;
import shared.communication.input.move.PlayMonopolyInput;
import shared.definitions.ResourceType;
import shared.model.GameModel;
import shared.model.bank.BankException;
import shared.model.bank.DevelopmentHand;
import shared.model.board.PlayerID;
import shared.model.player.Player;
public class PlayMonopolyCommand extends MoveCommand {
//private GameModel model;
public PlayMonopolyCommand() {
super();
}
/**
* @param input is a valid PlayMonopolyInput object
* @pre None
* @post All other players have given all of the specified resource to
* @return The GameModel after executing the changes
*/
@Override
public Object execute(String input) {
PlayMonopolyInput playMonopolyInput;
try {
playMonopolyInput = new ObjectMapper().readValue(input, PlayMonopolyInput.class);
int playerIndex = playMonopolyInput.getPlayerIndex();
String type = playMonopolyInput.getResource();
ResourceType realType = null;
switch(type){
case "brick":
realType = ResourceType.BRICK;
break;
case "wood":
realType = ResourceType.WOOD;
break;
case "sheep":
realType = ResourceType.SHEEP;
break;
case "wheat":
realType = ResourceType.WHEAT;
break;
case "ore":
realType = ResourceType.ORE;
break;
default:
System.out.println("dat ain't a real type 'o reasource - PlayMonopolyCommand");
}
int totalNumberOfCardsRecieved = 0;
for(int i = 0; i < 4; i++)
{
PlayerID id = new PlayerID(i);
Player p = model.getPlayer(id);
totalNumberOfCardsRecieved += p.getPlayerBank().getResourceStack(realType).getQuantity();
try {
p.getPlayerBank().getResourceStack(realType).setQuantity(0);
} catch (BankException e) {
e.printStackTrace();
}
}
PlayerID index = new PlayerID(playerIndex);
Player p = model.getPlayer(index);
try {
p.getPlayerBank().getResourceStack(realType).setQuantity(totalNumberOfCardsRecieved);
} catch (BankException e) {
e.printStackTrace();
}
try {
p.getPlayerBank().modifyDC(new DevelopmentHand(0,0,-1,0,0));
} catch (BankException e) {
e.printStackTrace();
}
} catch (IOException e1) {
e1.printStackTrace();
}
return model;
}
public void setModel(GameModel model) {
this.model = model;
}
}
| true
|
b87a8220377f7bd8199d624f397a40b7dd309290
|
Java
|
weisun10/testgit
|
/JavaHTTP1/Actions.java
|
UTF-8
| 419
| 1.617188
| 2
|
[] |
no_license
|
/*
* LoadRunner Java script. (Build: 3020)
*
* Script Description:
*
*/
import lrapi.lr;
public class Actions
{
public int init() throws Throwable {
return 0;
}//end of init
public int action() throws Throwable {
lr.error_message("my error message");
return 0;
}//end of action
public int end() throws Throwable {
return 0;
}//end of end
}
| true
|
61387d7c695626d483880532a7df2f60cd88be76
|
Java
|
josephguillaume/aquifer
|
/src/HydroModel/Boundary.java
|
UTF-8
| 127
| 1.90625
| 2
|
[] |
no_license
|
package HydroModel;
public class Boundary {
// ID of zone on other side of boundary
int neighbourID;
float flow;
}
| true
|
8ac915bb44e339bb31fd9bc3441ab931d8d3150d
|
Java
|
canonxu/DesignPattern
|
/src/test/java/com/canonxu/designpattern/Proxy/StaticClientProxyTest.java
|
UTF-8
| 314
| 1.875
| 2
|
[] |
no_license
|
package com.canonxu.designpattern.Proxy;
import org.junit.Test;
/**
* Created by canonxu on 2016/1/24.
*/
public class StaticClientProxyTest {
@Test
public void staticClientProxyTest(){
StaticClientProxy staticClientProxy = new StaticClientProxy();
staticClientProxy.login();
}
}
| true
|
7cbe0a22b7cc96ee2e555d8f205bace2772849c8
|
Java
|
Liamhardy04/Java1ClassWork
|
/Calculator/src/Calculator/Numbers.java
|
UTF-8
| 5,312
| 4.03125
| 4
|
[] |
no_license
|
package Calculator;
import java.util.Scanner;
public class Numbers {
public static void main(String[] args) {
boolean getAnswer = false;
boolean keepGoing = true;
boolean valid = true;
double prevAnswer;
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter '1' now to get help and see your calculating options. Enter a different number to continue.");
int enter = keyboard.nextInt();
if (enter == 1 ) {
System.out.println("Operator options: \n 1) '+' Adding two numbers together. \n 2) '-' Subtract one number from another number. \n "
+ "3) '*' Multiply two numbers together. \n 4) '/' Divide one number by another. \n 5) '^' Raise a number to the power of another number. \n "
+ "6) '%' Gives you the remainder of dividing a first number by a second number. \n Example: 6 % 4 = the remainder of 6 / 4, or 2. \n "
+ "7) '!' Multiplies a number by each whole number below it down to one. \n Example: 5! = 5 * 4 * 3 * 2 * 1. \n 8) 's' Acts as sqrt. Finds the number that if squared would equal your inputed number. \n "
+ " Example: 36 s = 6. \n 9) 'c' Restarts calculator. \n 10)'e' Ends the progran.");
}
System.out.println("Enter a number:");
double answer = keyboard.nextDouble();
OUTER:
while (getAnswer == false) {
if (keepGoing == false) {
System.out.println("Restarted Calculator.");
System.out.println("Enter '1' now to get help and see your calculating options. Enter a different number to continue.");
enter = keyboard.nextInt();
if (enter == 1 ) {
System.out.println("Operator options: \n 1) '+' Adding two numbers together. \n 2) '-' Subtract one number from another number. \n "
+ " 3) '*' Multiply two numbers together. \n 4) '/' Divide one number by another. \n 5) '^' Raise a number to the power of another number. \n "
+ "6) '%' Gives you the remainder of dividing a first number by a second number. \n Example: 6 % 4 = the remainder of 6 / 4, or 2. \n "
+ "7) Multiplies a number by each whole number below it down to one. \n Example: 5! = 5 * 4 * 3 * 2 * 1. \n 8) 's' Acts as sqrt. Finds the number that if squared would equal your inputed number. \n "
+ " Example: 36 s = 6. \n 9) 'c' Restarts calculator. \n 10)'e' Ends the program." );
}
System.out.println("Enter a number:");
answer = keyboard.nextDouble();
keepGoing = true;
}
System.out.println("Operator:");
char operator = keyboard.next().charAt(0);
switch (operator) {
case '!':
case 's':
case 'c':
case 'e':
double num11;
if (operator == 'c') {
keepGoing = false;
}
if (operator == 'e') {
getAnswer = true;
break OUTER;
}
if (operator == '!') {
System.out.println(answer);
num11 = answer;
for(int i = 0; i < num11 - 1; i++) {
answer = answer * (num11 - (i + 1));
}
System.out.println(num11 + "" + operator + " = " + answer );
}
else if ( operator == 's') {
prevAnswer = answer;
answer = Math.sqrt(answer);
System.out.println("Answer:");
System.out.println("√" + prevAnswer + " = " + answer);
}
break;
case '+':
case '-':
case '*':
case '/':
case '^':
case '%':
System.out.println("Next number:");
double num2 = keyboard.nextDouble();
switch (operator) {
case '+': answer = answer + num2;
break;
case '-': answer = answer - num2;
break;
case '*': answer = answer * num2;
break;
case '/': answer = answer / num2;
break;
case '^': answer = Math.pow(answer, num2);
break;
case '%': answer = answer % num2;
break;
} break;
default:
System.out.println("Invalid operator.");
valid = false;
break;
}
if (valid ==
true);
{
System.out.println("Answer: " + answer);
}
valid = true;
}
}
}
| true
|
f0a2b3d42689fe09d6932bb8911ce1556428452d
|
Java
|
levonyang/proper-his
|
/src/com/javahis/ui/sys/SYSAssessmentListControl.java
|
GB18030
| 8,512
| 1.914063
| 2
|
[] |
no_license
|
package com.javahis.ui.sys;
import java.awt.Color;
import jdo.sys.SystemTool;
//import jdo.sys.Operator;
//import jdo.util.Manager;
import com.dongyang.config.TConfig;
import com.dongyang.control.TControl;
import com.dongyang.data.TParm;
import com.dongyang.jdo.TJDODBTool;
//import com.dongyang.tui.text.ESingleChoose;
import com.dongyang.ui.TTable;
//import com.dongyang.ui.TWord;
//import com.dongyang.ui.base.TWordBase;
//import com.dongyang.util.TypeTool;
//import com.javahis.util.EmrUtil;
import com.javahis.util.StringUtil;
/**
* <p>Title: һ</p>
*
* <p>Description:һ </p>
*
* <p>Copyright: Copyright (c) </p>
*
* <p>Company: </p>
*
* @author zhangs 20151029
* @version 1.0
*/
public class SYSAssessmentListControl extends TControl{
private TTable tableM;
private TTable tableD;
private String caseNo="";
private TParm tableParm = null;
private String ipdNo="";
// TWORD
// private TWord word;
// ṹ·
private String[] saveFile;
// ṹ·
// private TParm pathParm, patParm;
// private ESingleChoose singleChoose;
/**
* ѡе
*/
// private int tableMSelectedRow = -1;
public void onInit(){
super.onInit();
// System.out.println("className:"+getParameter().getClass().getName());
// System.out.println(getParameter());
// this.singleChoose = ((ESingleChoose)getParameter());
// if (this.singleChoose == null) {
// return;
// }
tableM = (TTable) getComponent("tTable_M");
tableD = (TTable) getComponent("tTable_D");
// õǰ̨ݲʾڽ
TParm recptype = this.getInputParm();
System.out.println(recptype);
if (recptype != null) {
this.setValue("MR_NO", recptype.getValue("MR_NO"));
this.setValue("PAT_NAME", recptype.getValue("PAT_NAME"));
this.setValue("DEPT", recptype.getValue("DEPT_CODE"));
this.setValue("BED_NO", recptype.getValue("BED_NO_DESC"));
caseNo=recptype.getValue("CASE_NO");
ipdNo=recptype.getValue("IPD_NO");
}
this.onQuery();
}
public void onQuery(){
this.queryM(caseNo,getValueString("SOURCE"),getValueString("SORT"));
}
/**
* ѯ
*/
public void queryM(String caseNo,String source,String sort) {
String Sql =
" SELECT CASE T.WARNING_FLG WHEN '0' THEN '' WHEN '1' THEN '' END WARNING,CASE T.EVALUTION_CLASS WHEN '0' THEN '' WHEN '1' THEN 'ҽ' END EVALUTION, " +
" T.EVALUTION_DESC,T.SCORE,T.SCORE_DECS,T.EVALUTION_DATE,T.EVALUTION_CODE,T.SOURCE,T.NIS_ID,T.FILE_PATH,T.WARNING_FLG,T.EVALUTION_CLASS "+
" FROM EMR_EVALUTION_RECORD T "+
" WHERE T.CASE_NO='"+caseNo+"' " +
" AND T.EVALUTION_DATE=(SELECT MAX(T.EVALUTION_DATE) FROM EMR_EVALUTION_RECORD WHERE EVALUTION_CODE=T.EVALUTION_CODE) ";
if(!StringUtil.isNullString(source)){
Sql =Sql+" AND T.EVALUTION_CLASS='"+source+"' ";
}
if(!StringUtil.isNullString(sort)){
if(sort.equals("0")){
Sql =Sql+" ORDER BY T.EVALUTION_CLASS";
}else if(sort.equals("1")){
Sql =Sql+" ORDER BY T.EVALUTION_DATE";
}
}
// System.out.println("queryM==="+Sql);
TParm tabParm = new TParm(TJDODBTool.getInstance().select(Sql));
if(tabParm.getCount("WARNING_FLG")<0){
this.messageBox("ûҪѯݣ");
onClear();
return;
}
// tableM.setHeader("Ԥ,40;,40;,120;ֵ,60;ָ,120;ʱ,120,timestamp,yyyy/mm/dd hh:mm:ss");
// System.out.println("WARNING_FLG==="+tabParm.getCount("WARNING_FLG"));
// tableM.setParmMap("WARNING;EVALUTION;EVALUTION_DESC;SCORE;SCORE_DESC;EVALUTION_DATE;EVALUTION_CODE;SOURCE;NIS_ID;FILE_PATH;WARNING_FLG;EVALUTION_CLASS");
// table.setItem("DOSAGE_UNIT");
// tableM.setColumnHorizontalAlignmentData("0,left;1,left;2,left;3,left;4,left;5,left;6,right;7,left;8,right;9,left;10,left;11,left");
// table.setParmValue(tableinparm);
// System.out.println("tabParm==="+tabParm);
this.callFunction("UI|tTable_M|setParmValue", tabParm);
setTableColor(tableM);
// tableM.setParmValue(tabParm);
}
/**
* ¼
*/
public void onTableMClicked() {
int row = tableM.getSelectedRow();
// ѡͬһУִκβ
// if (tableMSelectedRow == row)
// return;
// tableMSelectedRow = row;
tableM.acceptText();
tableParm = tableM.getParmValue().getRow(row);
String Sql =
" SELECT CASE T.WARNING_FLG WHEN '0' THEN '' WHEN '1' THEN '' END WARNING," +
" T.EVALUTION_DATE,T.EVALUTION_DESC,T.SCORE,T.SCORE_DECS,T.EVALUTION_CODE,T.SOURCE,T.NIS_ID,T.FILE_PATH,T.WARNING_FLG "+
" FROM EMR_EVALUTION_RECORD T "+
" WHERE T.CASE_NO='"+caseNo+"' " +
" AND T.EVALUTION_CODE='"+tableParm.getValue("EVALUTION_CODE")+"' "+
" AND T.EVALUTION_CLASS='"+tableParm.getValue("EVALUTION_CLASS")+"' "+
" ORDER BY T.EVALUTION_DATE DESC ";
// System.out.println("onTableMClicked==="+Sql);
TParm tabParm = new TParm(TJDODBTool.getInstance().select(Sql));
if(tabParm.getCount("WARNING_FLG")<0){
this.messageBox("ûҪѯݣ");
return;
}
this.callFunction("UI|tTable_D|setParmValue", tabParm);
setTableColor(tableD);
// tableD.setParmValue(tabParm);
}
/**
* Mһ¼
*/
public void onTableMRightClicked() {
int row = tableM.getSelectedRow();
openWindow(tableM,row);
}
/**
* Dһ¼
*/
public void onTableDRightClicked() {
int row = tableD.getSelectedRow();
openWindow(tableD,row);
}
/**
* ҼĴ
*/
public void openWindow(TTable table,int row){
table.acceptText();
tableParm = table.getParmValue().getRow(row);
if(tableParm.getValue("SOURCE").equals("0")){
//NIS
openNIS(tableParm);
}else if(tableParm.getValue("SOURCE").equals("1")){
//HIS
openHIS(tableParm);
}
}
/**
* ԴHISĴ
*/
public void openHIS(TParm table){
// this.messageBox("openHIS(TTable table)"+table.getValue("FILE_PATH"));
saveFile=this.getFilePath(table.getValue("FILE_PATH"));
// System.out.println("emrParm="+saveFile[0]);
// System.out.println("emrParm="+saveFile[1]);
// word.onOpen(saveFile[0], saveFile[1], 3, false);
onOpen(caseNo,saveFile);
}
/**
* ԴNISĴ
*/
public void openNIS(TParm table){
// this.messageBox("openNIS(TTable table)"+table.getValue("NIS_ID"));
String url =
// m2Login_login=ʺ&encid=סԺ&patientid=&encType=I&formId=UUId&formType=
"http://"+ TConfig.getSystemValue("NisIP") +
"/Nis/m2/user/login?m2Login_login=administrator&encid="+this.caseNo+
"&patientid="+this.getValue("MR_NO")+"&encType=I&formId="+table.getValue("NIS_ID")+
"&formType="+table.getValue("EVALUTION_CODE");
// "http://172.20.1.70:8080/nis/m2/user/login?m2Login_login=administrator&encid=000000084283&patientid=000000099999&encType=I&formId=00000150DBAE7371&formType=EMR060206";
SystemTool.getInstance().OpenIE(url);
}
/**
* øΣ¼Ϊɫ
*/
public void setTableColor(TTable table){
table.acceptText();
tableParm = table.getParmValue();
// table.getRowColor(row);
for (int i = 0; i < tableParm.getCount(); i++) {
if (tableParm.getRow(i).getValue("WARNING_FLG").equals("1")){
table.setRowTextColor(i,Color.RED);
// table.setRowColor(i,Color.RED);
}else{
table.setRowTextColor(i,Color.BLACK);
// table.setRowColor(i,Color.WHITE);
}
}
}
/**
* ļ·
*/
public String[] getFilePath(String filePate){
//JHW\15\05\00000706\150530000003_ƳԺ¼_64
String saveFile[] = new String[2];
String temp[]=filePate.split("\\\\");
saveFile[1] = temp[temp.length-1];
saveFile[0]=filePate.replace("\\"+saveFile[1], "");
return saveFile;
}
/**
* Ӳ
*/
public void onOpen(String caseNo,String saveFile[]){
TParm parm = new TParm();
parm.setData("CASE_NO", caseNo);
parm.setData("FILE_NAME", saveFile[1]);
parm.setData("FILE_PATH", saveFile[0]);
this.openWindow("%ROOT%\\config\\sys\\SYSEmrView.x", parm);
}
/**
*
*/
public void onClear(){
this.tableM.removeRowAll();
this.tableD.removeRowAll();
}
}
| true
|
a42528cd61cee9b7317fc63a3e5e89809806f7a4
|
Java
|
duarterafael/Conformitate
|
/Yaoqiang/src/org/yaoqiang/bpmn/editor/dialog/panels/CategoryValuePanel.java
|
UTF-8
| 3,499
| 2.0625
| 2
|
[
"Apache-2.0"
] |
permissive
|
package org.yaoqiang.bpmn.editor.dialog.panels;
import java.awt.event.ActionEvent;
import java.util.ArrayList;
import java.util.List;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import org.yaoqiang.bpmn.editor.BPMNEditor;
import org.yaoqiang.bpmn.editor.dialog.PanelContainer;
import org.yaoqiang.bpmn.editor.dialog.XMLPanel;
import org.yaoqiang.bpmn.editor.dialog.XMLTablePanel;
import org.yaoqiang.bpmn.editor.dialog.XMLTextPanel;
import org.yaoqiang.bpmn.model.elements.XMLElement;
import org.yaoqiang.bpmn.model.elements.artifacts.CategoryValue;
import org.yaoqiang.bpmn.model.elements.core.common.FlowElement;
import com.mxgraph.util.mxResources;
/**
* CategoryValuePanel
*
* @author Shi Yaoqiang(shi_yaoqiang@yahoo.com)
*/
public class CategoryValuePanel extends XMLPanel {
private static final long serialVersionUID = 1L;
protected XMLTextPanel valuePanel;
protected XMLTablePanel flowElementsPanel;
public CategoryValuePanel(PanelContainer pc, CategoryValue owner) {
super(pc, owner);
this.setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
valuePanel = new XMLTextPanel(pc, owner.get("value"));
JPanel idValuePanel = new JPanel();
idValuePanel.setLayout(new BoxLayout(idValuePanel, BoxLayout.X_AXIS));
idValuePanel.add(new XMLTextPanel(pc, owner.get("id"), false));
idValuePanel.add(Box.createHorizontalGlue());
idValuePanel.add(valuePanel);
this.add(idValuePanel);
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(new BoxLayout(buttonPanel, BoxLayout.X_AXIS));
buttonPanel.add(Box.createHorizontalStrut(5));
buttonPanel.add(createToolbarButton(selectAction));
buttonPanel.add(Box.createHorizontalGlue());
this.add(buttonPanel);
List<String> columnsToShow = new ArrayList<String>();
columnsToShow.add("id");
columnsToShow.add("type");
columnsToShow.add("name");
flowElementsPanel = new XMLTablePanel(getPanelContainer(), owner, "", "categorizedFlowElements", columnsToShow, owner.getCategorizedFlowElements(),
350, 300, false, false);
this.add(flowElementsPanel);
}
public void saveObjects() {
if (valuePanel.getText().trim().length() == 0) {
JOptionPane.showMessageDialog(null, "Category Value is required!", mxResources.get("Warning"), JOptionPane.WARNING_MESSAGE);
return;
}
valuePanel.saveObjects();
super.saveObjects();
List<XMLElement> oldList = ((CategoryValue) owner).getCategorizedFlowElements(false);
for (XMLElement el : oldList) {
((FlowElement) el).removeCategoryValueRef(((CategoryValue) owner).getId());
}
List<XMLElement> newList = flowElementsPanel.getAllElements();
for (XMLElement el : newList) {
((FlowElement) el).addCategoryValueRef(((CategoryValue) owner).getId());
}
((CategoryValue) owner).setCategorizedFlowElements(newList);
}
public JButton createToolbarButton(Action a) {
String actionName = (String) a.getValue(Action.NAME);
JButton b = new JButton(mxResources.get(actionName));
b.setName(actionName);
b.addActionListener(a);
b.setToolTipText(mxResources.get(actionName));
return b;
}
protected Action selectAction = new AbstractAction("selectFlowElements") {
private static final long serialVersionUID = 1L;
public void actionPerformed(ActionEvent ae) {
BPMNEditor.getInstance().createDialog().initDialog().editBPMNElement(flowElementsPanel, "selectFlowElements", owner);
}
};
}
| true
|
2686400f5c2263effd0c1dac66089883c134a200
|
Java
|
DolphZiggler/order_print
|
/latte-btprint/src/main/java/com/flj/latte/btprint/detail/WaittingDelegate.java
|
UTF-8
| 7,239
| 1.828125
| 2
|
[] |
no_license
|
package com.flj.latte.btprint.detail;
import android.app.AlertDialog;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.flj.latte.app.AccountManager;
import com.flj.latte.app.Latte;
import com.flj.latte.btprint.R;
import com.flj.latte.btprint.bean.DeliveryMan;
import com.flj.latte.btprint.bean.OrderBean;
import com.flj.latte.btprint.index.IndexDelegate;
import com.flj.latte.btprint.list.OrderListDelegate;
import com.flj.latte.btprint.utils.Constants;
import com.flj.latte.btprint.utils.ConvertUtils;
import com.flj.latte.delegates.LatteDelegate;
import com.flj.latte.net.RestClient;
import com.flj.latte.ui.recycler.MultipleItemEntity;
public class WaittingDelegate extends LatteDelegate implements View.OnClickListener {
private OrderBean orderBean = null;
private DeliveryMan[] deliveryMEN = null;
private int mCurrentPosition = -1;
private boolean selectedFlag = false;
@Override
public Object setLayout() {
return R.layout.delegate_waitting;
}
@Override
public void onLazyInitView(@Nullable Bundle savedInstanceState) {
super.onLazyInitView(savedInstanceState);
loadDeliveryList();
}
private void loadDeliveryList() {
Latte.getHandler().postDelayed((
() -> RestClient.builder()
.url(Constants.DELIVERY_LIST)
.params("userid", AccountManager.getCurrentCustomerId())
.success(response -> {
final JSONObject object = JSON.parseObject(response);
initDeliverys(object);
})
.error((code, msg) -> Toast.makeText(Latte.getApplicationContext(), "请求错误:" + code + " " + msg, Toast.LENGTH_SHORT).show())
.failure(() -> Toast.makeText(Latte.getApplicationContext(), "网络故障,请求失败", Toast.LENGTH_SHORT).show())
.build()
.get())
, 0);
}
private void initDeliverys(JSONObject object) {
JSONArray data = object.getJSONArray("data");
int size = data.size();
deliveryMEN = new DeliveryMan[size];
for (int i = 0; i < size; i++) {
JSONObject obj = data.getJSONObject(i);
String deliveryName = obj.getString("deliveryName");
String deliveryId = obj.getString("deliveryId");
deliveryMEN[i] = new DeliveryMan().setDeliveryId(deliveryId).setDeliveryName(deliveryName);
}
}
@Override
public void onBindView(@Nullable Bundle savedInstanceState, @NonNull View rootView) {
orderBean = ConvertUtils.getOrderInDelegate(this);
((TextView) $(R.id.tv_order_waitting)).setText(ConvertUtils.convertText(ConvertUtils.orderBean2String(orderBean, true, false)));
$(R.id.btn_post_deliveryman).setOnClickListener(this);
$(R.id.tv_delivery_choose).setOnClickListener(this);
}
public static WaittingDelegate create(MultipleItemEntity itemEntity) {
WaittingDelegate waittingDelegate = new WaittingDelegate();
Bundle bundle = new Bundle();
bundle.putSerializable(Constants.ARG_ORDER_BEAN_PRINT, itemEntity);
waittingDelegate.setArguments(bundle);
return waittingDelegate;
}
@Override
public void onClick(View v) {
int id = v.getId();
if (id == R.id.btn_post_deliveryman) {
if (selectedFlag)
postDeliveryForOrder(mCurrentPosition);
else Toast.makeText(_mActivity, "请选择配送员", Toast.LENGTH_SHORT).show();
} else if (id == R.id.tv_delivery_choose) {
showPopWindow();
}
}
private void showPopWindow() {
View inflate = LayoutInflater.from(getContext()).inflate(R.layout.alert_content, null);
ListView viewById = inflate.findViewById(R.id.alert_content);
String[] adapterArray = new String[deliveryMEN.length];
for (int i = 0; i < deliveryMEN.length; i++) {
adapterArray[i] = deliveryMEN[i].getDeliveryName();
}
ArrayAdapter<String> adapter = new ArrayAdapter(getContext(), R.layout.spinner_item, adapterArray);
viewById.setAdapter(adapter);
AlertDialog.Builder builder = new AlertDialog.Builder(getContext())
.setMessage("选择配送员")
.setView(inflate);
AlertDialog alertDialog = builder.create();
alertDialog.show();
viewById.setOnItemClickListener((parent, view, position, id) -> {
((TextView) $(R.id.tv_delivery_choose)).setText(deliveryMEN[position].getDeliveryName());
mCurrentPosition = position;
selectedFlag = true;
alertDialog.dismiss();
});
}
private void postDeliveryForOrder(int position) {
/* OrderListDelegate orderListDelegate = new OrderListDelegate();
Bundle bundle = new Bundle();
bundle.putString("fresh", "fresh");
orderListDelegate.setArguments(bundle);
start(orderListDelegate,SINGLETASK);*/
Latte.getHandler().postDelayed((
() -> RestClient.builder()
.url(Constants.DELIVERY_LIST)
.params("orderId", orderBean.getOrderId())
.params("deliveryName", deliveryMEN[position].getDeliveryId())
.success((response) -> {
if ("1".equals(response)) {
OrderListDelegate orderListDelegate = new OrderListDelegate();
Bundle bundle = new Bundle();
bundle.putString("fresh", "fresh");
orderListDelegate.setArguments(bundle);
start(new IndexDelegate(), SINGLETASK);
} else {
Toast.makeText(_mActivity, response, Toast.LENGTH_SHORT).show();
}
})
.error((code, msg) -> Toast.makeText(Latte.getApplicationContext(), "请求错误:" + code + " " + msg, Toast.LENGTH_SHORT).show())
.failure(() -> Toast.makeText(Latte.getApplicationContext(), "网络故障,请求失败", Toast.LENGTH_SHORT).show())
.build()
.post())
, 0);
}
}
| true
|
2772731d897e5342381279d388a86e49876a2687
|
Java
|
VinithaJohny/Automation
|
/src/ReverseNumber.java
|
UTF-8
| 221
| 3.171875
| 3
|
[] |
no_license
|
public class ReverseNumber {
public static void main(String[] args) {
int number =1234;
int rev=0;
while(number>0)
{
rev = rev*10 + number%10;
number = number/10;
}
System.out.println(rev);
}
}
| true
|
04183ea1f7c30962b40d9c5bd9fe67d2518f57d3
|
Java
|
Benosu998/Java
|
/Lab7/src/Player.java
|
UTF-8
| 1,427
| 3.390625
| 3
|
[] |
no_license
|
public class Player implements Runnable {
private final int THINKING_TIME=1000;
private String name;
private Game game;
private Graph graph;
Player(){
this.name="John Doe";
graph=new Graph();
}
Player(String name){
this.name=name;
graph=new Graph();
}
public void setGame(Game game){
this.game=game;
}
private boolean play() throws InterruptedException {
if(this.game.haveWinner())
{
System.out.println("["+this.name+"]: Jucatorul casstigator este "+this.game.getWinner());
return false;
}
Board board = game.getBoard();
if (board.isEmpty()) { return false; }
graph.add( board.extract() );
Thread.sleep(THINKING_TIME); //declare this constant
if (graph.isSpanningTree(game.getBoard().getSize())) {
game.setWinner(this);
}
return true;
}
public void run(){
try {
while(this.play())
{
System.out.println("["+this.name+"]: Extrage muchie");
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
@Override
public String toString() {
return this.name+" avand urmatoarele muchii " +this.graph;
}
// implement the run() method, that will repeatedly extract edges
// implement the toString() method
}
| true
|
6d728c9706aa5e4399c70afd02402055e45a67b4
|
Java
|
ch656409110/springboot-study
|
/springboot高级主题/springboot-advanceTopics/chapter4-3/src/main/java/com/hu/study/chapter43/Chapter43Application.java
|
UTF-8
| 430
| 1.703125
| 2
|
[] |
no_license
|
package com.hu.study.chapter43;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
@SpringBootApplication
@ComponentScan({"com.hu.study.chapter43.http"})
public class Chapter43Application {
public static void main(String[] args) {
SpringApplication.run(Chapter43Application.class, args);
}
}
| true
|
d0cddb8cf8bc3076a873b895a4038ca8303f4662
|
Java
|
MrOrange1992/SWENGB_HW02
|
/src/rauchenwald/geometrie/zweidimensional/Dreieck.java
|
UTF-8
| 2,563
| 3.34375
| 3
|
[] |
no_license
|
package rauchenwald.geometrie.zweidimensional;
/**
* Created by Felix on 05/11/2016.
*/
public class Dreieck extends ZweiDimensional
{
//ATTRIBUTES
//------------------------------------------------------------------------------------------------------------------
private int sideA;
private int sideB;
//------------------------------------------------------------------------------------------------------------------
//CONSTRUCTOR
//------------------------------------------------------------------------------------------------------------------
//public Dreieck() {}
public Dreieck(int x, int y, int sideA, int sideB)
{
this.xKor = x;
this.yKor = y;
this.sideA = sideA;
this.sideB = sideB;
}
//------------------------------------------------------------------------------------------------------------------
//GETTER SETTER
//------------------------------------------------------------------------------------------------------------------
public int getSideA() { return sideA; }
public void setSideA(int sideA) { this.sideA = sideA; }
public int getSideB() { return sideB; }
public void setSideB(int sideB) { this.sideB = sideB; }
//------------------------------------------------------------------------------------------------------------------
//METHODS
//------------------------------------------------------------------------------------------------------------------
public double calculateArea() { return this.sideA * this.sideB / 2; }
public double calculatePerimeter()
{
return this.sideA + this.sideB + Math.sqrt(Math.pow(this.sideA, 2) + Math.pow(this.sideB, 2));
}
//------------------------------------------------------------------------------------------------------------------
//OVERRIDES
//------------------------------------------------------------------------------------------------------------------
@Override
public boolean equals(Object o)
{
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Dreieck dreieck = (Dreieck) o;
if (sideA != dreieck.sideA) return false;
return sideB == dreieck.sideB;
}
@Override
public int hashCode()
{
int result = sideA;
result = 31 * result + sideB;
return result;
}
//------------------------------------------------------------------------------------------------------------------
}
| true
|
0568e4aa966b143b36d69d914336476a893cbd4b
|
Java
|
shinodkharim/eCommerce
|
/admin/src/main/java/com/curiez/admin/model/Sku.java
|
UTF-8
| 955
| 1.78125
| 2
|
[] |
no_license
|
package com.curiez.admin.model;
//import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonInclude;
import lombok.*;
import org.springframework.data.annotation.Id;
import org.springframework.data.neo4j.core.schema.CompositeProperty;
import org.springframework.data.neo4j.core.schema.Node;
import org.springframework.data.neo4j.core.schema.Relationship;
import java.util.Map;
import java.util.Set;
@Data
@AllArgsConstructor
@NoArgsConstructor
@JsonInclude(JsonInclude.Include.NON_EMPTY)
@Node("sku")
@Builder
public class Sku{
@Id
private String id;
private String name;
private String description;
private Boolean isStock;
private Long inventory;
private Double list;
private Double sale;
private Double special;
@Relationship(type = "has_sku_image", direction = Relationship.Direction.INCOMING)
private Set<Media> medias;
@CompositeProperty
private Map<String,String> attributes;
}
| true
|
f27deb2cc29f3a0044637b0ac5bc3954183d45f3
|
Java
|
nevmmv/prozdep
|
/src/main/java/department/ui/controller/model/PaperViewModel.java
|
UTF-8
| 1,582
| 2.59375
| 3
|
[] |
no_license
|
/**
*
*/
package department.ui.controller.model;
import department.utils.Preconditions;
import lombok.AccessLevel;
import lombok.Getter;
import lombok.Value;
import rx.Observable;
import rx.subjects.BehaviorSubject;
@Value
@Getter(value = AccessLevel.NONE)
public class PaperViewModel {
int id;
BehaviorSubject<String> name;
BehaviorSubject<String> type;
BehaviorSubject<Integer> year;
public PaperViewModel(int id, String name, String type, int year) {
Preconditions.checkArgument(id > 0, "id <= 0");
Preconditions.checkArgument(year >= 1900, "year < 1900");
this.id = id;
this.name = BehaviorSubject.create(Preconditions.notNull(name));
this.type = BehaviorSubject.create(Preconditions.notNull(type));
this.year = BehaviorSubject.create(year);
}
public int getId() {
return id;
}
public Observable<String> getNameObs() {
return name.asObservable();
}
public String getName() {
return name.getValue();
}
public void setName(String name) {
this.name.onNext(name);
}
public Observable<String> getTypeObs() {
return type.asObservable();
}
public String getType() {
return type.getValue();
}
public void setType(String type) {
this.type.onNext(type);
}
public Observable<Integer> getYearObs() {
return year.asObservable();
}
public int getYear() {
return year.getValue();
}
public void setYear(int year) {
this.year.onNext(year);
}
}
| true
|
c1c8c49e05efb657650d9e51a12d8d5c00e87b56
|
Java
|
maheshkumar42/DreamItGetIt
|
/src/main/java/com/comrench/DAO/SkillDAO.java
|
UTF-8
| 240
| 1.984375
| 2
|
[] |
no_license
|
package com.comrench.DAO;
import com.comrench.Entity.Skills;
import java.util.List;
import java.util.Map;
public interface SkillDAO {
public List<Skills> getSkillsList();
public Map<Long, String> getSkillsMap(List<Skills> skills);
}
| true
|
86d7f7f67697861a65b72738b4763c26fe6d4b26
|
Java
|
andysteel/employee-manager
|
/src/main/java/com/gmail/andersoninfonet/employeemanager/monitoring/DatabaseService.java
|
UTF-8
| 731
| 2.484375
| 2
|
[] |
no_license
|
package com.gmail.andersoninfonet.employeemanager.monitoring;
import org.springframework.boot.actuate.health.Health;
import org.springframework.boot.actuate.health.HealthIndicator;
import org.springframework.stereotype.Component;
@Component
public class DatabaseService implements HealthIndicator {
private static final String DATABASE_SERVICE = "Database Service";
@Override
public Health health() {
if(isDatabaseHealthGood()) {
return Health.up().withDetail(DATABASE_SERVICE, "Database is running.").build();
}
return Health.down().withDetail(DATABASE_SERVICE, "Database is down").build();
}
private boolean isDatabaseHealthGood() {
return true;
}
}
| true
|
4da834f9a042e623ab071e97832f20944e321960
|
Java
|
sun-shining/j-leetcode
|
/src/main/java/cc/juddar/algorithm/J18FourSum.java
|
UTF-8
| 3,237
| 3.9375
| 4
|
[] |
no_license
|
package cc.juddar.algorithm;
import java.util.ArrayList;
import java.util.Arrays;
/**
* Given an array S of n integers, are there elements a, b, c,
* and d in S such that a + b + c + d = target?
* Find all unique quadruplets in the array which gives the sum of target.
* <p>
* Note:
* Elements in a quadruplet (a,b,c,d) must be in non-descending order. (ie, a ≤ b ≤ c ≤ d)
* The solution set must not contain duplicate quadruplets.
* For example, given array S = {1 0 -1 0 -2 2}, and target = 0.
* <p>
* A solution set is:
* (-1, 0, 0, 1)
* (-2, -1, 1, 2)
* (-2, 0, 0, 2)
*
* 这是网上一种利用递归的解法,不仅可以解决本题四个数字相加,还可以适用与任何多个数字相加
*/
public class J18FourSum {
public static void main(String[] args) {
int[] numbers = {1,0,-1,0,-2,2};
int target = 0;
ArrayList<ArrayList<Integer>> lists = J18FourSum.fourSum(numbers, target);
for (int i = 0; i < lists.size(); i++) {
ArrayList<Integer> list = lists.get(i);
System.err.println(list.toString());
}
}
public static ArrayList<ArrayList<Integer>> fourSum(int[] numbers, int target) {
Arrays.sort(numbers);
ArrayList<ArrayList<Integer>> ret = new ArrayList<>();
dfs(ret, new ArrayList<Integer>(), numbers, 0, target);
return ret;
}
private static void dfs(ArrayList<ArrayList<Integer>> ret, ArrayList<Integer> condidate, int[] numbers, int curIndex,
int target) {
// 以后求n数和,只要改这里就能解决,比如4改为3,改为5
if (condidate.size() == 4) {
int total = getSum(condidate);
if (total == target) {
// ret.add(condidate); condidate里代表是一组结果,
ret.add(new ArrayList<>(condidate));
}
return;
}
//如果索引已经超过数组长度了,没有继续的意义了
if (curIndex > numbers.length - 1) {
return;
}
for (int i = curIndex; i < numbers.length; i++) {
// 如果是一样的数字,直接忽略,否则会有重复的答案
if (i != curIndex && numbers[i] == numbers[i - 1]) {
continue;
}
condidate.add(numbers[i]);
// 如果已经大于target,并且当前数字大于0,再循环加下去已经没有意义了,因为只会更大,直接return
if (getSum(condidate) > target && numbers[i] > 0) {
if (!condidate.isEmpty()) {
condidate.remove(condidate.size() - 1);
}
return;
}
//递归的时候存放待选结果的就不能重新new一个新的了,得使用condidate
dfs(ret, condidate, numbers, i + 1, target);
if (!condidate.isEmpty()) {
condidate.remove(condidate.size() - 1);
}
}
}
//求list中元素的和
private static int getSum(ArrayList<Integer> condidate) {
int total = 0;
for (Integer num : condidate) {
total += num;
}
return total;
}
}
| true
|
b791804abc600ae7993aa5abf5662599b8481067
|
Java
|
itYangJie/NewCode
|
/src/com/xmu/interviewgold/EleFind.java
|
UTF-8
| 1,087
| 3.3125
| 3
|
[] |
no_license
|
package com.xmu.interviewgold;
public class EleFind {
public static void main(String[] args) {
// TODO Auto-generated method stub
}
public int findElement(int[] A, int n, int x) {
int i = 0, j = n - 1, mid;
while (i <= j) {
mid = (i + j) / 2;
if (A[mid] == x)
return mid;
if (A[mid] < x) {
if (A[mid] < A[i] && x > A[j])
j = mid - 1;
else
i = mid + 1;
} else {
if (A[mid] > A[i] && x < A[i])
i = mid + 1;
else
j = mid - 1;
}
}
return -1;
}
public int findString(String[] str, int n, String x) {
int l = 0, r = n - 1;
while (l <= r) {
int mid = (l + r) / 2;
if (str[mid].equals(x))
return mid;
if ("".equals(str[mid])) {
if (str[l].equals(x))
return l;
else
l++;
} else {
if (str[mid].compareTo(x) > 0)
r = mid - 1;
else
l = mid + 1;
}
}
return -1;
}
public int[] findElementInMat(int[][] mat, int n,
int m, int x) {
int i = n-1,j = 0;
while(mat[i][j]!=x) {
if(mat[i][j]>x)
i--;
else
j++;
}
return new int[] {i,j};
}
}
| true
|
94f901c2218c800f04afed38ba2c8722ecd5914b
|
Java
|
mnarendra333/Batch-19-CoreExamples
|
/ManyToOneWithAnnotations/src/pack1/Customer.java
|
UTF-8
| 1,195
| 2.46875
| 2
|
[] |
no_license
|
package pack1;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
@Entity
@Table
public class Customer {
@Override
public String toString() {
return "Customer [custId=" + custId + ", custName=" + custName
+ ", custAddr=" + custAddr + ", vendor=" + vendor + "]";
}
@Id
private int custId;
@Column(length=20)
private String custName;
@Column(length=20)
private String custAddr;
@ManyToOne(cascade=CascadeType.ALL,targetEntity=Vendor.class)
@JoinColumn(name="vendorId")
private Vendor vendor;
public int getCustId() {
return custId;
}
public void setCustId(int custId) {
this.custId = custId;
}
public String getCustName() {
return custName;
}
public void setCustName(String custName) {
this.custName = custName;
}
public String getCustAddr() {
return custAddr;
}
public void setCustAddr(String custAddr) {
this.custAddr = custAddr;
}
public Vendor getVendor() {
return vendor;
}
public void setVendor(Vendor vendor) {
this.vendor = vendor;
}
}
| true
|
c93eede4b6f5e2fdce9bacdbbde6542d987a16a9
|
Java
|
AlexFEIII/dailyTest
|
/src/main/java/com/pro/daily/dailyConfig/LoginSuccessConfig.java
|
UTF-8
| 800
| 2.078125
| 2
|
[] |
no_license
|
//package com.pro.daily.dailyConfig;
//
//import org.springframework.security.core.Authentication;
//import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
//
//import javax.servlet.ServletException;
//import javax.servlet.http.HttpServletRequest;
//import javax.servlet.http.HttpServletResponse;
//import java.io.IOException;
//
//public class LoginSuccessConfig extends SavedRequestAwareAuthenticationSuccessHandler {
// @Override
// public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication)throws ServletException,IOException{
// response.setCharacterEncoding("UTF-8");
// response.getWriter().println("{\"username\":\"XiaoMing\",\"role\":\"USER\"");
// }
//}
| true
|
d62b4bb2e534bb66df0b5a1e3cd90225695bb39c
|
Java
|
weitat95/mastersDissertation
|
/qardio_source/cfr_dec/com/getqardio/android/provider/WearableDataHelper$$Lambda$1.java
|
UTF-8
| 679
| 1.664063
| 2
|
[] |
no_license
|
/*
* Decompiled with CFR 0.147.
*/
package com.getqardio.android.provider;
import com.getqardio.android.provider.WearableDataHelper;
import io.reactivex.functions.Function;
import java.lang.invoke.LambdaForm;
import java.util.List;
final class WearableDataHelper$$Lambda$1
implements Function {
private static final WearableDataHelper$$Lambda$1 instance = new WearableDataHelper$$Lambda$1();
private WearableDataHelper$$Lambda$1() {
}
public static Function lambdaFactory$() {
return instance;
}
@LambdaForm.Hidden
public Object apply(Object object) {
return WearableDataHelper.lambda$getFollowingData$0((List)object);
}
}
| true
|