blob_id
stringlengths
40
40
__id__
int64
225
39,780B
directory_id
stringlengths
40
40
path
stringlengths
6
313
content_id
stringlengths
40
40
detected_licenses
list
license_type
stringclasses
2 values
repo_name
stringlengths
6
132
repo_url
stringlengths
25
151
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringlengths
4
70
visit_date
timestamp[ns]
revision_date
timestamp[ns]
committer_date
timestamp[ns]
github_id
int64
7.28k
689M
star_events_count
int64
0
131k
fork_events_count
int64
0
48k
gha_license_id
stringclasses
23 values
gha_fork
bool
2 classes
gha_event_created_at
timestamp[ns]
gha_created_at
timestamp[ns]
gha_updated_at
timestamp[ns]
gha_pushed_at
timestamp[ns]
gha_size
int64
0
40.4M
gha_stargazers_count
int32
0
112k
gha_forks_count
int32
0
39.4k
gha_open_issues_count
int32
0
11k
gha_language
stringlengths
1
21
gha_archived
bool
2 classes
gha_disabled
bool
1 class
content
stringlengths
7
4.37M
src_encoding
stringlengths
3
16
language
stringclasses
1 value
length_bytes
int64
7
4.37M
extension
stringclasses
24 values
filename
stringlengths
4
174
language_id
stringclasses
1 value
entities
list
contaminating_dataset
stringclasses
0 values
malware_signatures
list
redacted_content
stringlengths
7
4.37M
redacted_length_bytes
int64
7
4.37M
alphanum_fraction
float32
0.25
0.94
alpha_fraction
float32
0.25
0.94
num_lines
int32
1
84k
avg_line_length
float32
0.76
99.9
std_line_length
float32
0
220
max_line_length
int32
5
998
is_vendor
bool
2 classes
is_generated
bool
1 class
max_hex_length
int32
0
319
hex_fraction
float32
0
0.38
max_unicode_length
int32
0
408
unicode_fraction
float32
0
0.36
max_base64_length
int32
0
506
base64_fraction
float32
0
0.5
avg_csv_sep_count
float32
0
4
is_autogen_header
bool
1 class
is_empty_html
bool
1 class
shard
stringclasses
16 values
0356193d5b05e7feb9707ee26e29a468749730be
11,115,375,376,061
bb3589fc8a6f834a070c168379cb00c4af873e27
/src/main/java/seedu/address/logic/commands/AddCommand.java
599cbd9447c5fccfb769093f55fdf1cdad75992a
[ "MIT" ]
permissive
CS2103JAN2017-W10-B1/main
https://github.com/CS2103JAN2017-W10-B1/main
ad71cd72aa560447f9b0fca8c126bafb006da95d
373d599af32088ccc4bd787d09b96eda42260c22
refs/heads/master
2020-04-06T03:54:55.487000
2017-04-11T03:37:56
2017-04-11T03:37:56
83,100,171
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
//@@author A0138474X package seedu.address.logic.commands; import seedu.address.commons.exceptions.IllegalValueException; import seedu.address.logic.commands.exceptions.CommandException; import seedu.address.model.tag.Tag; import seedu.address.model.task.Description; import seedu.address.model.task.Event; import seedu.address.model.task.Name; import seedu.address.model.task.Priority; import seedu.address.model.task.ReadOnlyRecurringTask.RecurringMode; import seedu.address.model.task.ReadOnlyTask; import seedu.address.model.task.RecurringEvent; import seedu.address.model.task.RecurringTask; import seedu.address.model.task.Task; import seedu.address.model.task.TaskDate; import seedu.address.model.task.TaskTime; import seedu.address.model.task.UniqueTaskList; import seedu.address.model.task.Venue; /** * Adds a task/event/recurring task to Dueue. */ public class AddCommand extends AbleUndoCommand { public static final String COMMAND_WORD = "add"; public static final String COMMAND_ADD = COMMAND_WORD + COMMAND_SUFFIX; public static final String MESSAGE_USAGE = COMMAND_WORD + ": Adds a task to Dueue. \n" + "Parameters: NAME [due/DUE_DATE] [dueT/DUE_TIME] [start/START_DATE] [startT/START_TIME]\n" + "[#LISTNAME] [d/DESCRIPTION] [@VENUE] [p/PRIORITY_LEVEL] [*f] [f/REPEAT_PERIOD] \n" + "Examples: " + COMMAND_WORD + " \nTrip to Taiwan due/24/6/2017 start/tmr startT/16:00" + " dueT/18:00 p/3 *f\n" + COMMAND_WORD + " CS2103T Tutorial #CS2103 d/Finish asap p/important\n" + COMMAND_WORD + " CS2103 Demo f/weekly #CS2103 d/Exhausting module @SoC p/3\n"; public static final String MESSAGE_SUCCESS = "New task added: %1$s"; public static final String MESSAGE_DUPLICATE_TASK = "This task already exists in the Dueue"; private final Task toAdd; // indicate whether the command had been executed successfully private boolean isSuccess = false; // indicate for undoing deleting of occurring Task or Events private boolean isDeleteAllOcurrence = true; // indicate whether this command is performing undo for another command private boolean isUndo = false; /** * Creates an AddCommand using raw values. * * @throws IllegalValueException if any of the raw values are invalid */ public AddCommand(String name, String date, String startDate, String time, String startTime, String tag, String description, String venue, String priority, String frequency, boolean isFavourite, boolean isEvent, boolean isRecurring) throws IllegalValueException { RecurringMode mode = getRecurringMode(frequency); if (isEvent && isRecurring) { this.toAdd = buildRecurringEvent(name, date, startDate, time, startTime, tag, description, venue, priority, isFavourite, mode); } else if (isEvent) { this.toAdd = buildEvent(name, date, startDate, time, startTime, tag, description, venue, priority, isFavourite); } else if (isRecurring) { this.toAdd = buildRecurringTask(name, date, time, tag, description, venue, priority, isFavourite, mode); } else { this.toAdd = buildTask(name, date, time, tag, description, venue, priority, isFavourite); } } // constructor for undoing a delete command public AddCommand(ReadOnlyTask task, boolean isDeleteAllOcurrence) { this.toAdd = (Task) task; this.isDeleteAllOcurrence = isDeleteAllOcurrence; this.isUndo = true; } //create an event to add to Dueue private Event buildEvent(String name, String date, String startDate, String time, String startTime, String tag, String description, String venue, String priority, boolean isFavourite) throws IllegalValueException { if (!startDate.isEmpty()) { return new Event( new Name(name), new TaskDate(startDate), new TaskTime (startTime), new TaskDate(date), new TaskTime(time), new Description(description), new Tag(tag), new Venue(venue), new Priority(priority), isFavourite ); } else { return new Event( new Name(name), new TaskDate(date), new TaskTime (startTime), new TaskTime(time), new Description(description), new Tag(tag), new Venue(venue), new Priority(priority), isFavourite ); } } // create a recurring event to add to Dueue private Event buildRecurringEvent(String name, String date, String startDate, String time, String startTime, String tag, String description, String venue, String priority, boolean isFavourite, RecurringMode mode) throws IllegalValueException { if (mode == null) { return buildEvent(name, date, startDate, time, startTime, tag, description, venue, priority, isFavourite); } else { if (!startDate.isEmpty()) { return new RecurringEvent( new Name(name), new TaskDate(startDate), new TaskTime (startTime), new TaskDate(date), new TaskTime(time), new Description(description), new Tag(tag), new Venue(venue), new Priority(priority), isFavourite, mode ); } else { return new RecurringEvent( new Name(name), new TaskDate(date), new TaskTime (startTime), new TaskTime(time), new Description(description), new Tag(tag), new Venue(venue), new Priority(priority), isFavourite, mode ); } } } // create a task to add into Dueue private Task buildTask(String name, String date, String time, String tag, String description, String venue, String priority, boolean isFavourite) throws IllegalValueException { return new Task( new Name(name), new TaskDate(date), new TaskTime(time), new Description(description), new Tag(tag), new Venue(venue), new Priority(priority), isFavourite ); } // create a recurring task to add into Dueue private Task buildRecurringTask(String name, String date, String time, String tag, String description, String venue, String priority, boolean isFavourite, RecurringMode mode) throws IllegalValueException { if (mode == null) { return buildTask(name, date, time, tag, description, venue, priority, isFavourite); } else { return new RecurringTask( new Name(name), new TaskDate(date), new TaskTime(time), new Description(description), new Tag(tag), new Venue(venue), new Priority(priority), isFavourite, mode ); } } // convert the string to RecurringMode private RecurringMode getRecurringMode(String ocurring) { if (ocurring.matches(RecurringTask.PERIOD_DAY_REGEX)) { return RecurringMode.DAY; } else if (ocurring.matches(RecurringTask.PERIOD_WEEK_REGEX)) { return RecurringMode.WEEK; } else if (ocurring.matches(RecurringTask.PERIOD_MONTH_REGEX)) { return RecurringMode.MONTH; } return null; } @Override public CommandResult execute() throws CommandException { return execute(CommandFormatter.undoFormatter( String.format(MESSAGE_SUCCESS, toAdd.getName()), COMMAND_ADD)); } public CommandResult execute(String message) throws CommandException { assert model != null; try { model.addTask(toAdd); this.isSuccess = true; int taskIndex = model.getFilteredTaskList().indexOf(toAdd); highlightCurrentTaskName(taskIndex); highlightCurrentTagName(toAdd.getTag().toString()); return new CommandResult(message); } catch (UniqueTaskList.DuplicateTaskException e) { this.isSuccess = false; throw new CommandException(MESSAGE_DUPLICATE_TASK); } } @Override public boolean isUndoable() { return true; } @Override public CommandResult undo(String message) throws CommandException { return execute(CommandFormatter.undoMessageFormatter(message, getRedoCommandWord())); } // return the command that is equivalent to undoing add (DeleteCommand) @Override public Command getUndoCommand() { if (isSuccess) { return new DeleteCommand(toAdd, isDeleteAllOcurrence); } else { return null; } } @Override public String getUndoCommandWord() { return DeleteCommand.COMMAND_WORD + COMMAND_SUFFIX; } @Override public String getRedoCommandWord() { return COMMAND_WORD + COMMAND_SUFFIX; } }
UTF-8
Java
9,966
java
AddCommand.java
Java
[ { "context": "//@@author A0138474X\npackage seedu.address.logic.commands;\n\nimport see", "end": 20, "score": 0.9962583184242249, "start": 11, "tag": "USERNAME", "value": "A0138474X" }, { "context": " return new Event(\n new Name(name),\n new TaskDate(startDate),\n ", "end": 4035, "score": 0.9930362105369568, "start": 4031, "tag": "NAME", "value": "name" }, { "context": " return new Event(\n new Name(name),\n new TaskDate(date),\n ", "end": 4510, "score": 0.9646440148353577, "start": 4506, "tag": "NAME", "value": "name" }, { "context": " RecurringEvent(\n new Name(name),\n new TaskDate(startDate)", "end": 5481, "score": 0.9720044136047363, "start": 5477, "tag": "NAME", "value": "name" }, { "context": " RecurringEvent(\n new Name(name),\n new TaskDate(date),\n ", "end": 6047, "score": 0.8885233998298645, "start": 6043, "tag": "NAME", "value": "name" }, { "context": " return new Task(\n new Name(name),\n new TaskDate(date),\n ", "end": 6780, "score": 0.9735982418060303, "start": 6776, "tag": "NAME", "value": "name" } ]
null
[]
//@@author A0138474X package seedu.address.logic.commands; import seedu.address.commons.exceptions.IllegalValueException; import seedu.address.logic.commands.exceptions.CommandException; import seedu.address.model.tag.Tag; import seedu.address.model.task.Description; import seedu.address.model.task.Event; import seedu.address.model.task.Name; import seedu.address.model.task.Priority; import seedu.address.model.task.ReadOnlyRecurringTask.RecurringMode; import seedu.address.model.task.ReadOnlyTask; import seedu.address.model.task.RecurringEvent; import seedu.address.model.task.RecurringTask; import seedu.address.model.task.Task; import seedu.address.model.task.TaskDate; import seedu.address.model.task.TaskTime; import seedu.address.model.task.UniqueTaskList; import seedu.address.model.task.Venue; /** * Adds a task/event/recurring task to Dueue. */ public class AddCommand extends AbleUndoCommand { public static final String COMMAND_WORD = "add"; public static final String COMMAND_ADD = COMMAND_WORD + COMMAND_SUFFIX; public static final String MESSAGE_USAGE = COMMAND_WORD + ": Adds a task to Dueue. \n" + "Parameters: NAME [due/DUE_DATE] [dueT/DUE_TIME] [start/START_DATE] [startT/START_TIME]\n" + "[#LISTNAME] [d/DESCRIPTION] [@VENUE] [p/PRIORITY_LEVEL] [*f] [f/REPEAT_PERIOD] \n" + "Examples: " + COMMAND_WORD + " \nTrip to Taiwan due/24/6/2017 start/tmr startT/16:00" + " dueT/18:00 p/3 *f\n" + COMMAND_WORD + " CS2103T Tutorial #CS2103 d/Finish asap p/important\n" + COMMAND_WORD + " CS2103 Demo f/weekly #CS2103 d/Exhausting module @SoC p/3\n"; public static final String MESSAGE_SUCCESS = "New task added: %1$s"; public static final String MESSAGE_DUPLICATE_TASK = "This task already exists in the Dueue"; private final Task toAdd; // indicate whether the command had been executed successfully private boolean isSuccess = false; // indicate for undoing deleting of occurring Task or Events private boolean isDeleteAllOcurrence = true; // indicate whether this command is performing undo for another command private boolean isUndo = false; /** * Creates an AddCommand using raw values. * * @throws IllegalValueException if any of the raw values are invalid */ public AddCommand(String name, String date, String startDate, String time, String startTime, String tag, String description, String venue, String priority, String frequency, boolean isFavourite, boolean isEvent, boolean isRecurring) throws IllegalValueException { RecurringMode mode = getRecurringMode(frequency); if (isEvent && isRecurring) { this.toAdd = buildRecurringEvent(name, date, startDate, time, startTime, tag, description, venue, priority, isFavourite, mode); } else if (isEvent) { this.toAdd = buildEvent(name, date, startDate, time, startTime, tag, description, venue, priority, isFavourite); } else if (isRecurring) { this.toAdd = buildRecurringTask(name, date, time, tag, description, venue, priority, isFavourite, mode); } else { this.toAdd = buildTask(name, date, time, tag, description, venue, priority, isFavourite); } } // constructor for undoing a delete command public AddCommand(ReadOnlyTask task, boolean isDeleteAllOcurrence) { this.toAdd = (Task) task; this.isDeleteAllOcurrence = isDeleteAllOcurrence; this.isUndo = true; } //create an event to add to Dueue private Event buildEvent(String name, String date, String startDate, String time, String startTime, String tag, String description, String venue, String priority, boolean isFavourite) throws IllegalValueException { if (!startDate.isEmpty()) { return new Event( new Name(name), new TaskDate(startDate), new TaskTime (startTime), new TaskDate(date), new TaskTime(time), new Description(description), new Tag(tag), new Venue(venue), new Priority(priority), isFavourite ); } else { return new Event( new Name(name), new TaskDate(date), new TaskTime (startTime), new TaskTime(time), new Description(description), new Tag(tag), new Venue(venue), new Priority(priority), isFavourite ); } } // create a recurring event to add to Dueue private Event buildRecurringEvent(String name, String date, String startDate, String time, String startTime, String tag, String description, String venue, String priority, boolean isFavourite, RecurringMode mode) throws IllegalValueException { if (mode == null) { return buildEvent(name, date, startDate, time, startTime, tag, description, venue, priority, isFavourite); } else { if (!startDate.isEmpty()) { return new RecurringEvent( new Name(name), new TaskDate(startDate), new TaskTime (startTime), new TaskDate(date), new TaskTime(time), new Description(description), new Tag(tag), new Venue(venue), new Priority(priority), isFavourite, mode ); } else { return new RecurringEvent( new Name(name), new TaskDate(date), new TaskTime (startTime), new TaskTime(time), new Description(description), new Tag(tag), new Venue(venue), new Priority(priority), isFavourite, mode ); } } } // create a task to add into Dueue private Task buildTask(String name, String date, String time, String tag, String description, String venue, String priority, boolean isFavourite) throws IllegalValueException { return new Task( new Name(name), new TaskDate(date), new TaskTime(time), new Description(description), new Tag(tag), new Venue(venue), new Priority(priority), isFavourite ); } // create a recurring task to add into Dueue private Task buildRecurringTask(String name, String date, String time, String tag, String description, String venue, String priority, boolean isFavourite, RecurringMode mode) throws IllegalValueException { if (mode == null) { return buildTask(name, date, time, tag, description, venue, priority, isFavourite); } else { return new RecurringTask( new Name(name), new TaskDate(date), new TaskTime(time), new Description(description), new Tag(tag), new Venue(venue), new Priority(priority), isFavourite, mode ); } } // convert the string to RecurringMode private RecurringMode getRecurringMode(String ocurring) { if (ocurring.matches(RecurringTask.PERIOD_DAY_REGEX)) { return RecurringMode.DAY; } else if (ocurring.matches(RecurringTask.PERIOD_WEEK_REGEX)) { return RecurringMode.WEEK; } else if (ocurring.matches(RecurringTask.PERIOD_MONTH_REGEX)) { return RecurringMode.MONTH; } return null; } @Override public CommandResult execute() throws CommandException { return execute(CommandFormatter.undoFormatter( String.format(MESSAGE_SUCCESS, toAdd.getName()), COMMAND_ADD)); } public CommandResult execute(String message) throws CommandException { assert model != null; try { model.addTask(toAdd); this.isSuccess = true; int taskIndex = model.getFilteredTaskList().indexOf(toAdd); highlightCurrentTaskName(taskIndex); highlightCurrentTagName(toAdd.getTag().toString()); return new CommandResult(message); } catch (UniqueTaskList.DuplicateTaskException e) { this.isSuccess = false; throw new CommandException(MESSAGE_DUPLICATE_TASK); } } @Override public boolean isUndoable() { return true; } @Override public CommandResult undo(String message) throws CommandException { return execute(CommandFormatter.undoMessageFormatter(message, getRedoCommandWord())); } // return the command that is equivalent to undoing add (DeleteCommand) @Override public Command getUndoCommand() { if (isSuccess) { return new DeleteCommand(toAdd, isDeleteAllOcurrence); } else { return null; } } @Override public String getUndoCommandWord() { return DeleteCommand.COMMAND_WORD + COMMAND_SUFFIX; } @Override public String getRedoCommandWord() { return COMMAND_WORD + COMMAND_SUFFIX; } }
9,966
0.584086
0.579972
251
38.705181
27.330366
120
false
false
0
0
0
0
0
0
0.85259
false
false
4
a2a609013f16968c293ce2031acce80b79d0614a
9,397,388,475,330
51b0113105c204b93973b2521a66e34dc2b1fc7a
/src/main/java/ps5/reports/pointandclick/data/beans/work/WorkBean.java
c8abb49a7ea9807d21195ce227d98c2ad445cd10
[]
no_license
uzair1990/SVN_BackUP_CLK
https://github.com/uzair1990/SVN_BackUP_CLK
8109f091fe94f860b9c672801e15880aff3a4eeb
7f4fed9bf309bbaea05926bdb5af374e0a126333
refs/heads/master
2017-11-30T11:25:05.537000
2016-11-11T17:17:50
2016-11-11T17:17:50
81,482,743
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package ps5.reports.pointandclick.data.beans.work; import java.text.DecimalFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Collections; import java.util.Date; import java.util.HashSet; import java.util.List; import java.util.Set; import ps5.bestpractices.BestPractice; import ps5.psapi.IdeaHelp; import ps5.psapi.WorkHelp; import ps5.psapi.date.PSDate; import ps5.psapi.date.PSDateAdjust; import ps5.psapi.programs.ProgramHelp; import ps5.psapi.project.DiscussionItemBean; import ps5.psapi.project.DiscussionItemHelp; import ps5.psapi.project.ReferencedWork; import ps5.psapi.project.statusreports.StatusReportFrequency; import ps5.reports.ReportSession; import ps5.reports.pointandclick.PointAndClickRuntimeException; import ps5.reports.pointandclick.ReportRunContext; import ps5.reports.pointandclick.data.beans.Bean; import ps5.reports.pointandclick.data.beans.DynamicProperties; import ps5.reports.pointandclick.data.beans.annotations.AddedByDefault; import ps5.reports.pointandclick.data.beans.annotations.ColorProperty; import ps5.reports.pointandclick.data.beans.annotations.Column; import ps5.reports.pointandclick.data.beans.annotations.ContextSwitch; import ps5.reports.pointandclick.data.beans.annotations.CurrencyConversionAttribute; import ps5.reports.pointandclick.data.beans.annotations.DeprecatedElement; import ps5.reports.pointandclick.data.beans.annotations.FilterByBeanProperty; import ps5.reports.pointandclick.data.beans.annotations.GanttObjectId; import ps5.reports.pointandclick.data.beans.annotations.LinkUrlProperty; import ps5.reports.pointandclick.data.beans.annotations.OptionalSortByBeanProperty; import ps5.reports.pointandclick.data.beans.annotations.ReferencedAsPropertyValue; import ps5.reports.pointandclick.data.beans.annotations.ReferencedBean; import ps5.reports.pointandclick.data.beans.annotations.ReferencedUsingReflection; import ps5.reports.pointandclick.data.beans.annotations.RelatedColumn; import ps5.reports.pointandclick.data.beans.annotations.RelatedColumn.Position; import ps5.reports.pointandclick.data.beans.annotations.RelatedEntity; import ps5.reports.pointandclick.data.beans.annotations.RequiredFeatures; import ps5.reports.pointandclick.data.beans.annotations.RequiredPermissions; import ps5.reports.pointandclick.data.beans.annotations.SelectedByDefault; import ps5.reports.pointandclick.data.beans.annotations.columnfilters.DBColumn; import ps5.reports.pointandclick.data.beans.annotations.columnfilters.DBColumns; import ps5.reports.pointandclick.data.beans.annotations.columnfilters.DBTable; import ps5.reports.pointandclick.data.beans.annotations.columnfilters.Filter; import ps5.reports.pointandclick.data.beans.annotations.columnfilters.NoFilter; import ps5.reports.pointandclick.data.beans.annotations.columnfilters.SQLRelationship; import ps5.reports.pointandclick.data.beans.base.PSObjectBean; import ps5.reports.pointandclick.data.beans.currency.CurrencyConversionAttributeData; import ps5.reports.pointandclick.data.beans.currency.WorkCostCurrencyConversionAttributeData; import ps5.reports.pointandclick.data.beans.entities.TimesheetBean; import ps5.reports.pointandclick.data.beans.entities.UserBean; import ps5.reports.pointandclick.data.beans.measures.MeasureByProjectDynamicProperties; import ps5.reports.pointandclick.data.beans.role.WorkRolesDynamicProperties; import ps5.reports.pointandclick.data.beans.statusreports.StatusReportBean; import ps5.reports.pointandclick.data.beans.tags.WorkTagDynamicProperties; import ps5.reports.pointandclick.data.definition.DBColumnDefinition; import ps5.reports.pointandclick.data.filters.CurrencyFilter; import ps5.reports.pointandclick.data.filters.bestpractices.BestPracticeStatusFilter; import ps5.reports.pointandclick.data.filters.entities.SingleUserFilter; import ps5.reports.pointandclick.data.filters.metrics.AttachedMetricTemplatesFilter; import ps5.reports.pointandclick.data.filters.rate.RateTableFilter; import ps5.reports.pointandclick.data.filters.resources.ResourceCalendarFilter; import ps5.reports.pointandclick.data.filters.statusreports.StatusReportFrequencyFilter; import ps5.reports.pointandclick.data.filters.time.UserDateRangeFilter; import ps5.reports.pointandclick.data.filters.timesheets.ActivityFilter; import ps5.reports.pointandclick.data.filters.work.IdeaApprovalStatusFilter; import ps5.reports.pointandclick.data.filters.work.MasterProjectsFilter; import ps5.reports.pointandclick.data.filters.work.ProjectFilter; import ps5.reports.pointandclick.data.filters.work.TopProjectsFilter; import ps5.reports.pointandclick.data.filters.work.WithScheduleConstraintTypeFilter; import ps5.reports.pointandclick.data.filters.work.WorkPrioritiesFilter; import ps5.reports.pointandclick.data.filters.work.WorkReferencesFilter; import ps5.reports.pointandclick.data.filters.work.WorkStatusFilter; import ps5.reports.pointandclick.data.filters.work.WorkTypesFilter; import ps5.reports.pointandclick.data.filters.work.WorkflowStatusFilter; import ps5.reports.pointandclick.data.filters.work.WorksFilter; import ps5.reports.pointandclick.data.filters.work.schedule.ScheduleTypeFilter; import ps5.reports.pointandclick.data.filters.work.tollgate.ProcessPhasesWithoutCompletedFilter; import ps5.workflow.WorkflowUtils; import com.cinteractive.database.PersistentKey; import com.cinteractive.jdbc.sql.CompositeCriteria; import com.cinteractive.jdbc.sql.Criteria; import com.cinteractive.jdbc.sql.SqlSelectQuery; import com.cinteractive.ps3.PSObject; import com.cinteractive.ps3.discussion.Discussion; import com.cinteractive.ps3.discussion.DiscussionItem; import com.cinteractive.ps3.discussion.Risk; import com.cinteractive.ps3.documents.VersionableDocument; import com.cinteractive.ps3.entities.User; import com.cinteractive.ps3.events.BaseObjectEvent; import com.cinteractive.ps3.events.ObjectEvent; import com.cinteractive.ps3.events.StatusChangeEvent; import com.cinteractive.ps3.events.WorkflowChangeEvent; import com.cinteractive.ps3.measures.MeasureHelper; import com.cinteractive.ps3.measures.MeasureInstance; import com.cinteractive.ps3.metrics.MetricInstance; import com.cinteractive.ps3.newsecurity.Verbs; import com.cinteractive.ps3.pstransactions.ActivityType; import com.cinteractive.ps3.pstransactions.PSTransaction; import com.cinteractive.ps3.reports.attributes.Accessors; import com.cinteractive.ps3.schedule.ScheduleType; import com.cinteractive.ps3.scheduler.calendar.DateCalculator; import com.cinteractive.ps3.scheduler.calendar.DateCalculatorImpl; import com.cinteractive.ps3.tagext.uix.Uix; import com.cinteractive.ps3.tollgate.Checkpoint; import com.cinteractive.ps3.work.Template; import com.cinteractive.ps3.work.UpdateFrequency; import com.cinteractive.ps3.work.Work; import com.cinteractive.ps3.work.WorkStatus; import com.cinteractive.scheduler.Duration; import com.cinteractive.util.CIFilter; import com.cinteractive.util.FilterChain; /** * * @author Damian Kober * @date 10/10/2008 */ /** * ColumnFilters SQL mappings * Map this bean to an equivalent table in DB */ @DBTable(name="Pac_Work", onColumns={"work_id"}) /** * Map of supported properties to equivalent SQL columns for filtering purposes */ @DBColumns(onColumns={ @DBColumn(property="name"), @DBColumn(property="creationDate",onColumns={"create_date"}), @DBColumn(property="lastUpdated", onColumns={"last_change_date"}), @DBColumn(property="createdBy", onColumns={"created_by"}), @DBColumn(property="powerSteeringId", onColumns={"work_id"}), @DBColumn(property="isProject", onColumns={"type"}), @DBColumn(property="type", onColumns={"type"}), @DBColumn(property="owner", onColumns={"owner_id"}), @DBColumn(property="status", onColumns={"status"}), @DBColumn(property="objective"), @DBColumn(property="actualStartDate", onColumns={"actual_start_date"}), @DBColumn(property="actualEndDate", onColumns={"actual_end_date"}), @DBColumn(property="plannedStartDate", onColumns={"planned_start_date"}), @DBColumn(property="plannedEndDate", onColumns={"planned_end_date"}), @DBColumn(property="systemStartDate", onColumns={"system_start_date"}), @DBColumn(property="systemEndDate", onColumns={"system_end_date"}), @DBColumn(property="baselineStartDate", onColumns={"baseline_start_date"}), @DBColumn(property="baselineEndDate", onColumns={"baseline_end_date"}), @DBColumn(property="tracksResources", onColumns={"is_track_resource"}), @DBColumn(property="projectId", onColumns={"peer_id"}), @DBColumn(property="priority", onColumns={"priority"}), @DBColumn(property="percentComplete", onColumns={"percent_complete"}), @DBColumn(property="ideaStatus",onColumns={"idea_status","is_idea"}), @DBColumn(property="ownerBean", onColumns={"owner_id"}), @DBColumn(property="creatorBean", onColumns={"created_by"}), @DBColumn(property="parentBean", onColumns={"parent_id"}), @DBColumn(property="parent", onColumns={"parent_id"}), @DBColumn(property="topProject", onColumns={"work_id"}), @DBColumn(property="masterProject", onColumns={"work_id"}), @DBColumn(property="mostRecentStatusReport", onColumns={"work_id",DBTable.SKIP_THIS_PARAMETER}), @DBColumn(property="workRoles", onColumns={"work_id"}), @DBColumn(property="topProjectBean", onColumns={"work_id"}), @DBColumn(property="masterProjectBean", onColumns={"work_id"}), @DBColumn(property="scheduleConstraintType", onColumns={"work_id"}), @DBColumn(property="scheduleType", onColumns={"work_id"}), @DBColumn(property="currency", onColumns={"currency_id"}), @DBColumn(property="isBestPractice",onColumns={"is_best_practice"}), @DBColumn(property="bestPracticeStatus",onColumns={"best_practice_status"}), @DBColumn(property="bestPracticeNominatedByBean",onColumns={"best_practice_nomination_user_id"}), @DBColumn(property="bestPracticeNominatedBy",onColumns={"best_practice_nomination_user_id"}), @DBColumn(property="bestPracticeNominatedOn",onColumns={"best_practice_nomination_time"}), @DBColumn(property="bestPracticeNominationComment",onColumns={"best_practice_nomination_comments"}), @DBColumn(property="bestPracticeApprovedByBean",onColumns={"best_practice_approval_user_id"}), @DBColumn(property="bestPracticeApprovedBy",onColumns={"best_practice_approval_user_id"}), @DBColumn(property="bestPracticeApprovedOn",onColumns={"best_practice_approval_time"}), @DBColumn(property="bestPracticeApprovalComment",onColumns={"best_practice_approval_comments"}), @DBColumn(property="bestPracticeRejectedByBean",onColumns={"best_practice_rejected_user_id"}), @DBColumn(property="bestPracticeRejectedBy",onColumns={"best_practice_rejected_user_id"}), @DBColumn(property="bestPracticeRejectedOn",onColumns={"best_practice_rejected_time"}), @DBColumn(property="bestPracticeRejectedComment",onColumns={"best_practice_rejected_comments"}), @DBColumn(property="bestPracticeDesignationRemovedByBean",onColumns={"best_practice_designation_removed_user_id"}), @DBColumn(property="bestPracticeDesignationRemovedBy",onColumns={"best_practice_designation_removed_user_id"}), @DBColumn(property="bestPracticeDesignationRemovedOn",onColumns={"best_practice_designation_removed_time"}), @DBColumn(property="bestPracticeDesignationRemovedComment",onColumns={"best_practice_designation_removed_comments"}), @DBColumn(property="customFields", onColumns={"work_id", "type"}), @DBColumn(property="isIdea", onColumns={"is_idea"}), @DBColumn(property="workflowStatus", onColumns={"workflow_status"}) }) public class WorkBean extends PSObjectBean { protected static final String SCHEDULE_SECTION = "schedule-section"; protected static final String HIERARCHY_SECTION = "hierarchy-section"; protected static final String ISSUES_SECTION = "issues-section"; protected static final String DISCUSSIONS_SECTION = "discussions-section"; protected static final String RISKS_SECTION = "risks-section"; protected static final String DOCUMENTS_SECTION = "documents-section"; protected static final String IDEAS_SECTION = "ideas-section"; protected static final String RESOURCE_PLANNING_SECTION = "resource-planning-section"; protected static final String BUDGET_SECTION = "budget-section"; protected static final String BEST_PRACTICE_SECTION = "best-practice-section"; protected static final String CONFIG_SECTION = "config-section"; private final Work _work; /** * * Constructor * * @param parameters * @param reportRunContext */ public WorkBean(List<Object> parameters, ReportRunContext reportRunContext) { super(parameters, reportRunContext); _work = (Work) getPSObject(); } @Column(width=Bean.LONG_NAME_WIDTH, order=0.01f,relatedColumns={@Column.RelatedColumn(value="typeIconPath"),@Column.RelatedColumn(value="statusIconPath"),@Column.RelatedColumn(value="completePath")}) @SelectedByDefault @OptionalSortByBeanProperty(Bean.SORTABLE_UID_PROPERTY) @LinkUrlProperty("url") @GanttObjectId("workId") @ReferencedBean(parameters="workId",clazz=WorkBean.class) public String getName() { return getPSObject().getName(getLocale()); } @RelatedColumn(type=RelatedColumn.RelatedColumnType.IndentProperty, position=Position.Left, width=1) public String getCompletePath(){ final List<Work> list = WorkHelp.getPath(_work); final StringBuilder builder = new StringBuilder(); for(int i = list.size() - 1; i >=0;i--) { Work item = list.get(i); if(builder.length()!=0)builder.append("_"); builder.append(item.getId()); } return builder.toString(); } @RelatedColumn(type=RelatedColumn.RelatedColumnType.IconColumn, position=Position.Left, width=20) public String getTypeIconPath(){ return getPSObject().getTypeIconPath(); } @RelatedColumn(type=RelatedColumn.RelatedColumnType.IconColumn, position=Position.Left, width=15) public String getStatusIconPath(){ return getWork().getStatusIconPath(); } public String getSortableUid() { String sequenceWithinParentStr; Integer sequenceWithinParent = _work.getSequenceWithinParent(); if(null!=sequenceWithinParent) { sequenceWithinParentStr = new DecimalFormat("00000").format(sequenceWithinParent); } else { sequenceWithinParentStr = "_"; //sort higher if has no sequence } String parentStr; GenericWorkBean parent = getParentBean(); if(null!=parent) { parentStr = parent.getSortableUid(); } else { parentStr = "_"; //sort higher if has no parent } return parentStr + SORTABLE_ID_SEPARATOR + sequenceWithinParentStr + SORTABLE_ID_SEPARATOR + getName() + SORTABLE_ID_SEPARATOR + getUid(); } public boolean mayView() { return super.mayView() && !Template.TYPE.equals(_work.getPSType()); } @ReferencedAsPropertyValue public String getWorkId(){ return getWork().getId().toString(); } @Column(width=Bean.TYPE_WIDTH, order=0.02f) @ColorProperty(property="statusColor", availableColorsMethod="statusAvailableColors") @OptionalSortByBeanProperty("statusSortableUid") @Filter(className=WorkStatusFilter.class) @FilterByBeanProperty("statusFilterProperty") public String getStatus() { if(!WorkHelp.hideStatus(_work)) { return _work.getWorkStatus().getStatus().getLocalizedName(getLocale(),getContext()); } else { return null; } } @ReferencedAsPropertyValue public String getStatusColor() { if(!WorkHelp.hideStatus(_work)) { return _work.getWorkStatus().getStatus().getExportableColorCode(); } else { return null; } } @ReferencedAsPropertyValue public static List<String> getStatusAvailableColors(ReportSession session){ if(null != session){ List<String> result = new ArrayList<String>(); for(WorkStatus ws : WorkStatus.values()){ if(ws.isWorkStatusActive(session.getContext())){ result.add(ws.getExportableColorCode()); } } return result; } return null; } @ReferencedAsPropertyValue public Integer getStatusSortableUid() { return _work.getWorkStatus().getStatus().getSequence(); } @ReferencedAsPropertyValue public String getStatusFilterProperty(){ if(!WorkHelp.hideStatus(_work)) { return _work.getWorkStatus().getStatus().getCode(); } else { return null; } } @Column(width=Bean.DATE_WIDTH, order=0.021f) public Date getStatusChangeDate() { return StatusChangeEvent.getStatusChangeDate(_work); } @Column(width=Bean.DATE_WIDTH, order=0.022f) public Date getCancelDate() { return toDayStart(PSDateAdjust.toContext12(_work.getCancelDate()),getContext().getTimeZone()); } @Column(width=Bean.DESCRIPTION_WIDTH, order=20.0134f) public String getObjective() {return _work.getObjectiveRTF(); } @Column(width=Bean.TYPE_WIDTH, order=0.11f) @Filter(className=WorkTypesFilter.class) @FilterByBeanProperty("typeCode") @DeprecatedElement public String getType() {return getType1(); } @Column(width=Bean.TYPE_WIDTH, order=20.01f,section=CONFIG_SECTION) @Filter(className=WorkTypesFilter.class) @FilterByBeanProperty("typeCode") public String getType1() {return getPSObject().getContextPSType().getLocalizedDetails(getLocale()).getName(); } @Column(section=SCHEDULE_SECTION, order=1.011f) @Filter(className=WithScheduleConstraintTypeFilter.class) @FilterByBeanProperty("scheduleConstraintTypeFilterProperty") public String getScheduleConstraintType() { return null!=_work.getSchedules() && null!=_work.getSchedules().getConstraintType() ? _work.getSchedules().getConstraintType().getName(getLocale()) : null; } @ReferencedAsPropertyValue public String getScheduleConstraintTypeFilterProperty(){ return null!=_work.getSchedules() && null!=_work.getSchedules().getConstraintType() ? _work.getSchedules().getConstraintType().getCode() : null; } @Column(section=SCHEDULE_SECTION, order=1.012f) @FilterByBeanProperty("scheduleTypeFilterProperty") @Filter(className=ScheduleTypeFilter.class) public String getScheduleType() { if(_work.isScheduled()) { if(WorkHelp.isSequentalGates(_work)) return ScheduleTypeFilter.getESGLabel(getLocale()); else if(_work.isManuallyScheduled()) return ScheduleTypeFilter.getManualLabel(getLocale()); else return ScheduleTypeFilter.getAutomaticLabel(getLocale()); } return ScheduleTypeFilter.getNotScheduledLabel(getLocale()); } @ReferencedAsPropertyValue public String getScheduleTypeFilterProperty(){ if(_work.isScheduled()) { if(WorkHelp.isSequentalGates(_work)) return ScheduleTypeFilter.getESGCode(); else if(_work.getSchedules().isManuallyScheduled()) return ScheduleTypeFilter.getManualCode(); else return ScheduleTypeFilter.getAutomaticCode(); } return ScheduleTypeFilter.getNotScheduledCode(); } /* Actual Dates */ @Column(section=SCHEDULE_SECTION,width=Bean.DATE_WIDTH, order=1.013f) public Date getActualStartDate() { return toDayStart( PSDateAdjust.toContext12(_work.getActualStartDate()),getContext().getTimeZone() ); } @Column(section=SCHEDULE_SECTION,width=Bean.DATE_WIDTH, order=1.02f) public Date getActualEndDate() { return toDayStart( PSDateAdjust.toContext12(_work.getActualEndDate()),getContext().getTimeZone() ); } @Column(section=SCHEDULE_SECTION, order=1.03f) public Integer getActualCycleTimeInDays() { return getCycleTimeInDays(ScheduleType.ACTUAL); } @Column(section=SCHEDULE_SECTION, order=1.031f) public Integer getActualDurationInDays() { return getDurationInDays(ScheduleType.ACTUAL); } /* Planned Dates */ @Column(section=SCHEDULE_SECTION,width=Bean.DATE_WIDTH, order=1.04f) public Date getPlannedStartDate() { return toDayStart( PSDateAdjust.toContext12(_work.getPlannedStartDate()),getContext().getTimeZone() ); } @Column(section=SCHEDULE_SECTION,width=Bean.DATE_WIDTH, order=1.05f) public Date getPlannedEndDate() { return toDayStart( PSDateAdjust.toContext12(_work.getPlannedEndDate()),getContext().getTimeZone() ); } @Column(section=SCHEDULE_SECTION, order=1.06f) public Integer getPlannedCycleTimeInDays() { return getCycleTimeInDays(ScheduleType.CONSTRAINT); } @Column(section=SCHEDULE_SECTION, order=1.061f) public Integer getPlannedDurationInDays() { return getDurationInDays(ScheduleType.CONSTRAINT); } /*System dates */ @Column(section=SCHEDULE_SECTION,width=Bean.DATE_WIDTH, order=1.07f) public Date getSystemStartDate() { return toDayStart( PSDateAdjust.toContext12(_work.getSystemStartDate()),getContext().getTimeZone() ); } @Column(section=SCHEDULE_SECTION,width=Bean.DATE_WIDTH, order=1.08f) public Date getSystemEndDate() { return toDayStart( PSDateAdjust.toContext12(_work.getSystemEndDate()),getContext().getTimeZone() ); } @Column(section=SCHEDULE_SECTION, order=1.09f) public Integer getEstimatedCycleTimeInDays() { return getCycleTimeInDays(ScheduleType.SYSTEM); } @Column(section=SCHEDULE_SECTION, order=1.091f) public Integer getEstimatedDurationInDays() { return getDurationInDays(ScheduleType.SYSTEM); } /* Baseline dates */ @Column(section=SCHEDULE_SECTION,width=Bean.DATE_WIDTH, order=1.10f) public Date getBaselineStartDate() { return toDayStart( PSDateAdjust.toContext12(_work.getBaselineStartDate()),getContext().getTimeZone() ); } @Column(section=SCHEDULE_SECTION,width=Bean.DATE_WIDTH, order=1.11f) public Date getBaselineEndDate() { return toDayStart( PSDateAdjust.toContext12(_work.getBaselineEndDate()),getContext().getTimeZone() ); } @Column(section=SCHEDULE_SECTION, order=1.12f) public Integer getBaselineCycleTimeInDays() { return getCycleTimeInDays(ScheduleType.BASELINE); } @Column(section=SCHEDULE_SECTION, order=1.121f) public Integer getBaselineDurationInDays() { return getDurationInDays(ScheduleType.BASELINE); } /* Off track by columns*/ @Column(section=SCHEDULE_SECTION, order = 1.13f) public Integer getOffTrackByInDays() { Duration duration = (Duration) Accessors.getWorkOffTrackBy(getSession().getPSSession()).access(_work); Float amount = null!=duration ? Float.valueOf(duration.getAmount()) : null; return null!=amount && !amount.isNaN() ? Integer.valueOf(amount.intValue()) : null; } protected Integer getOffTrackByInDays(PSDate pEnd, PSDate aEnd) { if (pEnd == null) return null; if (aEnd != null && aEnd.before(pEnd)) return Integer.valueOf(0); if (aEnd == null) aEnd = _work.getContext().getDateService().createToday(); if (aEnd.before(pEnd)) return null; final DateCalculator calc = new DateCalculatorImpl(_work.getCalendar(), _work.getContext().getTimeZone(), _work.getContext().getDateService()); Duration duration = calc.laborDurationInDays(pEnd, aEnd); Float amount = null!=duration ? Float.valueOf(duration.getAmount()) : null; return null!=amount && !amount.isNaN() ? Integer.valueOf(amount.intValue()) : null; } @Column(section=RESOURCE_PLANNING_SECTION,width=Bean.NUMBER_WIDTH,order=9.01f) public Float getUnassignedHours() { return _work.getUnassignedLoad(true); } @Column(section=RESOURCE_PLANNING_SECTION,width=Bean.NUMBER_WIDTH,order=9.02f) public Float getUnassignedPercent() { return _work.getUnassignedLoad(false); } @Column(section=RESOURCE_PLANNING_SECTION,width=Bean.NUMBER_WIDTH,order=9.03f) @RequiredFeatures(Uix.FEATURE_RESOURCE_PLANNING) public Boolean getTracksResources() { return Boolean.valueOf(_work.isUseResourcePlanning()); } @Column(width=Bean.DEFAULT_WIDTH, order=0.21f) public String getSequenceNumber() { return _work.getSequence(); } @Column(width=Bean.SHORT_NAME_WIDTH, order=0.22f) @RequiredFeatures("idnumber") public String getProjectId() { if(WorkHelp.isShowProjectId(_work.getContext(),_work,getSession().getCurrentUser())) { return _work.getPeerId(); } else { return null; } } @Column(width=Bean.DESCRIPTION_WIDTH, order=0.15f) public String getFullPath() { List<Work> list = WorkHelp.getPath(_work); StringBuilder builder = new StringBuilder(); String separator = ""; for(int i = list.size() - 1; i >=0;i--) { Work item = list.get(i); builder.append(separator + (mayView(item) ? item.getName() : getNotEnoughPermissionsText())); separator = WorkHelp.WORK_PATH_SEPARATOR; } return builder.toString(); } @Column(width=Bean.NUMBER_WIDTH, order=0.04f) @Filter(className=WorkPrioritiesFilter.class) public Integer getPriority() { return _work.getAssignedPriority(); } @Column(width=Bean.BOOLEAN_WIDTH, order=0.12f) @Filter(className=ProjectFilter.class) @DeprecatedElement public Boolean getIsProject() { return getIsProject1(); } @Column(width=Bean.BOOLEAN_WIDTH, order=20.02f, section=CONFIG_SECTION) @Filter(className=ProjectFilter.class) public Boolean getIsProject1() { return WorkHelp.isProject(_work); } @Column(width=Bean.BOOLEAN_WIDTH, order=20.03f, section=CONFIG_SECTION) public Boolean getIsIdea() { return WorkHelp.isIdea(_work); } @Column(width=Bean.BOOLEAN_WIDTH, order=20.04f, section=CONFIG_SECTION) public Boolean getIsOrganization() { return WorkHelp.isOrganization(_work); } @Column(width=Bean.BOOLEAN_WIDTH, order=20.05f, section=CONFIG_SECTION) public Boolean getInheritPermissions() { return _work.getInheritPermissions(); } @Column(width=Bean.BOOLEAN_WIDTH, order=20.06f, section=CONFIG_SECTION) public Boolean getInheritCalendar() { return _work.getInheritCalendar(); } @Column(width=Bean.SHORT_NAME_WIDTH, order=20.07f, section=CONFIG_SECTION) @FilterByBeanProperty(value="calendarFilterProperty") @Filter(className=ResourceCalendarFilter.class) public String getCalendar(){ return null != _work.getCalendar() ? _work.getCalendar().getName() : null; } @ReferencedAsPropertyValue public String getCalendarFilterProperty(){ return null != _work.getCalendarId() ? _work.getCalendarId().toString() : null; } @Column(width=Bean.BOOLEAN_WIDTH, order=20.08f, section=CONFIG_SECTION) public Boolean getIsStatusReporting() { return null != _work.getUpdateFrequency() ? !UpdateFrequency.NEVER.equals(_work.getUpdateFrequency()):false; } @Column(width=Bean.SHORT_NAME_WIDTH, order=20.09f, section=CONFIG_SECTION) @FilterByBeanProperty(value="updateFrequencyFilterProperty") @Filter(className=StatusReportFrequencyFilter.class) //postfilter only public String getStatusReportUpdateFrequency(){ return null != _work.getUpdateFrequency() ? _work.getUpdateFrequency().getFreqTerm(getLocale()) : null; } @ReferencedAsPropertyValue public String getUpdateFrequencyFilterProperty(){ return null != _work.getUpdateFrequency() ? StatusReportFrequency.translateUpdateFreq(_work.getUpdateFrequency().getCode()).toString() : null; } @Column(width=Bean.BOOLEAN_WIDTH, order=20.10f, section=CONFIG_SECTION) public Boolean getIsManualScheduleChildren() { return _work.isManualScheduleChildren(); } @Column(width=Bean.BOOLEAN_WIDTH, order=20.12f, section=CONFIG_SECTION) public Boolean getInheritControls() { return _work.getInheritControls();} @Column(width=Bean.BOOLEAN_WIDTH, order=20.13f, section=CONFIG_SECTION) public Boolean getControlCosts() { return _work.getControlCost();} @Column(width=Bean.SYMBOL_WIDTH, order=20.134f) @Filter(className=CurrencyFilter.class) @DeprecatedElement public String getCurrency() { return getCurrency1(); } @Column(width=Bean.SYMBOL_WIDTH, order=20.135f,section=CONFIG_SECTION) @Filter(className=CurrencyFilter.class) public String getCurrency1() { if(null!=_work.getCurrency()) { return _work.getCurrency().getCode(); } else { return null; } } @Column(width=Bean.BOOLEAN_WIDTH, order=20.14f, section=CONFIG_SECTION) public Boolean getInheritPersonalRateRule() { return _work.getInheritPersonalRateRule();} @Column(width=Bean.SHORT_NAME_WIDTH, order=20.155f, section=CONFIG_SECTION) @FilterByBeanProperty(value="rateTableFilterProperty") @Filter(className=RateTableFilter.class) //postfilter only public String getRateTable() { return null != _work.getRateTable() ? _work.getRateTable().getName(getLocale()) : null;} @ReferencedAsPropertyValue public String getRateTableFilterProperty() { return null !=_work.getRateTable() ? _work.getRateTable().getId().toString() : null;} @Column(width=Bean.BOOLEAN_WIDTH, order=20.15f, section=CONFIG_SECTION) public Boolean getUsePersonalRates() { return _work.getUsePersonalRates();} @Column(width=Bean.BOOLEAN_WIDTH, order=20.16f, section=CONFIG_SECTION) public Boolean getUseResourcePlanning() { return _work.isUseResourcePlanning();} @Column(width=Bean.BOOLEAN_WIDTH, order=20.17f, section=CONFIG_SECTION) public Boolean getIncludeTasksToResourcePlan() { return _work.getIncludeTasksToResourcePlan();} @Column(width=Bean.BOOLEAN_WIDTH, order=20.17f, section=CONFIG_SECTION) public Boolean getAllowTimeEntry() { return _work.getAllowTimeEntry();} @Column(width=Bean.SHORT_NAME_WIDTH, order=20.19f, section=CONFIG_SECTION) @FilterByBeanProperty(value="metricTemplatesAttachedFilterProperty") @Filter(className=AttachedMetricTemplatesFilter.class) //postfilter only public String getMetricTemplatesAttached() { final StringBuilder sb = new StringBuilder(); for (PersistentKey id : _work.getMetricIds()) { final MetricInstance metric = (MetricInstance) MetricInstance.get(id, _work.getContext()); if (!metric.isDeleted()) { sb.append(formatListItem(metric.getName(getLocale()), sb.length() ==0)); } } return sb.length() > 0 ?sb.toString() : null; } @ReferencedAsPropertyValue public List<String> getMetricTemplatesAttachedFilterProperty() { final List<String> result = new ArrayList<String>(); for (PersistentKey id : _work.getMetricIds()) { final MetricInstance metric = (MetricInstance) MetricInstance.get(id, _work.getContext()); if (!metric.isDeleted()) { result.add(metric.getTemplateId().toString()); } } return result; } @Column(width=Bean.SHORT_NAME_WIDTH, order=20.20f, section=CONFIG_SECTION) @NoFilter //because there are not defined templates, measures can be defined on the fly... public String getMeasuresAttached() { final List<MeasureInstance> measures = MeasureHelper.getAttachedMeasures(_work, getSession().getPSSession(), Verbs.VIEW); final StringBuilder sb = new StringBuilder(); for(MeasureInstance mi : measures){ sb.append(formatListItem(mi.getName(getLocale()), sb.length() == 0)); } return sb.length() > 0 ? sb.toString() : null; } @Column(width=Bean.BOOLEAN_WIDTH, order=20.21f, section=CONFIG_SECTION) public Boolean getInheritActivityTypesFromParent() { return _work.getInheritActivities(); } @Column(width=Bean.SHORT_NAME_WIDTH, order=20.22f, section=CONFIG_SECTION) @FilterByBeanProperty(value="activityTypesFilterProperty") @Filter(className=ActivityFilter.class) public String getActivityTypes() { final Set<ActivityType> activityTypes = _work.getActivityTypes(); final StringBuilder sb = new StringBuilder(); for (ActivityType activityType : activityTypes) { sb.append(formatListItem(activityType.getName(getLocale()), sb.length() ==0)); } return sb.length() > 0 ?sb.toString() : null; } @ReferencedAsPropertyValue public List<String> getActivityTypesFilterProperty() { final Set<ActivityType> activityTypes = _work.getActivityTypes(); final List<String> result = new ArrayList<String>(); for (ActivityType activityType : activityTypes) { result.add(activityType.getId().toString()); } return result; } @Column(width=Bean.BOOLEAN_WIDTH, order=20.23f, section=CONFIG_SECTION) public Boolean getInheritDefaultActivity() { return _work.getInheritDefaultActivity(); } @Column(width=Bean.SHORT_NAME_WIDTH, order=20.24f, section=CONFIG_SECTION) @FilterByBeanProperty(value="defaultActivityFilterProperty") @Filter(className=ActivityFilter.class) public String getDefaultActivity() { return null!=_work.getDefaultActivity() ? _work.getDefaultActivity().getName(getLocale()) : null; } @ReferencedAsPropertyValue public String getDefaultActivityFilterProperty() { return null!=_work.getDefaultActivity() ? _work.getDefaultActivity().getId().toString() : null; } /** * * @return Number of descendant projects (including independent work) */ @Column(section=HIERARCHY_SECTION,width=Bean.DEFAULT_WIDTH,order=2.011f) public Integer getNumberOfDescendantProjectsIncludingIndependentWork() { return ((List)getPropertyValueForInternalUse("descendantProjectsIncludingIndependentWork")).size(); } @ReferencedAsPropertyValue public ReferencedWork getReferencedWork() { return new ReferencedWork(_work,getSession().getPSSession()); } @Column(section=HIERARCHY_SECTION,width=Bean.DESCRIPTION_WIDTH,order=2.02f) @Filter(className=WorkReferencesFilter.class) @FilterByBeanProperty(value="referenceToFilterProperty") public String getReferenceToList() { StringBuilder builder = new StringBuilder(); for(PSObject psObject : ((ReferencedWork)getPropertyValueForInternalUse("referencedWork")).getRefTo()) { builder.append(formatListItem((mayView(psObject) ? psObject.getName() : getNotEnoughPermissionsText()),builder.length()==0)); } return builder.toString(); } @ReferencedAsPropertyValue public List<String> getReferenceToFilterProperty() { List<String> result = new ArrayList<String>(); for(PSObject psObject : getReferencedWork().getRefTo()) { if(mayView(psObject)){ result.add(psObject.getId().toString()); } } return result; } @Column(section=HIERARCHY_SECTION,width=Bean.DESCRIPTION_WIDTH,order=2.03f) @Filter(className=WorkReferencesFilter.class) @FilterByBeanProperty(value="referenceFromFilterProperty") public String getReferenceFromList() { StringBuilder builder = new StringBuilder(); for(PSObject psObject : ((ReferencedWork)getPropertyValueForInternalUse("referencedWork")).getRefBy()) { builder.append(formatListItem((mayView(psObject) ? psObject.getName() : getNotEnoughPermissionsText()),builder.length()==0)); } return builder.toString(); } @ReferencedAsPropertyValue public List<String> getReferenceFromFilterProperty() { List<String> result = new ArrayList<String>(); for(PSObject psObject : getReferencedWork().getRefBy()) { if(mayView(psObject)){ result.add(psObject.getId().toString()); } } return result; } /** * * @return descendant projects (including independent work) */ @ReferencedAsPropertyValue public List<Work> getDescendantProjectsIncludingIndependentWork() { return _work.getChildrenFromFilteredHierarchyBranches(null); } /** * * @return descendant projects (dependent work) */ protected List<Work> getDependentProjects() { // TODO use cache? return _work.getChildrenFromFilteredHierarchyBranches( new FilterChain() { protected boolean filterImpl(Object o) { return !WorkHelp.isProject((PSObject)o); } } ); } /** * * @return */ protected List<WorkBean> getDependentProjectBeans() { List<WorkBean> list = new ArrayList<WorkBean>(); for(Work work: getDependentProjects()) { list.add((WorkBean) get(WorkBean.class,work.getId())); } return list; } /** * * @return Number of descendant projects (dependent work) */ @Column(section=HIERARCHY_SECTION,width=Bean.DEFAULT_WIDTH,order=2.04f) public Integer getNumberOfDependentProjects() { return getDependentProjects().size(); } @RelatedEntity @SQLRelationship(type=ps5.reports.pointandclick.data.SQLRelationship.OneToOneRelationship.class) public GenericWorkBean getParentBean() { return _work.hasParent() ? (GenericWorkBean) get(GenericWorkBean.class,((Work)_work.getParent()).getId()) : null; } @Column(width=Bean.LONG_NAME_WIDTH, order=17) @OptionalSortByBeanProperty("parentSortableUid") @LinkUrlProperty("parentUrl") @Filter(className=WorksFilter.class) @FilterByBeanProperty("parentFilterProperty") public String getParent() { WorkBean topProject = getParentBean(); return null!=topProject ? topProject.getName() : null; } @ReferencedAsPropertyValue public String getParentSortableUid() { WorkBean parent = getParentBean(); return null!=parent ? parent.getSortableUid() : null; } @ReferencedAsPropertyValue public String getParentUrl() { WorkBean parent = getParentBean(); return null!=parent ? parent.getUrl() : null; } @ReferencedAsPropertyValue public String getParentFilterProperty(){ WorkBean parent = getParentBean(); return null!=parent ? parent.getWork().getId().toString(): null; } @Column(width=Bean.LONG_NAME_WIDTH,order=17.5f) @Filter(className=WorksFilter.class) @FilterByBeanProperty(value="programFilterProperty") @LinkUrlProperty("programListUrl") @ContextSwitch("isProgramEnabled") public String getProgramList() { StringBuilder builder = new StringBuilder(); for(Work work : getPrograms()) { builder.append(formatListItem((mayView(work) ? work.getName(getLocale()) : getNotEnoughPermissionsText()),builder.length()==0)); } return builder.toString(); } @ReferencedAsPropertyValue public String getProgramListUrl() { List<Work> programs = getPrograms(); return programs.isEmpty() ? null : programs.size() == 1 ? programs.get(0).getEntryUrl() : getUrl(); } @ReferencedAsPropertyValue public List<String> getProgramFilterProperty() { List<String> result = new ArrayList<String>(); for (Work work : getPrograms()) { if (mayView(work)) { result.add(work.getId().toString()); } } return result; } /** * internal * * @return the list of programs for this work item */ private List<Work> getPrograms() { return ProgramHelp.getParents(getWork()).toList(getSession().getPSSession()); } @Column(width=Bean.LONG_NAME_WIDTH, order=18) @OptionalSortByBeanProperty("phaseSortableUid") @LinkUrlProperty("phaseUrl") @Filter(className=ProcessPhasesWithoutCompletedFilter.class) @FilterByBeanProperty("phaseFilterProperty") public String getPhase() { GateGeneralColumnsBean gate = getGateBean(); return null!=gate ? gate.getName() : null; } @ReferencedAsPropertyValue public String getPhaseSortableUid() { GateGeneralColumnsBean gate = getGateBean(); return null!=gate ? gate.getSortableUid() : null; } @ReferencedAsPropertyValue public String getPhaseUrl() { GateGeneralColumnsBean gate = getGateBean(); return null!=gate ? gate.getUrl() : null; } @ReferencedAsPropertyValue public String getPhaseFilterProperty() { GateGeneralColumnsBean gate = getGateBean(); return null!=gate && null != gate.getGate() ? gate.getGate().getWork().getPhaseTag().getId().toString() : null; } /** * @return First work above the project for which is_project = yes */ @RelatedEntity //need special sql relationship @SQLRelationship(type=MasterProjectSQLRelationship.class) public GenericWorkBean getMasterProjectBean() { Work masterProject = WorkHelp.getMasterProject(_work); return null!=masterProject ? (GenericWorkBean) get(GenericWorkBean.class,masterProject.getId()) : null; } /** * * @return the higher project in the hierarchy */ @RelatedEntity //need special sql relationship @SQLRelationship(type=TopProjectSQLRelationship.class) public GenericWorkBean getTopProjectBean() { Work topProject = WorkHelp.getTopProject(_work); return null!=topProject && WorkHelp.isProject(topProject) ? (GenericWorkBean) get(GenericWorkBean.class,topProject.getId()) : null; } @Column(width=Bean.ENTITY_NAME_WIDTH, order=6) @OptionalSortByBeanProperty("ownerSortableUid") @LinkUrlProperty("ownerUrl") @Filter(className=SingleUserFilter.class) @FilterByBeanProperty("ownerFilterProperty") public String getOwner() { UserBean owner = getOwnerBean(); return null!=owner ? owner.getName() : null; } @ReferencedAsPropertyValue public String getOwnerUrl() { UserBean owner = getOwnerBean(); return null!=owner ? owner.getUrl() : null; } @ReferencedAsPropertyValue public String getOwnerSortableUid() { UserBean owner = getOwnerBean(); return null!=owner ? owner.getSortableUid() : null; } @ReferencedAsPropertyValue public String getOwnerFilterProperty(){ UserBean owner = getOwnerBean(); return null!=owner ? owner.getUser().getId().toString() : null; } /** * @see getTopProjectBean() */ @Column(width=Bean.LONG_NAME_WIDTH, order=19) @OptionalSortByBeanProperty("topProjectSortableUid") @LinkUrlProperty("topProjectUrl") @Filter(className=TopProjectsFilter.class) @FilterByBeanProperty("topProjectFilterProperty") public String getTopProject() { WorkBean topProject = getTopProjectBean(); if(null!=topProject) { if(!topProject.mayView()) { return getNotEnoughPermissionsText(); } else { return topProject.getName(); } } else { return null; } } @ReferencedAsPropertyValue public String getTopProjectSortableUid() { WorkBean topProject = getTopProjectBean(); if(null!=topProject) { if(!topProject.mayView()) { return null; } else { return topProject.getSortableUid(); } } else { return null; } } @ReferencedAsPropertyValue public String getTopProjectUrl() { WorkBean topProject = getTopProjectBean(); if(null!=topProject) { if(!topProject.mayView()) { return null; } else { return topProject.getUrl(); } } else { return null; } } @ReferencedAsPropertyValue public String getTopProjectFilterProperty() { WorkBean topProject = getTopProjectBean(); if(null!=topProject) { if(!topProject.mayView()) { return null; } else { return topProject.getWork().getId().toString(); } } else { return null; } } /** * @see getMasterProjectBean() */ @Column(width=Bean.LONG_NAME_WIDTH, order=18) @OptionalSortByBeanProperty("masterProjectSortableUid") @LinkUrlProperty("masterProjectUrl") @Filter(className=MasterProjectsFilter.class) @FilterByBeanProperty("masterProjectFilterProperty") public String getMasterProject() { WorkBean masterProject = getMasterProjectBean(); if(null!=masterProject) { if(!masterProject.mayView()) { return getNotEnoughPermissionsText(); } else { return masterProject.getName(); } } else { return null; } } @ReferencedAsPropertyValue public String getMasterProjectSortableUid() { WorkBean masterProject = getMasterProjectBean(); if(null!=masterProject) { if(!masterProject.mayView()) { return null; } else { return masterProject.getSortableUid(); } } else { return null; } } @ReferencedAsPropertyValue public String getMasterProjectUrl() { WorkBean masterProject = getMasterProjectBean(); if(null!=masterProject) { if(!masterProject.mayView()) { return null; } else { return masterProject.getUrl(); } } else { return null; } } @ReferencedAsPropertyValue public String getMasterProjectFilterProperty(){ WorkBean masterProject = getMasterProjectBean(); if(null!=masterProject) { if(!masterProject.mayView()) { return null; } else { return masterProject.getWork().getId().toString(); } } else { return null; } } @RelatedEntity @SQLRelationship(type=ps5.reports.pointandclick.data.SQLRelationship.OneToOneRelationship.class) public UserBean getOwnerBean() { return null!=_work.getOwnerId() ? (UserBean) get(UserBean.class,_work.getOwnerId()) : null; } /** * try to call this as property value for performance * @return */ @ReferencedAsPropertyValue public List<DiscussionItemBean> getDiscussionItems() { final CIFilter filter = DiscussionItem.createRootFilter(); return DiscussionItemHelp.getDiscussionItems(getSession().getCurrentUser(),_work,filter,null,false,true); } /** * try to call this as a property value for better performance * * for cache reasons, must declare with another name for getting discussionitems list with descendentworks * (using a parameter will detect that cached version is the same!) * @return */ @ReferencedAsPropertyValue public List<DiscussionItemBean> getDiscussionItemsIncludeDescendants() { final CIFilter filter = DiscussionItem.createRootFilter(); return DiscussionItemHelp.getDiscussionItems(getSession().getCurrentUser(),_work,filter,null,true,true); } /** * try to call this as a property value for better performance * * @return */ @ReferencedAsPropertyValue public List<Risk> getRisks() { Set roots = Collections.singleton(_work); List<Risk> results = Risk.findBySearch("%",null, roots, Risk.TYPE.getCode(), Risk.createTitleComparator(true)); return null!=results ? results : new ArrayList<Risk>(); } /** * try to call this as a property value for better performance * * for cache reasons, must declare with another name for getting risks list with descendant works * (using a parameter will detect that cached version is the same!) * @return */ @ReferencedAsPropertyValue public List<Risk> getRisksIncludeDescendants() { Set<Discussion> roots = getAllLevels(_work); List<Risk> results = null; if(!roots.isEmpty()) { results = Risk.findBySearch("%",null, roots, Risk.TYPE.getCode(), Risk.createTitleComparator(true)); } return null!=results ? results : new ArrayList<Risk>(); } /** * * @param work * @return */ protected Set<Discussion> getAllLevels(Work work) { Set<Discussion> roots = new HashSet<Discussion>(); if (!WorkHelp.isCheckpoint(work)) roots.add(work); List<Work> children = work.getFilteredChildren(Work.createVisibilityFilter(getSession().getPSSession())); for(Work child: children) roots.addAll(getAllLevels(child)); return roots; } /** * * @return */ protected List<DiscussionItemBean> getIssues() { List<DiscussionItemBean> issues = new ArrayList<DiscussionItemBean>(); for(DiscussionItemBean issue: ((List<DiscussionItemBean>)getPropertyValueForInternalUse("discussionItems"))) { if(DiscussionItemHelp.getIsIssue(issue.getItem())) { issues.add(issue); } } return issues; } /** * for cache reasons, must declare with another name for getting issues list with descendentworks * (using a parameter will detect that cached version is the same!) * @return */ protected List<DiscussionItemBean> getIssuesIncludeDescendants() { List<DiscussionItemBean> issues = new ArrayList<DiscussionItemBean>(); for(DiscussionItemBean issue: ((List<DiscussionItemBean>) getPropertyValueForInternalUse("discussionItemsIncludeDescendants"))) { if(DiscussionItemHelp.getIsIssue(issue.getItem())) { issues.add(issue); } } return issues; } /** * * @return */ protected List<DiscussionItemBean> getOpenIssues() { List<DiscussionItemBean> open = new ArrayList<DiscussionItemBean>(); for(DiscussionItemBean issue: getIssues()) { if(issue.getItem().isOpen()) { open.add(issue); } } return open; } /** * for cache reasons, must declare with another name for getting open issues list with descendant works * (using a parameter will detect that cached version is the same!) * @return */ protected List<DiscussionItemBean> getOpenIssuesIncludeDescendants() { List<DiscussionItemBean> open = new ArrayList<DiscussionItemBean>(); for(DiscussionItemBean issue: getIssuesIncludeDescendants()) { if(issue.getItem().isOpen()) { open.add(issue); } } return open; } /** * * @return */ protected List<DiscussionItemBean> getClosedIssues() { List<DiscussionItemBean> open = new ArrayList<DiscussionItemBean>(); for(DiscussionItemBean issue: getIssues()) { if(issue.isClosed()) { open.add(issue); } } return open; } /** * for cache reasons, must declare with another name for getting closed Issues list with descendant works * (using a parameter will detect that cached version is the same!) * @return */ protected List<DiscussionItemBean> getClosedIssuesIncludeDescendants() { List<DiscussionItemBean> open = new ArrayList<DiscussionItemBean>(); for(DiscussionItemBean issue: getIssuesIncludeDescendants()) { if(issue.isClosed()) { open.add(issue); } } return open; } /** * * @return */ protected List<Risk> getOpenRisks() { List<Risk> open = new ArrayList<Risk>(); for(Risk risk: (List<Risk>)getPropertyValueForInternalUse("risks")) { if(risk.isOpen()) { open.add(risk); } } return open; } /** * * @return */ protected List<Risk> getClosedRisks() { List<Risk> open = new ArrayList<Risk>(); for(Risk risk: (List<Risk>)getPropertyValueForInternalUse("risks")) { if(risk.isClosed()) { open.add(risk); } } return open; } /** * for cache reasons, must declare with another name for getting open risks list with descendant works * (using a parameter will detect that cached version is the same!) * @return */ protected List<Risk> getOpenRisksIncludeDescendants() { List<Risk> open = new ArrayList<Risk>(); for(Risk risk: (List<Risk>) getPropertyValueForInternalUse("risksIncludeDescendants")) { if(risk.isOpen()) { open.add(risk); } } return open; } /** * for cache reasons, must declare with another name for getting closed risks list with descendant works * (using a parameter will detect that cached version is the same!) * @return */ protected List<Risk> getClosedRisksIncludeDescendents() { List<Risk> open = new ArrayList<Risk>(); for(Risk risk: (List<Risk>) getPropertyValueForInternalUse("risksIncludeDescendants")) { if(risk.isClosed()) { open.add(risk); } } return open; } @Column(section=DISCUSSIONS_SECTION,width=Bean.NUMBER_WIDTH,order=4.01f) public Integer getDiscussionCount() { return ((List)getPropertyValueForInternalUse("discussionItems")).size(); } /** * @return Discussions on this project and all dependent work */ @Column(section=DISCUSSIONS_SECTION,width=Bean.DEFAULT_WIDTH,order=4.02f) public Integer getDependentProjectDiscussionCount() { return ((List<DiscussionItemBean>) getPropertyValueForInternalUse("discussionItemsIncludeDescendants")).size() - getDiscussionCount(); } @Column(section=ISSUES_SECTION,width=Bean.NUMBER_WIDTH,order=3.01f) @RequiredFeatures(Uix.FEATURE_ISSUES) public Integer getIssueCount() { return getIssues().size(); } /** * @return Issues on this project and all dependent work */ @Column(section=ISSUES_SECTION,width=Bean.DEFAULT_WIDTH,order=3.02f) @RequiredFeatures(Uix.FEATURE_ISSUES) public Integer getDependentProjectIssueCount() { return getIssuesIncludeDescendants().size() - getIssueCount(); } @Column(section=ISSUES_SECTION,width=Bean.NUMBER_WIDTH,order=3.03f) @RequiredFeatures(Uix.FEATURE_ISSUES) public Integer getOpenIssueCount() { return getOpenIssues().size(); } /** * @return Open issues on this project and all dependent work */ @Column(section=ISSUES_SECTION,width=Bean.DEFAULT_WIDTH,order=3.04f) @RequiredFeatures(Uix.FEATURE_ISSUES) public Integer getDependentProjectOpenIssueCount() { return getOpenIssuesIncludeDescendants().size() - getOpenIssueCount(); } @Column(section=ISSUES_SECTION,width=Bean.NUMBER_WIDTH,order=3.05f) @RequiredFeatures(Uix.FEATURE_ISSUES) public Integer getClosedIssueCount() { return getClosedIssues().size(); } /** * @return Closed issues on this project and all dependent work */ @Column(section=ISSUES_SECTION,width=Bean.DEFAULT_WIDTH,order=3.06f) @RequiredFeatures(Uix.FEATURE_ISSUES) public Integer getDependentProjectClosedIssueCount() { return getClosedIssuesIncludeDescendants().size() - getClosedIssueCount(); } @Column(section=RISKS_SECTION,width=Bean.NUMBER_WIDTH,order=5.01f) @RequiredFeatures(Uix.FEATURE_RISKS) public Integer getClosedRiskCount() { return getClosedRisks().size(); } /** * @return Closed risks on this project and all dependent work */ @Column(section=RISKS_SECTION,width=Bean.DEFAULT_WIDTH,order=5.02f) @RequiredFeatures(Uix.FEATURE_RISKS) public Integer getDependentProjectClosedRiskCount() { return getClosedRisksIncludeDescendents().size() - getClosedRiskCount(); } @Column(section=RISKS_SECTION,width=Bean.NUMBER_WIDTH,order=5.03f) @RequiredFeatures(Uix.FEATURE_RISKS) public Integer getOpenRiskCount() { return getOpenRisks().size(); } /** * @return Open risks on this project and all dependent work */ @Column(section=RISKS_SECTION,width=Bean.DEFAULT_WIDTH,order=5.04f) @RequiredFeatures(Uix.FEATURE_RISKS) public Integer getDependentProjectOpenRiskCount() { return getOpenRisksIncludeDescendants().size() - getOpenRiskCount(); } @Column(section=RISKS_SECTION,order=5.05f) @RequiredFeatures(Uix.FEATURE_RISKS) public Integer getRiskCount() { return ((List)getPropertyValueForInternalUse("risks")).size(); } /** * @return risks on this project and all dependent work */ @Column(section=RISKS_SECTION,width=Bean.DEFAULT_WIDTH,order=5.06f) @RequiredFeatures(Uix.FEATURE_RISKS) public Integer getDependentProjectRiskCount() { return ((List<Risk>) getPropertyValueForInternalUse("risksIncludeDescendants")).size() - getRiskCount(); } /** * * @return */ protected List<VersionableDocument> getDocuments() { return _work.getDocuments(); } @Column(section=DOCUMENTS_SECTION,width=Bean.NUMBER_WIDTH,order=7.01f) public Integer getDocumentCount() { return getDocuments().size(); } /** * @return documents on this project and all dependent work */ @Column(section=DOCUMENTS_SECTION,width=Bean.DEFAULT_WIDTH,order=7.02f) public Integer getDependentProjectDocumentCount() { int count = 0; for(WorkBean work:getDependentProjectBeans()) { count+=work.getDocumentCount(); } return count; } /** * * @param scheduleType * @return */ protected Integer getCycleTimeInDays(ScheduleType scheduleType) { Duration duration = _work.getCycleTime(scheduleType); Float amount = null!=duration ? Float.valueOf(duration.getAmount()) : null; return null!=amount && !amount.isNaN() ? Integer.valueOf(amount.intValue()) : null; } protected Integer getDurationInDays(ScheduleType scheduleType) { final Duration duration = scheduleType.getLaborTime(_work.getSchedules()); final Float amount = null!=duration ? Float.valueOf(duration.getAmount()) : null; if(null != amount && !amount.isNaN()){ final Integer value = Integer.valueOf(amount.intValue()); if(value > 0) return value; } return null; } @Column(width=Bean.NUMBER_WIDTH,relatedColumns={@Column.RelatedColumn(value="percentCompleteSymbol")}, order=3) public Integer getPercentComplete() { if(!WorkHelp.hidePercentComplete(_work)) { Integer result = _work.getPercentComplete(); return null!=result ? result : Integer.valueOf(0); } else { return null; } } @RelatedColumn(type=RelatedColumn.RelatedColumnType.PercentSymbolColumn) @SelectedByDefault public String getPercentCompleteSymbol(){ if(null!=getPercentComplete()) { return "%"; } else { return null; } } @Column(section=IDEAS_SECTION,width=Bean.TYPE_WIDTH,order=8.01f) @Filter(className=IdeaApprovalStatusFilter.class) @FilterByBeanProperty("ideaStatusFilterProperty") public String getIdeaStatus() { return WorkHelp.isIdea(_work) ? IdeaHelp.getIdeaStatus(_work).getName(getLocale()) : null; } @ReferencedAsPropertyValue public String getIdeaStatusFilterProperty() { return IdeaApprovalStatusFilter.getFilterProperty(_work); } @RelatedEntity(inheritsOptionLimitations=true) @SQLRelationship(type=StatusReportBean.LastStatusReportSQLRelationship.class) public StatusReportBean getMostRecentStatusReport() { return (StatusReportBean) get(StatusReportBean.class, _work.getId()); } /** * * @return */ @AddedByDefault @ReferencedUsingReflection @SQLRelationship(type=ps5.reports.pointandclick.data.SQLRelationship.OneToOneRelationship.class) public static DynamicProperties getTags() { return new WorkTagDynamicProperties(); } @RequiredFeatures(Uix.FEATURE_MEASURE) @ReferencedUsingReflection public static DynamicProperties getCurrentMeasureRawValues() { return new MeasureByProjectDynamicProperties("raw"); } @RequiredFeatures(Uix.FEATURE_MEASURE) @ReferencedUsingReflection public static DynamicProperties getCurrentMeasureFormattedValues() { return new MeasureByProjectDynamicProperties("rawFmt"); } @RequiredFeatures(Uix.FEATURE_MEASURE) @ReferencedUsingReflection public static DynamicProperties getCurrentMeasureValueDates() { return new MeasureByProjectDynamicProperties("valueDate"); } /** * * @return */ @AddedByDefault @SQLRelationship(type=ps5.reports.pointandclick.data.SQLRelationship.OneToOneRelationship.class) public static DynamicProperties getCustomFields() { return new WorkCustomFieldDynamicProperties(); } public Work getWork() { return _work; } /** * all work roles columns * @return */ @AddedByDefault @SQLRelationship(type=ps5.reports.pointandclick.data.SQLRelationship.OneToOneRelationship.class) public static DynamicProperties getWorkRoles() { return new WorkRolesDynamicProperties(); } public static class MasterProjectSQLRelationship extends ps5.reports.pointandclick.data.SQLRelationship{ @Override public void applyJoinToQuery(SqlSelectQuery query, String withDBTable, List<DBColumnDefinition> withDBColumns, List<DBColumnDefinition> onSourceDBColumns, boolean useLeftJoin) { final String innerTableAlias = "mp" + getInnerTableAliasSubfix(); //issue#89859 Avoid applying join unnecessarily if already added, otherwise causes to clear out previous column filters queries added. if (query.hasTable(innerTableAlias)) { // already added, so ignore return; } // add each sql column into join criteria. (only those in @DBTable // annotation are used) final CompositeCriteria criteria = Criteria.and(); final CompositeCriteria lastCriteria = Criteria.and(); //add inner join to fn_MasterProjects() and extract master project id lastCriteria.add(Criteria.equalColumn(onSourceDBColumns.get(0).getCompositeName(), innerTableAlias + ".work_id")); //then match master_project_id with workbean criteria.add(Criteria.equalColumn(withDBColumns.get(0).getCompositeName(), innerTableAlias + ".master_project_id")); //if allow nulls, then status reports columns can be null, otherwise, restrict output to 'only with status reports' if (!useLeftJoin) { query.addRightInnerJoin(onSourceDBColumns.get(0).getTable(),"PaC_Works_Master_And_Top_Project", innerTableAlias, lastCriteria); query.addRightInnerJoin(innerTableAlias , withDBTable, withDBColumns.get(0).getTable(), criteria); } else { query.addLeftOuterJoin(onSourceDBColumns.get(0).getTable(),"PaC_Works_Master_And_Top_Project", innerTableAlias, lastCriteria); query.addLeftOuterJoin(innerTableAlias , withDBTable, withDBColumns.get(0).getTable(), criteria); } } @Override public void applyJoinToQuery(SqlSelectQuery query, String withDBTable, String withDBTableAlias, String toDBTable, Criteria customCriteria, boolean useLeftJoin) { //do nothing! throw new PointAndClickRuntimeException("Unsupported functionality!"); } protected String getInnerTableAliasSubfix() { return ("t" + hashCode()).replace("-", "_"); } } public static class TopProjectSQLRelationship extends ps5.reports.pointandclick.data.SQLRelationship{ @Override public void applyJoinToQuery(final SqlSelectQuery query, String withDBTable, List<DBColumnDefinition> withDBColumns, List<DBColumnDefinition> onSourceDBColumns, boolean useLeftJoin) { final String innerTableAlias = "mp" + getInnerTableAliasSubfix(); //issue#89859 Avoid applying join unnecessarily if already added, otherwise causes to clear out previous column filters queries added. if (query.hasTable(innerTableAlias)) { // already added, so ignore return; } // add each sql column into join criteria. (only those in @DBTable // annotation are used) final CompositeCriteria criteria = Criteria.and(); final CompositeCriteria lastCriteria = Criteria.and(); //add inner join to fn_TopProjects() and extract master project id lastCriteria.add(Criteria.equalColumn(onSourceDBColumns.get(0).getCompositeName(), innerTableAlias + ".work_id")); //then match master_project_id with workbean criteria.add(Criteria.equalColumn(withDBColumns.get(0).getCompositeName(), innerTableAlias + ".top_project_id")); //if allow nulls, then status reports columns can be null, otherwise, restrict output to 'only with status reports' if (!useLeftJoin) { query.addRightInnerJoin(onSourceDBColumns.get(0).getTable(),"PaC_Works_Master_And_Top_Project", innerTableAlias, lastCriteria); query.addRightInnerJoin(innerTableAlias , withDBTable, withDBColumns.get(0).getTable(), criteria); } else { query.addLeftOuterJoin(onSourceDBColumns.get(0).getTable(),"PaC_Works_Master_And_Top_Project", innerTableAlias, lastCriteria); query.addLeftOuterJoin(innerTableAlias , withDBTable, withDBColumns.get(0).getTable(), criteria); } } @Override public void applyJoinToQuery(SqlSelectQuery query, String withDBTable, String withDBTableAlias, String toDBTable, Criteria customCriteria, boolean useLeftJoin) { //do nothing! throw new PointAndClickRuntimeException("Unsupported functionality!"); } protected String getInnerTableAliasSubfix() { return ("t" + hashCode()).replace("-", "_"); } } public Integer getDurationInHours() { Duration duration = _work.getDurationInHours(true, getContext().getCalendarService().getDefaultCalendar()); return null!=duration? Integer.valueOf(Float.valueOf(duration.toFloat()).intValue()) : null; } @Column(section=BUDGET_SECTION,relatedColumns={@Column.RelatedColumn(value="budgetCurrencySymbol")},order=9.01f) @RequiredPermissions(Verbs.VIEW_COST) @CurrencyConversionAttribute("budgetCurrencyConversionAttribute") public Double getCostBudgetTotal(){ return _work.getBudgetedCostAmount(); } @Column(section=BUDGET_SECTION,relatedColumns={@Column.RelatedColumn(value="baselineCurrencySymbol")},order=9.02f) @RequiredPermissions(Verbs.VIEW_COST) @CurrencyConversionAttribute("baselineCurrencyConversionAttribute") public Double getCostBaselineTotal(){ return _work.getBaselineBudgetAmount(); } @Column(section=BUDGET_SECTION,relatedColumns={@Column.RelatedColumn(value="estimateCurrencySymbol")},order=9.03f) @RequiredPermissions(Verbs.VIEW_COST) @CurrencyConversionAttribute("estimateCurrencyConversionAttribute") public Double getCostEstimateTotal(){ return null != _work.getEstimatedCost(false) ? _work.getEstimatedCost(false).getAmount() : null; } @Column(section=BUDGET_SECTION,relatedColumns={@Column.RelatedColumn(value="actualCurrencySymbol")},order=9.04f) @RequiredPermissions(Verbs.VIEW_COST) @CurrencyConversionAttribute("actualCurrencyConversionAttribute") public Double getCostActualTotal(){ return null != _work.getActualCost(false) ? _work.getActualCost(false).getAmount() : null; } @Column(section=BUDGET_SECTION,relatedColumns={@Column.RelatedColumn(value="estimatePercentSymbol")},order=9.05f) @RequiredPermissions(Verbs.VIEW_COST) public Integer getCostEstimatedBudgetPercent(){ return calculatePercent(getCostBudgetTotal(),getCostEstimateTotal()); } @Column(section=BUDGET_SECTION,relatedColumns={@Column.RelatedColumn(value="estimatePercentSymbol")},order=9.06f) @RequiredPermissions(Verbs.VIEW_COST) public Integer getCostEstimatedBaselinePercent(){ return calculatePercent(getCostBaselineTotal(),getCostEstimateTotal()); } @Column(section=BUDGET_SECTION,relatedColumns={@Column.RelatedColumn(value="actualPercentSymbol")},order=9.07f) @RequiredPermissions(Verbs.VIEW_COST) public Integer getCostActualBudgetPercent(){ return calculatePercent(getCostBudgetTotal(),getCostActualTotal()); } @Column(section=BUDGET_SECTION,relatedColumns={@Column.RelatedColumn(value="actualPercentSymbol")},order=9.08f) @RequiredPermissions(Verbs.VIEW_COST) public Integer getCostActualBaselinePercent(){ return calculatePercent(getCostBaselineTotal(),getCostActualTotal()); } private static Integer calculatePercent(Double fixedTotal, Double value){ Integer estPercent = null; if (fixedTotal != null && !fixedTotal.isNaN() && value != null && !value.isNaN()) estPercent = (int) Math.round(100 * value.doubleValue() / fixedTotal.doubleValue()); return estPercent; } /* * * related columns for costs columns */ @RelatedColumn(type=RelatedColumn.RelatedColumnType.PercentSymbolColumn) @SelectedByDefault public String getEstimatePercentSymbol(){ return getPercentSymbol(getCostEstimateTotal()); } @RelatedColumn(type=RelatedColumn.RelatedColumnType.PercentSymbolColumn) @SelectedByDefault public String getActualPercentSymbol(){ return getPercentSymbol(getCostActualTotal()); } @RelatedColumn(type=RelatedColumn.RelatedColumnType.CurrencySymbolColumn,position=RelatedColumn.Position.Left) @SelectedByDefault public String getEstimateCurrencySymbol(){ return getCurrencySymbol(getCostEstimateTotal()); } @RelatedColumn(type=RelatedColumn.RelatedColumnType.CurrencySymbolColumn,position=RelatedColumn.Position.Left) @SelectedByDefault public String getActualCurrencySymbol(){ return getCurrencySymbol(getCostActualTotal()); } @RelatedColumn(type=RelatedColumn.RelatedColumnType.CurrencySymbolColumn,position=RelatedColumn.Position.Left) @SelectedByDefault public String getBudgetCurrencySymbol(){ return getCurrencySymbol(getCostBudgetTotal()); } @RelatedColumn(type=RelatedColumn.RelatedColumnType.CurrencySymbolColumn,position=RelatedColumn.Position.Left) @SelectedByDefault public String getBaselineCurrencySymbol(){ return getCurrencySymbol(getCostBaselineTotal()); } @ReferencedAsPropertyValue public CurrencyConversionAttributeData getBudgetCurrencyConversionAttribute(){ return getCurrencyConversionAttribute(getCostBudgetTotal()); } @ReferencedAsPropertyValue public CurrencyConversionAttributeData getBaselineCurrencyConversionAttribute(){ return getCurrencyConversionAttribute(getCostBaselineTotal()); } @ReferencedAsPropertyValue public CurrencyConversionAttributeData getActualCurrencyConversionAttribute(){ return getWorkCostCurrencyConversionAttributeData(getCostActualTotal(),false); } @ReferencedAsPropertyValue public CurrencyConversionAttributeData getEstimateCurrencyConversionAttribute(){ return getWorkCostCurrencyConversionAttributeData(getCostEstimateTotal(),true); } private String getCurrencySymbol(Double value){ if(null!=value && null!=_work.getCurrency()) { return _work.getCurrency().getSymbol(); } return null; } private WorkCostCurrencyConversionAttributeData getWorkCostCurrencyConversionAttributeData(Number value, boolean isEstimate){ if(null != value && null!=_work.getCurrency() ) { final Calendar currDate = Calendar.getInstance(getContext().getTimeZone()); final WorkCostCurrencyConversionAttributeData currencyConversionAttribute = new WorkCostCurrencyConversionAttributeData(_work.getCurrency().getCode(),currDate.getTime(), _work.getId(), isEstimate); return currencyConversionAttribute; } return null; } private CurrencyConversionAttributeData getCurrencyConversionAttribute(Number value){ if(null != value && null!=_work.getCurrency() ) { final Calendar currDate = Calendar.getInstance(getContext().getTimeZone()); final CurrencyConversionAttributeData currencyConversionAttribute = new CurrencyConversionAttributeData(_work.getCurrency().getCode(),currDate.getTime()); return currencyConversionAttribute; } return null; } private String getPercentSymbol(Double value){ if(null!=value) { return "%"; } else { return null; } } @Column(width = Bean.BOOLEAN_WIDTH, order = 23) public Boolean getIsArchived() { return getPSObject().isArchived(); } /** * work up the tree until you hit a gate or work where is_project= yes, * or if current work is a gate return itself as a GateGeneralColumnsBean (Issue#86340.1.1.1.1.1.1) * Hitting the gate gets you the information you need. Hitting work where * is_project=yes means that source work is a descendant of a non-gated * project. Using this logic, if the source work is is_project=yes, then * there is no gate. * * @return */ @RelatedEntity public GateGeneralColumnsBean getGateBean() { //Issue#86340.1.1.1.1.1.1 Include itself if work is a gate. if (WorkHelp.isCheckpoint(_work)) { Checkpoint gate = (Checkpoint) _work; return (GateGeneralColumnsBean) get(GateGeneralColumnsBean.class,gate.getGateNumber(),gate.getProcess().getId(),gate.getTollgate().getId()); } Work parent = getWork().getParentWork(); while (null != parent) { if (WorkHelp.isCheckpoint(parent)) { Checkpoint gate = (Checkpoint) parent; return (GateGeneralColumnsBean) get(GateGeneralColumnsBean.class,gate.getGateNumber(),gate.getProcess().getId(),gate.getTollgate().getId()); } if(WorkHelp.isProject(parent)) { // If master project for source work is not gated, the gate // value is null return null; } parent = parent.getParentWork(); } return null; } @RelatedEntity public WorkHoursBean getWorkHoursBean() { return (WorkHoursBean) get(WorkHoursBean.class,getWork().getId()); } /** * Timesheets directly attached to this work item * cached for performance * @return */ public List<PSTransaction> getTimesheets() { return (List<PSTransaction>) getPropertyValueForInternalUse("timesheetsToBeCached"); } /** * Timesheets directly attached to this work item + lower work ones * cached for performance * @return */ public List<PSTransaction> getTimesheetsIncludingLowerWork() { return (List<PSTransaction>) getPropertyValueForInternalUse("timesheetsIncludingLowerWorkToBeCached"); } /** * FOR INTERNAL USE: NEVER CALL DIRECTLY! * Call getTimesheets() instead * @see #getTimesheets() */ @ReferencedAsPropertyValue public List<PSTransaction> getTimesheetsToBeCached() { return TimesheetBean.getTimesheets(getWork(), false); } /** * FOR INTERNAL USE: NEVER CALL DIRECTLY! * Call getTimesheetsIncludingLowerWork() instead * @see #getTimesheetsIncludingLowerWork() */ @ReferencedAsPropertyValue public List<PSTransaction> getTimesheetsIncludingLowerWorkToBeCached() { return TimesheetBean.getTimesheets(getWork(), true); } @Column(section = BEST_PRACTICE_SECTION, width=Bean.BOOLEAN_WIDTH,order=30.01f) @RequiredFeatures(Uix.FEATURE_BEST_PRACTICES) public Boolean getIsBestPractice() { return BestPractice.isApproved(getPSObject()); } @Column(section = BEST_PRACTICE_SECTION, width=Bean.BOOLEAN_WIDTH,order=30.02f) @RequiredFeatures(Uix.FEATURE_BEST_PRACTICES) public Boolean getIsBestPracticeNominee() { return BestPractice.isNominated(getPSObject()); } @Column(section = BEST_PRACTICE_SECTION, width=Bean.DEFAULT_WIDTH,order=30.03f) @RequiredFeatures(Uix.FEATURE_BEST_PRACTICES) @Filter(className=BestPracticeStatusFilter.class) @FilterByBeanProperty("bestPracticeStatusId") public String getBestPracticeStatus() { return BestPractice.getStatusLabel(getPSObject(),getLocale()); } @ReferencedAsPropertyValue @RequiredFeatures(Uix.FEATURE_BEST_PRACTICES) public String getBestPracticeStatusId() { return getWork().getBestPracticeStatus(); } @RelatedEntity @SQLRelationship(type=ps5.reports.pointandclick.data.SQLRelationship.OneToOneRelationship.class) @RequiredFeatures(Uix.FEATURE_BEST_PRACTICES) public UserBean getBestPracticeNominatedByBean() { User user = BestPractice.getNominationUser(getPSObject()); return null!=user ? (UserBean) get(UserBean.class,user.getId()) : null; } @Column(section = BEST_PRACTICE_SECTION, width=Bean.ENTITY_NAME_WIDTH,order=30.04f) @OptionalSortByBeanProperty("bestPracticeNominatedBySortableUid") @Filter(className=SingleUserFilter.class) @FilterByBeanProperty("bestPracticeNominatedById") @LinkUrlProperty("bestPracticeNominatedByUrl") @RequiredFeatures(Uix.FEATURE_BEST_PRACTICES) public String getBestPracticeNominatedBy() { UserBean user = getBestPracticeNominatedByBean(); return null!=user ? user.getName() : null; } @ReferencedAsPropertyValue public String getBestPracticeNominatedById() { UserBean user = getBestPracticeNominatedByBean(); return null!=user ? user.getUser().getId().toString() : null; } @ReferencedAsPropertyValue public String getBestPracticeNominatedBySortableUid() { UserBean user = getBestPracticeNominatedByBean(); return null!=user ? user.getUid() : null; } @ReferencedAsPropertyValue public String getBestPracticeNominatedByUrl() { UserBean user = getBestPracticeNominatedByBean(); return null!=user ? user.getUrl() : null; } @Column(section = BEST_PRACTICE_SECTION, width=Bean.DATE_WIDTH,order=30.05f) @RequiredFeatures(Uix.FEATURE_BEST_PRACTICES) @Filter(className=UserDateRangeFilter.class) public Date getBestPracticeNominatedOn() { return toDayStart(BestPractice.getNominationDate(getPSObject())); } @Column(section = BEST_PRACTICE_SECTION, width=Bean.DESCRIPTION_WIDTH,order=30.06f) @RequiredFeatures(Uix.FEATURE_BEST_PRACTICES) public String getBestPracticeNominationComment() { return BestPractice.getNominationComments(getPSObject()); } @RelatedEntity @SQLRelationship(type=ps5.reports.pointandclick.data.SQLRelationship.OneToOneRelationship.class) @RequiredFeatures(Uix.FEATURE_BEST_PRACTICES) public UserBean getBestPracticeApprovedByBean() { User user = BestPractice.getApprovalUser(getPSObject()); return null!=user ? (UserBean) get(UserBean.class,user.getId()) : null; } @Column(section = BEST_PRACTICE_SECTION, width=Bean.ENTITY_NAME_WIDTH,order=30.07f) @OptionalSortByBeanProperty("bestPracticeApprovedBySortableUid") @Filter(className=SingleUserFilter.class) @FilterByBeanProperty("bestPracticeApprovedById") @LinkUrlProperty("bestPracticeApprovedByUrl") @RequiredFeatures(Uix.FEATURE_BEST_PRACTICES) public String getBestPracticeApprovedBy() { UserBean user = getBestPracticeApprovedByBean(); return null!=user ? user.getName() : null; } @ReferencedAsPropertyValue public String getBestPracticeApprovedById() { UserBean user = getBestPracticeApprovedByBean(); return null!=user ? user.getUser().getId().toString() : null; } @ReferencedAsPropertyValue public String getBestPracticeApprovedBySortableUid() { UserBean user = getBestPracticeApprovedByBean(); return null!=user ? user.getUid() : null; } @ReferencedAsPropertyValue public String getBestPracticeApprovedByUrl() { UserBean user = getBestPracticeApprovedByBean(); return null!=user ? user.getUrl() : null; } @Column(section = BEST_PRACTICE_SECTION, width=Bean.DATE_WIDTH,order=30.08f) @RequiredFeatures(Uix.FEATURE_BEST_PRACTICES) @Filter(className=UserDateRangeFilter.class) public Date getBestPracticeApprovedOn() { return toDayStart(BestPractice.getApprovalDate(getPSObject())); } @Column(section = BEST_PRACTICE_SECTION, width=Bean.DESCRIPTION_WIDTH,order=30.09f) @RequiredFeatures(Uix.FEATURE_BEST_PRACTICES) public String getBestPracticeApprovalComment() { return BestPractice.getApprovalComments(getPSObject()); } @RelatedEntity @SQLRelationship(type=ps5.reports.pointandclick.data.SQLRelationship.OneToOneRelationship.class) @RequiredFeatures(Uix.FEATURE_BEST_PRACTICES) public UserBean getBestPracticeRejectedByBean() { User user = BestPractice.getRejectionUser(getPSObject()); return null!=user ? (UserBean) get(UserBean.class,user.getId()) : null; } @Column(section = BEST_PRACTICE_SECTION, width=Bean.ENTITY_NAME_WIDTH,order=30.10f) @OptionalSortByBeanProperty("bestPracticeRejectedBySortableUid") @Filter(className=SingleUserFilter.class) @FilterByBeanProperty("bestPracticeRejectedById") @LinkUrlProperty("bestPracticeRejectedByUrl") @RequiredFeatures(Uix.FEATURE_BEST_PRACTICES) public String getBestPracticeRejectedBy() { UserBean user = getBestPracticeRejectedByBean(); return null!=user ? user.getName() : null; } @ReferencedAsPropertyValue public String getBestPracticeRejectedById() { UserBean user = getBestPracticeRejectedByBean(); return null!=user ? user.getUser().getId().toString() : null; } @ReferencedAsPropertyValue public String getBestPracticeRejectedBySortableUid() { UserBean user = getBestPracticeRejectedByBean(); return null!=user ? user.getUid() : null; } @ReferencedAsPropertyValue public String getBestPracticeRejectedByUrl() { UserBean user = getBestPracticeRejectedByBean(); return null!=user ? user.getUrl() : null; } @Column(section = BEST_PRACTICE_SECTION, width=Bean.DATE_WIDTH,order=30.11f) @RequiredFeatures(Uix.FEATURE_BEST_PRACTICES) @Filter(className=UserDateRangeFilter.class) public Date getBestPracticeRejectedOn() { return toDayStart(BestPractice.getRejectionDate(getPSObject())); } @Column(section = BEST_PRACTICE_SECTION, width=Bean.DESCRIPTION_WIDTH,order=30.12f) @RequiredFeatures(Uix.FEATURE_BEST_PRACTICES) public String getBestPracticeRejectedComment() { return BestPractice.getRejectionComments(getPSObject()); } @RelatedEntity @SQLRelationship(type=ps5.reports.pointandclick.data.SQLRelationship.OneToOneRelationship.class) @RequiredFeatures(Uix.FEATURE_BEST_PRACTICES) public UserBean getBestPracticeDesignationRemovedByBean() { User user = BestPractice.getDesignationRemovedUser(getPSObject()); return null!=user ? (UserBean) get(UserBean.class,user.getId()) : null; } @Column(section = BEST_PRACTICE_SECTION, width=Bean.ENTITY_NAME_WIDTH,order=30.13f) @OptionalSortByBeanProperty("bestPracticeDesignationRemovedBySortableUid") @Filter(className=SingleUserFilter.class) @FilterByBeanProperty("bestPracticeDesignationRemovedById") @LinkUrlProperty("bestPracticeDesignationRemovedByUrl") @RequiredFeatures(Uix.FEATURE_BEST_PRACTICES) public String getBestPracticeDesignationRemovedBy() { UserBean user = getBestPracticeDesignationRemovedByBean(); return null!=user ? user.getName() : null; } @ReferencedAsPropertyValue public String getBestPracticeDesignationRemovedById() { UserBean user = getBestPracticeDesignationRemovedByBean(); return null!=user ? user.getUser().getId().toString() : null; } @ReferencedAsPropertyValue public String getBestPracticeDesignationRemovedBySortableUid() { UserBean user = getBestPracticeDesignationRemovedByBean(); return null!=user ? user.getUid() : null; } @ReferencedAsPropertyValue public String getBestPracticeDesignationRemovedByUrl() { UserBean user = getBestPracticeDesignationRemovedByBean(); return null!=user ? user.getUrl() : null; } @Column(section = BEST_PRACTICE_SECTION, width=Bean.DATE_WIDTH,order=30.14f) @RequiredFeatures(Uix.FEATURE_BEST_PRACTICES) @Filter(className=UserDateRangeFilter.class) public Date getBestPracticeDesignationRemovedOn() { return toDayStart(BestPractice.getDesignationRemovedDate(getPSObject())); } @Column(section = BEST_PRACTICE_SECTION, width=Bean.DESCRIPTION_WIDTH,order=30.15f) @RequiredFeatures(Uix.FEATURE_BEST_PRACTICES) public String getBestPracticeDesignationRemovedComment() { return BestPractice.getDesignationRemovedComments(getPSObject()); } @Column(width=Bean.BOOLEAN_WIDTH, order=30.25f, section = CONFIG_SECTION) @RequiredFeatures(Uix.FEATURE_WORKFLOW_ENABLED) public Boolean getIsWorkflow() { return _work.isWorkflow(); } @Column(width=Bean.TYPE_WIDTH, order=30.26f, section = CONFIG_SECTION) @Filter(className=WorkflowStatusFilter.class) @FilterByBeanProperty("workflowStatusFilterProperty") @RequiredFeatures(Uix.FEATURE_WORKFLOW_ENABLED) public String getWorkflowStatus() { return WorkflowUtils.getWorkflowStatus(_work, getLocale()); } @ReferencedAsPropertyValue public String getWorkflowStatusFilterProperty() { if(null != _work.getWorkflowStatus()){ return _work.getWorkflowStatus().name(); } return null; } @Column(width=Bean.TYPE_WIDTH, order=30.27f, section = CONFIG_SECTION) @RequiredFeatures(Uix.FEATURE_WORKFLOW_ENABLED) public String getLastWorkflowAction() { if(null != getWork().getWorkflowStatus()){ final ObjectEvent evt = ObjectEvent.findLastByObjectAndType(getWork(),WorkflowChangeEvent.TYPE); if(null != evt && WorkflowChangeEvent.TYPE.equals(evt.getType())){ return evt.getFullDescription(BaseObjectEvent.TYPE_TXT, getSession().getCurrentUser()); } } return null; } @Column(width = Bean.TYPE_WIDTH, order = 0.06f) public String getTemplateName(){ return getWork().getAssociatedTemplate() != null? getWork().getAssociatedTemplate().getName(): null; } @Column(width = Bean.TYPE_WIDTH, order = 0.16f) public String getRootWorkObject(){ return this.getType() != null? this.getType().toString(): null; } }
UTF-8
Java
83,740
java
WorkBean.java
Java
[ { "context": "eractive.util.FilterChain;\r\n\r\n/**\r\n * \r\n * @author Damian Kober\r\n * @date 10/10/2008\r\n */\r\n/**\r\n * ColumnFilters ", "end": 7083, "score": 0.999873161315918, "start": 7071, "tag": "NAME", "value": "Damian Kober" } ]
null
[]
package ps5.reports.pointandclick.data.beans.work; import java.text.DecimalFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Collections; import java.util.Date; import java.util.HashSet; import java.util.List; import java.util.Set; import ps5.bestpractices.BestPractice; import ps5.psapi.IdeaHelp; import ps5.psapi.WorkHelp; import ps5.psapi.date.PSDate; import ps5.psapi.date.PSDateAdjust; import ps5.psapi.programs.ProgramHelp; import ps5.psapi.project.DiscussionItemBean; import ps5.psapi.project.DiscussionItemHelp; import ps5.psapi.project.ReferencedWork; import ps5.psapi.project.statusreports.StatusReportFrequency; import ps5.reports.ReportSession; import ps5.reports.pointandclick.PointAndClickRuntimeException; import ps5.reports.pointandclick.ReportRunContext; import ps5.reports.pointandclick.data.beans.Bean; import ps5.reports.pointandclick.data.beans.DynamicProperties; import ps5.reports.pointandclick.data.beans.annotations.AddedByDefault; import ps5.reports.pointandclick.data.beans.annotations.ColorProperty; import ps5.reports.pointandclick.data.beans.annotations.Column; import ps5.reports.pointandclick.data.beans.annotations.ContextSwitch; import ps5.reports.pointandclick.data.beans.annotations.CurrencyConversionAttribute; import ps5.reports.pointandclick.data.beans.annotations.DeprecatedElement; import ps5.reports.pointandclick.data.beans.annotations.FilterByBeanProperty; import ps5.reports.pointandclick.data.beans.annotations.GanttObjectId; import ps5.reports.pointandclick.data.beans.annotations.LinkUrlProperty; import ps5.reports.pointandclick.data.beans.annotations.OptionalSortByBeanProperty; import ps5.reports.pointandclick.data.beans.annotations.ReferencedAsPropertyValue; import ps5.reports.pointandclick.data.beans.annotations.ReferencedBean; import ps5.reports.pointandclick.data.beans.annotations.ReferencedUsingReflection; import ps5.reports.pointandclick.data.beans.annotations.RelatedColumn; import ps5.reports.pointandclick.data.beans.annotations.RelatedColumn.Position; import ps5.reports.pointandclick.data.beans.annotations.RelatedEntity; import ps5.reports.pointandclick.data.beans.annotations.RequiredFeatures; import ps5.reports.pointandclick.data.beans.annotations.RequiredPermissions; import ps5.reports.pointandclick.data.beans.annotations.SelectedByDefault; import ps5.reports.pointandclick.data.beans.annotations.columnfilters.DBColumn; import ps5.reports.pointandclick.data.beans.annotations.columnfilters.DBColumns; import ps5.reports.pointandclick.data.beans.annotations.columnfilters.DBTable; import ps5.reports.pointandclick.data.beans.annotations.columnfilters.Filter; import ps5.reports.pointandclick.data.beans.annotations.columnfilters.NoFilter; import ps5.reports.pointandclick.data.beans.annotations.columnfilters.SQLRelationship; import ps5.reports.pointandclick.data.beans.base.PSObjectBean; import ps5.reports.pointandclick.data.beans.currency.CurrencyConversionAttributeData; import ps5.reports.pointandclick.data.beans.currency.WorkCostCurrencyConversionAttributeData; import ps5.reports.pointandclick.data.beans.entities.TimesheetBean; import ps5.reports.pointandclick.data.beans.entities.UserBean; import ps5.reports.pointandclick.data.beans.measures.MeasureByProjectDynamicProperties; import ps5.reports.pointandclick.data.beans.role.WorkRolesDynamicProperties; import ps5.reports.pointandclick.data.beans.statusreports.StatusReportBean; import ps5.reports.pointandclick.data.beans.tags.WorkTagDynamicProperties; import ps5.reports.pointandclick.data.definition.DBColumnDefinition; import ps5.reports.pointandclick.data.filters.CurrencyFilter; import ps5.reports.pointandclick.data.filters.bestpractices.BestPracticeStatusFilter; import ps5.reports.pointandclick.data.filters.entities.SingleUserFilter; import ps5.reports.pointandclick.data.filters.metrics.AttachedMetricTemplatesFilter; import ps5.reports.pointandclick.data.filters.rate.RateTableFilter; import ps5.reports.pointandclick.data.filters.resources.ResourceCalendarFilter; import ps5.reports.pointandclick.data.filters.statusreports.StatusReportFrequencyFilter; import ps5.reports.pointandclick.data.filters.time.UserDateRangeFilter; import ps5.reports.pointandclick.data.filters.timesheets.ActivityFilter; import ps5.reports.pointandclick.data.filters.work.IdeaApprovalStatusFilter; import ps5.reports.pointandclick.data.filters.work.MasterProjectsFilter; import ps5.reports.pointandclick.data.filters.work.ProjectFilter; import ps5.reports.pointandclick.data.filters.work.TopProjectsFilter; import ps5.reports.pointandclick.data.filters.work.WithScheduleConstraintTypeFilter; import ps5.reports.pointandclick.data.filters.work.WorkPrioritiesFilter; import ps5.reports.pointandclick.data.filters.work.WorkReferencesFilter; import ps5.reports.pointandclick.data.filters.work.WorkStatusFilter; import ps5.reports.pointandclick.data.filters.work.WorkTypesFilter; import ps5.reports.pointandclick.data.filters.work.WorkflowStatusFilter; import ps5.reports.pointandclick.data.filters.work.WorksFilter; import ps5.reports.pointandclick.data.filters.work.schedule.ScheduleTypeFilter; import ps5.reports.pointandclick.data.filters.work.tollgate.ProcessPhasesWithoutCompletedFilter; import ps5.workflow.WorkflowUtils; import com.cinteractive.database.PersistentKey; import com.cinteractive.jdbc.sql.CompositeCriteria; import com.cinteractive.jdbc.sql.Criteria; import com.cinteractive.jdbc.sql.SqlSelectQuery; import com.cinteractive.ps3.PSObject; import com.cinteractive.ps3.discussion.Discussion; import com.cinteractive.ps3.discussion.DiscussionItem; import com.cinteractive.ps3.discussion.Risk; import com.cinteractive.ps3.documents.VersionableDocument; import com.cinteractive.ps3.entities.User; import com.cinteractive.ps3.events.BaseObjectEvent; import com.cinteractive.ps3.events.ObjectEvent; import com.cinteractive.ps3.events.StatusChangeEvent; import com.cinteractive.ps3.events.WorkflowChangeEvent; import com.cinteractive.ps3.measures.MeasureHelper; import com.cinteractive.ps3.measures.MeasureInstance; import com.cinteractive.ps3.metrics.MetricInstance; import com.cinteractive.ps3.newsecurity.Verbs; import com.cinteractive.ps3.pstransactions.ActivityType; import com.cinteractive.ps3.pstransactions.PSTransaction; import com.cinteractive.ps3.reports.attributes.Accessors; import com.cinteractive.ps3.schedule.ScheduleType; import com.cinteractive.ps3.scheduler.calendar.DateCalculator; import com.cinteractive.ps3.scheduler.calendar.DateCalculatorImpl; import com.cinteractive.ps3.tagext.uix.Uix; import com.cinteractive.ps3.tollgate.Checkpoint; import com.cinteractive.ps3.work.Template; import com.cinteractive.ps3.work.UpdateFrequency; import com.cinteractive.ps3.work.Work; import com.cinteractive.ps3.work.WorkStatus; import com.cinteractive.scheduler.Duration; import com.cinteractive.util.CIFilter; import com.cinteractive.util.FilterChain; /** * * @author <NAME> * @date 10/10/2008 */ /** * ColumnFilters SQL mappings * Map this bean to an equivalent table in DB */ @DBTable(name="Pac_Work", onColumns={"work_id"}) /** * Map of supported properties to equivalent SQL columns for filtering purposes */ @DBColumns(onColumns={ @DBColumn(property="name"), @DBColumn(property="creationDate",onColumns={"create_date"}), @DBColumn(property="lastUpdated", onColumns={"last_change_date"}), @DBColumn(property="createdBy", onColumns={"created_by"}), @DBColumn(property="powerSteeringId", onColumns={"work_id"}), @DBColumn(property="isProject", onColumns={"type"}), @DBColumn(property="type", onColumns={"type"}), @DBColumn(property="owner", onColumns={"owner_id"}), @DBColumn(property="status", onColumns={"status"}), @DBColumn(property="objective"), @DBColumn(property="actualStartDate", onColumns={"actual_start_date"}), @DBColumn(property="actualEndDate", onColumns={"actual_end_date"}), @DBColumn(property="plannedStartDate", onColumns={"planned_start_date"}), @DBColumn(property="plannedEndDate", onColumns={"planned_end_date"}), @DBColumn(property="systemStartDate", onColumns={"system_start_date"}), @DBColumn(property="systemEndDate", onColumns={"system_end_date"}), @DBColumn(property="baselineStartDate", onColumns={"baseline_start_date"}), @DBColumn(property="baselineEndDate", onColumns={"baseline_end_date"}), @DBColumn(property="tracksResources", onColumns={"is_track_resource"}), @DBColumn(property="projectId", onColumns={"peer_id"}), @DBColumn(property="priority", onColumns={"priority"}), @DBColumn(property="percentComplete", onColumns={"percent_complete"}), @DBColumn(property="ideaStatus",onColumns={"idea_status","is_idea"}), @DBColumn(property="ownerBean", onColumns={"owner_id"}), @DBColumn(property="creatorBean", onColumns={"created_by"}), @DBColumn(property="parentBean", onColumns={"parent_id"}), @DBColumn(property="parent", onColumns={"parent_id"}), @DBColumn(property="topProject", onColumns={"work_id"}), @DBColumn(property="masterProject", onColumns={"work_id"}), @DBColumn(property="mostRecentStatusReport", onColumns={"work_id",DBTable.SKIP_THIS_PARAMETER}), @DBColumn(property="workRoles", onColumns={"work_id"}), @DBColumn(property="topProjectBean", onColumns={"work_id"}), @DBColumn(property="masterProjectBean", onColumns={"work_id"}), @DBColumn(property="scheduleConstraintType", onColumns={"work_id"}), @DBColumn(property="scheduleType", onColumns={"work_id"}), @DBColumn(property="currency", onColumns={"currency_id"}), @DBColumn(property="isBestPractice",onColumns={"is_best_practice"}), @DBColumn(property="bestPracticeStatus",onColumns={"best_practice_status"}), @DBColumn(property="bestPracticeNominatedByBean",onColumns={"best_practice_nomination_user_id"}), @DBColumn(property="bestPracticeNominatedBy",onColumns={"best_practice_nomination_user_id"}), @DBColumn(property="bestPracticeNominatedOn",onColumns={"best_practice_nomination_time"}), @DBColumn(property="bestPracticeNominationComment",onColumns={"best_practice_nomination_comments"}), @DBColumn(property="bestPracticeApprovedByBean",onColumns={"best_practice_approval_user_id"}), @DBColumn(property="bestPracticeApprovedBy",onColumns={"best_practice_approval_user_id"}), @DBColumn(property="bestPracticeApprovedOn",onColumns={"best_practice_approval_time"}), @DBColumn(property="bestPracticeApprovalComment",onColumns={"best_practice_approval_comments"}), @DBColumn(property="bestPracticeRejectedByBean",onColumns={"best_practice_rejected_user_id"}), @DBColumn(property="bestPracticeRejectedBy",onColumns={"best_practice_rejected_user_id"}), @DBColumn(property="bestPracticeRejectedOn",onColumns={"best_practice_rejected_time"}), @DBColumn(property="bestPracticeRejectedComment",onColumns={"best_practice_rejected_comments"}), @DBColumn(property="bestPracticeDesignationRemovedByBean",onColumns={"best_practice_designation_removed_user_id"}), @DBColumn(property="bestPracticeDesignationRemovedBy",onColumns={"best_practice_designation_removed_user_id"}), @DBColumn(property="bestPracticeDesignationRemovedOn",onColumns={"best_practice_designation_removed_time"}), @DBColumn(property="bestPracticeDesignationRemovedComment",onColumns={"best_practice_designation_removed_comments"}), @DBColumn(property="customFields", onColumns={"work_id", "type"}), @DBColumn(property="isIdea", onColumns={"is_idea"}), @DBColumn(property="workflowStatus", onColumns={"workflow_status"}) }) public class WorkBean extends PSObjectBean { protected static final String SCHEDULE_SECTION = "schedule-section"; protected static final String HIERARCHY_SECTION = "hierarchy-section"; protected static final String ISSUES_SECTION = "issues-section"; protected static final String DISCUSSIONS_SECTION = "discussions-section"; protected static final String RISKS_SECTION = "risks-section"; protected static final String DOCUMENTS_SECTION = "documents-section"; protected static final String IDEAS_SECTION = "ideas-section"; protected static final String RESOURCE_PLANNING_SECTION = "resource-planning-section"; protected static final String BUDGET_SECTION = "budget-section"; protected static final String BEST_PRACTICE_SECTION = "best-practice-section"; protected static final String CONFIG_SECTION = "config-section"; private final Work _work; /** * * Constructor * * @param parameters * @param reportRunContext */ public WorkBean(List<Object> parameters, ReportRunContext reportRunContext) { super(parameters, reportRunContext); _work = (Work) getPSObject(); } @Column(width=Bean.LONG_NAME_WIDTH, order=0.01f,relatedColumns={@Column.RelatedColumn(value="typeIconPath"),@Column.RelatedColumn(value="statusIconPath"),@Column.RelatedColumn(value="completePath")}) @SelectedByDefault @OptionalSortByBeanProperty(Bean.SORTABLE_UID_PROPERTY) @LinkUrlProperty("url") @GanttObjectId("workId") @ReferencedBean(parameters="workId",clazz=WorkBean.class) public String getName() { return getPSObject().getName(getLocale()); } @RelatedColumn(type=RelatedColumn.RelatedColumnType.IndentProperty, position=Position.Left, width=1) public String getCompletePath(){ final List<Work> list = WorkHelp.getPath(_work); final StringBuilder builder = new StringBuilder(); for(int i = list.size() - 1; i >=0;i--) { Work item = list.get(i); if(builder.length()!=0)builder.append("_"); builder.append(item.getId()); } return builder.toString(); } @RelatedColumn(type=RelatedColumn.RelatedColumnType.IconColumn, position=Position.Left, width=20) public String getTypeIconPath(){ return getPSObject().getTypeIconPath(); } @RelatedColumn(type=RelatedColumn.RelatedColumnType.IconColumn, position=Position.Left, width=15) public String getStatusIconPath(){ return getWork().getStatusIconPath(); } public String getSortableUid() { String sequenceWithinParentStr; Integer sequenceWithinParent = _work.getSequenceWithinParent(); if(null!=sequenceWithinParent) { sequenceWithinParentStr = new DecimalFormat("00000").format(sequenceWithinParent); } else { sequenceWithinParentStr = "_"; //sort higher if has no sequence } String parentStr; GenericWorkBean parent = getParentBean(); if(null!=parent) { parentStr = parent.getSortableUid(); } else { parentStr = "_"; //sort higher if has no parent } return parentStr + SORTABLE_ID_SEPARATOR + sequenceWithinParentStr + SORTABLE_ID_SEPARATOR + getName() + SORTABLE_ID_SEPARATOR + getUid(); } public boolean mayView() { return super.mayView() && !Template.TYPE.equals(_work.getPSType()); } @ReferencedAsPropertyValue public String getWorkId(){ return getWork().getId().toString(); } @Column(width=Bean.TYPE_WIDTH, order=0.02f) @ColorProperty(property="statusColor", availableColorsMethod="statusAvailableColors") @OptionalSortByBeanProperty("statusSortableUid") @Filter(className=WorkStatusFilter.class) @FilterByBeanProperty("statusFilterProperty") public String getStatus() { if(!WorkHelp.hideStatus(_work)) { return _work.getWorkStatus().getStatus().getLocalizedName(getLocale(),getContext()); } else { return null; } } @ReferencedAsPropertyValue public String getStatusColor() { if(!WorkHelp.hideStatus(_work)) { return _work.getWorkStatus().getStatus().getExportableColorCode(); } else { return null; } } @ReferencedAsPropertyValue public static List<String> getStatusAvailableColors(ReportSession session){ if(null != session){ List<String> result = new ArrayList<String>(); for(WorkStatus ws : WorkStatus.values()){ if(ws.isWorkStatusActive(session.getContext())){ result.add(ws.getExportableColorCode()); } } return result; } return null; } @ReferencedAsPropertyValue public Integer getStatusSortableUid() { return _work.getWorkStatus().getStatus().getSequence(); } @ReferencedAsPropertyValue public String getStatusFilterProperty(){ if(!WorkHelp.hideStatus(_work)) { return _work.getWorkStatus().getStatus().getCode(); } else { return null; } } @Column(width=Bean.DATE_WIDTH, order=0.021f) public Date getStatusChangeDate() { return StatusChangeEvent.getStatusChangeDate(_work); } @Column(width=Bean.DATE_WIDTH, order=0.022f) public Date getCancelDate() { return toDayStart(PSDateAdjust.toContext12(_work.getCancelDate()),getContext().getTimeZone()); } @Column(width=Bean.DESCRIPTION_WIDTH, order=20.0134f) public String getObjective() {return _work.getObjectiveRTF(); } @Column(width=Bean.TYPE_WIDTH, order=0.11f) @Filter(className=WorkTypesFilter.class) @FilterByBeanProperty("typeCode") @DeprecatedElement public String getType() {return getType1(); } @Column(width=Bean.TYPE_WIDTH, order=20.01f,section=CONFIG_SECTION) @Filter(className=WorkTypesFilter.class) @FilterByBeanProperty("typeCode") public String getType1() {return getPSObject().getContextPSType().getLocalizedDetails(getLocale()).getName(); } @Column(section=SCHEDULE_SECTION, order=1.011f) @Filter(className=WithScheduleConstraintTypeFilter.class) @FilterByBeanProperty("scheduleConstraintTypeFilterProperty") public String getScheduleConstraintType() { return null!=_work.getSchedules() && null!=_work.getSchedules().getConstraintType() ? _work.getSchedules().getConstraintType().getName(getLocale()) : null; } @ReferencedAsPropertyValue public String getScheduleConstraintTypeFilterProperty(){ return null!=_work.getSchedules() && null!=_work.getSchedules().getConstraintType() ? _work.getSchedules().getConstraintType().getCode() : null; } @Column(section=SCHEDULE_SECTION, order=1.012f) @FilterByBeanProperty("scheduleTypeFilterProperty") @Filter(className=ScheduleTypeFilter.class) public String getScheduleType() { if(_work.isScheduled()) { if(WorkHelp.isSequentalGates(_work)) return ScheduleTypeFilter.getESGLabel(getLocale()); else if(_work.isManuallyScheduled()) return ScheduleTypeFilter.getManualLabel(getLocale()); else return ScheduleTypeFilter.getAutomaticLabel(getLocale()); } return ScheduleTypeFilter.getNotScheduledLabel(getLocale()); } @ReferencedAsPropertyValue public String getScheduleTypeFilterProperty(){ if(_work.isScheduled()) { if(WorkHelp.isSequentalGates(_work)) return ScheduleTypeFilter.getESGCode(); else if(_work.getSchedules().isManuallyScheduled()) return ScheduleTypeFilter.getManualCode(); else return ScheduleTypeFilter.getAutomaticCode(); } return ScheduleTypeFilter.getNotScheduledCode(); } /* Actual Dates */ @Column(section=SCHEDULE_SECTION,width=Bean.DATE_WIDTH, order=1.013f) public Date getActualStartDate() { return toDayStart( PSDateAdjust.toContext12(_work.getActualStartDate()),getContext().getTimeZone() ); } @Column(section=SCHEDULE_SECTION,width=Bean.DATE_WIDTH, order=1.02f) public Date getActualEndDate() { return toDayStart( PSDateAdjust.toContext12(_work.getActualEndDate()),getContext().getTimeZone() ); } @Column(section=SCHEDULE_SECTION, order=1.03f) public Integer getActualCycleTimeInDays() { return getCycleTimeInDays(ScheduleType.ACTUAL); } @Column(section=SCHEDULE_SECTION, order=1.031f) public Integer getActualDurationInDays() { return getDurationInDays(ScheduleType.ACTUAL); } /* Planned Dates */ @Column(section=SCHEDULE_SECTION,width=Bean.DATE_WIDTH, order=1.04f) public Date getPlannedStartDate() { return toDayStart( PSDateAdjust.toContext12(_work.getPlannedStartDate()),getContext().getTimeZone() ); } @Column(section=SCHEDULE_SECTION,width=Bean.DATE_WIDTH, order=1.05f) public Date getPlannedEndDate() { return toDayStart( PSDateAdjust.toContext12(_work.getPlannedEndDate()),getContext().getTimeZone() ); } @Column(section=SCHEDULE_SECTION, order=1.06f) public Integer getPlannedCycleTimeInDays() { return getCycleTimeInDays(ScheduleType.CONSTRAINT); } @Column(section=SCHEDULE_SECTION, order=1.061f) public Integer getPlannedDurationInDays() { return getDurationInDays(ScheduleType.CONSTRAINT); } /*System dates */ @Column(section=SCHEDULE_SECTION,width=Bean.DATE_WIDTH, order=1.07f) public Date getSystemStartDate() { return toDayStart( PSDateAdjust.toContext12(_work.getSystemStartDate()),getContext().getTimeZone() ); } @Column(section=SCHEDULE_SECTION,width=Bean.DATE_WIDTH, order=1.08f) public Date getSystemEndDate() { return toDayStart( PSDateAdjust.toContext12(_work.getSystemEndDate()),getContext().getTimeZone() ); } @Column(section=SCHEDULE_SECTION, order=1.09f) public Integer getEstimatedCycleTimeInDays() { return getCycleTimeInDays(ScheduleType.SYSTEM); } @Column(section=SCHEDULE_SECTION, order=1.091f) public Integer getEstimatedDurationInDays() { return getDurationInDays(ScheduleType.SYSTEM); } /* Baseline dates */ @Column(section=SCHEDULE_SECTION,width=Bean.DATE_WIDTH, order=1.10f) public Date getBaselineStartDate() { return toDayStart( PSDateAdjust.toContext12(_work.getBaselineStartDate()),getContext().getTimeZone() ); } @Column(section=SCHEDULE_SECTION,width=Bean.DATE_WIDTH, order=1.11f) public Date getBaselineEndDate() { return toDayStart( PSDateAdjust.toContext12(_work.getBaselineEndDate()),getContext().getTimeZone() ); } @Column(section=SCHEDULE_SECTION, order=1.12f) public Integer getBaselineCycleTimeInDays() { return getCycleTimeInDays(ScheduleType.BASELINE); } @Column(section=SCHEDULE_SECTION, order=1.121f) public Integer getBaselineDurationInDays() { return getDurationInDays(ScheduleType.BASELINE); } /* Off track by columns*/ @Column(section=SCHEDULE_SECTION, order = 1.13f) public Integer getOffTrackByInDays() { Duration duration = (Duration) Accessors.getWorkOffTrackBy(getSession().getPSSession()).access(_work); Float amount = null!=duration ? Float.valueOf(duration.getAmount()) : null; return null!=amount && !amount.isNaN() ? Integer.valueOf(amount.intValue()) : null; } protected Integer getOffTrackByInDays(PSDate pEnd, PSDate aEnd) { if (pEnd == null) return null; if (aEnd != null && aEnd.before(pEnd)) return Integer.valueOf(0); if (aEnd == null) aEnd = _work.getContext().getDateService().createToday(); if (aEnd.before(pEnd)) return null; final DateCalculator calc = new DateCalculatorImpl(_work.getCalendar(), _work.getContext().getTimeZone(), _work.getContext().getDateService()); Duration duration = calc.laborDurationInDays(pEnd, aEnd); Float amount = null!=duration ? Float.valueOf(duration.getAmount()) : null; return null!=amount && !amount.isNaN() ? Integer.valueOf(amount.intValue()) : null; } @Column(section=RESOURCE_PLANNING_SECTION,width=Bean.NUMBER_WIDTH,order=9.01f) public Float getUnassignedHours() { return _work.getUnassignedLoad(true); } @Column(section=RESOURCE_PLANNING_SECTION,width=Bean.NUMBER_WIDTH,order=9.02f) public Float getUnassignedPercent() { return _work.getUnassignedLoad(false); } @Column(section=RESOURCE_PLANNING_SECTION,width=Bean.NUMBER_WIDTH,order=9.03f) @RequiredFeatures(Uix.FEATURE_RESOURCE_PLANNING) public Boolean getTracksResources() { return Boolean.valueOf(_work.isUseResourcePlanning()); } @Column(width=Bean.DEFAULT_WIDTH, order=0.21f) public String getSequenceNumber() { return _work.getSequence(); } @Column(width=Bean.SHORT_NAME_WIDTH, order=0.22f) @RequiredFeatures("idnumber") public String getProjectId() { if(WorkHelp.isShowProjectId(_work.getContext(),_work,getSession().getCurrentUser())) { return _work.getPeerId(); } else { return null; } } @Column(width=Bean.DESCRIPTION_WIDTH, order=0.15f) public String getFullPath() { List<Work> list = WorkHelp.getPath(_work); StringBuilder builder = new StringBuilder(); String separator = ""; for(int i = list.size() - 1; i >=0;i--) { Work item = list.get(i); builder.append(separator + (mayView(item) ? item.getName() : getNotEnoughPermissionsText())); separator = WorkHelp.WORK_PATH_SEPARATOR; } return builder.toString(); } @Column(width=Bean.NUMBER_WIDTH, order=0.04f) @Filter(className=WorkPrioritiesFilter.class) public Integer getPriority() { return _work.getAssignedPriority(); } @Column(width=Bean.BOOLEAN_WIDTH, order=0.12f) @Filter(className=ProjectFilter.class) @DeprecatedElement public Boolean getIsProject() { return getIsProject1(); } @Column(width=Bean.BOOLEAN_WIDTH, order=20.02f, section=CONFIG_SECTION) @Filter(className=ProjectFilter.class) public Boolean getIsProject1() { return WorkHelp.isProject(_work); } @Column(width=Bean.BOOLEAN_WIDTH, order=20.03f, section=CONFIG_SECTION) public Boolean getIsIdea() { return WorkHelp.isIdea(_work); } @Column(width=Bean.BOOLEAN_WIDTH, order=20.04f, section=CONFIG_SECTION) public Boolean getIsOrganization() { return WorkHelp.isOrganization(_work); } @Column(width=Bean.BOOLEAN_WIDTH, order=20.05f, section=CONFIG_SECTION) public Boolean getInheritPermissions() { return _work.getInheritPermissions(); } @Column(width=Bean.BOOLEAN_WIDTH, order=20.06f, section=CONFIG_SECTION) public Boolean getInheritCalendar() { return _work.getInheritCalendar(); } @Column(width=Bean.SHORT_NAME_WIDTH, order=20.07f, section=CONFIG_SECTION) @FilterByBeanProperty(value="calendarFilterProperty") @Filter(className=ResourceCalendarFilter.class) public String getCalendar(){ return null != _work.getCalendar() ? _work.getCalendar().getName() : null; } @ReferencedAsPropertyValue public String getCalendarFilterProperty(){ return null != _work.getCalendarId() ? _work.getCalendarId().toString() : null; } @Column(width=Bean.BOOLEAN_WIDTH, order=20.08f, section=CONFIG_SECTION) public Boolean getIsStatusReporting() { return null != _work.getUpdateFrequency() ? !UpdateFrequency.NEVER.equals(_work.getUpdateFrequency()):false; } @Column(width=Bean.SHORT_NAME_WIDTH, order=20.09f, section=CONFIG_SECTION) @FilterByBeanProperty(value="updateFrequencyFilterProperty") @Filter(className=StatusReportFrequencyFilter.class) //postfilter only public String getStatusReportUpdateFrequency(){ return null != _work.getUpdateFrequency() ? _work.getUpdateFrequency().getFreqTerm(getLocale()) : null; } @ReferencedAsPropertyValue public String getUpdateFrequencyFilterProperty(){ return null != _work.getUpdateFrequency() ? StatusReportFrequency.translateUpdateFreq(_work.getUpdateFrequency().getCode()).toString() : null; } @Column(width=Bean.BOOLEAN_WIDTH, order=20.10f, section=CONFIG_SECTION) public Boolean getIsManualScheduleChildren() { return _work.isManualScheduleChildren(); } @Column(width=Bean.BOOLEAN_WIDTH, order=20.12f, section=CONFIG_SECTION) public Boolean getInheritControls() { return _work.getInheritControls();} @Column(width=Bean.BOOLEAN_WIDTH, order=20.13f, section=CONFIG_SECTION) public Boolean getControlCosts() { return _work.getControlCost();} @Column(width=Bean.SYMBOL_WIDTH, order=20.134f) @Filter(className=CurrencyFilter.class) @DeprecatedElement public String getCurrency() { return getCurrency1(); } @Column(width=Bean.SYMBOL_WIDTH, order=20.135f,section=CONFIG_SECTION) @Filter(className=CurrencyFilter.class) public String getCurrency1() { if(null!=_work.getCurrency()) { return _work.getCurrency().getCode(); } else { return null; } } @Column(width=Bean.BOOLEAN_WIDTH, order=20.14f, section=CONFIG_SECTION) public Boolean getInheritPersonalRateRule() { return _work.getInheritPersonalRateRule();} @Column(width=Bean.SHORT_NAME_WIDTH, order=20.155f, section=CONFIG_SECTION) @FilterByBeanProperty(value="rateTableFilterProperty") @Filter(className=RateTableFilter.class) //postfilter only public String getRateTable() { return null != _work.getRateTable() ? _work.getRateTable().getName(getLocale()) : null;} @ReferencedAsPropertyValue public String getRateTableFilterProperty() { return null !=_work.getRateTable() ? _work.getRateTable().getId().toString() : null;} @Column(width=Bean.BOOLEAN_WIDTH, order=20.15f, section=CONFIG_SECTION) public Boolean getUsePersonalRates() { return _work.getUsePersonalRates();} @Column(width=Bean.BOOLEAN_WIDTH, order=20.16f, section=CONFIG_SECTION) public Boolean getUseResourcePlanning() { return _work.isUseResourcePlanning();} @Column(width=Bean.BOOLEAN_WIDTH, order=20.17f, section=CONFIG_SECTION) public Boolean getIncludeTasksToResourcePlan() { return _work.getIncludeTasksToResourcePlan();} @Column(width=Bean.BOOLEAN_WIDTH, order=20.17f, section=CONFIG_SECTION) public Boolean getAllowTimeEntry() { return _work.getAllowTimeEntry();} @Column(width=Bean.SHORT_NAME_WIDTH, order=20.19f, section=CONFIG_SECTION) @FilterByBeanProperty(value="metricTemplatesAttachedFilterProperty") @Filter(className=AttachedMetricTemplatesFilter.class) //postfilter only public String getMetricTemplatesAttached() { final StringBuilder sb = new StringBuilder(); for (PersistentKey id : _work.getMetricIds()) { final MetricInstance metric = (MetricInstance) MetricInstance.get(id, _work.getContext()); if (!metric.isDeleted()) { sb.append(formatListItem(metric.getName(getLocale()), sb.length() ==0)); } } return sb.length() > 0 ?sb.toString() : null; } @ReferencedAsPropertyValue public List<String> getMetricTemplatesAttachedFilterProperty() { final List<String> result = new ArrayList<String>(); for (PersistentKey id : _work.getMetricIds()) { final MetricInstance metric = (MetricInstance) MetricInstance.get(id, _work.getContext()); if (!metric.isDeleted()) { result.add(metric.getTemplateId().toString()); } } return result; } @Column(width=Bean.SHORT_NAME_WIDTH, order=20.20f, section=CONFIG_SECTION) @NoFilter //because there are not defined templates, measures can be defined on the fly... public String getMeasuresAttached() { final List<MeasureInstance> measures = MeasureHelper.getAttachedMeasures(_work, getSession().getPSSession(), Verbs.VIEW); final StringBuilder sb = new StringBuilder(); for(MeasureInstance mi : measures){ sb.append(formatListItem(mi.getName(getLocale()), sb.length() == 0)); } return sb.length() > 0 ? sb.toString() : null; } @Column(width=Bean.BOOLEAN_WIDTH, order=20.21f, section=CONFIG_SECTION) public Boolean getInheritActivityTypesFromParent() { return _work.getInheritActivities(); } @Column(width=Bean.SHORT_NAME_WIDTH, order=20.22f, section=CONFIG_SECTION) @FilterByBeanProperty(value="activityTypesFilterProperty") @Filter(className=ActivityFilter.class) public String getActivityTypes() { final Set<ActivityType> activityTypes = _work.getActivityTypes(); final StringBuilder sb = new StringBuilder(); for (ActivityType activityType : activityTypes) { sb.append(formatListItem(activityType.getName(getLocale()), sb.length() ==0)); } return sb.length() > 0 ?sb.toString() : null; } @ReferencedAsPropertyValue public List<String> getActivityTypesFilterProperty() { final Set<ActivityType> activityTypes = _work.getActivityTypes(); final List<String> result = new ArrayList<String>(); for (ActivityType activityType : activityTypes) { result.add(activityType.getId().toString()); } return result; } @Column(width=Bean.BOOLEAN_WIDTH, order=20.23f, section=CONFIG_SECTION) public Boolean getInheritDefaultActivity() { return _work.getInheritDefaultActivity(); } @Column(width=Bean.SHORT_NAME_WIDTH, order=20.24f, section=CONFIG_SECTION) @FilterByBeanProperty(value="defaultActivityFilterProperty") @Filter(className=ActivityFilter.class) public String getDefaultActivity() { return null!=_work.getDefaultActivity() ? _work.getDefaultActivity().getName(getLocale()) : null; } @ReferencedAsPropertyValue public String getDefaultActivityFilterProperty() { return null!=_work.getDefaultActivity() ? _work.getDefaultActivity().getId().toString() : null; } /** * * @return Number of descendant projects (including independent work) */ @Column(section=HIERARCHY_SECTION,width=Bean.DEFAULT_WIDTH,order=2.011f) public Integer getNumberOfDescendantProjectsIncludingIndependentWork() { return ((List)getPropertyValueForInternalUse("descendantProjectsIncludingIndependentWork")).size(); } @ReferencedAsPropertyValue public ReferencedWork getReferencedWork() { return new ReferencedWork(_work,getSession().getPSSession()); } @Column(section=HIERARCHY_SECTION,width=Bean.DESCRIPTION_WIDTH,order=2.02f) @Filter(className=WorkReferencesFilter.class) @FilterByBeanProperty(value="referenceToFilterProperty") public String getReferenceToList() { StringBuilder builder = new StringBuilder(); for(PSObject psObject : ((ReferencedWork)getPropertyValueForInternalUse("referencedWork")).getRefTo()) { builder.append(formatListItem((mayView(psObject) ? psObject.getName() : getNotEnoughPermissionsText()),builder.length()==0)); } return builder.toString(); } @ReferencedAsPropertyValue public List<String> getReferenceToFilterProperty() { List<String> result = new ArrayList<String>(); for(PSObject psObject : getReferencedWork().getRefTo()) { if(mayView(psObject)){ result.add(psObject.getId().toString()); } } return result; } @Column(section=HIERARCHY_SECTION,width=Bean.DESCRIPTION_WIDTH,order=2.03f) @Filter(className=WorkReferencesFilter.class) @FilterByBeanProperty(value="referenceFromFilterProperty") public String getReferenceFromList() { StringBuilder builder = new StringBuilder(); for(PSObject psObject : ((ReferencedWork)getPropertyValueForInternalUse("referencedWork")).getRefBy()) { builder.append(formatListItem((mayView(psObject) ? psObject.getName() : getNotEnoughPermissionsText()),builder.length()==0)); } return builder.toString(); } @ReferencedAsPropertyValue public List<String> getReferenceFromFilterProperty() { List<String> result = new ArrayList<String>(); for(PSObject psObject : getReferencedWork().getRefBy()) { if(mayView(psObject)){ result.add(psObject.getId().toString()); } } return result; } /** * * @return descendant projects (including independent work) */ @ReferencedAsPropertyValue public List<Work> getDescendantProjectsIncludingIndependentWork() { return _work.getChildrenFromFilteredHierarchyBranches(null); } /** * * @return descendant projects (dependent work) */ protected List<Work> getDependentProjects() { // TODO use cache? return _work.getChildrenFromFilteredHierarchyBranches( new FilterChain() { protected boolean filterImpl(Object o) { return !WorkHelp.isProject((PSObject)o); } } ); } /** * * @return */ protected List<WorkBean> getDependentProjectBeans() { List<WorkBean> list = new ArrayList<WorkBean>(); for(Work work: getDependentProjects()) { list.add((WorkBean) get(WorkBean.class,work.getId())); } return list; } /** * * @return Number of descendant projects (dependent work) */ @Column(section=HIERARCHY_SECTION,width=Bean.DEFAULT_WIDTH,order=2.04f) public Integer getNumberOfDependentProjects() { return getDependentProjects().size(); } @RelatedEntity @SQLRelationship(type=ps5.reports.pointandclick.data.SQLRelationship.OneToOneRelationship.class) public GenericWorkBean getParentBean() { return _work.hasParent() ? (GenericWorkBean) get(GenericWorkBean.class,((Work)_work.getParent()).getId()) : null; } @Column(width=Bean.LONG_NAME_WIDTH, order=17) @OptionalSortByBeanProperty("parentSortableUid") @LinkUrlProperty("parentUrl") @Filter(className=WorksFilter.class) @FilterByBeanProperty("parentFilterProperty") public String getParent() { WorkBean topProject = getParentBean(); return null!=topProject ? topProject.getName() : null; } @ReferencedAsPropertyValue public String getParentSortableUid() { WorkBean parent = getParentBean(); return null!=parent ? parent.getSortableUid() : null; } @ReferencedAsPropertyValue public String getParentUrl() { WorkBean parent = getParentBean(); return null!=parent ? parent.getUrl() : null; } @ReferencedAsPropertyValue public String getParentFilterProperty(){ WorkBean parent = getParentBean(); return null!=parent ? parent.getWork().getId().toString(): null; } @Column(width=Bean.LONG_NAME_WIDTH,order=17.5f) @Filter(className=WorksFilter.class) @FilterByBeanProperty(value="programFilterProperty") @LinkUrlProperty("programListUrl") @ContextSwitch("isProgramEnabled") public String getProgramList() { StringBuilder builder = new StringBuilder(); for(Work work : getPrograms()) { builder.append(formatListItem((mayView(work) ? work.getName(getLocale()) : getNotEnoughPermissionsText()),builder.length()==0)); } return builder.toString(); } @ReferencedAsPropertyValue public String getProgramListUrl() { List<Work> programs = getPrograms(); return programs.isEmpty() ? null : programs.size() == 1 ? programs.get(0).getEntryUrl() : getUrl(); } @ReferencedAsPropertyValue public List<String> getProgramFilterProperty() { List<String> result = new ArrayList<String>(); for (Work work : getPrograms()) { if (mayView(work)) { result.add(work.getId().toString()); } } return result; } /** * internal * * @return the list of programs for this work item */ private List<Work> getPrograms() { return ProgramHelp.getParents(getWork()).toList(getSession().getPSSession()); } @Column(width=Bean.LONG_NAME_WIDTH, order=18) @OptionalSortByBeanProperty("phaseSortableUid") @LinkUrlProperty("phaseUrl") @Filter(className=ProcessPhasesWithoutCompletedFilter.class) @FilterByBeanProperty("phaseFilterProperty") public String getPhase() { GateGeneralColumnsBean gate = getGateBean(); return null!=gate ? gate.getName() : null; } @ReferencedAsPropertyValue public String getPhaseSortableUid() { GateGeneralColumnsBean gate = getGateBean(); return null!=gate ? gate.getSortableUid() : null; } @ReferencedAsPropertyValue public String getPhaseUrl() { GateGeneralColumnsBean gate = getGateBean(); return null!=gate ? gate.getUrl() : null; } @ReferencedAsPropertyValue public String getPhaseFilterProperty() { GateGeneralColumnsBean gate = getGateBean(); return null!=gate && null != gate.getGate() ? gate.getGate().getWork().getPhaseTag().getId().toString() : null; } /** * @return First work above the project for which is_project = yes */ @RelatedEntity //need special sql relationship @SQLRelationship(type=MasterProjectSQLRelationship.class) public GenericWorkBean getMasterProjectBean() { Work masterProject = WorkHelp.getMasterProject(_work); return null!=masterProject ? (GenericWorkBean) get(GenericWorkBean.class,masterProject.getId()) : null; } /** * * @return the higher project in the hierarchy */ @RelatedEntity //need special sql relationship @SQLRelationship(type=TopProjectSQLRelationship.class) public GenericWorkBean getTopProjectBean() { Work topProject = WorkHelp.getTopProject(_work); return null!=topProject && WorkHelp.isProject(topProject) ? (GenericWorkBean) get(GenericWorkBean.class,topProject.getId()) : null; } @Column(width=Bean.ENTITY_NAME_WIDTH, order=6) @OptionalSortByBeanProperty("ownerSortableUid") @LinkUrlProperty("ownerUrl") @Filter(className=SingleUserFilter.class) @FilterByBeanProperty("ownerFilterProperty") public String getOwner() { UserBean owner = getOwnerBean(); return null!=owner ? owner.getName() : null; } @ReferencedAsPropertyValue public String getOwnerUrl() { UserBean owner = getOwnerBean(); return null!=owner ? owner.getUrl() : null; } @ReferencedAsPropertyValue public String getOwnerSortableUid() { UserBean owner = getOwnerBean(); return null!=owner ? owner.getSortableUid() : null; } @ReferencedAsPropertyValue public String getOwnerFilterProperty(){ UserBean owner = getOwnerBean(); return null!=owner ? owner.getUser().getId().toString() : null; } /** * @see getTopProjectBean() */ @Column(width=Bean.LONG_NAME_WIDTH, order=19) @OptionalSortByBeanProperty("topProjectSortableUid") @LinkUrlProperty("topProjectUrl") @Filter(className=TopProjectsFilter.class) @FilterByBeanProperty("topProjectFilterProperty") public String getTopProject() { WorkBean topProject = getTopProjectBean(); if(null!=topProject) { if(!topProject.mayView()) { return getNotEnoughPermissionsText(); } else { return topProject.getName(); } } else { return null; } } @ReferencedAsPropertyValue public String getTopProjectSortableUid() { WorkBean topProject = getTopProjectBean(); if(null!=topProject) { if(!topProject.mayView()) { return null; } else { return topProject.getSortableUid(); } } else { return null; } } @ReferencedAsPropertyValue public String getTopProjectUrl() { WorkBean topProject = getTopProjectBean(); if(null!=topProject) { if(!topProject.mayView()) { return null; } else { return topProject.getUrl(); } } else { return null; } } @ReferencedAsPropertyValue public String getTopProjectFilterProperty() { WorkBean topProject = getTopProjectBean(); if(null!=topProject) { if(!topProject.mayView()) { return null; } else { return topProject.getWork().getId().toString(); } } else { return null; } } /** * @see getMasterProjectBean() */ @Column(width=Bean.LONG_NAME_WIDTH, order=18) @OptionalSortByBeanProperty("masterProjectSortableUid") @LinkUrlProperty("masterProjectUrl") @Filter(className=MasterProjectsFilter.class) @FilterByBeanProperty("masterProjectFilterProperty") public String getMasterProject() { WorkBean masterProject = getMasterProjectBean(); if(null!=masterProject) { if(!masterProject.mayView()) { return getNotEnoughPermissionsText(); } else { return masterProject.getName(); } } else { return null; } } @ReferencedAsPropertyValue public String getMasterProjectSortableUid() { WorkBean masterProject = getMasterProjectBean(); if(null!=masterProject) { if(!masterProject.mayView()) { return null; } else { return masterProject.getSortableUid(); } } else { return null; } } @ReferencedAsPropertyValue public String getMasterProjectUrl() { WorkBean masterProject = getMasterProjectBean(); if(null!=masterProject) { if(!masterProject.mayView()) { return null; } else { return masterProject.getUrl(); } } else { return null; } } @ReferencedAsPropertyValue public String getMasterProjectFilterProperty(){ WorkBean masterProject = getMasterProjectBean(); if(null!=masterProject) { if(!masterProject.mayView()) { return null; } else { return masterProject.getWork().getId().toString(); } } else { return null; } } @RelatedEntity @SQLRelationship(type=ps5.reports.pointandclick.data.SQLRelationship.OneToOneRelationship.class) public UserBean getOwnerBean() { return null!=_work.getOwnerId() ? (UserBean) get(UserBean.class,_work.getOwnerId()) : null; } /** * try to call this as property value for performance * @return */ @ReferencedAsPropertyValue public List<DiscussionItemBean> getDiscussionItems() { final CIFilter filter = DiscussionItem.createRootFilter(); return DiscussionItemHelp.getDiscussionItems(getSession().getCurrentUser(),_work,filter,null,false,true); } /** * try to call this as a property value for better performance * * for cache reasons, must declare with another name for getting discussionitems list with descendentworks * (using a parameter will detect that cached version is the same!) * @return */ @ReferencedAsPropertyValue public List<DiscussionItemBean> getDiscussionItemsIncludeDescendants() { final CIFilter filter = DiscussionItem.createRootFilter(); return DiscussionItemHelp.getDiscussionItems(getSession().getCurrentUser(),_work,filter,null,true,true); } /** * try to call this as a property value for better performance * * @return */ @ReferencedAsPropertyValue public List<Risk> getRisks() { Set roots = Collections.singleton(_work); List<Risk> results = Risk.findBySearch("%",null, roots, Risk.TYPE.getCode(), Risk.createTitleComparator(true)); return null!=results ? results : new ArrayList<Risk>(); } /** * try to call this as a property value for better performance * * for cache reasons, must declare with another name for getting risks list with descendant works * (using a parameter will detect that cached version is the same!) * @return */ @ReferencedAsPropertyValue public List<Risk> getRisksIncludeDescendants() { Set<Discussion> roots = getAllLevels(_work); List<Risk> results = null; if(!roots.isEmpty()) { results = Risk.findBySearch("%",null, roots, Risk.TYPE.getCode(), Risk.createTitleComparator(true)); } return null!=results ? results : new ArrayList<Risk>(); } /** * * @param work * @return */ protected Set<Discussion> getAllLevels(Work work) { Set<Discussion> roots = new HashSet<Discussion>(); if (!WorkHelp.isCheckpoint(work)) roots.add(work); List<Work> children = work.getFilteredChildren(Work.createVisibilityFilter(getSession().getPSSession())); for(Work child: children) roots.addAll(getAllLevels(child)); return roots; } /** * * @return */ protected List<DiscussionItemBean> getIssues() { List<DiscussionItemBean> issues = new ArrayList<DiscussionItemBean>(); for(DiscussionItemBean issue: ((List<DiscussionItemBean>)getPropertyValueForInternalUse("discussionItems"))) { if(DiscussionItemHelp.getIsIssue(issue.getItem())) { issues.add(issue); } } return issues; } /** * for cache reasons, must declare with another name for getting issues list with descendentworks * (using a parameter will detect that cached version is the same!) * @return */ protected List<DiscussionItemBean> getIssuesIncludeDescendants() { List<DiscussionItemBean> issues = new ArrayList<DiscussionItemBean>(); for(DiscussionItemBean issue: ((List<DiscussionItemBean>) getPropertyValueForInternalUse("discussionItemsIncludeDescendants"))) { if(DiscussionItemHelp.getIsIssue(issue.getItem())) { issues.add(issue); } } return issues; } /** * * @return */ protected List<DiscussionItemBean> getOpenIssues() { List<DiscussionItemBean> open = new ArrayList<DiscussionItemBean>(); for(DiscussionItemBean issue: getIssues()) { if(issue.getItem().isOpen()) { open.add(issue); } } return open; } /** * for cache reasons, must declare with another name for getting open issues list with descendant works * (using a parameter will detect that cached version is the same!) * @return */ protected List<DiscussionItemBean> getOpenIssuesIncludeDescendants() { List<DiscussionItemBean> open = new ArrayList<DiscussionItemBean>(); for(DiscussionItemBean issue: getIssuesIncludeDescendants()) { if(issue.getItem().isOpen()) { open.add(issue); } } return open; } /** * * @return */ protected List<DiscussionItemBean> getClosedIssues() { List<DiscussionItemBean> open = new ArrayList<DiscussionItemBean>(); for(DiscussionItemBean issue: getIssues()) { if(issue.isClosed()) { open.add(issue); } } return open; } /** * for cache reasons, must declare with another name for getting closed Issues list with descendant works * (using a parameter will detect that cached version is the same!) * @return */ protected List<DiscussionItemBean> getClosedIssuesIncludeDescendants() { List<DiscussionItemBean> open = new ArrayList<DiscussionItemBean>(); for(DiscussionItemBean issue: getIssuesIncludeDescendants()) { if(issue.isClosed()) { open.add(issue); } } return open; } /** * * @return */ protected List<Risk> getOpenRisks() { List<Risk> open = new ArrayList<Risk>(); for(Risk risk: (List<Risk>)getPropertyValueForInternalUse("risks")) { if(risk.isOpen()) { open.add(risk); } } return open; } /** * * @return */ protected List<Risk> getClosedRisks() { List<Risk> open = new ArrayList<Risk>(); for(Risk risk: (List<Risk>)getPropertyValueForInternalUse("risks")) { if(risk.isClosed()) { open.add(risk); } } return open; } /** * for cache reasons, must declare with another name for getting open risks list with descendant works * (using a parameter will detect that cached version is the same!) * @return */ protected List<Risk> getOpenRisksIncludeDescendants() { List<Risk> open = new ArrayList<Risk>(); for(Risk risk: (List<Risk>) getPropertyValueForInternalUse("risksIncludeDescendants")) { if(risk.isOpen()) { open.add(risk); } } return open; } /** * for cache reasons, must declare with another name for getting closed risks list with descendant works * (using a parameter will detect that cached version is the same!) * @return */ protected List<Risk> getClosedRisksIncludeDescendents() { List<Risk> open = new ArrayList<Risk>(); for(Risk risk: (List<Risk>) getPropertyValueForInternalUse("risksIncludeDescendants")) { if(risk.isClosed()) { open.add(risk); } } return open; } @Column(section=DISCUSSIONS_SECTION,width=Bean.NUMBER_WIDTH,order=4.01f) public Integer getDiscussionCount() { return ((List)getPropertyValueForInternalUse("discussionItems")).size(); } /** * @return Discussions on this project and all dependent work */ @Column(section=DISCUSSIONS_SECTION,width=Bean.DEFAULT_WIDTH,order=4.02f) public Integer getDependentProjectDiscussionCount() { return ((List<DiscussionItemBean>) getPropertyValueForInternalUse("discussionItemsIncludeDescendants")).size() - getDiscussionCount(); } @Column(section=ISSUES_SECTION,width=Bean.NUMBER_WIDTH,order=3.01f) @RequiredFeatures(Uix.FEATURE_ISSUES) public Integer getIssueCount() { return getIssues().size(); } /** * @return Issues on this project and all dependent work */ @Column(section=ISSUES_SECTION,width=Bean.DEFAULT_WIDTH,order=3.02f) @RequiredFeatures(Uix.FEATURE_ISSUES) public Integer getDependentProjectIssueCount() { return getIssuesIncludeDescendants().size() - getIssueCount(); } @Column(section=ISSUES_SECTION,width=Bean.NUMBER_WIDTH,order=3.03f) @RequiredFeatures(Uix.FEATURE_ISSUES) public Integer getOpenIssueCount() { return getOpenIssues().size(); } /** * @return Open issues on this project and all dependent work */ @Column(section=ISSUES_SECTION,width=Bean.DEFAULT_WIDTH,order=3.04f) @RequiredFeatures(Uix.FEATURE_ISSUES) public Integer getDependentProjectOpenIssueCount() { return getOpenIssuesIncludeDescendants().size() - getOpenIssueCount(); } @Column(section=ISSUES_SECTION,width=Bean.NUMBER_WIDTH,order=3.05f) @RequiredFeatures(Uix.FEATURE_ISSUES) public Integer getClosedIssueCount() { return getClosedIssues().size(); } /** * @return Closed issues on this project and all dependent work */ @Column(section=ISSUES_SECTION,width=Bean.DEFAULT_WIDTH,order=3.06f) @RequiredFeatures(Uix.FEATURE_ISSUES) public Integer getDependentProjectClosedIssueCount() { return getClosedIssuesIncludeDescendants().size() - getClosedIssueCount(); } @Column(section=RISKS_SECTION,width=Bean.NUMBER_WIDTH,order=5.01f) @RequiredFeatures(Uix.FEATURE_RISKS) public Integer getClosedRiskCount() { return getClosedRisks().size(); } /** * @return Closed risks on this project and all dependent work */ @Column(section=RISKS_SECTION,width=Bean.DEFAULT_WIDTH,order=5.02f) @RequiredFeatures(Uix.FEATURE_RISKS) public Integer getDependentProjectClosedRiskCount() { return getClosedRisksIncludeDescendents().size() - getClosedRiskCount(); } @Column(section=RISKS_SECTION,width=Bean.NUMBER_WIDTH,order=5.03f) @RequiredFeatures(Uix.FEATURE_RISKS) public Integer getOpenRiskCount() { return getOpenRisks().size(); } /** * @return Open risks on this project and all dependent work */ @Column(section=RISKS_SECTION,width=Bean.DEFAULT_WIDTH,order=5.04f) @RequiredFeatures(Uix.FEATURE_RISKS) public Integer getDependentProjectOpenRiskCount() { return getOpenRisksIncludeDescendants().size() - getOpenRiskCount(); } @Column(section=RISKS_SECTION,order=5.05f) @RequiredFeatures(Uix.FEATURE_RISKS) public Integer getRiskCount() { return ((List)getPropertyValueForInternalUse("risks")).size(); } /** * @return risks on this project and all dependent work */ @Column(section=RISKS_SECTION,width=Bean.DEFAULT_WIDTH,order=5.06f) @RequiredFeatures(Uix.FEATURE_RISKS) public Integer getDependentProjectRiskCount() { return ((List<Risk>) getPropertyValueForInternalUse("risksIncludeDescendants")).size() - getRiskCount(); } /** * * @return */ protected List<VersionableDocument> getDocuments() { return _work.getDocuments(); } @Column(section=DOCUMENTS_SECTION,width=Bean.NUMBER_WIDTH,order=7.01f) public Integer getDocumentCount() { return getDocuments().size(); } /** * @return documents on this project and all dependent work */ @Column(section=DOCUMENTS_SECTION,width=Bean.DEFAULT_WIDTH,order=7.02f) public Integer getDependentProjectDocumentCount() { int count = 0; for(WorkBean work:getDependentProjectBeans()) { count+=work.getDocumentCount(); } return count; } /** * * @param scheduleType * @return */ protected Integer getCycleTimeInDays(ScheduleType scheduleType) { Duration duration = _work.getCycleTime(scheduleType); Float amount = null!=duration ? Float.valueOf(duration.getAmount()) : null; return null!=amount && !amount.isNaN() ? Integer.valueOf(amount.intValue()) : null; } protected Integer getDurationInDays(ScheduleType scheduleType) { final Duration duration = scheduleType.getLaborTime(_work.getSchedules()); final Float amount = null!=duration ? Float.valueOf(duration.getAmount()) : null; if(null != amount && !amount.isNaN()){ final Integer value = Integer.valueOf(amount.intValue()); if(value > 0) return value; } return null; } @Column(width=Bean.NUMBER_WIDTH,relatedColumns={@Column.RelatedColumn(value="percentCompleteSymbol")}, order=3) public Integer getPercentComplete() { if(!WorkHelp.hidePercentComplete(_work)) { Integer result = _work.getPercentComplete(); return null!=result ? result : Integer.valueOf(0); } else { return null; } } @RelatedColumn(type=RelatedColumn.RelatedColumnType.PercentSymbolColumn) @SelectedByDefault public String getPercentCompleteSymbol(){ if(null!=getPercentComplete()) { return "%"; } else { return null; } } @Column(section=IDEAS_SECTION,width=Bean.TYPE_WIDTH,order=8.01f) @Filter(className=IdeaApprovalStatusFilter.class) @FilterByBeanProperty("ideaStatusFilterProperty") public String getIdeaStatus() { return WorkHelp.isIdea(_work) ? IdeaHelp.getIdeaStatus(_work).getName(getLocale()) : null; } @ReferencedAsPropertyValue public String getIdeaStatusFilterProperty() { return IdeaApprovalStatusFilter.getFilterProperty(_work); } @RelatedEntity(inheritsOptionLimitations=true) @SQLRelationship(type=StatusReportBean.LastStatusReportSQLRelationship.class) public StatusReportBean getMostRecentStatusReport() { return (StatusReportBean) get(StatusReportBean.class, _work.getId()); } /** * * @return */ @AddedByDefault @ReferencedUsingReflection @SQLRelationship(type=ps5.reports.pointandclick.data.SQLRelationship.OneToOneRelationship.class) public static DynamicProperties getTags() { return new WorkTagDynamicProperties(); } @RequiredFeatures(Uix.FEATURE_MEASURE) @ReferencedUsingReflection public static DynamicProperties getCurrentMeasureRawValues() { return new MeasureByProjectDynamicProperties("raw"); } @RequiredFeatures(Uix.FEATURE_MEASURE) @ReferencedUsingReflection public static DynamicProperties getCurrentMeasureFormattedValues() { return new MeasureByProjectDynamicProperties("rawFmt"); } @RequiredFeatures(Uix.FEATURE_MEASURE) @ReferencedUsingReflection public static DynamicProperties getCurrentMeasureValueDates() { return new MeasureByProjectDynamicProperties("valueDate"); } /** * * @return */ @AddedByDefault @SQLRelationship(type=ps5.reports.pointandclick.data.SQLRelationship.OneToOneRelationship.class) public static DynamicProperties getCustomFields() { return new WorkCustomFieldDynamicProperties(); } public Work getWork() { return _work; } /** * all work roles columns * @return */ @AddedByDefault @SQLRelationship(type=ps5.reports.pointandclick.data.SQLRelationship.OneToOneRelationship.class) public static DynamicProperties getWorkRoles() { return new WorkRolesDynamicProperties(); } public static class MasterProjectSQLRelationship extends ps5.reports.pointandclick.data.SQLRelationship{ @Override public void applyJoinToQuery(SqlSelectQuery query, String withDBTable, List<DBColumnDefinition> withDBColumns, List<DBColumnDefinition> onSourceDBColumns, boolean useLeftJoin) { final String innerTableAlias = "mp" + getInnerTableAliasSubfix(); //issue#89859 Avoid applying join unnecessarily if already added, otherwise causes to clear out previous column filters queries added. if (query.hasTable(innerTableAlias)) { // already added, so ignore return; } // add each sql column into join criteria. (only those in @DBTable // annotation are used) final CompositeCriteria criteria = Criteria.and(); final CompositeCriteria lastCriteria = Criteria.and(); //add inner join to fn_MasterProjects() and extract master project id lastCriteria.add(Criteria.equalColumn(onSourceDBColumns.get(0).getCompositeName(), innerTableAlias + ".work_id")); //then match master_project_id with workbean criteria.add(Criteria.equalColumn(withDBColumns.get(0).getCompositeName(), innerTableAlias + ".master_project_id")); //if allow nulls, then status reports columns can be null, otherwise, restrict output to 'only with status reports' if (!useLeftJoin) { query.addRightInnerJoin(onSourceDBColumns.get(0).getTable(),"PaC_Works_Master_And_Top_Project", innerTableAlias, lastCriteria); query.addRightInnerJoin(innerTableAlias , withDBTable, withDBColumns.get(0).getTable(), criteria); } else { query.addLeftOuterJoin(onSourceDBColumns.get(0).getTable(),"PaC_Works_Master_And_Top_Project", innerTableAlias, lastCriteria); query.addLeftOuterJoin(innerTableAlias , withDBTable, withDBColumns.get(0).getTable(), criteria); } } @Override public void applyJoinToQuery(SqlSelectQuery query, String withDBTable, String withDBTableAlias, String toDBTable, Criteria customCriteria, boolean useLeftJoin) { //do nothing! throw new PointAndClickRuntimeException("Unsupported functionality!"); } protected String getInnerTableAliasSubfix() { return ("t" + hashCode()).replace("-", "_"); } } public static class TopProjectSQLRelationship extends ps5.reports.pointandclick.data.SQLRelationship{ @Override public void applyJoinToQuery(final SqlSelectQuery query, String withDBTable, List<DBColumnDefinition> withDBColumns, List<DBColumnDefinition> onSourceDBColumns, boolean useLeftJoin) { final String innerTableAlias = "mp" + getInnerTableAliasSubfix(); //issue#89859 Avoid applying join unnecessarily if already added, otherwise causes to clear out previous column filters queries added. if (query.hasTable(innerTableAlias)) { // already added, so ignore return; } // add each sql column into join criteria. (only those in @DBTable // annotation are used) final CompositeCriteria criteria = Criteria.and(); final CompositeCriteria lastCriteria = Criteria.and(); //add inner join to fn_TopProjects() and extract master project id lastCriteria.add(Criteria.equalColumn(onSourceDBColumns.get(0).getCompositeName(), innerTableAlias + ".work_id")); //then match master_project_id with workbean criteria.add(Criteria.equalColumn(withDBColumns.get(0).getCompositeName(), innerTableAlias + ".top_project_id")); //if allow nulls, then status reports columns can be null, otherwise, restrict output to 'only with status reports' if (!useLeftJoin) { query.addRightInnerJoin(onSourceDBColumns.get(0).getTable(),"PaC_Works_Master_And_Top_Project", innerTableAlias, lastCriteria); query.addRightInnerJoin(innerTableAlias , withDBTable, withDBColumns.get(0).getTable(), criteria); } else { query.addLeftOuterJoin(onSourceDBColumns.get(0).getTable(),"PaC_Works_Master_And_Top_Project", innerTableAlias, lastCriteria); query.addLeftOuterJoin(innerTableAlias , withDBTable, withDBColumns.get(0).getTable(), criteria); } } @Override public void applyJoinToQuery(SqlSelectQuery query, String withDBTable, String withDBTableAlias, String toDBTable, Criteria customCriteria, boolean useLeftJoin) { //do nothing! throw new PointAndClickRuntimeException("Unsupported functionality!"); } protected String getInnerTableAliasSubfix() { return ("t" + hashCode()).replace("-", "_"); } } public Integer getDurationInHours() { Duration duration = _work.getDurationInHours(true, getContext().getCalendarService().getDefaultCalendar()); return null!=duration? Integer.valueOf(Float.valueOf(duration.toFloat()).intValue()) : null; } @Column(section=BUDGET_SECTION,relatedColumns={@Column.RelatedColumn(value="budgetCurrencySymbol")},order=9.01f) @RequiredPermissions(Verbs.VIEW_COST) @CurrencyConversionAttribute("budgetCurrencyConversionAttribute") public Double getCostBudgetTotal(){ return _work.getBudgetedCostAmount(); } @Column(section=BUDGET_SECTION,relatedColumns={@Column.RelatedColumn(value="baselineCurrencySymbol")},order=9.02f) @RequiredPermissions(Verbs.VIEW_COST) @CurrencyConversionAttribute("baselineCurrencyConversionAttribute") public Double getCostBaselineTotal(){ return _work.getBaselineBudgetAmount(); } @Column(section=BUDGET_SECTION,relatedColumns={@Column.RelatedColumn(value="estimateCurrencySymbol")},order=9.03f) @RequiredPermissions(Verbs.VIEW_COST) @CurrencyConversionAttribute("estimateCurrencyConversionAttribute") public Double getCostEstimateTotal(){ return null != _work.getEstimatedCost(false) ? _work.getEstimatedCost(false).getAmount() : null; } @Column(section=BUDGET_SECTION,relatedColumns={@Column.RelatedColumn(value="actualCurrencySymbol")},order=9.04f) @RequiredPermissions(Verbs.VIEW_COST) @CurrencyConversionAttribute("actualCurrencyConversionAttribute") public Double getCostActualTotal(){ return null != _work.getActualCost(false) ? _work.getActualCost(false).getAmount() : null; } @Column(section=BUDGET_SECTION,relatedColumns={@Column.RelatedColumn(value="estimatePercentSymbol")},order=9.05f) @RequiredPermissions(Verbs.VIEW_COST) public Integer getCostEstimatedBudgetPercent(){ return calculatePercent(getCostBudgetTotal(),getCostEstimateTotal()); } @Column(section=BUDGET_SECTION,relatedColumns={@Column.RelatedColumn(value="estimatePercentSymbol")},order=9.06f) @RequiredPermissions(Verbs.VIEW_COST) public Integer getCostEstimatedBaselinePercent(){ return calculatePercent(getCostBaselineTotal(),getCostEstimateTotal()); } @Column(section=BUDGET_SECTION,relatedColumns={@Column.RelatedColumn(value="actualPercentSymbol")},order=9.07f) @RequiredPermissions(Verbs.VIEW_COST) public Integer getCostActualBudgetPercent(){ return calculatePercent(getCostBudgetTotal(),getCostActualTotal()); } @Column(section=BUDGET_SECTION,relatedColumns={@Column.RelatedColumn(value="actualPercentSymbol")},order=9.08f) @RequiredPermissions(Verbs.VIEW_COST) public Integer getCostActualBaselinePercent(){ return calculatePercent(getCostBaselineTotal(),getCostActualTotal()); } private static Integer calculatePercent(Double fixedTotal, Double value){ Integer estPercent = null; if (fixedTotal != null && !fixedTotal.isNaN() && value != null && !value.isNaN()) estPercent = (int) Math.round(100 * value.doubleValue() / fixedTotal.doubleValue()); return estPercent; } /* * * related columns for costs columns */ @RelatedColumn(type=RelatedColumn.RelatedColumnType.PercentSymbolColumn) @SelectedByDefault public String getEstimatePercentSymbol(){ return getPercentSymbol(getCostEstimateTotal()); } @RelatedColumn(type=RelatedColumn.RelatedColumnType.PercentSymbolColumn) @SelectedByDefault public String getActualPercentSymbol(){ return getPercentSymbol(getCostActualTotal()); } @RelatedColumn(type=RelatedColumn.RelatedColumnType.CurrencySymbolColumn,position=RelatedColumn.Position.Left) @SelectedByDefault public String getEstimateCurrencySymbol(){ return getCurrencySymbol(getCostEstimateTotal()); } @RelatedColumn(type=RelatedColumn.RelatedColumnType.CurrencySymbolColumn,position=RelatedColumn.Position.Left) @SelectedByDefault public String getActualCurrencySymbol(){ return getCurrencySymbol(getCostActualTotal()); } @RelatedColumn(type=RelatedColumn.RelatedColumnType.CurrencySymbolColumn,position=RelatedColumn.Position.Left) @SelectedByDefault public String getBudgetCurrencySymbol(){ return getCurrencySymbol(getCostBudgetTotal()); } @RelatedColumn(type=RelatedColumn.RelatedColumnType.CurrencySymbolColumn,position=RelatedColumn.Position.Left) @SelectedByDefault public String getBaselineCurrencySymbol(){ return getCurrencySymbol(getCostBaselineTotal()); } @ReferencedAsPropertyValue public CurrencyConversionAttributeData getBudgetCurrencyConversionAttribute(){ return getCurrencyConversionAttribute(getCostBudgetTotal()); } @ReferencedAsPropertyValue public CurrencyConversionAttributeData getBaselineCurrencyConversionAttribute(){ return getCurrencyConversionAttribute(getCostBaselineTotal()); } @ReferencedAsPropertyValue public CurrencyConversionAttributeData getActualCurrencyConversionAttribute(){ return getWorkCostCurrencyConversionAttributeData(getCostActualTotal(),false); } @ReferencedAsPropertyValue public CurrencyConversionAttributeData getEstimateCurrencyConversionAttribute(){ return getWorkCostCurrencyConversionAttributeData(getCostEstimateTotal(),true); } private String getCurrencySymbol(Double value){ if(null!=value && null!=_work.getCurrency()) { return _work.getCurrency().getSymbol(); } return null; } private WorkCostCurrencyConversionAttributeData getWorkCostCurrencyConversionAttributeData(Number value, boolean isEstimate){ if(null != value && null!=_work.getCurrency() ) { final Calendar currDate = Calendar.getInstance(getContext().getTimeZone()); final WorkCostCurrencyConversionAttributeData currencyConversionAttribute = new WorkCostCurrencyConversionAttributeData(_work.getCurrency().getCode(),currDate.getTime(), _work.getId(), isEstimate); return currencyConversionAttribute; } return null; } private CurrencyConversionAttributeData getCurrencyConversionAttribute(Number value){ if(null != value && null!=_work.getCurrency() ) { final Calendar currDate = Calendar.getInstance(getContext().getTimeZone()); final CurrencyConversionAttributeData currencyConversionAttribute = new CurrencyConversionAttributeData(_work.getCurrency().getCode(),currDate.getTime()); return currencyConversionAttribute; } return null; } private String getPercentSymbol(Double value){ if(null!=value) { return "%"; } else { return null; } } @Column(width = Bean.BOOLEAN_WIDTH, order = 23) public Boolean getIsArchived() { return getPSObject().isArchived(); } /** * work up the tree until you hit a gate or work where is_project= yes, * or if current work is a gate return itself as a GateGeneralColumnsBean (Issue#86340.1.1.1.1.1.1) * Hitting the gate gets you the information you need. Hitting work where * is_project=yes means that source work is a descendant of a non-gated * project. Using this logic, if the source work is is_project=yes, then * there is no gate. * * @return */ @RelatedEntity public GateGeneralColumnsBean getGateBean() { //Issue#86340.1.1.1.1.1.1 Include itself if work is a gate. if (WorkHelp.isCheckpoint(_work)) { Checkpoint gate = (Checkpoint) _work; return (GateGeneralColumnsBean) get(GateGeneralColumnsBean.class,gate.getGateNumber(),gate.getProcess().getId(),gate.getTollgate().getId()); } Work parent = getWork().getParentWork(); while (null != parent) { if (WorkHelp.isCheckpoint(parent)) { Checkpoint gate = (Checkpoint) parent; return (GateGeneralColumnsBean) get(GateGeneralColumnsBean.class,gate.getGateNumber(),gate.getProcess().getId(),gate.getTollgate().getId()); } if(WorkHelp.isProject(parent)) { // If master project for source work is not gated, the gate // value is null return null; } parent = parent.getParentWork(); } return null; } @RelatedEntity public WorkHoursBean getWorkHoursBean() { return (WorkHoursBean) get(WorkHoursBean.class,getWork().getId()); } /** * Timesheets directly attached to this work item * cached for performance * @return */ public List<PSTransaction> getTimesheets() { return (List<PSTransaction>) getPropertyValueForInternalUse("timesheetsToBeCached"); } /** * Timesheets directly attached to this work item + lower work ones * cached for performance * @return */ public List<PSTransaction> getTimesheetsIncludingLowerWork() { return (List<PSTransaction>) getPropertyValueForInternalUse("timesheetsIncludingLowerWorkToBeCached"); } /** * FOR INTERNAL USE: NEVER CALL DIRECTLY! * Call getTimesheets() instead * @see #getTimesheets() */ @ReferencedAsPropertyValue public List<PSTransaction> getTimesheetsToBeCached() { return TimesheetBean.getTimesheets(getWork(), false); } /** * FOR INTERNAL USE: NEVER CALL DIRECTLY! * Call getTimesheetsIncludingLowerWork() instead * @see #getTimesheetsIncludingLowerWork() */ @ReferencedAsPropertyValue public List<PSTransaction> getTimesheetsIncludingLowerWorkToBeCached() { return TimesheetBean.getTimesheets(getWork(), true); } @Column(section = BEST_PRACTICE_SECTION, width=Bean.BOOLEAN_WIDTH,order=30.01f) @RequiredFeatures(Uix.FEATURE_BEST_PRACTICES) public Boolean getIsBestPractice() { return BestPractice.isApproved(getPSObject()); } @Column(section = BEST_PRACTICE_SECTION, width=Bean.BOOLEAN_WIDTH,order=30.02f) @RequiredFeatures(Uix.FEATURE_BEST_PRACTICES) public Boolean getIsBestPracticeNominee() { return BestPractice.isNominated(getPSObject()); } @Column(section = BEST_PRACTICE_SECTION, width=Bean.DEFAULT_WIDTH,order=30.03f) @RequiredFeatures(Uix.FEATURE_BEST_PRACTICES) @Filter(className=BestPracticeStatusFilter.class) @FilterByBeanProperty("bestPracticeStatusId") public String getBestPracticeStatus() { return BestPractice.getStatusLabel(getPSObject(),getLocale()); } @ReferencedAsPropertyValue @RequiredFeatures(Uix.FEATURE_BEST_PRACTICES) public String getBestPracticeStatusId() { return getWork().getBestPracticeStatus(); } @RelatedEntity @SQLRelationship(type=ps5.reports.pointandclick.data.SQLRelationship.OneToOneRelationship.class) @RequiredFeatures(Uix.FEATURE_BEST_PRACTICES) public UserBean getBestPracticeNominatedByBean() { User user = BestPractice.getNominationUser(getPSObject()); return null!=user ? (UserBean) get(UserBean.class,user.getId()) : null; } @Column(section = BEST_PRACTICE_SECTION, width=Bean.ENTITY_NAME_WIDTH,order=30.04f) @OptionalSortByBeanProperty("bestPracticeNominatedBySortableUid") @Filter(className=SingleUserFilter.class) @FilterByBeanProperty("bestPracticeNominatedById") @LinkUrlProperty("bestPracticeNominatedByUrl") @RequiredFeatures(Uix.FEATURE_BEST_PRACTICES) public String getBestPracticeNominatedBy() { UserBean user = getBestPracticeNominatedByBean(); return null!=user ? user.getName() : null; } @ReferencedAsPropertyValue public String getBestPracticeNominatedById() { UserBean user = getBestPracticeNominatedByBean(); return null!=user ? user.getUser().getId().toString() : null; } @ReferencedAsPropertyValue public String getBestPracticeNominatedBySortableUid() { UserBean user = getBestPracticeNominatedByBean(); return null!=user ? user.getUid() : null; } @ReferencedAsPropertyValue public String getBestPracticeNominatedByUrl() { UserBean user = getBestPracticeNominatedByBean(); return null!=user ? user.getUrl() : null; } @Column(section = BEST_PRACTICE_SECTION, width=Bean.DATE_WIDTH,order=30.05f) @RequiredFeatures(Uix.FEATURE_BEST_PRACTICES) @Filter(className=UserDateRangeFilter.class) public Date getBestPracticeNominatedOn() { return toDayStart(BestPractice.getNominationDate(getPSObject())); } @Column(section = BEST_PRACTICE_SECTION, width=Bean.DESCRIPTION_WIDTH,order=30.06f) @RequiredFeatures(Uix.FEATURE_BEST_PRACTICES) public String getBestPracticeNominationComment() { return BestPractice.getNominationComments(getPSObject()); } @RelatedEntity @SQLRelationship(type=ps5.reports.pointandclick.data.SQLRelationship.OneToOneRelationship.class) @RequiredFeatures(Uix.FEATURE_BEST_PRACTICES) public UserBean getBestPracticeApprovedByBean() { User user = BestPractice.getApprovalUser(getPSObject()); return null!=user ? (UserBean) get(UserBean.class,user.getId()) : null; } @Column(section = BEST_PRACTICE_SECTION, width=Bean.ENTITY_NAME_WIDTH,order=30.07f) @OptionalSortByBeanProperty("bestPracticeApprovedBySortableUid") @Filter(className=SingleUserFilter.class) @FilterByBeanProperty("bestPracticeApprovedById") @LinkUrlProperty("bestPracticeApprovedByUrl") @RequiredFeatures(Uix.FEATURE_BEST_PRACTICES) public String getBestPracticeApprovedBy() { UserBean user = getBestPracticeApprovedByBean(); return null!=user ? user.getName() : null; } @ReferencedAsPropertyValue public String getBestPracticeApprovedById() { UserBean user = getBestPracticeApprovedByBean(); return null!=user ? user.getUser().getId().toString() : null; } @ReferencedAsPropertyValue public String getBestPracticeApprovedBySortableUid() { UserBean user = getBestPracticeApprovedByBean(); return null!=user ? user.getUid() : null; } @ReferencedAsPropertyValue public String getBestPracticeApprovedByUrl() { UserBean user = getBestPracticeApprovedByBean(); return null!=user ? user.getUrl() : null; } @Column(section = BEST_PRACTICE_SECTION, width=Bean.DATE_WIDTH,order=30.08f) @RequiredFeatures(Uix.FEATURE_BEST_PRACTICES) @Filter(className=UserDateRangeFilter.class) public Date getBestPracticeApprovedOn() { return toDayStart(BestPractice.getApprovalDate(getPSObject())); } @Column(section = BEST_PRACTICE_SECTION, width=Bean.DESCRIPTION_WIDTH,order=30.09f) @RequiredFeatures(Uix.FEATURE_BEST_PRACTICES) public String getBestPracticeApprovalComment() { return BestPractice.getApprovalComments(getPSObject()); } @RelatedEntity @SQLRelationship(type=ps5.reports.pointandclick.data.SQLRelationship.OneToOneRelationship.class) @RequiredFeatures(Uix.FEATURE_BEST_PRACTICES) public UserBean getBestPracticeRejectedByBean() { User user = BestPractice.getRejectionUser(getPSObject()); return null!=user ? (UserBean) get(UserBean.class,user.getId()) : null; } @Column(section = BEST_PRACTICE_SECTION, width=Bean.ENTITY_NAME_WIDTH,order=30.10f) @OptionalSortByBeanProperty("bestPracticeRejectedBySortableUid") @Filter(className=SingleUserFilter.class) @FilterByBeanProperty("bestPracticeRejectedById") @LinkUrlProperty("bestPracticeRejectedByUrl") @RequiredFeatures(Uix.FEATURE_BEST_PRACTICES) public String getBestPracticeRejectedBy() { UserBean user = getBestPracticeRejectedByBean(); return null!=user ? user.getName() : null; } @ReferencedAsPropertyValue public String getBestPracticeRejectedById() { UserBean user = getBestPracticeRejectedByBean(); return null!=user ? user.getUser().getId().toString() : null; } @ReferencedAsPropertyValue public String getBestPracticeRejectedBySortableUid() { UserBean user = getBestPracticeRejectedByBean(); return null!=user ? user.getUid() : null; } @ReferencedAsPropertyValue public String getBestPracticeRejectedByUrl() { UserBean user = getBestPracticeRejectedByBean(); return null!=user ? user.getUrl() : null; } @Column(section = BEST_PRACTICE_SECTION, width=Bean.DATE_WIDTH,order=30.11f) @RequiredFeatures(Uix.FEATURE_BEST_PRACTICES) @Filter(className=UserDateRangeFilter.class) public Date getBestPracticeRejectedOn() { return toDayStart(BestPractice.getRejectionDate(getPSObject())); } @Column(section = BEST_PRACTICE_SECTION, width=Bean.DESCRIPTION_WIDTH,order=30.12f) @RequiredFeatures(Uix.FEATURE_BEST_PRACTICES) public String getBestPracticeRejectedComment() { return BestPractice.getRejectionComments(getPSObject()); } @RelatedEntity @SQLRelationship(type=ps5.reports.pointandclick.data.SQLRelationship.OneToOneRelationship.class) @RequiredFeatures(Uix.FEATURE_BEST_PRACTICES) public UserBean getBestPracticeDesignationRemovedByBean() { User user = BestPractice.getDesignationRemovedUser(getPSObject()); return null!=user ? (UserBean) get(UserBean.class,user.getId()) : null; } @Column(section = BEST_PRACTICE_SECTION, width=Bean.ENTITY_NAME_WIDTH,order=30.13f) @OptionalSortByBeanProperty("bestPracticeDesignationRemovedBySortableUid") @Filter(className=SingleUserFilter.class) @FilterByBeanProperty("bestPracticeDesignationRemovedById") @LinkUrlProperty("bestPracticeDesignationRemovedByUrl") @RequiredFeatures(Uix.FEATURE_BEST_PRACTICES) public String getBestPracticeDesignationRemovedBy() { UserBean user = getBestPracticeDesignationRemovedByBean(); return null!=user ? user.getName() : null; } @ReferencedAsPropertyValue public String getBestPracticeDesignationRemovedById() { UserBean user = getBestPracticeDesignationRemovedByBean(); return null!=user ? user.getUser().getId().toString() : null; } @ReferencedAsPropertyValue public String getBestPracticeDesignationRemovedBySortableUid() { UserBean user = getBestPracticeDesignationRemovedByBean(); return null!=user ? user.getUid() : null; } @ReferencedAsPropertyValue public String getBestPracticeDesignationRemovedByUrl() { UserBean user = getBestPracticeDesignationRemovedByBean(); return null!=user ? user.getUrl() : null; } @Column(section = BEST_PRACTICE_SECTION, width=Bean.DATE_WIDTH,order=30.14f) @RequiredFeatures(Uix.FEATURE_BEST_PRACTICES) @Filter(className=UserDateRangeFilter.class) public Date getBestPracticeDesignationRemovedOn() { return toDayStart(BestPractice.getDesignationRemovedDate(getPSObject())); } @Column(section = BEST_PRACTICE_SECTION, width=Bean.DESCRIPTION_WIDTH,order=30.15f) @RequiredFeatures(Uix.FEATURE_BEST_PRACTICES) public String getBestPracticeDesignationRemovedComment() { return BestPractice.getDesignationRemovedComments(getPSObject()); } @Column(width=Bean.BOOLEAN_WIDTH, order=30.25f, section = CONFIG_SECTION) @RequiredFeatures(Uix.FEATURE_WORKFLOW_ENABLED) public Boolean getIsWorkflow() { return _work.isWorkflow(); } @Column(width=Bean.TYPE_WIDTH, order=30.26f, section = CONFIG_SECTION) @Filter(className=WorkflowStatusFilter.class) @FilterByBeanProperty("workflowStatusFilterProperty") @RequiredFeatures(Uix.FEATURE_WORKFLOW_ENABLED) public String getWorkflowStatus() { return WorkflowUtils.getWorkflowStatus(_work, getLocale()); } @ReferencedAsPropertyValue public String getWorkflowStatusFilterProperty() { if(null != _work.getWorkflowStatus()){ return _work.getWorkflowStatus().name(); } return null; } @Column(width=Bean.TYPE_WIDTH, order=30.27f, section = CONFIG_SECTION) @RequiredFeatures(Uix.FEATURE_WORKFLOW_ENABLED) public String getLastWorkflowAction() { if(null != getWork().getWorkflowStatus()){ final ObjectEvent evt = ObjectEvent.findLastByObjectAndType(getWork(),WorkflowChangeEvent.TYPE); if(null != evt && WorkflowChangeEvent.TYPE.equals(evt.getType())){ return evt.getFullDescription(BaseObjectEvent.TYPE_TXT, getSession().getCurrentUser()); } } return null; } @Column(width = Bean.TYPE_WIDTH, order = 0.06f) public String getTemplateName(){ return getWork().getAssociatedTemplate() != null? getWork().getAssociatedTemplate().getName(): null; } @Column(width = Bean.TYPE_WIDTH, order = 0.16f) public String getRootWorkObject(){ return this.getType() != null? this.getType().toString(): null; } }
83,734
0.734643
0.727251
2,196
36.129326
31.893946
204
false
false
0
0
0
0
0
0
1.823315
false
false
4
6558e6196a2c7dd5675ffff5d9b84f11e0637b53
12,257,836,678,935
b4cacd3255287c08b2d8e5cd14c0cf03251ea670
/myalbum-commons-service/src/main/java/cn/yan_wm/myalbum/commons/service/config/Swagger2Configuration.java
8ca86365cc654b6d3ac5edb411dfb722e7cfd7e0
[]
no_license
moon928/MyAlbum-Boot
https://github.com/moon928/MyAlbum-Boot
33143428ed7c485bf7c27f9c5d5c52d9b7e1b6f8
e71490161058ab8b89134329fc9f9d75992b31e7
refs/heads/master
2022-06-26T04:06:44.246000
2020-06-04T08:31:02
2020-06-04T08:31:02
227,991,961
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package cn.yan_wm.myalbum.commons.service.config; import com.google.common.net.HttpHeaders; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import springfox.documentation.builders.ApiInfoBuilder; import springfox.documentation.builders.PathSelectors; import springfox.documentation.builders.RequestHandlerSelectors; import springfox.documentation.service.*; import springfox.documentation.spi.DocumentationType; import springfox.documentation.spi.service.contexts.SecurityContext; import springfox.documentation.spring.web.plugins.Docket; import springfox.documentation.swagger.web.*; import java.util.Arrays; import java.util.Collections; import java.util.List; import static org.hibernate.validator.internal.util.CollectionHelper.newArrayList; @Configuration public class Swagger2Configuration { // @Value("${config.oauth2.accessTokenUri}") private String accessTokenUri ="http://39.105.137.236:10000/auth/oauth/token"; // private String accessTokenUri ="http://192.168.50.2:10000/auth/oauth/token"; // private String accessTokenUri ="http://localhost:10000/auth/oauth/token"; // @Bean // public Docket createRestApi() { // return new Docket(DocumentationType.SWAGGER_2) // .apiInfo(apiInfo()) // .select() // .apis(RequestHandlerSelectors.basePackage("com.yan_wm.mydemo.service")) // .paths(PathSelectors.any()) // .build(); // } private ApiInfo apiInfo() { return new ApiInfoBuilder() .title("MyDemo API 文档") .description("MyDemo API 网关接口,http://www.yan-wm.cn") .termsOfServiceUrl("http://www.yan-wm.cn") .version("1.0.0") .build(); } @Bean public Docket api() { return new Docket(DocumentationType.SWAGGER_2) .apiInfo(apiInfo()) .select() .apis(RequestHandlerSelectors.basePackage("cn.yan_wm.myalbum.service")) //.apis(RequestHandlerSelectors.withClassAnnotation(Api.class)) .paths(PathSelectors.any()) .build() .securityContexts(Collections.singletonList(securityContext())) .securitySchemes(Arrays.asList(securitySchema(), apiKey(), apiCookieKey())); // .globalOperationParameters( // newArrayList(new ParameterBuilder() // .name("access_token") // .description("AccessToken") // .modelRef(new ModelRef("string")) // .parameterType("query") // .required(true) // .build())); } @Bean public SecurityScheme apiKey() { return new ApiKey(HttpHeaders.AUTHORIZATION, "apiKey", "header"); } @Bean public SecurityScheme apiCookieKey() { return new ApiKey(HttpHeaders.COOKIE, "apiKey", "cookie"); } private OAuth securitySchema() { List<AuthorizationScope> authorizationScopeList = newArrayList(); authorizationScopeList.add(new AuthorizationScope("read", "read all")); authorizationScopeList.add(new AuthorizationScope("write", "access all")); List<GrantType> grantTypes = newArrayList(); GrantType passwordCredentialsGrant = new ResourceOwnerPasswordCredentialsGrant(accessTokenUri); grantTypes.add(passwordCredentialsGrant); return new OAuth("oauth2", authorizationScopeList, grantTypes); } private SecurityContext securityContext() { return SecurityContext.builder().securityReferences(defaultAuth()) .build(); } private List<SecurityReference> defaultAuth() { final AuthorizationScope[] authorizationScopes = new AuthorizationScope[3]; authorizationScopes[0] = new AuthorizationScope("read", "read all"); authorizationScopes[1] = new AuthorizationScope("trust", "trust all"); authorizationScopes[2] = new AuthorizationScope("write", "write all"); return Collections.singletonList(new SecurityReference("oauth2", authorizationScopes)); } // @Bean // public SecurityConfiguration security() { // return new SecurityConfiguration // ("client", "secret", "", "", "Bearer access token", ApiKeyVehicle.HEADER, HttpHeaders.AUTHORIZATION,""); // } @Bean SecurityConfiguration security() { return SecurityConfigurationBuilder.builder() .clientId("client") .clientSecret("secret") .realm("test-app-realm") .appName("test-app") .scopeSeparator(",") .additionalQueryStringParams(null) .useBasicAuthenticationWithAccessCodeGrant(false) .build(); } @Bean UiConfiguration uiConfig() { return UiConfigurationBuilder.builder() .deepLinking(true) .displayOperationId(false) .defaultModelsExpandDepth(1) .defaultModelExpandDepth(1) .defaultModelRendering(ModelRendering.EXAMPLE) .displayRequestDuration(false) .docExpansion(DocExpansion.NONE) .filter(false) .maxDisplayedTags(null) .operationsSorter(OperationsSorter.ALPHA) .showExtensions(false) .tagsSorter(TagsSorter.ALPHA) .validatorUrl(null) .build(); } }
UTF-8
Java
5,671
java
Swagger2Configuration.java
Java
[ { "context": "Uri}\")\n private String accessTokenUri =\"http://39.105.137.236:10000/auth/oauth/token\";\n// private String acc", "end": 973, "score": 0.9996863603591919, "start": 959, "tag": "IP_ADDRESS", "value": "39.105.137.236" }, { "context": "en\";\n// private String accessTokenUri =\"http://192.168.50.2:10000/auth/oauth/token\";\n// private String acc", "end": 1056, "score": 0.9996464252471924, "start": 1044, "tag": "IP_ADDRESS", "value": "192.168.50.2" }, { "context": "clientId(\"client\")\n .clientSecret(\"secret\")\n .realm(\"test-app-realm\")\n ", "end": 4688, "score": 0.9820566177368164, "start": 4682, "tag": "KEY", "value": "secret" } ]
null
[]
package cn.yan_wm.myalbum.commons.service.config; import com.google.common.net.HttpHeaders; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import springfox.documentation.builders.ApiInfoBuilder; import springfox.documentation.builders.PathSelectors; import springfox.documentation.builders.RequestHandlerSelectors; import springfox.documentation.service.*; import springfox.documentation.spi.DocumentationType; import springfox.documentation.spi.service.contexts.SecurityContext; import springfox.documentation.spring.web.plugins.Docket; import springfox.documentation.swagger.web.*; import java.util.Arrays; import java.util.Collections; import java.util.List; import static org.hibernate.validator.internal.util.CollectionHelper.newArrayList; @Configuration public class Swagger2Configuration { // @Value("${config.oauth2.accessTokenUri}") private String accessTokenUri ="http://172.16.58.3:10000/auth/oauth/token"; // private String accessTokenUri ="http://192.168.50.2:10000/auth/oauth/token"; // private String accessTokenUri ="http://localhost:10000/auth/oauth/token"; // @Bean // public Docket createRestApi() { // return new Docket(DocumentationType.SWAGGER_2) // .apiInfo(apiInfo()) // .select() // .apis(RequestHandlerSelectors.basePackage("com.yan_wm.mydemo.service")) // .paths(PathSelectors.any()) // .build(); // } private ApiInfo apiInfo() { return new ApiInfoBuilder() .title("MyDemo API 文档") .description("MyDemo API 网关接口,http://www.yan-wm.cn") .termsOfServiceUrl("http://www.yan-wm.cn") .version("1.0.0") .build(); } @Bean public Docket api() { return new Docket(DocumentationType.SWAGGER_2) .apiInfo(apiInfo()) .select() .apis(RequestHandlerSelectors.basePackage("cn.yan_wm.myalbum.service")) //.apis(RequestHandlerSelectors.withClassAnnotation(Api.class)) .paths(PathSelectors.any()) .build() .securityContexts(Collections.singletonList(securityContext())) .securitySchemes(Arrays.asList(securitySchema(), apiKey(), apiCookieKey())); // .globalOperationParameters( // newArrayList(new ParameterBuilder() // .name("access_token") // .description("AccessToken") // .modelRef(new ModelRef("string")) // .parameterType("query") // .required(true) // .build())); } @Bean public SecurityScheme apiKey() { return new ApiKey(HttpHeaders.AUTHORIZATION, "apiKey", "header"); } @Bean public SecurityScheme apiCookieKey() { return new ApiKey(HttpHeaders.COOKIE, "apiKey", "cookie"); } private OAuth securitySchema() { List<AuthorizationScope> authorizationScopeList = newArrayList(); authorizationScopeList.add(new AuthorizationScope("read", "read all")); authorizationScopeList.add(new AuthorizationScope("write", "access all")); List<GrantType> grantTypes = newArrayList(); GrantType passwordCredentialsGrant = new ResourceOwnerPasswordCredentialsGrant(accessTokenUri); grantTypes.add(passwordCredentialsGrant); return new OAuth("oauth2", authorizationScopeList, grantTypes); } private SecurityContext securityContext() { return SecurityContext.builder().securityReferences(defaultAuth()) .build(); } private List<SecurityReference> defaultAuth() { final AuthorizationScope[] authorizationScopes = new AuthorizationScope[3]; authorizationScopes[0] = new AuthorizationScope("read", "read all"); authorizationScopes[1] = new AuthorizationScope("trust", "trust all"); authorizationScopes[2] = new AuthorizationScope("write", "write all"); return Collections.singletonList(new SecurityReference("oauth2", authorizationScopes)); } // @Bean // public SecurityConfiguration security() { // return new SecurityConfiguration // ("client", "secret", "", "", "Bearer access token", ApiKeyVehicle.HEADER, HttpHeaders.AUTHORIZATION,""); // } @Bean SecurityConfiguration security() { return SecurityConfigurationBuilder.builder() .clientId("client") .clientSecret("secret") .realm("test-app-realm") .appName("test-app") .scopeSeparator(",") .additionalQueryStringParams(null) .useBasicAuthenticationWithAccessCodeGrant(false) .build(); } @Bean UiConfiguration uiConfig() { return UiConfigurationBuilder.builder() .deepLinking(true) .displayOperationId(false) .defaultModelsExpandDepth(1) .defaultModelExpandDepth(1) .defaultModelRendering(ModelRendering.EXAMPLE) .displayRequestDuration(false) .docExpansion(DocExpansion.NONE) .filter(false) .maxDisplayedTags(null) .operationsSorter(OperationsSorter.ALPHA) .showExtensions(false) .tagsSorter(TagsSorter.ALPHA) .validatorUrl(null) .build(); } }
5,668
0.622238
0.613399
140
39.407143
27.581282
122
false
false
0
0
0
0
0
0
0.45
false
false
4
f66507a718105aef81eb5ab9fcf092dc46ef88e5
17,111,149,730,719
64cb97346ee6b4225e76aa24eda42841b354bbea
/dtb-shop-service/src/main/java/com/xinyunlian/xpdj/persistence/MarketSyncLogMapper.java
800cd96264a663eaee38a23cfcc6204c78520f99
[]
no_license
rsdgjb/DTB
https://github.com/rsdgjb/DTB
eecf5d9af42b1ba3c937b26ac9779f571d894ac3
d9367d020e99454039e9acf2a8821ad2d4ebb368
HEAD
2018-09-09T06:59:17.508000
2018-06-05T02:08:20
2018-06-05T02:08:20
112,153,572
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.xinyunlian.xpdj.persistence; import java.util.Date; import org.apache.ibatis.annotations.Insert; import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Select; @Mapper public interface MarketSyncLogMapper { @Select("select max(sync_time) last from market_sync_log where status = 1") Date getLastSuccessfulDate(); @Insert("insert into market_sync_log(sync_time, status, message) values(#{arg0}, #{arg1}, #{arg2}) ") void insertMarketSyncLog(Date date, int status, String message); }
UTF-8
Java
548
java
MarketSyncLogMapper.java
Java
[]
null
[]
package com.xinyunlian.xpdj.persistence; import java.util.Date; import org.apache.ibatis.annotations.Insert; import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Select; @Mapper public interface MarketSyncLogMapper { @Select("select max(sync_time) last from market_sync_log where status = 1") Date getLastSuccessfulDate(); @Insert("insert into market_sync_log(sync_time, status, message) values(#{arg0}, #{arg1}, #{arg2}) ") void insertMarketSyncLog(Date date, int status, String message); }
548
0.74635
0.739051
17
30.235294
29.853622
102
false
false
0
0
0
0
0
0
1.058824
false
false
4
65ea1cef35f7eecbe4286aa84cfc1a83e62351d3
7,834,020,368,601
28f40a778a17a1db11e9e1fc4e7602a778aec9fc
/src/pizzastore/product/ingredient/BlackOlives.java
2f25073fd73944eb38f449f15798c92f579193c6
[]
no_license
micapp7/DesignPatterns
https://github.com/micapp7/DesignPatterns
85e448daee2bbf06ea3c5b161dfa805ba9c7b62d
10a047642537eebb1b6f6f7d688610e41e349c05
refs/heads/master
2020-03-23T13:59:59.241000
2018-10-05T03:46:20
2018-10-05T03:46:20
141,649,707
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package pizzastore.product.ingredient; public class BlackOlives implements Veggies { }
UTF-8
Java
88
java
BlackOlives.java
Java
[]
null
[]
package pizzastore.product.ingredient; public class BlackOlives implements Veggies { }
88
0.829545
0.829545
4
21
20.651876
45
false
false
0
0
0
0
0
0
0.25
false
false
4
69e1bcde5e1324d689efc5b682ec38ac7467eae0
33,260,226,756,454
48facba5a607dd37410da12b83de5520169deaaf
/src/model/Directions.java
4bb718dd6d62b8f7bd6366780b935e54df204132
[]
no_license
goldenXcode/connecting-dots-for-android
https://github.com/goldenXcode/connecting-dots-for-android
9fa18fe2b6760095e243600c947e6c907f6d62a3
5575b540fb24eb96cc9d08aceae28c5fc5bf9a72
refs/heads/master
2020-06-04T03:42:03.728000
2014-03-04T03:03:47
2014-03-04T03:03:47
32,835,083
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package model; /** * Representing the direction for play. * L is for Left. * R is for Right. * U is for Up. * D is for Down. * @author random * */ public enum Directions { L, R, U, D }
UTF-8
Java
213
java
Directions.java
Java
[ { "context": "t.\r\n * U is for Up.\r\n * D is for Down.\r\n * @author random\r\n *\r\n */\r\npublic enum Directions {\r\n\r\n\tL, R, U, D", "end": 156, "score": 0.998598039150238, "start": 150, "tag": "USERNAME", "value": "random" } ]
null
[]
package model; /** * Representing the direction for play. * L is for Left. * R is for Right. * U is for Up. * D is for Down. * @author random * */ public enum Directions { L, R, U, D }
213
0.553991
0.553991
16
11.3125
10.62261
39
false
false
0
0
0
0
0
0
0.3125
false
false
4
5b6c388fdf231655bd6ca223c4c734801a07b736
25,769,803,796,455
485aca20c670a31405f194fc2d61dd894ab4ece6
/src/test/java/com/guidesmiths/martian_robot/web/RobotControllerTest.java
d04896c4b8332b2a6fd6c91410845386c59c3089
[]
no_license
osopromadze/martian-robots
https://github.com/osopromadze/martian-robots
b21569eb4f79e10ac10eabb934e86efe121baef6
614023d17b50283d58eafbef6fdac044abff128a
refs/heads/main
2023-05-29T22:05:44.283000
2021-06-07T10:11:14
2021-06-07T10:11:14
373,234,095
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.guidesmiths.martian_robot.web; import com.guidesmiths.martian_robot.dto.InputOutputDto; import com.guidesmiths.martian_robot.repository.InputOutputRepository; import com.guidesmiths.martian_robot.service.RobotService; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.TestInstance; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.security.reactive.ReactiveSecurityAutoConfiguration; import org.springframework.boot.test.autoconfigure.web.reactive.WebFluxTest; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.context.ApplicationContext; import org.springframework.core.io.FileUrlResource; import org.springframework.http.HttpStatus; import org.springframework.test.context.TestPropertySource; import org.springframework.test.web.reactive.server.EntityExchangeResult; import org.springframework.test.web.reactive.server.WebTestClient; import org.springframework.web.reactive.function.BodyInserters; import java.net.MalformedURLException; import java.net.URL; import java.time.Duration; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyList; import static org.mockito.Mockito.doCallRealMethod; @WebFluxTest(value = {RobotController.class}, excludeAutoConfiguration = {ReactiveSecurityAutoConfiguration.class}) @TestPropertySource(properties = { "size.max=10" }) @TestInstance(TestInstance.Lifecycle.PER_CLASS) class RobotControllerTest { @Autowired private ApplicationContext context; @MockBean private RobotService robotService; @MockBean private InputOutputRepository inputOutputRepository; private WebTestClient testClient; @BeforeAll void init() { testClient = WebTestClient.bindToApplicationContext(context) .configureClient() .responseTimeout(Duration.ofMillis(900000)) .build(); } @Test void okForSampleInputTest() throws MalformedURLException { doCallRealMethod().when(robotService).moveRobots(anyList(), any(InputOutputDto.class)); URL fileUrl = new URL("file:src/test/resources/files/sample-input.txt"); EntityExchangeResult<String> response = testClient.post() .uri(uriBuilder -> uriBuilder.path("/martian-robots/move-robots") .build()) .body(BodyInserters.fromResource(new FileUrlResource(fileUrl))) .exchange() .expectStatus().isOk() .expectBody(String.class) .returnResult(); String responseBody = response.getResponseBody(); String expectedBody = "1 1 E\n" + "3 3 N LOST\n" + "2 3 S\n"; assertEquals(expectedBody, responseBody); } @Test void invalidLineCountTest() throws MalformedURLException { URL fileUrl = new URL("file:src/test/resources/files/invalid-line-count.txt"); EntityExchangeResult<String> response = testClient.post() .uri(uriBuilder -> uriBuilder.path("/martian-robots/move-robots") .build()) .body(BodyInserters.fromResource(new FileUrlResource(fileUrl))) .exchange() .expectStatus().is4xxClientError() .expectBody(String.class) .returnResult(); assertEquals(HttpStatus.BAD_REQUEST, response.getStatus()); assertEquals("Invalid input", response.getResponseBody()); } @Test void invalidMarsCoordinatesTest() throws MalformedURLException { URL fileUrl = new URL("file:src/test/resources/files/invalid-mars-coordinates.txt"); EntityExchangeResult<String> response = testClient.post() .uri(uriBuilder -> uriBuilder.path("/martian-robots/move-robots") .build()) .body(BodyInserters.fromResource(new FileUrlResource(fileUrl))) .exchange() .expectStatus().is4xxClientError() .expectBody(String.class) .returnResult(); assertEquals(HttpStatus.BAD_REQUEST, response.getStatus()); assertEquals("Invalid input", response.getResponseBody()); } @Test void invalidRobotPositionsTest() throws MalformedURLException { URL fileUrl = new URL("file:src/test/resources/files/invalid-robot-positions.txt"); EntityExchangeResult<String> response = testClient.post() .uri(uriBuilder -> uriBuilder.path("/martian-robots/move-robots") .build()) .body(BodyInserters.fromResource(new FileUrlResource(fileUrl))) .exchange() .expectStatus().is4xxClientError() .expectBody(String.class) .returnResult(); assertEquals(HttpStatus.BAD_REQUEST, response.getStatus()); assertEquals("Invalid input", response.getResponseBody()); } }
UTF-8
Java
5,138
java
RobotControllerTest.java
Java
[]
null
[]
package com.guidesmiths.martian_robot.web; import com.guidesmiths.martian_robot.dto.InputOutputDto; import com.guidesmiths.martian_robot.repository.InputOutputRepository; import com.guidesmiths.martian_robot.service.RobotService; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.TestInstance; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.security.reactive.ReactiveSecurityAutoConfiguration; import org.springframework.boot.test.autoconfigure.web.reactive.WebFluxTest; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.context.ApplicationContext; import org.springframework.core.io.FileUrlResource; import org.springframework.http.HttpStatus; import org.springframework.test.context.TestPropertySource; import org.springframework.test.web.reactive.server.EntityExchangeResult; import org.springframework.test.web.reactive.server.WebTestClient; import org.springframework.web.reactive.function.BodyInserters; import java.net.MalformedURLException; import java.net.URL; import java.time.Duration; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyList; import static org.mockito.Mockito.doCallRealMethod; @WebFluxTest(value = {RobotController.class}, excludeAutoConfiguration = {ReactiveSecurityAutoConfiguration.class}) @TestPropertySource(properties = { "size.max=10" }) @TestInstance(TestInstance.Lifecycle.PER_CLASS) class RobotControllerTest { @Autowired private ApplicationContext context; @MockBean private RobotService robotService; @MockBean private InputOutputRepository inputOutputRepository; private WebTestClient testClient; @BeforeAll void init() { testClient = WebTestClient.bindToApplicationContext(context) .configureClient() .responseTimeout(Duration.ofMillis(900000)) .build(); } @Test void okForSampleInputTest() throws MalformedURLException { doCallRealMethod().when(robotService).moveRobots(anyList(), any(InputOutputDto.class)); URL fileUrl = new URL("file:src/test/resources/files/sample-input.txt"); EntityExchangeResult<String> response = testClient.post() .uri(uriBuilder -> uriBuilder.path("/martian-robots/move-robots") .build()) .body(BodyInserters.fromResource(new FileUrlResource(fileUrl))) .exchange() .expectStatus().isOk() .expectBody(String.class) .returnResult(); String responseBody = response.getResponseBody(); String expectedBody = "1 1 E\n" + "3 3 N LOST\n" + "2 3 S\n"; assertEquals(expectedBody, responseBody); } @Test void invalidLineCountTest() throws MalformedURLException { URL fileUrl = new URL("file:src/test/resources/files/invalid-line-count.txt"); EntityExchangeResult<String> response = testClient.post() .uri(uriBuilder -> uriBuilder.path("/martian-robots/move-robots") .build()) .body(BodyInserters.fromResource(new FileUrlResource(fileUrl))) .exchange() .expectStatus().is4xxClientError() .expectBody(String.class) .returnResult(); assertEquals(HttpStatus.BAD_REQUEST, response.getStatus()); assertEquals("Invalid input", response.getResponseBody()); } @Test void invalidMarsCoordinatesTest() throws MalformedURLException { URL fileUrl = new URL("file:src/test/resources/files/invalid-mars-coordinates.txt"); EntityExchangeResult<String> response = testClient.post() .uri(uriBuilder -> uriBuilder.path("/martian-robots/move-robots") .build()) .body(BodyInserters.fromResource(new FileUrlResource(fileUrl))) .exchange() .expectStatus().is4xxClientError() .expectBody(String.class) .returnResult(); assertEquals(HttpStatus.BAD_REQUEST, response.getStatus()); assertEquals("Invalid input", response.getResponseBody()); } @Test void invalidRobotPositionsTest() throws MalformedURLException { URL fileUrl = new URL("file:src/test/resources/files/invalid-robot-positions.txt"); EntityExchangeResult<String> response = testClient.post() .uri(uriBuilder -> uriBuilder.path("/martian-robots/move-robots") .build()) .body(BodyInserters.fromResource(new FileUrlResource(fileUrl))) .exchange() .expectStatus().is4xxClientError() .expectBody(String.class) .returnResult(); assertEquals(HttpStatus.BAD_REQUEST, response.getStatus()); assertEquals("Invalid input", response.getResponseBody()); } }
5,138
0.683534
0.680226
132
37.93182
28.446173
98
false
false
0
0
0
0
0
0
0.431818
false
false
4
146ad0e295a506420046e878e6bfaeca68f173fd
32,933,809,245,019
01749866e07116394218861ffd21307f9ceecde8
/lazylisp/Printer.java
334bb36cb9b5d5893d6a78046c4b169832d946a3
[]
no_license
Lucus16/LazyLisp
https://github.com/Lucus16/LazyLisp
cd80f6d12874f8bd289838f492caa291a95f9e46
9dde0f5f9860f0b3ddeb6ee26e0c7d9f7ea6f1c4
refs/heads/master
2021-01-23T17:18:44.649000
2015-04-04T12:31:34
2015-04-04T12:31:34
32,425,660
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package lazylisp; import lazylisp.types.AbstractFunction; import lazylisp.types.Atom; import lazylisp.types.Cons; import lazylisp.types.LLObject; public class Printer { public static String print(LLObject arg) throws LLException { arg = arg.dethunk(); StringBuilder sb = new StringBuilder(); if (arg instanceof Atom) { sb.append(((Atom)arg).getName()); } else if (arg instanceof Cons) { sb.append('('); boolean first = true; while (arg instanceof Cons) { if (!first) { sb.append(' '); } first = false; Cons cons = (Cons)arg; sb.append(print(cons.getCar().dethunk())); arg = cons.getCdr().dethunk(); } sb.append(')'); } else if (arg instanceof AbstractFunction) { sb.append(arg); // TODO } else { throw new LLException("Unprintable type."); } return sb.toString(); } }
UTF-8
Java
832
java
Printer.java
Java
[]
null
[]
package lazylisp; import lazylisp.types.AbstractFunction; import lazylisp.types.Atom; import lazylisp.types.Cons; import lazylisp.types.LLObject; public class Printer { public static String print(LLObject arg) throws LLException { arg = arg.dethunk(); StringBuilder sb = new StringBuilder(); if (arg instanceof Atom) { sb.append(((Atom)arg).getName()); } else if (arg instanceof Cons) { sb.append('('); boolean first = true; while (arg instanceof Cons) { if (!first) { sb.append(' '); } first = false; Cons cons = (Cons)arg; sb.append(print(cons.getCar().dethunk())); arg = cons.getCdr().dethunk(); } sb.append(')'); } else if (arg instanceof AbstractFunction) { sb.append(arg); // TODO } else { throw new LLException("Unprintable type."); } return sb.toString(); } }
832
0.658654
0.658654
32
25
15.239751
62
false
false
0
0
0
0
0
0
2.53125
false
false
4
1fd93b6dc3e6ab311e77ee32b021ab55d60d8968
19,550,691,150,822
41cdaaddb09e0df20f9668f3c0acdc7c93ec34cd
/src/main/java/chapter07/exercise09/Gerbil.java
55bd508ed36fbfc5f80c2d6c1dfadaa6cef38d46
[]
no_license
Filakkin/thinking-in-java-exercises
https://github.com/Filakkin/thinking-in-java-exercises
7f7aac43997d5933999aeb0ce1acda05c5842b02
391abb1651c3fb43b45b0ce0019f8f1ed6f3aafd
refs/heads/master
2018-03-20T14:39:27.368000
2016-11-18T10:14:51
2016-11-18T10:14:51
66,831,663
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package chapter07.exercise09; /** * Created by Fffdsddd on 04.11.2016. */ public class Gerbil extends Rodent { @Override void eat() { System.out.println("Gerbil eats"); } @Override void sleep() { System.out.println("Gerbil sleeps"); } @Override void poop() { System.out.println("Gerbil poops"); } @Override void reproduce() { System.out.println("Making more gerbils"); } @Override public String toString() { return "Gerbil"; } }
UTF-8
Java
536
java
Gerbil.java
Java
[ { "context": "package chapter07.exercise09;\n\n/**\n * Created by Fffdsddd on 04.11.2016.\n */\npublic class Gerbil extends Ro", "end": 57, "score": 0.9987038969993591, "start": 49, "tag": "USERNAME", "value": "Fffdsddd" } ]
null
[]
package chapter07.exercise09; /** * Created by Fffdsddd on 04.11.2016. */ public class Gerbil extends Rodent { @Override void eat() { System.out.println("Gerbil eats"); } @Override void sleep() { System.out.println("Gerbil sleeps"); } @Override void poop() { System.out.println("Gerbil poops"); } @Override void reproduce() { System.out.println("Making more gerbils"); } @Override public String toString() { return "Gerbil"; } }
536
0.570895
0.548507
31
16.290323
15.183168
50
false
false
0
0
0
0
0
0
0.193548
false
false
4
5661d7d8d1e10dcc5510ae39b81894d6a9c29090
24,799,141,187,545
919c0a53991cc7fd4a07d799a7a430e3ace26cff
/src/java/com/cong/logiware/edi/gtnexus/shippinginstruction/Vessel.java
c487a2abdc09d7ab128107244226cefea27925a9
[]
no_license
sks40gb/logiLCL
https://github.com/sks40gb/logiLCL
949073a9ed3365cd6d1ffd593997ddba1b268c49
cf284aa30b0c1d2899a6ec6dff05364112f488b4
refs/heads/master
2016-09-26T17:13:24.358000
2016-09-11T15:15:35
2016-09-11T15:15:35
51,379,218
0
0
null
false
2016-11-10T16:59:09
2016-02-09T16:22:13
2016-02-09T16:35:36
2016-11-10T16:59:09
185,906
0
0
1
Java
null
null
// // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4-2 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2015.03.03 at 11:23:36 AM IST // package com.cong.logiware.edi.gtnexus.shippinginstruction; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; import javax.xml.bind.annotation.adapters.CollapsedStringAdapter; import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; /** * <p>Java class for anonymous complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="Name"> * &lt;simpleType> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}string"> * &lt;minLength value="2"/> * &lt;maxLength value="28"/> * &lt;/restriction> * &lt;/simpleType> * &lt;/element> * &lt;/sequence> * &lt;attribute name="Country"> * &lt;simpleType> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}string"> * &lt;minLength value="2"/> * &lt;maxLength value="35"/> * &lt;/restriction> * &lt;/simpleType> * &lt;/attribute> * &lt;attribute name="Scac"> * &lt;simpleType> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}string"> * &lt;minLength value="2"/> * &lt;maxLength value="4"/> * &lt;/restriction> * &lt;/simpleType> * &lt;/attribute> * &lt;attribute name="Code"> * &lt;simpleType> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}string"> * &lt;minLength value="1"/> * &lt;maxLength value="8"/> * &lt;/restriction> * &lt;/simpleType> * &lt;/attribute> * &lt;attribute name="Qualifier"> * &lt;simpleType> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}NMTOKEN"> * &lt;enumeration value="Lloyds"/> * &lt;/restriction> * &lt;/simpleType> * &lt;/attribute> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "name" }) @XmlRootElement(name = "Vessel") public class Vessel { @XmlElement(name = "Name", required = true) protected String name; @XmlAttribute(name = "Country") protected String country; @XmlAttribute(name = "Scac") protected String scac; @XmlAttribute(name = "Code") protected String code; @XmlAttribute(name = "Qualifier") @XmlJavaTypeAdapter(CollapsedStringAdapter.class) protected String qualifier; /** * Gets the value of the name property. * * @return * possible object is * {@link String } * */ public String getName() { return name; } /** * Sets the value of the name property. * * @param value * allowed object is * {@link String } * */ public void setName(String value) { this.name = value; } /** * Gets the value of the country property. * * @return * possible object is * {@link String } * */ public String getCountry() { return country; } /** * Sets the value of the country property. * * @param value * allowed object is * {@link String } * */ public void setCountry(String value) { this.country = value; } /** * Gets the value of the scac property. * * @return * possible object is * {@link String } * */ public String getScac() { return scac; } /** * Sets the value of the scac property. * * @param value * allowed object is * {@link String } * */ public void setScac(String value) { this.scac = value; } /** * Gets the value of the code property. * * @return * possible object is * {@link String } * */ public String getCode() { return code; } /** * Sets the value of the code property. * * @param value * allowed object is * {@link String } * */ public void setCode(String value) { this.code = value; } /** * Gets the value of the qualifier property. * * @return * possible object is * {@link String } * */ public String getQualifier() { return qualifier; } /** * Sets the value of the qualifier property. * * @param value * allowed object is * {@link String } * */ public void setQualifier(String value) { this.qualifier = value; } }
UTF-8
Java
5,531
java
Vessel.java
Java
[]
null
[]
// // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4-2 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2015.03.03 at 11:23:36 AM IST // package com.cong.logiware.edi.gtnexus.shippinginstruction; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; import javax.xml.bind.annotation.adapters.CollapsedStringAdapter; import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; /** * <p>Java class for anonymous complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="Name"> * &lt;simpleType> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}string"> * &lt;minLength value="2"/> * &lt;maxLength value="28"/> * &lt;/restriction> * &lt;/simpleType> * &lt;/element> * &lt;/sequence> * &lt;attribute name="Country"> * &lt;simpleType> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}string"> * &lt;minLength value="2"/> * &lt;maxLength value="35"/> * &lt;/restriction> * &lt;/simpleType> * &lt;/attribute> * &lt;attribute name="Scac"> * &lt;simpleType> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}string"> * &lt;minLength value="2"/> * &lt;maxLength value="4"/> * &lt;/restriction> * &lt;/simpleType> * &lt;/attribute> * &lt;attribute name="Code"> * &lt;simpleType> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}string"> * &lt;minLength value="1"/> * &lt;maxLength value="8"/> * &lt;/restriction> * &lt;/simpleType> * &lt;/attribute> * &lt;attribute name="Qualifier"> * &lt;simpleType> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}NMTOKEN"> * &lt;enumeration value="Lloyds"/> * &lt;/restriction> * &lt;/simpleType> * &lt;/attribute> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "name" }) @XmlRootElement(name = "Vessel") public class Vessel { @XmlElement(name = "Name", required = true) protected String name; @XmlAttribute(name = "Country") protected String country; @XmlAttribute(name = "Scac") protected String scac; @XmlAttribute(name = "Code") protected String code; @XmlAttribute(name = "Qualifier") @XmlJavaTypeAdapter(CollapsedStringAdapter.class) protected String qualifier; /** * Gets the value of the name property. * * @return * possible object is * {@link String } * */ public String getName() { return name; } /** * Sets the value of the name property. * * @param value * allowed object is * {@link String } * */ public void setName(String value) { this.name = value; } /** * Gets the value of the country property. * * @return * possible object is * {@link String } * */ public String getCountry() { return country; } /** * Sets the value of the country property. * * @param value * allowed object is * {@link String } * */ public void setCountry(String value) { this.country = value; } /** * Gets the value of the scac property. * * @return * possible object is * {@link String } * */ public String getScac() { return scac; } /** * Sets the value of the scac property. * * @param value * allowed object is * {@link String } * */ public void setScac(String value) { this.scac = value; } /** * Gets the value of the code property. * * @return * possible object is * {@link String } * */ public String getCode() { return code; } /** * Sets the value of the code property. * * @param value * allowed object is * {@link String } * */ public void setCode(String value) { this.code = value; } /** * Gets the value of the qualifier property. * * @return * possible object is * {@link String } * */ public String getQualifier() { return qualifier; } /** * Sets the value of the qualifier property. * * @param value * allowed object is * {@link String } * */ public void setQualifier(String value) { this.qualifier = value; } }
5,531
0.547641
0.537154
217
24.48848
19.968664
111
false
false
0
0
0
0
0
0
0.341014
false
false
4
6139ff95fc3a68990800ca659a523281be62ee11
9,809,705,329,489
ba7262b697abfb3a5929eccc4f410137fc01bf6e
/TestProjectAkash2/src/test1/Test3_2.java
1e1eb91ce89742c5dde1b770a81ed2f1bd06ccef
[]
no_license
akashdutta900/TestRepo3
https://github.com/akashdutta900/TestRepo3
ba28d5178e9f6c24ec73d95c362a0b29799dec7e
52888dfa07f51caf2c6f28aa4b73e0ce2c2c6cce
refs/heads/master
2022-12-18T03:24:15.423000
2020-09-02T17:41:55
2020-09-02T17:41:55
292,348,806
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package test1; public class Test3_2 { }
UTF-8
Java
42
java
Test3_2.java
Java
[]
null
[]
package test1; public class Test3_2 { }
42
0.690476
0.619048
5
7.4
9.024411
22
false
false
0
0
0
0
0
0
0.2
false
false
4
fb366d79b4806a0be1de89ae615517639172d12d
31,138,512,919,471
78125612f63f915940cb335e89e2611c78f546d7
/hw13/book_application_back/src/test/java/ru/otus/spring/sagina/repository/GenreRepositoryTest.java
c67aebc1d14a1743227f06f4fbb0cfd574868cce
[]
no_license
VeronikaSagina/2019-11-otus-spring-sagina
https://github.com/VeronikaSagina/2019-11-otus-spring-sagina
8630f523b90926cd5dacbb11082a325385ad8f77
cdc0fd9dca2fa845e6ba9aea0e70b0f5dff92707
refs/heads/master
2021-07-11T09:55:59.297000
2020-05-26T15:34:02
2020-05-26T15:34:02
225,143,555
0
0
null
false
2022-06-14T06:58:27
2019-12-01T10:32:32
2020-05-26T15:34:06
2021-01-05T22:47:33
677
0
0
1
Java
false
false
package ru.otus.spring.sagina.repository; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; import ru.otus.spring.sagina.entity.Genre; import ru.otus.spring.sagina.testdata.GenreData; import java.util.Comparator; import java.util.List; import static org.junit.jupiter.api.Assertions.assertEquals; @DataJpaTest class GenreRepositoryTest { @Autowired private GenreRepository genreRepository; @Test void getByIdsTest() { List<Genre> expected = List.of(GenreData.NOVEL, GenreData.DETECTIVE, GenreData.FANTASY); List<Genre> actual = genreRepository.findAllByIdIn(List.of(1L, 2L, 3L)); actual.sort(Comparator.comparing(Genre::getId)); assertEquals(expected, actual); } }
UTF-8
Java
843
java
GenreRepositoryTest.java
Java
[]
null
[]
package ru.otus.spring.sagina.repository; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; import ru.otus.spring.sagina.entity.Genre; import ru.otus.spring.sagina.testdata.GenreData; import java.util.Comparator; import java.util.List; import static org.junit.jupiter.api.Assertions.assertEquals; @DataJpaTest class GenreRepositoryTest { @Autowired private GenreRepository genreRepository; @Test void getByIdsTest() { List<Genre> expected = List.of(GenreData.NOVEL, GenreData.DETECTIVE, GenreData.FANTASY); List<Genre> actual = genreRepository.findAllByIdIn(List.of(1L, 2L, 3L)); actual.sort(Comparator.comparing(Genre::getId)); assertEquals(expected, actual); } }
843
0.761566
0.758007
27
30.222221
27.221088
96
false
false
0
0
0
0
0
0
0.703704
false
false
4
95fc05138df7e4358dda52e7ae15e7e7ccfe33e1
6,227,702,605,665
aeb1020d3c09cca757bfabba3f4ee1bdfbf572a4
/src/pac/HelloWorld.java
504c3f3dfabf9965990476fbde4bb0f2e8822923
[]
no_license
BongHoLee/HtmlToPdf
https://github.com/BongHoLee/HtmlToPdf
154032aed5f7c960fda73e403c259c81ce821619
b2bdb4c365e61f05c0665e9398af70cf28b45057
refs/heads/master
2020-03-27T09:12:31.906000
2018-08-30T09:54:56
2018-08-30T09:54:56
146,322,236
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package pac; /* * Copyright 2016-2017, iText Group NV. * This example was created by Bruno Lowagie. * It was written in the context of the following book: * https://leanpub.com/itext7_pdfHTML * Go to http://developers.itextpdf.com for more info. */ import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import com.itextpdf.html2pdf.ConverterProperties; import com.itextpdf.html2pdf.HtmlConverter; import com.itextpdf.html2pdf.css.media.MediaDeviceDescription; import com.itextpdf.html2pdf.css.media.MediaType; import com.itextpdf.html2pdf.resolver.font.DefaultFontProvider; import com.itextpdf.io.font.FontProgram; import com.itextpdf.io.font.FontProgramFactory; import com.itextpdf.kernel.geom.PageSize; import com.itextpdf.kernel.pdf.PdfDocument; import com.itextpdf.kernel.pdf.PdfWriter; import com.itextpdf.layout.font.FontProvider; /** * Converts a simple Hello World HTML String to a PDF document. */ public class HelloWorld { /** The HTML-string that we are going to convert to PDF. */ public static final String HTML = "<h1>Test</h1><p>Hello Worlddsfsdfsdfsdf</p>"; /** The target folder for the result. */ public static final String TARGET = "/Users/leebongho/Desktop/Hi/"; /** The path to the resulting PDF file. */ public static final String DEST = String.format("%stest-01.pdf", TARGET); public static final String SRC = String.format("%stest1.html", TARGET); public static final String FONT = "/Users/leebongho/Desktop/font/malgun.ttf"; /** * The main method of this example. * * @param args no arguments are needed to run this example. * @throws IOException Signals that an I/O exception has occurred. */ public static void main(String[] args) throws IOException { File file = new File(TARGET); file.mkdirs(); HelloWorld he = new HelloWorld(); he.createPdf(Fileing(), FONT,DEST, SRC, TARGET); } /** * Creates the PDF file. * * @param html the HTML as a String value * @param dest the path of the resulting PDF * @throws IOException Signals that an I/O exception has occurred. */ public void createPdf(String html, String font, String dest, String src, String base) throws IOException { PdfWriter writer = new PdfWriter(dest); PdfDocument pdf = new PdfDocument(writer); pdf.setTagged(); PageSize pageSize = PageSize.A4.rotate(); pdf.setDefaultPageSize(pageSize); ConverterProperties properties = new ConverterProperties(); FontProvider fontProvider = new DefaultFontProvider(); FontProgram fontProgram = FontProgramFactory.createFont(font); fontProvider.addFont(fontProgram); properties.setFontProvider(fontProvider); //properties.setBaseUri(html); properties.setBaseUri(base); MediaDeviceDescription mediaDeviceDescription = new MediaDeviceDescription(MediaType.SCREEN); mediaDeviceDescription.setWidth(pageSize.getWidth()); properties.setMediaDeviceDescription(mediaDeviceDescription); HtmlConverter.convertToPdf(new FileInputStream(src), pdf, properties); System.out.println("suc"); } public static String Cralwing() throws FileNotFoundException{ Document doc; String defaultUrl = "http://www.google.com/"; String returnValue = null; FileOutputStream out = new FileOutputStream("/Users/leebongho/Desktop/Hi/test1.txt"); try { doc = Jsoup.connect("https://www.google.co.kr/search?q=java&oq=java&aqs=chrome..69i57j69i60l4j69i65.1574j0j7&sourceid=chrome&ie=UTF-8").get(); //System.out.println(doc.html()); returnValue = doc.html(); returnValue= returnValue.replaceAll("src=\"/", "src=\"" + defaultUrl); returnValue= returnValue.replaceAll("(?is)<script.*?>.*?</script>", ""); // remove javascript returnValue = returnValue.replaceAll("&.{2,5};|&#.{2,5};", " "); // remove special char out.write(returnValue.getBytes()); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return returnValue; } public static String Fileing() throws FileNotFoundException{ Document doc; String defaultUrl = "http://www.google.com/"; String returnValue = null; FileOutputStream out = new FileOutputStream("/Users/leebongho/Desktop/Hi/test1.html"); try { doc = Jsoup.connect("https://www.google.co.kr/search?q=java&oq=java&aqs=chrome..69i57j69i60l4j69i65.1574j0j7&sourceid=chrome&ie=UTF-8").get(); //System.out.println(doc.html()); returnValue = doc.html(); returnValue= returnValue.replaceAll("src=\"/", "src=\"" + defaultUrl); returnValue= returnValue.replaceAll("(?is)<script.*?>.*?</script>", ""); // remove javascript returnValue= returnValue.replaceAll("(?is)<noscript.*?>.*?</noscript>", ""); // remove javascript returnValue = returnValue.replaceAll("&.{2,5};|&#.{2,5};", " "); // remove special char out.write(returnValue.getBytes()); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return "/Users/leebongho/Desktop/Hi/test1.html"; } }
UTF-8
Java
5,321
java
HelloWorld.java
Java
[ { "context": "17, iText Group NV.\n * This example was created by Bruno Lowagie.\n * It was written in the context of the followin", "end": 101, "score": 0.9998775124549866, "start": 88, "tag": "NAME", "value": "Bruno Lowagie" } ]
null
[]
package pac; /* * Copyright 2016-2017, iText Group NV. * This example was created by <NAME>. * It was written in the context of the following book: * https://leanpub.com/itext7_pdfHTML * Go to http://developers.itextpdf.com for more info. */ import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import com.itextpdf.html2pdf.ConverterProperties; import com.itextpdf.html2pdf.HtmlConverter; import com.itextpdf.html2pdf.css.media.MediaDeviceDescription; import com.itextpdf.html2pdf.css.media.MediaType; import com.itextpdf.html2pdf.resolver.font.DefaultFontProvider; import com.itextpdf.io.font.FontProgram; import com.itextpdf.io.font.FontProgramFactory; import com.itextpdf.kernel.geom.PageSize; import com.itextpdf.kernel.pdf.PdfDocument; import com.itextpdf.kernel.pdf.PdfWriter; import com.itextpdf.layout.font.FontProvider; /** * Converts a simple Hello World HTML String to a PDF document. */ public class HelloWorld { /** The HTML-string that we are going to convert to PDF. */ public static final String HTML = "<h1>Test</h1><p>Hello Worlddsfsdfsdfsdf</p>"; /** The target folder for the result. */ public static final String TARGET = "/Users/leebongho/Desktop/Hi/"; /** The path to the resulting PDF file. */ public static final String DEST = String.format("%stest-01.pdf", TARGET); public static final String SRC = String.format("%stest1.html", TARGET); public static final String FONT = "/Users/leebongho/Desktop/font/malgun.ttf"; /** * The main method of this example. * * @param args no arguments are needed to run this example. * @throws IOException Signals that an I/O exception has occurred. */ public static void main(String[] args) throws IOException { File file = new File(TARGET); file.mkdirs(); HelloWorld he = new HelloWorld(); he.createPdf(Fileing(), FONT,DEST, SRC, TARGET); } /** * Creates the PDF file. * * @param html the HTML as a String value * @param dest the path of the resulting PDF * @throws IOException Signals that an I/O exception has occurred. */ public void createPdf(String html, String font, String dest, String src, String base) throws IOException { PdfWriter writer = new PdfWriter(dest); PdfDocument pdf = new PdfDocument(writer); pdf.setTagged(); PageSize pageSize = PageSize.A4.rotate(); pdf.setDefaultPageSize(pageSize); ConverterProperties properties = new ConverterProperties(); FontProvider fontProvider = new DefaultFontProvider(); FontProgram fontProgram = FontProgramFactory.createFont(font); fontProvider.addFont(fontProgram); properties.setFontProvider(fontProvider); //properties.setBaseUri(html); properties.setBaseUri(base); MediaDeviceDescription mediaDeviceDescription = new MediaDeviceDescription(MediaType.SCREEN); mediaDeviceDescription.setWidth(pageSize.getWidth()); properties.setMediaDeviceDescription(mediaDeviceDescription); HtmlConverter.convertToPdf(new FileInputStream(src), pdf, properties); System.out.println("suc"); } public static String Cralwing() throws FileNotFoundException{ Document doc; String defaultUrl = "http://www.google.com/"; String returnValue = null; FileOutputStream out = new FileOutputStream("/Users/leebongho/Desktop/Hi/test1.txt"); try { doc = Jsoup.connect("https://www.google.co.kr/search?q=java&oq=java&aqs=chrome..69i57j69i60l4j69i65.1574j0j7&sourceid=chrome&ie=UTF-8").get(); //System.out.println(doc.html()); returnValue = doc.html(); returnValue= returnValue.replaceAll("src=\"/", "src=\"" + defaultUrl); returnValue= returnValue.replaceAll("(?is)<script.*?>.*?</script>", ""); // remove javascript returnValue = returnValue.replaceAll("&.{2,5};|&#.{2,5};", " "); // remove special char out.write(returnValue.getBytes()); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return returnValue; } public static String Fileing() throws FileNotFoundException{ Document doc; String defaultUrl = "http://www.google.com/"; String returnValue = null; FileOutputStream out = new FileOutputStream("/Users/leebongho/Desktop/Hi/test1.html"); try { doc = Jsoup.connect("https://www.google.co.kr/search?q=java&oq=java&aqs=chrome..69i57j69i60l4j69i65.1574j0j7&sourceid=chrome&ie=UTF-8").get(); //System.out.println(doc.html()); returnValue = doc.html(); returnValue= returnValue.replaceAll("src=\"/", "src=\"" + defaultUrl); returnValue= returnValue.replaceAll("(?is)<script.*?>.*?</script>", ""); // remove javascript returnValue= returnValue.replaceAll("(?is)<noscript.*?>.*?</noscript>", ""); // remove javascript returnValue = returnValue.replaceAll("&.{2,5};|&#.{2,5};", " "); // remove special char out.write(returnValue.getBytes()); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return "/Users/leebongho/Desktop/Hi/test1.html"; } }
5,314
0.696486
0.683142
136
38.125
30.692602
145
false
false
0
0
0
0
0
0
1.544118
false
false
4
3bdb9a1f272bdc75cdd538ab41ea4ac484928eb5
8,512,625,209,812
59c08fbc191d2c058185429e95622ca1e2fa708f
/DentalSystem/dentalclinic/src/main/java/DAO/ILoginAsDentistDAO.java
6bd2bdde35edf4ef3aa291bf73c391ac447b6457
[]
no_license
ArshadIT/Projects
https://github.com/ArshadIT/Projects
1972d71738b1ddb183aa6cb8c8b308c5ec4b785c
87e46c7254a68813af5e618bcbbbd5b5aa920a27
refs/heads/master
2020-08-02T21:53:37.708000
2019-10-14T12:57:39
2019-10-14T12:57:39
211,517,467
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package DAO; import model.Dentist; import model.LoginAsDentist; public interface ILoginAsDentistDAO { public LoginAsDentist getPasswordByDentistId(int dentistId); public Dentist getDentistByDentistId(int dentistId); }
UTF-8
Java
236
java
ILoginAsDentistDAO.java
Java
[]
null
[]
package DAO; import model.Dentist; import model.LoginAsDentist; public interface ILoginAsDentistDAO { public LoginAsDentist getPasswordByDentistId(int dentistId); public Dentist getDentistByDentistId(int dentistId); }
236
0.788136
0.788136
11
19.454546
21.546413
61
false
false
0
0
0
0
0
0
0.727273
false
false
4
e2616a84613c803b64ab694b91d89c2645e147e4
19,619,410,636,166
c951e591622486a291aad658030da8afe27aab3a
/algoritmJava/02/src/ru/geekbrains/BubbleSortArray.java
c9440cf41d25ac8bb65791e0661948f6cc7f4f74
[]
no_license
LuninDima/GeekBrains_Calcultaor
https://github.com/LuninDima/GeekBrains_Calcultaor
6d61df0d23c4524c4352c46a62cd94da96248401
9820fb63ec84bd4b80cb4ce8768b709d14d49bce
refs/heads/master
2023-06-10T20:21:54.403000
2021-06-28T08:15:56
2021-06-28T08:15:56
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package ru.geekbrains; public class BubbleSortArray { long[] array; int elems; public BubbleSortArray(int max) { array = new long[max]; elems = 0; } public void into(long value) { array[elems] = value; elems++; } public void printer() { for (int i = 0; i < elems; i++) { System.out.print(array[i] + ", "); } System.out.println(); } private void toSwap(int first, int second) { long buffer = array[first]; array[first] = array[second]; array[second] = buffer; } public void bubbleSorted() { for (int i = elems - 1; i >= 1; i--) { for (int j = 0; j < i; j++) { if (array[j] > array[j + 1]) { toSwap(j, j + 1); } } } } }
UTF-8
Java
856
java
BubbleSortArray.java
Java
[]
null
[]
package ru.geekbrains; public class BubbleSortArray { long[] array; int elems; public BubbleSortArray(int max) { array = new long[max]; elems = 0; } public void into(long value) { array[elems] = value; elems++; } public void printer() { for (int i = 0; i < elems; i++) { System.out.print(array[i] + ", "); } System.out.println(); } private void toSwap(int first, int second) { long buffer = array[first]; array[first] = array[second]; array[second] = buffer; } public void bubbleSorted() { for (int i = elems - 1; i >= 1; i--) { for (int j = 0; j < i; j++) { if (array[j] > array[j + 1]) { toSwap(j, j + 1); } } } } }
856
0.450935
0.442757
39
20.948717
15.914755
48
false
false
0
0
0
0
0
0
0.564103
false
false
4
05d9988ed6d5e8186dc9332256e41cb83fc0f21c
23,940,147,731,442
dd87660b5dcc19fd623a68b7a9e33b526b579717
/PHRASAL_VERBS/PhrasalVerbs_v6.0_apkpure.com_source_from_JADX/PhrasalVerbs_v6.0_apkpure.com_source_from_JADX/sources/android/support/p030v7/widget/C0522K.java
3b244701d4b7c82f66cb8c239323d22f1739888b
[]
no_license
PhongNgo1776/NEW_FLUTTER_PROJECTS
https://github.com/PhongNgo1776/NEW_FLUTTER_PROJECTS
69045dafdbf732fb1ee9600527ee86eccd9e7f3c
80b25ace5b84edff9c9d31f082a4160347e98493
refs/heads/master
2020-12-01T14:17:05.006000
2020-11-26T11:12:54
2020-11-26T11:12:54
230,645,895
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package android.support.p030v7.widget; import android.support.p030v7.view.menu.C0485v.C0486a; import android.view.Menu; import android.view.Window.Callback; /* renamed from: android.support.v7.widget.K */ public interface C0522K { /* renamed from: a */ void mo2455a(int i); /* renamed from: a */ void mo2456a(Menu menu, C0486a aVar); /* renamed from: a */ boolean mo2457a(); /* renamed from: b */ void mo2458b(); /* renamed from: c */ boolean mo2459c(); /* renamed from: d */ boolean mo2461d(); /* renamed from: e */ boolean mo2463e(); /* renamed from: f */ boolean mo2464f(); /* renamed from: g */ void mo2466g(); void setWindowCallback(Callback callback); void setWindowTitle(CharSequence charSequence); }
UTF-8
Java
800
java
C0522K.java
Java
[]
null
[]
package android.support.p030v7.widget; import android.support.p030v7.view.menu.C0485v.C0486a; import android.view.Menu; import android.view.Window.Callback; /* renamed from: android.support.v7.widget.K */ public interface C0522K { /* renamed from: a */ void mo2455a(int i); /* renamed from: a */ void mo2456a(Menu menu, C0486a aVar); /* renamed from: a */ boolean mo2457a(); /* renamed from: b */ void mo2458b(); /* renamed from: c */ boolean mo2459c(); /* renamed from: d */ boolean mo2461d(); /* renamed from: e */ boolean mo2463e(); /* renamed from: f */ boolean mo2464f(); /* renamed from: g */ void mo2466g(); void setWindowCallback(Callback callback); void setWindowTitle(CharSequence charSequence); }
800
0.63625
0.56
39
19.512821
16.019014
54
false
false
0
0
0
0
0
0
0.410256
false
false
4
776de09dae85881f312ae529adacc1dda6192b24
27,822,798,169,107
e57e538fd2e5b1a706af7fb07e827edfe59b753d
/src/main/java/edu/ucla/library/bucketeer/converters/AbstractConverter.java
dd6f7cb5641d199428d6da11ad6f776da3e60fdc
[ "BSD-3-Clause" ]
permissive
kanyu/bucketeer
https://github.com/kanyu/bucketeer
102b2a3d97c147afbb59987082fd440310c1d539
a21ee3972f2fadcf81d8c9579d8c3194c86a92ee
refs/heads/master
2022-12-24T02:39:20.956000
2020-09-15T02:36:55
2020-09-15T02:36:55
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package edu.ucla.library.bucketeer.converters; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import info.freelibrary.util.IOUtils; import info.freelibrary.util.Logger; import edu.ucla.library.bucketeer.MessageCodes; abstract class AbstractConverter { /** * Get the executable command. * * @return The executable command */ protected abstract String getExecutable(); /** * Run the conversion process. * * @param aProcessBuilder A process builder that has the process to run * @param aID The ID for the image that's being converted * @throws IOException If the process has trouble reading or writing * @throws InterruptedException If the process has been interrupted */ protected void run(final ProcessBuilder aProcessBuilder, final String aID, final Logger aLogger) throws IOException, InterruptedException { final Process process = aProcessBuilder.start(); if (process.waitFor() != 0) { aLogger.error(getMessage(new BufferedReader(new InputStreamReader(process.getErrorStream())))); throw new IOException(aLogger.getMessage(MessageCodes.BUCKETEER_001, aID)); } else if (aLogger.isDebugEnabled()) { aLogger.debug(getMessage(new BufferedReader(new InputStreamReader(process.getInputStream())))); } } private String getMessage(final BufferedReader aReader) throws IOException { final StringBuilder buffer = new StringBuilder(); String line; while ((line = aReader.readLine()) != null) { buffer.append(line); } IOUtils.closeQuietly(aReader); return buffer.toString(); } }
UTF-8
Java
1,751
java
AbstractConverter.java
Java
[]
null
[]
package edu.ucla.library.bucketeer.converters; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import info.freelibrary.util.IOUtils; import info.freelibrary.util.Logger; import edu.ucla.library.bucketeer.MessageCodes; abstract class AbstractConverter { /** * Get the executable command. * * @return The executable command */ protected abstract String getExecutable(); /** * Run the conversion process. * * @param aProcessBuilder A process builder that has the process to run * @param aID The ID for the image that's being converted * @throws IOException If the process has trouble reading or writing * @throws InterruptedException If the process has been interrupted */ protected void run(final ProcessBuilder aProcessBuilder, final String aID, final Logger aLogger) throws IOException, InterruptedException { final Process process = aProcessBuilder.start(); if (process.waitFor() != 0) { aLogger.error(getMessage(new BufferedReader(new InputStreamReader(process.getErrorStream())))); throw new IOException(aLogger.getMessage(MessageCodes.BUCKETEER_001, aID)); } else if (aLogger.isDebugEnabled()) { aLogger.debug(getMessage(new BufferedReader(new InputStreamReader(process.getInputStream())))); } } private String getMessage(final BufferedReader aReader) throws IOException { final StringBuilder buffer = new StringBuilder(); String line; while ((line = aReader.readLine()) != null) { buffer.append(line); } IOUtils.closeQuietly(aReader); return buffer.toString(); } }
1,751
0.686465
0.68418
54
31.407408
30.387936
107
false
false
0
0
0
0
0
0
0.388889
false
false
4
829578f114a9b9e44c9348409d8e0d9460b520a5
31,988,916,451,441
a716e7c64d7e3bef50d6ee72d02d171ea1a5231c
/app/src/main/java/com/somworld/seller_ui/views/UpdateOffer.java
8ad4fc4b24cfc8ccb5afaccf0270f2cab1c5a604
[]
no_license
somesh9827/seller-ui
https://github.com/somesh9827/seller-ui
371b183115d8f6d4c4da5848874f336b4772ddd9
da3efb1a8ffa2d8886d07cd4e10d22f6e9cfc662
refs/heads/master
2021-01-21T19:28:52.330000
2015-03-23T21:25:50
2015-03-23T21:25:50
28,020,215
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.somworld.seller_ui.views; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; import com.somworld.seller_ui.R; import com.somworld.seller_ui.helpers.OfferHelper; import com.somworld.seller_ui.helpers.Utils; import com.somworld.seller_ui.helpers.validators.IValidatorListener; import com.somworld.seller_ui.helpers.validators.RuleValueAdapter; import com.somworld.seller_ui.helpers.validators.ValidationError; import com.somworld.seller_ui.helpers.validators.Validator; import com.somworld.seller_ui.helpers.validators.rules.MinDate; import com.somworld.seller_ui.helpers.validators.rules.NotEmpty; import com.somworld.seller_ui.helpers.validators.rules.RULE; import com.somworld.seller_ui.models.OfferItems; import com.somworld.seller_ui.models.OnCompleteListener; import com.somworld.seller_ui.models.ParcelableKeys; import java.lang.ref.WeakReference; import java.text.ParseException; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Map; import java.util.Vector; public class UpdateOffer extends Activity implements View.OnClickListener, OnCompleteListener { private int dateContext = -1; private EditText product; private EditText productDescription; private EditText offerStartDate; private EditText offerEndDate; private EditText validOfferTime; private Button saveButton; private Button cancelButton; private OfferItems mOffer; @Override public void complete(int status, Map<String, Object> data) { if (status == OnCompleteListener.SUCCESS) { if (data.containsKey("date")) { Date date = new Date(((Date) (data.get("date"))).getTime()); setDateToTextBox(date); } else if (data.containsKey("fromTime") && data.containsKey("toTime")) { } } else { } } private void setDateToTextBox(Date date) { if (dateContext == Utils.START_DATE_CONTEXT && offerStartDate != null) { offerStartDate .setText(OfferHelper.formatDate(date, Utils.START_DATE_CONTEXT, Utils.getDateFormat())); } else if (dateContext == Utils.END_DATE_CONTEXT && offerEndDate != null) { offerEndDate .setText(OfferHelper.formatDate(date, Utils.END_DATE_CONTEXT, Utils.getDateFormat())); } } private void setTimeToTextBox(Date fromTime, Date toTime) { String ValidOfferTimeString = Utils.validTimeToValidTimeString(fromTime, toTime); EditText validOfferTimeText = (EditText) findViewById(R.id.update_offer_valid_time); validOfferTimeText.setText(ValidOfferTimeString); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_update_offer); Intent intent = getIntent(); Bundle mBundle = intent.getExtras(); mOffer = mBundle.getParcelable(ParcelableKeys.OFFER_ITEM); offerStartDate = (EditText) findViewById(R.id.update_offer_start_date); offerEndDate = (EditText) findViewById(R.id.update_offer_end_date); product = (EditText) findViewById(R.id.update_offer_product); productDescription = (EditText) findViewById(R.id.update_offer_description); saveButton = (Button) findViewById(R.id.update_offer_save_button); cancelButton = (Button) findViewById(R.id.update_offer_cancel_button); validOfferTime = (EditText) findViewById(R.id.update_offer_valid_time); product.setText(mOffer.getProduct()); productDescription.setText(mOffer.getDescription()); offerStartDate.setText(OfferHelper.formatDate(mOffer.getStartDate(), Utils.START_DATE_CONTEXT, Utils.getDateFormat())); offerEndDate.setText( OfferHelper.formatDate(mOffer.getEndDate(), Utils.END_DATE_CONTEXT, Utils.getDateFormat())); validOfferTime.setText( Utils.validTimeToValidTimeString(mOffer.getStartValidTime(), mOffer.getEndValidTime())); WeakReference<UpdateOffer> updateOfferWeakReference = new WeakReference<UpdateOffer>(this); UpdateOfferOnClickListener updateOfferOnClickListener = new UpdateOfferOnClickListener(updateOfferWeakReference.get()); saveButton.setOnClickListener(updateOfferOnClickListener); cancelButton.setOnClickListener(updateOfferOnClickListener); offerStartDate.setOnClickListener(updateOfferOnClickListener); offerEndDate.setOnClickListener(updateOfferOnClickListener); validOfferTime.setOnClickListener(updateOfferOnClickListener); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.update_offer, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } @Override public void onClick(View view) { switch (view.getId()) { case R.id.update_offer_start_date: dateContext = Utils.START_DATE_CONTEXT; new DateAndTimePickerDialog(UpdateOffer.this, this).show(); break; case R.id.update_offer_end_date: dateContext = Utils.END_DATE_CONTEXT; new DateAndTimePickerDialog(UpdateOffer.this, this).show(); break; case R.id.update_offer_save_button: saveOffer(); break; case R.id.update_offer_cancel_button: cancelUpdate(); break; default: break; } } private void setErrorMessage(String errorMessage) { TextView errorTextView = (TextView) findViewById(R.id.update_offer_error_message); errorTextView.setText(errorMessage); errorTextView.setVisibility(View.VISIBLE); } private void resetErrorMessage() { TextView errorTextView = (TextView) findViewById(R.id.update_offer_error_message); errorTextView.setText(""); errorTextView.setVisibility(View.GONE); } private void saveOffer() { try { mOffer.setProduct(product.getText().toString()); mOffer.setDescription(productDescription.getText().toString()); //mOffer.setStartDate(Utils.getTimeFormat().parse(offerStartDate.getText().toString())); mOffer.setStartDate(offerStartDate.getText().toString(), Utils.getDateFormat()); //mOffer.setEndDate(Utils.getTimeFormat().parse(offerEndDate.getText().toString())); mOffer.setEndDate(offerEndDate.getText().toString(), Utils.getDateFormat()); Bundle mBundle = new Bundle(); mBundle.putParcelable(ParcelableKeys.OFFER_ITEM, mOffer); Intent showDashBoardIntent = new Intent(); showDashBoardIntent.putExtras(mBundle); setResult(RESULT_OK, showDashBoardIntent); finish(); } catch (ParseException e) { e.printStackTrace(); } } private void cancelUpdate() { setResult(RESULT_CANCELED); finish(); } private static class UpdateOfferOnClickListener implements View.OnClickListener, OnCompleteListener, IValidatorListener { private UpdateOffer mParent; UpdateOfferOnClickListener(UpdateOffer offerActivity) { mParent = offerActivity; } @Override public void onClick(View view) { if (mParent == null) { return; } switch (view.getId()) { case R.id.update_offer_start_date: mParent.dateContext = Utils.START_DATE_CONTEXT; new DateAndTimePickerDialog(mParent, this).show(); break; case R.id.update_offer_end_date: mParent.dateContext = Utils.END_DATE_CONTEXT; new DateAndTimePickerDialog(mParent, this).show(); break; case R.id.update_offer_valid_time: new TimePickerDialog(mParent, this).show(); break; case R.id.update_offer_save_button: validateOffer(); break; case R.id.update_offer_cancel_button: mParent.cancelUpdate(); break; default: break; } } private void validateOffer() { if (mParent == null) { return; } try { String description = ((EditText) mParent.findViewById(R.id.update_offer_description)).getText().toString(); String productName = ((EditText) mParent.findViewById(R.id.update_offer_product)).getText().toString(); String startTimeString = ((EditText) mParent.findViewById(R.id.update_offer_start_date)).getText().toString(); String endTimeString = ((EditText) mParent.findViewById(R.id.update_offer_end_date)).getText().toString(); Date startTime = Utils.getDateFormat().parse(startTimeString); Date endTime = Utils.getDateFormat().parse(endTimeString); description = description.equals(mParent.getString(R.string.product_description)) ? "" : description; productName = productName.equals(mParent.getString(R.string.product_name)) ? "" : productName; List<RuleValueAdapter> ruleValueAdapters = new ArrayList<RuleValueAdapter>(); RULE NotEmptyRule2 = new NotEmpty(); RuleValueAdapter<String> ruleValueAdapter2 = new RuleValueAdapter<String>(R.id.update_offer_product, productName); ruleValueAdapter2.addRule(NotEmptyRule2, String .format(mParent.getString(R.string.not_empty_error), "Product Name")); ruleValueAdapters.add(ruleValueAdapter2); RULE NotEmptyRule = new NotEmpty(); RuleValueAdapter<String> ruleValueAdapter1 = new RuleValueAdapter<String>(R.id.update_offer_description, description); ruleValueAdapter1.addRule(NotEmptyRule, String .format(mParent.getString(R.string.not_empty_error), "Product Description")); ruleValueAdapters.add(ruleValueAdapter1); RULE NotEmptyRule3 = new NotEmpty(); RULE minDateRule = new MinDate(startTime); RuleValueAdapter<Date> ruleValueAdapter3 = new RuleValueAdapter<Date>(R.id.update_offer_end_date, endTime); ruleValueAdapter3.addRule(NotEmptyRule3, String.format(mParent.getString(R.string.not_empty_error), "End Date")); ruleValueAdapter3.addRule(minDateRule, String .format(mParent.getString(R.string.min_error), "Start Date", "End Date")); ruleValueAdapters.add(ruleValueAdapter3); RULE NotEmptyRule4 = new NotEmpty(); RULE minDateRule1 = new MinDate(Utils.getMinAllowedStartTime(Utils.getCurrentDate())); RuleValueAdapter<Date> ruleValueAdapter4 = new RuleValueAdapter<Date>(R.id.update_offer_start_date, startTime); ruleValueAdapter4.addRule(NotEmptyRule4, String .format(mParent.getString(R.string.not_empty_error), "Start Date")); ruleValueAdapter4.addRule(minDateRule1, String .format(mParent.getString(R.string.min_error), "Start Date", "Current Date")); ruleValueAdapters.add(ruleValueAdapter4); Validator validator = new Validator(this); validator.validate(ruleValueAdapters); } catch (ParseException e) { Toast.makeText(mParent, "In Correct Data", Toast.LENGTH_LONG).show(); } } @Override public void complete(int status, Map<String, Object> data) { if (mParent == null) { return; } if (status == OnCompleteListener.SUCCESS) { if (data.containsKey("date")) { Date date = new Date(((Date) (data.get("date"))).getTime()); mParent.setDateToTextBox(date); } else if (data.containsKey("fromTime") && data.containsKey("toTime")) { Date fromTime = new Date(((Date) (data.get("fromTime"))).getTime()); Date toTime = new Date(((Date) (data.get("toTime"))).getTime()); mParent.setTimeToTextBox(fromTime, toTime); } } else { } } @Override public void onValidationFail(ValidationError error) { Vector<Integer> keys = error.getAllKeys(); int firstKey = keys.get(0); String errorMessage = error.getFirstErrorMessage(firstKey); //Toast.makeText(mParent,errorMessage,Toast.LENGTH_LONG).show(); mParent.setErrorMessage(errorMessage); } @Override public void onValidationSuccess(List<RuleValueAdapter> ruleValueAdapters) { OfferItems offer = new OfferItems(); for (RuleValueAdapter field : ruleValueAdapters) { switch (field.getId()) { case R.id.update_offer_description: offer.setDescription(field.getValue().toString()); break; case R.id.update_offer_product: offer.setProduct(field.getValue().toString()); break; case R.id.update_offer_start_date: offer.setStartDate((Date) field.getValue()); break; case R.id.update_offer_end_date: offer.setEndDate((Date) field.getValue()); break; default: break; } } offer.setId(mParent.mOffer.getId()); offer.setActive(true); offer.setDiscount(""); offer.setActive(OfferHelper.isValid(offer)); String validTimeString = ((EditText) mParent.findViewById(R.id.update_offer_valid_time)).getText().toString(); try { Map<String, Date> validTime = Utils.validTimeStringToValidTime(validTimeString); offer.setStartValidTime(validTime.get("fromTime")); offer.setEndValidTime(validTime.get("toTime")); } catch (ParseException e) { e.printStackTrace(); } Bundle mBundle = new Bundle(); mBundle.putParcelable(ParcelableKeys.OFFER_ITEM, offer); Intent showDashBoardIntent = new Intent(); showDashBoardIntent.putExtras(mBundle); mParent.resetErrorMessage(); mParent.setResult(RESULT_OK, showDashBoardIntent); mParent.resetErrorMessage(); mParent.finish(); } } }
UTF-8
Java
14,186
java
UpdateOffer.java
Java
[]
null
[]
package com.somworld.seller_ui.views; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; import com.somworld.seller_ui.R; import com.somworld.seller_ui.helpers.OfferHelper; import com.somworld.seller_ui.helpers.Utils; import com.somworld.seller_ui.helpers.validators.IValidatorListener; import com.somworld.seller_ui.helpers.validators.RuleValueAdapter; import com.somworld.seller_ui.helpers.validators.ValidationError; import com.somworld.seller_ui.helpers.validators.Validator; import com.somworld.seller_ui.helpers.validators.rules.MinDate; import com.somworld.seller_ui.helpers.validators.rules.NotEmpty; import com.somworld.seller_ui.helpers.validators.rules.RULE; import com.somworld.seller_ui.models.OfferItems; import com.somworld.seller_ui.models.OnCompleteListener; import com.somworld.seller_ui.models.ParcelableKeys; import java.lang.ref.WeakReference; import java.text.ParseException; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Map; import java.util.Vector; public class UpdateOffer extends Activity implements View.OnClickListener, OnCompleteListener { private int dateContext = -1; private EditText product; private EditText productDescription; private EditText offerStartDate; private EditText offerEndDate; private EditText validOfferTime; private Button saveButton; private Button cancelButton; private OfferItems mOffer; @Override public void complete(int status, Map<String, Object> data) { if (status == OnCompleteListener.SUCCESS) { if (data.containsKey("date")) { Date date = new Date(((Date) (data.get("date"))).getTime()); setDateToTextBox(date); } else if (data.containsKey("fromTime") && data.containsKey("toTime")) { } } else { } } private void setDateToTextBox(Date date) { if (dateContext == Utils.START_DATE_CONTEXT && offerStartDate != null) { offerStartDate .setText(OfferHelper.formatDate(date, Utils.START_DATE_CONTEXT, Utils.getDateFormat())); } else if (dateContext == Utils.END_DATE_CONTEXT && offerEndDate != null) { offerEndDate .setText(OfferHelper.formatDate(date, Utils.END_DATE_CONTEXT, Utils.getDateFormat())); } } private void setTimeToTextBox(Date fromTime, Date toTime) { String ValidOfferTimeString = Utils.validTimeToValidTimeString(fromTime, toTime); EditText validOfferTimeText = (EditText) findViewById(R.id.update_offer_valid_time); validOfferTimeText.setText(ValidOfferTimeString); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_update_offer); Intent intent = getIntent(); Bundle mBundle = intent.getExtras(); mOffer = mBundle.getParcelable(ParcelableKeys.OFFER_ITEM); offerStartDate = (EditText) findViewById(R.id.update_offer_start_date); offerEndDate = (EditText) findViewById(R.id.update_offer_end_date); product = (EditText) findViewById(R.id.update_offer_product); productDescription = (EditText) findViewById(R.id.update_offer_description); saveButton = (Button) findViewById(R.id.update_offer_save_button); cancelButton = (Button) findViewById(R.id.update_offer_cancel_button); validOfferTime = (EditText) findViewById(R.id.update_offer_valid_time); product.setText(mOffer.getProduct()); productDescription.setText(mOffer.getDescription()); offerStartDate.setText(OfferHelper.formatDate(mOffer.getStartDate(), Utils.START_DATE_CONTEXT, Utils.getDateFormat())); offerEndDate.setText( OfferHelper.formatDate(mOffer.getEndDate(), Utils.END_DATE_CONTEXT, Utils.getDateFormat())); validOfferTime.setText( Utils.validTimeToValidTimeString(mOffer.getStartValidTime(), mOffer.getEndValidTime())); WeakReference<UpdateOffer> updateOfferWeakReference = new WeakReference<UpdateOffer>(this); UpdateOfferOnClickListener updateOfferOnClickListener = new UpdateOfferOnClickListener(updateOfferWeakReference.get()); saveButton.setOnClickListener(updateOfferOnClickListener); cancelButton.setOnClickListener(updateOfferOnClickListener); offerStartDate.setOnClickListener(updateOfferOnClickListener); offerEndDate.setOnClickListener(updateOfferOnClickListener); validOfferTime.setOnClickListener(updateOfferOnClickListener); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.update_offer, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } @Override public void onClick(View view) { switch (view.getId()) { case R.id.update_offer_start_date: dateContext = Utils.START_DATE_CONTEXT; new DateAndTimePickerDialog(UpdateOffer.this, this).show(); break; case R.id.update_offer_end_date: dateContext = Utils.END_DATE_CONTEXT; new DateAndTimePickerDialog(UpdateOffer.this, this).show(); break; case R.id.update_offer_save_button: saveOffer(); break; case R.id.update_offer_cancel_button: cancelUpdate(); break; default: break; } } private void setErrorMessage(String errorMessage) { TextView errorTextView = (TextView) findViewById(R.id.update_offer_error_message); errorTextView.setText(errorMessage); errorTextView.setVisibility(View.VISIBLE); } private void resetErrorMessage() { TextView errorTextView = (TextView) findViewById(R.id.update_offer_error_message); errorTextView.setText(""); errorTextView.setVisibility(View.GONE); } private void saveOffer() { try { mOffer.setProduct(product.getText().toString()); mOffer.setDescription(productDescription.getText().toString()); //mOffer.setStartDate(Utils.getTimeFormat().parse(offerStartDate.getText().toString())); mOffer.setStartDate(offerStartDate.getText().toString(), Utils.getDateFormat()); //mOffer.setEndDate(Utils.getTimeFormat().parse(offerEndDate.getText().toString())); mOffer.setEndDate(offerEndDate.getText().toString(), Utils.getDateFormat()); Bundle mBundle = new Bundle(); mBundle.putParcelable(ParcelableKeys.OFFER_ITEM, mOffer); Intent showDashBoardIntent = new Intent(); showDashBoardIntent.putExtras(mBundle); setResult(RESULT_OK, showDashBoardIntent); finish(); } catch (ParseException e) { e.printStackTrace(); } } private void cancelUpdate() { setResult(RESULT_CANCELED); finish(); } private static class UpdateOfferOnClickListener implements View.OnClickListener, OnCompleteListener, IValidatorListener { private UpdateOffer mParent; UpdateOfferOnClickListener(UpdateOffer offerActivity) { mParent = offerActivity; } @Override public void onClick(View view) { if (mParent == null) { return; } switch (view.getId()) { case R.id.update_offer_start_date: mParent.dateContext = Utils.START_DATE_CONTEXT; new DateAndTimePickerDialog(mParent, this).show(); break; case R.id.update_offer_end_date: mParent.dateContext = Utils.END_DATE_CONTEXT; new DateAndTimePickerDialog(mParent, this).show(); break; case R.id.update_offer_valid_time: new TimePickerDialog(mParent, this).show(); break; case R.id.update_offer_save_button: validateOffer(); break; case R.id.update_offer_cancel_button: mParent.cancelUpdate(); break; default: break; } } private void validateOffer() { if (mParent == null) { return; } try { String description = ((EditText) mParent.findViewById(R.id.update_offer_description)).getText().toString(); String productName = ((EditText) mParent.findViewById(R.id.update_offer_product)).getText().toString(); String startTimeString = ((EditText) mParent.findViewById(R.id.update_offer_start_date)).getText().toString(); String endTimeString = ((EditText) mParent.findViewById(R.id.update_offer_end_date)).getText().toString(); Date startTime = Utils.getDateFormat().parse(startTimeString); Date endTime = Utils.getDateFormat().parse(endTimeString); description = description.equals(mParent.getString(R.string.product_description)) ? "" : description; productName = productName.equals(mParent.getString(R.string.product_name)) ? "" : productName; List<RuleValueAdapter> ruleValueAdapters = new ArrayList<RuleValueAdapter>(); RULE NotEmptyRule2 = new NotEmpty(); RuleValueAdapter<String> ruleValueAdapter2 = new RuleValueAdapter<String>(R.id.update_offer_product, productName); ruleValueAdapter2.addRule(NotEmptyRule2, String .format(mParent.getString(R.string.not_empty_error), "Product Name")); ruleValueAdapters.add(ruleValueAdapter2); RULE NotEmptyRule = new NotEmpty(); RuleValueAdapter<String> ruleValueAdapter1 = new RuleValueAdapter<String>(R.id.update_offer_description, description); ruleValueAdapter1.addRule(NotEmptyRule, String .format(mParent.getString(R.string.not_empty_error), "Product Description")); ruleValueAdapters.add(ruleValueAdapter1); RULE NotEmptyRule3 = new NotEmpty(); RULE minDateRule = new MinDate(startTime); RuleValueAdapter<Date> ruleValueAdapter3 = new RuleValueAdapter<Date>(R.id.update_offer_end_date, endTime); ruleValueAdapter3.addRule(NotEmptyRule3, String.format(mParent.getString(R.string.not_empty_error), "End Date")); ruleValueAdapter3.addRule(minDateRule, String .format(mParent.getString(R.string.min_error), "Start Date", "End Date")); ruleValueAdapters.add(ruleValueAdapter3); RULE NotEmptyRule4 = new NotEmpty(); RULE minDateRule1 = new MinDate(Utils.getMinAllowedStartTime(Utils.getCurrentDate())); RuleValueAdapter<Date> ruleValueAdapter4 = new RuleValueAdapter<Date>(R.id.update_offer_start_date, startTime); ruleValueAdapter4.addRule(NotEmptyRule4, String .format(mParent.getString(R.string.not_empty_error), "Start Date")); ruleValueAdapter4.addRule(minDateRule1, String .format(mParent.getString(R.string.min_error), "Start Date", "Current Date")); ruleValueAdapters.add(ruleValueAdapter4); Validator validator = new Validator(this); validator.validate(ruleValueAdapters); } catch (ParseException e) { Toast.makeText(mParent, "In Correct Data", Toast.LENGTH_LONG).show(); } } @Override public void complete(int status, Map<String, Object> data) { if (mParent == null) { return; } if (status == OnCompleteListener.SUCCESS) { if (data.containsKey("date")) { Date date = new Date(((Date) (data.get("date"))).getTime()); mParent.setDateToTextBox(date); } else if (data.containsKey("fromTime") && data.containsKey("toTime")) { Date fromTime = new Date(((Date) (data.get("fromTime"))).getTime()); Date toTime = new Date(((Date) (data.get("toTime"))).getTime()); mParent.setTimeToTextBox(fromTime, toTime); } } else { } } @Override public void onValidationFail(ValidationError error) { Vector<Integer> keys = error.getAllKeys(); int firstKey = keys.get(0); String errorMessage = error.getFirstErrorMessage(firstKey); //Toast.makeText(mParent,errorMessage,Toast.LENGTH_LONG).show(); mParent.setErrorMessage(errorMessage); } @Override public void onValidationSuccess(List<RuleValueAdapter> ruleValueAdapters) { OfferItems offer = new OfferItems(); for (RuleValueAdapter field : ruleValueAdapters) { switch (field.getId()) { case R.id.update_offer_description: offer.setDescription(field.getValue().toString()); break; case R.id.update_offer_product: offer.setProduct(field.getValue().toString()); break; case R.id.update_offer_start_date: offer.setStartDate((Date) field.getValue()); break; case R.id.update_offer_end_date: offer.setEndDate((Date) field.getValue()); break; default: break; } } offer.setId(mParent.mOffer.getId()); offer.setActive(true); offer.setDiscount(""); offer.setActive(OfferHelper.isValid(offer)); String validTimeString = ((EditText) mParent.findViewById(R.id.update_offer_valid_time)).getText().toString(); try { Map<String, Date> validTime = Utils.validTimeStringToValidTime(validTimeString); offer.setStartValidTime(validTime.get("fromTime")); offer.setEndValidTime(validTime.get("toTime")); } catch (ParseException e) { e.printStackTrace(); } Bundle mBundle = new Bundle(); mBundle.putParcelable(ParcelableKeys.OFFER_ITEM, offer); Intent showDashBoardIntent = new Intent(); showDashBoardIntent.putExtras(mBundle); mParent.resetErrorMessage(); mParent.setResult(RESULT_OK, showDashBoardIntent); mParent.resetErrorMessage(); mParent.finish(); } } }
14,186
0.679332
0.67764
393
35.096691
28.210871
106
false
false
0
0
0
0
0
0
0.633588
false
false
4
f8850e1b3075dd13df4f4c2eea11fcd0e07fc252
31,988,916,453,725
a754234377616c4bdeb90c3994a6d9ab0c38cc15
/Assignment1/Assignment1/src/Treap.java
156ec920ed4db9ccc640385dc624e3a6a235de18
[]
no_license
maxpoi/UniMelb-Advaced-Algorithm-Data-Structure-Study-Notes-Assignments
https://github.com/maxpoi/UniMelb-Advaced-Algorithm-Data-Structure-Study-Notes-Assignments
65412527bf1682625a256dc89e42923ccb8d4794
db8f2c8516cc9444319593bb8b4d52f52c50ccd0
refs/heads/main
2023-04-18T22:21:15.704000
2021-04-26T15:39:50
2021-04-26T15:39:50
361,803,975
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import java.util.Random; public class Treap { public Treap left, right; public int priority; public DataElement data; public Treap() { left = null; right = null; data = null; Random rand = new Random(); priority = rand.nextInt(Main.M); } public static Treap rotateLeft(Treap treap) { Treap right = treap.right; Treap rightLeft = right.left; right.left = treap; treap.right = rightLeft; return right; } public static Treap rotateRight(Treap treap) { Treap left = treap.left; Treap leftRight = left.right; left.right = treap; treap.left = leftRight; return left; } public static Treap insert(DataElement data, Treap treap) { if (treap == null || treap.data == null) { Treap leaf = new Treap(); leaf.data = data; return leaf; } else { if (data.key > treap.data.key || ((data.key == treap.data.key) && data.id > treap.data.id)) { treap.right = insert(data, treap.right); if (treap.priority > treap.right.priority) treap = rotateLeft(treap); } else if(data.key < treap.data.key || ((data.key == treap.data.key) && data.id < treap.data.id)) { treap.left = insert(data, treap.left); if (treap.priority > treap.left.priority) treap = rotateRight(treap); } return treap; } } public static Treap delete(int key, Treap treap) { // if (treap == null) // return null; // search through the treap if (key > treap.data.key) { if (treap.right == null) return treap; treap.right = delete(key, treap.right); } else if (key < treap.data.key) { if (treap.left == null) return treap; treap.left = delete(key, treap.left); } else { // found it, rotate to leaf if (treap.left != null && treap.right != null) { if (treap.left.priority < treap.right.priority) { treap = rotateRight(treap); treap.right = delete(key, treap.right); } else { treap = rotateLeft(treap); treap.left = delete(key, treap.left); } } else if (treap.left == null && treap.right != null) { treap = rotateLeft(treap); treap.left = delete(key, treap.left); } else if (treap.right == null && treap.left != null) { treap = rotateRight(treap); treap.right = delete(key, treap.right); } else // now at the leaf, delete it treap = null; } return treap; } public static DataElement search(int key, Treap treap) { if (treap == null) return null; if (key > treap.data.key) return search(key, treap.right); else if (key < treap.data.key) return search(key, treap.left); else return treap.data; } public static int treapSize(Treap treap, int size) { if (treap == null) return 0; size += treapSize(treap.left, 0); size += 1; size += treapSize(treap.right, 0); return size; } }
UTF-8
Java
3,555
java
Treap.java
Java
[]
null
[]
import java.util.Random; public class Treap { public Treap left, right; public int priority; public DataElement data; public Treap() { left = null; right = null; data = null; Random rand = new Random(); priority = rand.nextInt(Main.M); } public static Treap rotateLeft(Treap treap) { Treap right = treap.right; Treap rightLeft = right.left; right.left = treap; treap.right = rightLeft; return right; } public static Treap rotateRight(Treap treap) { Treap left = treap.left; Treap leftRight = left.right; left.right = treap; treap.left = leftRight; return left; } public static Treap insert(DataElement data, Treap treap) { if (treap == null || treap.data == null) { Treap leaf = new Treap(); leaf.data = data; return leaf; } else { if (data.key > treap.data.key || ((data.key == treap.data.key) && data.id > treap.data.id)) { treap.right = insert(data, treap.right); if (treap.priority > treap.right.priority) treap = rotateLeft(treap); } else if(data.key < treap.data.key || ((data.key == treap.data.key) && data.id < treap.data.id)) { treap.left = insert(data, treap.left); if (treap.priority > treap.left.priority) treap = rotateRight(treap); } return treap; } } public static Treap delete(int key, Treap treap) { // if (treap == null) // return null; // search through the treap if (key > treap.data.key) { if (treap.right == null) return treap; treap.right = delete(key, treap.right); } else if (key < treap.data.key) { if (treap.left == null) return treap; treap.left = delete(key, treap.left); } else { // found it, rotate to leaf if (treap.left != null && treap.right != null) { if (treap.left.priority < treap.right.priority) { treap = rotateRight(treap); treap.right = delete(key, treap.right); } else { treap = rotateLeft(treap); treap.left = delete(key, treap.left); } } else if (treap.left == null && treap.right != null) { treap = rotateLeft(treap); treap.left = delete(key, treap.left); } else if (treap.right == null && treap.left != null) { treap = rotateRight(treap); treap.right = delete(key, treap.right); } else // now at the leaf, delete it treap = null; } return treap; } public static DataElement search(int key, Treap treap) { if (treap == null) return null; if (key > treap.data.key) return search(key, treap.right); else if (key < treap.data.key) return search(key, treap.left); else return treap.data; } public static int treapSize(Treap treap, int size) { if (treap == null) return 0; size += treapSize(treap.left, 0); size += 1; size += treapSize(treap.right, 0); return size; } }
3,555
0.490577
0.489451
125
27.440001
20.941214
80
false
false
0
0
0
0
0
0
0.608
false
false
4
59e37fdb691e6003e34f3318c7cddd504d87c70b
29,265,907,184,944
defb1f35ff2d6677c8342f6486382d21fabc4ec8
/AGI_union-master-alltypes/idacq/src/main/java/com/adapter/event/StreamReport/StreamReportManager.java
d82c6dc5ca66d2297583114b74096e8cce2cba30
[]
no_license
lyx5216288/AGI_union_alltypes
https://github.com/lyx5216288/AGI_union_alltypes
f4d12fc6288147ffffed6d036a51ee7edc9ef999
da1273125da316c29b63acf9fe73fb60ea2372a5
refs/heads/master
2021-09-09T12:42:19.309000
2018-03-16T06:27:36
2018-03-16T06:27:36
125,471,277
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.adapter.event.StreamReport; import com.adapter.CommonClass.StreamReport; import java.util.Collection; import java.util.HashSet; import java.util.Iterator; import java.util.List; /** * Created by usr on 2017/7/13. */ public class StreamReportManager { private static StreamReportManager instance = null; synchronized public static StreamReportManager getInstance(){ if (instance == null) { instance = new StreamReportManager(); } return instance; } private StreamReportManager() { } private Collection listeners; synchronized public void addListener(StreamReportListener listener) { if (listeners == null) { listeners = new HashSet(); } listeners.add(listener); } /** * 移除事件 * * @param listener * DoorListener */ synchronized public void removeListener(StreamReportListener listener) { if (listeners == null) return; listeners.remove(listener); } synchronized public void fireEvent(List<StreamReport> lists ) { if (listeners == null) return; StreamReportEvent event = new StreamReportEvent(this, lists); notifyListeners(event); } synchronized private void notifyListeners(StreamReportEvent event) { Iterator iter = listeners.iterator(); while (iter.hasNext()) { StreamReportListener listener = (StreamReportListener) iter.next(); listener.streamReportHandle(event); } } }
UTF-8
Java
1,595
java
StreamReportManager.java
Java
[ { "context": "terator;\nimport java.util.List;\n\n/**\n * Created by usr on 2017/7/13.\n */\npublic class StreamReportManage", "end": 214, "score": 0.9790864586830139, "start": 211, "tag": "USERNAME", "value": "usr" } ]
null
[]
package com.adapter.event.StreamReport; import com.adapter.CommonClass.StreamReport; import java.util.Collection; import java.util.HashSet; import java.util.Iterator; import java.util.List; /** * Created by usr on 2017/7/13. */ public class StreamReportManager { private static StreamReportManager instance = null; synchronized public static StreamReportManager getInstance(){ if (instance == null) { instance = new StreamReportManager(); } return instance; } private StreamReportManager() { } private Collection listeners; synchronized public void addListener(StreamReportListener listener) { if (listeners == null) { listeners = new HashSet(); } listeners.add(listener); } /** * 移除事件 * * @param listener * DoorListener */ synchronized public void removeListener(StreamReportListener listener) { if (listeners == null) return; listeners.remove(listener); } synchronized public void fireEvent(List<StreamReport> lists ) { if (listeners == null) return; StreamReportEvent event = new StreamReportEvent(this, lists); notifyListeners(event); } synchronized private void notifyListeners(StreamReportEvent event) { Iterator iter = listeners.iterator(); while (iter.hasNext()) { StreamReportListener listener = (StreamReportListener) iter.next(); listener.streamReportHandle(event); } } }
1,595
0.63327
0.628859
70
21.671429
22.661308
79
false
false
0
0
0
0
0
0
0.3
false
false
4
e6362150c9430671257ada6d84c80e5ecc384760
28,845,000,397,045
9b8ff45507d94ea04d7c0fa37fdda09776fc98f7
/Automation/src/Sandbox/AutoSuggestion.java
2e8a0d52c14f38d9b50bcff4fae30e265d53ab52
[]
no_license
devarapallypavani/test3
https://github.com/devarapallypavani/test3
03a782c649b4dd07224675480fec041ec503cce9
4ca5f0d919dc2e93fbeadd065b1592b8c863ecf0
refs/heads/master
2022-05-13T22:01:30.006000
2022-03-22T11:41:45
2022-03-22T11:41:45
215,337,778
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package Sandbox; import java.util.List; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; public class AutoSuggestion { public static void main(String[] args) throws InterruptedException { // TODO Auto-generated method stub System.out.println("Hello World"); System.setProperty("webdriver.chrome.driver", "C://Users//User//Desktop//Automation//chromedriver.exe"); WebDriver driver = new ChromeDriver(); // login to url driver.get("https://rahulshettyacademy.com/dropdownsPractise/"); // maximizing the browser driver.manage().window().maximize(); // for selecting radio button driver.findElement(By.xpath("//div[@id='travelOptions']/table/tbody/tr/td[2]/input")).click(); // //for dynamic drop down // driver.findElement(By.id("ctl00_mainContent_ddl_originStation1_CTXT")).click(); // Thread.sleep(3000); // driver.findElement(By.xpath("//div[@id='ctl00_mainContent_ddl_originStation1_CTNR'] //a[@value='BLR']")).click(); // Thread.sleep(3000); // driver.findElement(By.xpath("//div[@id='ctl00_mainContent_ddl_destinationStation1_CTNR'] //a[@value='HYD']")).click(); // // for dropdown driver.findElement(By.id("divpaxinfo")).click(); Thread.sleep(3000); int i = 1; while (i < 5) { driver.findElement(By.xpath("//div[@id='divpaxOptions']/div[1]/div[2]/span[3]")).click(); i++; } // selection done button driver.findElement(By.id("btnclosepaxoption")).click(); // auto suggestion driver.findElement(By.id("autosuggest")).sendKeys("Ind"); // storing the webelements in results Thread.sleep(3000); List<WebElement> results = driver.findElements(By.xpath("//li[@class='ui-menu-item']/a")); // System.out.println(results); // comparing the webelement with the value what we want for (WebElement option : results) { // System.out.println(option); if (option.getText().equalsIgnoreCase("India")) { option.click(); break; } } // for selecting check boxes driver.findElement(By.cssSelector("input[name*='friendsandfamily']")).click(); System.out.println(driver.findElement(By.cssSelector("input[name*='friendsandfamily']")).isSelected()); // to get count of number of check boxes in UI page System.out.println(driver.findElements(By.cssSelector("input[type='checkbox']")).size()); } }
UTF-8
Java
2,489
java
AutoSuggestion.java
Java
[ { "context": " driver.findElement(By.xpath(\"//div[@id='ctl00_mainContent_ddl_originStation1_CTNR'] //a[@value='BLR']\")).click();\r\n//", "end": 1062, "score": 0.558729887008667, "start": 1037, "tag": "EMAIL", "value": "00_mainContent_ddl_origin" }, { "context": "th(\"//div[@id='ctl00_mainContent_ddl_originStation1_CTNR'] //a[@value='BLR']\")).click();\r\n// ", "end": 1070, "score": 0.5437796711921692, "start": 1069, "tag": "EMAIL", "value": "1" }, { "context": " driver.findElement(By.xpath(\"//div[@id='ctl00_mainContent_ddl_destinationStation1_CTNR'] //a[@value='HYD']\")).click();\r\n// // fo", "end": 1237, "score": 0.7195560336112976, "start": 1194, "tag": "EMAIL", "value": "00_mainContent_ddl_destinationStation1_CTNR" } ]
null
[]
package Sandbox; import java.util.List; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; public class AutoSuggestion { public static void main(String[] args) throws InterruptedException { // TODO Auto-generated method stub System.out.println("Hello World"); System.setProperty("webdriver.chrome.driver", "C://Users//User//Desktop//Automation//chromedriver.exe"); WebDriver driver = new ChromeDriver(); // login to url driver.get("https://rahulshettyacademy.com/dropdownsPractise/"); // maximizing the browser driver.manage().window().maximize(); // for selecting radio button driver.findElement(By.xpath("//div[@id='travelOptions']/table/tbody/tr/td[2]/input")).click(); // //for dynamic drop down // driver.findElement(By.id("ctl00_mainContent_ddl_originStation1_CTXT")).click(); // Thread.sleep(3000); // driver.findElement(By.xpath("//div[@id='ctl<EMAIL>Station1_CTNR'] //a[@value='BLR']")).click(); // Thread.sleep(3000); // driver.findElement(By.xpath("//div[@id='ctl<EMAIL>'] //a[@value='HYD']")).click(); // // for dropdown driver.findElement(By.id("divpaxinfo")).click(); Thread.sleep(3000); int i = 1; while (i < 5) { driver.findElement(By.xpath("//div[@id='divpaxOptions']/div[1]/div[2]/span[3]")).click(); i++; } // selection done button driver.findElement(By.id("btnclosepaxoption")).click(); // auto suggestion driver.findElement(By.id("autosuggest")).sendKeys("Ind"); // storing the webelements in results Thread.sleep(3000); List<WebElement> results = driver.findElements(By.xpath("//li[@class='ui-menu-item']/a")); // System.out.println(results); // comparing the webelement with the value what we want for (WebElement option : results) { // System.out.println(option); if (option.getText().equalsIgnoreCase("India")) { option.click(); break; } } // for selecting check boxes driver.findElement(By.cssSelector("input[name*='friendsandfamily']")).click(); System.out.println(driver.findElement(By.cssSelector("input[name*='friendsandfamily']")).isSelected()); // to get count of number of check boxes in UI page System.out.println(driver.findElements(By.cssSelector("input[type='checkbox']")).size()); } }
2,435
0.67497
0.662515
62
38.145161
32.956886
129
false
false
0
0
0
0
0
0
1.951613
false
false
4
e1186ada94315f738ea87888a2f53a0567754cc8
30,064,771,109,339
48c35afdd206d81ffebc708491f2f48e1f011850
/src/main/java/com/qtpselenium/facebook/pom/util/DataUtil.java
2e8fca0596ecfa0c87f3179117cf55fd2ba3887c
[]
no_license
anariky1/AnanthAshish2018USPageObject
https://github.com/anariky1/AnanthAshish2018USPageObject
e66f3ea3461c562929e6c3ab44ed2d9967881528
02b6d8657b154e77622d6f9c8d745b995f32aa76
refs/heads/master
2020-03-28T19:58:12.300000
2018-09-25T22:06:09
2018-09-25T22:06:09
149,026,339
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.qtpselenium.facebook.pom.util; import java.util.Hashtable; public class DataUtil { public static Object[][] getData(Xls_Reader xls,String testCaseName){ String sheetName=FBConstants.TESTDATA_SHEET; int testStartRowNum=1; while(!xls.getCellData(sheetName, 0, testStartRowNum).equals(testCaseName)){ testStartRowNum++; } System.out.println("Test starts from row -"+testStartRowNum); int colStartRowNum=testStartRowNum+1; int dataStartRowNum=testStartRowNum+2; //calculate rows of data int rows=0; while(!xls.getCellData(sheetName, 0, dataStartRowNum+rows).equals("")){ rows++; } System.out.println("Total rows are : "+rows); //total cols of data int cols=0; while(!xls.getCellData(sheetName, cols, colStartRowNum).equals("")){ cols++; } System.out.println("Total cols are : "+cols); Object[][] data = new Object[rows][1]; //read the data int dataRow=0; Hashtable<String,String>table=null; for(int rNum=dataStartRowNum;rNum<dataStartRowNum+rows;rNum++){ table = new Hashtable<String,String>(); for(int cNum=0;cNum<=cols-1;cNum++){ String key=xls.getCellData(sheetName, cNum, colStartRowNum); String value=xls.getCellData(sheetName, cNum, rNum); table.put(key, value); } data[dataRow][0]=table; dataRow++; } return data; } public static boolean isTestExecutable(Xls_Reader xls,String testCaseName){ int rows =xls.getRowCount(FBConstants.TESTCASE_SHEET); for(int rNum=2;rNum<=rows;rNum++){ String tcid=xls.getCellData(FBConstants.TESTCASE_SHEET, "TCID", rNum); if(tcid.equals(testCaseName)){ String runMode=xls.getCellData(FBConstants.TESTCASE_SHEET, "RunMode", rNum); if(runMode.equals("Y")){ return true; }else{ return false; } } } return false; } }
UTF-8
Java
1,836
java
DataUtil.java
Java
[]
null
[]
package com.qtpselenium.facebook.pom.util; import java.util.Hashtable; public class DataUtil { public static Object[][] getData(Xls_Reader xls,String testCaseName){ String sheetName=FBConstants.TESTDATA_SHEET; int testStartRowNum=1; while(!xls.getCellData(sheetName, 0, testStartRowNum).equals(testCaseName)){ testStartRowNum++; } System.out.println("Test starts from row -"+testStartRowNum); int colStartRowNum=testStartRowNum+1; int dataStartRowNum=testStartRowNum+2; //calculate rows of data int rows=0; while(!xls.getCellData(sheetName, 0, dataStartRowNum+rows).equals("")){ rows++; } System.out.println("Total rows are : "+rows); //total cols of data int cols=0; while(!xls.getCellData(sheetName, cols, colStartRowNum).equals("")){ cols++; } System.out.println("Total cols are : "+cols); Object[][] data = new Object[rows][1]; //read the data int dataRow=0; Hashtable<String,String>table=null; for(int rNum=dataStartRowNum;rNum<dataStartRowNum+rows;rNum++){ table = new Hashtable<String,String>(); for(int cNum=0;cNum<=cols-1;cNum++){ String key=xls.getCellData(sheetName, cNum, colStartRowNum); String value=xls.getCellData(sheetName, cNum, rNum); table.put(key, value); } data[dataRow][0]=table; dataRow++; } return data; } public static boolean isTestExecutable(Xls_Reader xls,String testCaseName){ int rows =xls.getRowCount(FBConstants.TESTCASE_SHEET); for(int rNum=2;rNum<=rows;rNum++){ String tcid=xls.getCellData(FBConstants.TESTCASE_SHEET, "TCID", rNum); if(tcid.equals(testCaseName)){ String runMode=xls.getCellData(FBConstants.TESTCASE_SHEET, "RunMode", rNum); if(runMode.equals("Y")){ return true; }else{ return false; } } } return false; } }
1,836
0.686819
0.679739
78
22.538462
23.978458
79
false
false
0
0
0
0
0
0
2.692308
false
false
4
917ad5c08d0efda2cdb7f6917ede3709f5f2bd7f
30,064,771,107,878
80b563f1952eea2eb530f9700aee2132f8154721
/src/main/java/Entity/SrdcovyBonus.java
b94e2bc1128f4840959fffacd8d2e131d420a43b
[]
no_license
paz1cmipa/modlitebnicekObrazky
https://github.com/paz1cmipa/modlitebnicekObrazky
8a2eb341884aabb65e32ed6844a32e2ff5b59b47
e0f948799a1a728ffb85126ed9b87b3583d77de7
refs/heads/master
2021-01-10T05:25:21.180000
2016-02-10T19:54:47
2016-02-10T19:54:47
51,467,649
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package Entity; import java.util.ArrayList; import java.util.List; public class SrdcovyBonus { private String zdroj; private String text; public SrdcovyBonus(String zdroj, String text) { this.zdroj = zdroj; this.text = text; } @Override public String toString() { return text + "\n" + "\n" + zdroj; } public SrdcovyBonus() { } public String getZdroj() { return zdroj; } public void setZdroj(String zdroj) { this.zdroj = zdroj; } public String getText() { return text; } public void setText(String text) { this.text = text; } }
UTF-8
Java
770
java
SrdcovyBonus.java
Java
[]
null
[]
package Entity; import java.util.ArrayList; import java.util.List; public class SrdcovyBonus { private String zdroj; private String text; public SrdcovyBonus(String zdroj, String text) { this.zdroj = zdroj; this.text = text; } @Override public String toString() { return text + "\n" + "\n" + zdroj; } public SrdcovyBonus() { } public String getZdroj() { return zdroj; } public void setZdroj(String zdroj) { this.zdroj = zdroj; } public String getText() { return text; } public void setText(String text) { this.text = text; } }
770
0.496104
0.496104
45
14.177778
14.269297
52
false
false
0
0
0
0
0
0
0.288889
false
false
4
1c31458845e778f0e6c9b395535a92763881b4a2
17,798,344,512,774
d13e5df9e758906d773d1337628f9e35780d0b20
/maxkey-core/src/main/java/org/maxkey/web/WebConstants.java
6a04ea672c66ab7ef724f91bcda99e44a0ef25fb
[ "Apache-2.0", "CDDL-1.0", "CPL-1.0", "Zlib", "EPL-1.0", "bzip2-1.0.6", "LicenseRef-scancode-unknown-license-reference", "LZMA-exception" ]
permissive
charles-cai/MaxKey
https://github.com/charles-cai/MaxKey
b171f941f34ed2a4d26c4e056c9ac2f9b8df85ae
585397b9264d39097530bd64e0830202e9b07b2f
refs/heads/master
2022-11-11T21:31:03.612000
2020-07-01T01:57:46
2020-07-01T01:57:46
276,896,629
1
0
Apache-2.0
true
2020-07-03T12:38:37
2020-07-03T12:38:36
2020-07-03T12:38:30
2020-07-01T01:57:56
231,520
0
0
0
null
false
false
package org.maxkey.web; /** * Web Application Constants define. * * @author Crystal.Sea * */ public class WebConstants { public static final String USERNAME = "username"; public static final String REMOTE_USERNAME = "remote_username"; public static final String CURRENT_USER = "current_user"; public static final String CURRENT_USER_SESSION_ID = "current_user_session_id"; public static final String CURRENT_COMPANY = "current_user_company"; public static final String CURRENT_DEPARTMENT = "current_user_department"; public static final String CURRENT_USER_NAVIGATIONS = "current_user_navigations"; public static final String CURRENT_USER_ROLES = "current_user_roles"; public static final String CURRENT_USER_SYSTEM_ROLES = "current_user_system_roles"; public static final String CURRENT_LOGIN_USER_PASSWORD_SET_TYPE = "current_login_user_password_set_type"; public static final String CURRENT_MESSAGE = "current_message"; // SPRING_SECURITY_SAVED_REQUEST public static final String FIRST_SAVED_REQUEST_PARAMETER = "SPRING_SECURITY_SAVED_REQUEST"; public static final String KAPTCHA_SESSION_KEY = "kaptcha_session_key"; public static final String SINGLE_SIGN_ON_APP_ID = "single_sign_on_app_id"; public static final String REMEBER_ME_SESSION = "remeber_me_session"; public static final String KERBEROS_TOKEN_PARAMETER = "kerberosToken"; public static final String CAS_SERVICE_PARAMETER = "service"; public static final String KERBEROS_USERDOMAIN_PARAMETER = "kerberosUserDomain"; public static final String REMEBER_ME_COOKIE = "sign_in_remeber_me"; public static final String JWT_TOKEN_PARAMETER = "jwt"; public static final String CURRENT_SINGLESIGNON_URI = "current_singlesignon_uri"; public static final String AUTHENTICATION = "current_authentication"; public static final String THEME_COOKIE_NAME = "maxkey_theme"; }
UTF-8
Java
1,977
java
WebConstants.java
Java
[ { "context": "* Web Application Constants define.\n * \n * @author Crystal.Sea\n *\n */\npublic class WebConstants {\n\n public st", "end": 92, "score": 0.9806732535362244, "start": 81, "tag": "NAME", "value": "Crystal.Sea" }, { "context": "nts {\n\n public static final String USERNAME = \"username\";\n\n public static final String REMOTE_USERNAME", "end": 180, "score": 0.999150812625885, "start": 172, "tag": "USERNAME", "value": "username" }, { "context": " public static final String REMOTE_USERNAME = \"remote_username\";\n\n public static final String CURRENT_USER =", "end": 249, "score": 0.9994503855705261, "start": 234, "tag": "USERNAME", "value": "remote_username" } ]
null
[]
package org.maxkey.web; /** * Web Application Constants define. * * @author Crystal.Sea * */ public class WebConstants { public static final String USERNAME = "username"; public static final String REMOTE_USERNAME = "remote_username"; public static final String CURRENT_USER = "current_user"; public static final String CURRENT_USER_SESSION_ID = "current_user_session_id"; public static final String CURRENT_COMPANY = "current_user_company"; public static final String CURRENT_DEPARTMENT = "current_user_department"; public static final String CURRENT_USER_NAVIGATIONS = "current_user_navigations"; public static final String CURRENT_USER_ROLES = "current_user_roles"; public static final String CURRENT_USER_SYSTEM_ROLES = "current_user_system_roles"; public static final String CURRENT_LOGIN_USER_PASSWORD_SET_TYPE = "current_login_user_password_set_type"; public static final String CURRENT_MESSAGE = "current_message"; // SPRING_SECURITY_SAVED_REQUEST public static final String FIRST_SAVED_REQUEST_PARAMETER = "SPRING_SECURITY_SAVED_REQUEST"; public static final String KAPTCHA_SESSION_KEY = "kaptcha_session_key"; public static final String SINGLE_SIGN_ON_APP_ID = "single_sign_on_app_id"; public static final String REMEBER_ME_SESSION = "remeber_me_session"; public static final String KERBEROS_TOKEN_PARAMETER = "kerberosToken"; public static final String CAS_SERVICE_PARAMETER = "service"; public static final String KERBEROS_USERDOMAIN_PARAMETER = "kerberosUserDomain"; public static final String REMEBER_ME_COOKIE = "sign_in_remeber_me"; public static final String JWT_TOKEN_PARAMETER = "jwt"; public static final String CURRENT_SINGLESIGNON_URI = "current_singlesignon_uri"; public static final String AUTHENTICATION = "current_authentication"; public static final String THEME_COOKIE_NAME = "maxkey_theme"; }
1,977
0.728882
0.728882
59
32.508476
35.296024
96
false
false
0
0
0
0
0
0
0.40678
false
false
4
7b853058769050ea34fd28639f60e07afa66a09c
7,430,293,466,860
8d8baac179d6bb26120f1a2e5925c868983473b1
/src/main/java/com/uem/simple/manager/model/enums/TipoProduto.java
3f7ae8768b263a2048bb00dccfb0ced69ac307c0
[]
no_license
fersilverio/CS-Small-Trade-Manager
https://github.com/fersilverio/CS-Small-Trade-Manager
ef61cc75a22204b3977867147158fd5ab43cf53f
1a9bbdab5f54d1e81bb575b47c0caa26ffb65bdd
refs/heads/master
2023-04-09T22:19:14.816000
2021-04-20T20:27:22
2021-04-20T20:27:22
339,191,493
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.uem.simple.manager.model.enums; public enum TipoProduto { PrF("Produto Físico"), INF("Info-produto"), SERV("Serviço"); private String tipo; public String getTipo(){ return tipo; } TipoProduto (String tipo){ this.tipo = tipo; } }
UTF-8
Java
302
java
TipoProduto.java
Java
[]
null
[]
package com.uem.simple.manager.model.enums; public enum TipoProduto { PrF("Produto Físico"), INF("Info-produto"), SERV("Serviço"); private String tipo; public String getTipo(){ return tipo; } TipoProduto (String tipo){ this.tipo = tipo; } }
302
0.59
0.59
20
14
13.337915
43
false
false
0
0
0
0
0
0
0.35
false
false
4
69fc0eecd4e0ffbea63e1a396570b71adb5aafe8
32,392,643,390,730
32c964025aeb2693040c3a0fa4ad1b41aa813dd3
/src/main/java/com/citonline/db/interfaces/impl/ProgramJdbcDaoSupport.java
80c8e33ca925c504fb03cf4262a85c12cdde0378
[]
no_license
Hexcii/adfsprint2
https://github.com/Hexcii/adfsprint2
5c1ff02911ee05a7eba6a33360e22f17ae5efe32
393237c107b3e8fad70f72685477bf20dd5a7e0f
refs/heads/master
2021-01-17T10:39:09.908000
2015-01-07T23:24:51
2015-01-07T23:24:51
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.citonline.db.interfaces.impl; import java.util.ArrayList; import java.util.List; import javax.annotation.PostConstruct; import javax.sql.DataSource; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.support.JdbcDaoSupport; import org.springframework.stereotype.Repository; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; import com.citonline.db.interfaces.ProgramDAO; import com.citonline.domain.Program; import com.citonline.domain.Semester; import com.citonline.interfaces.impl.ProgramImpl; /* * Author: Tim Wallace * Date: 04/11/14 * * Description: Program Jdbc Template * * Inputs: Program String programName, String programCode, ArrayList<Semester> semesterList * * Expected Outputs: create, delete, update, list semesters, return Program sql */ @Repository public class ProgramJdbcDaoSupport extends JdbcDaoSupport implements ProgramDAO { @Autowired private DataSource dataSource; @PostConstruct private void initialize() { setDataSource(dataSource); } @Override public void createProgram(String programName, String programCode) { String SQL = "INSERT INTO Program (program_Name, program_Code) " + "VALUES(?, ?)"; getJdbcTemplate().update(SQL, new Object[] { programName, programCode}); System.out.println("Created Program Name = " + programName + "\nProgram Code = " + programCode ); } @Override public void deleteProgram(Integer id) { String SQL = "delete from Program where id_program= ?"; getJdbcTemplate().update(SQL, new Object[] {id}); System.out.println("Deleted program where id_program = " + id ); } @Override public ArrayList<Semester> listSemesters() { String SQL = "select * from semester"; ArrayList<Semester> semesterList = (ArrayList<Semester>) getJdbcTemplate().query(SQL, new ProgramMapper()); return semesterList; } @Override public Program getProgram(Integer id) { String SQL = "select * from Program where id_program = ?"; Program program = (Program) getJdbcTemplate().queryForObject(SQL, new Object[]{id}, new ProgramMapper()); return program; } @Override public void updateProgramName(Integer id, String programName) { String SQL = "update program set program_name = ? where id_program = ?"; getJdbcTemplate().update(SQL, new Object[] {programName,id}); System.out.println("Updated program_name to " + programName + " where id_program = " + id ); } @Override public void updateProgramCode(Integer id, String programCode) { String SQL = "update program set program_code = ? where id_program = ?"; getJdbcTemplate().update(SQL, new Object[] {programCode,id}); System.out.println("Updated program_code to " + programCode + " where id_program = " + id ); } @Override @Transactional(readOnly = true, propagation = Propagation.REQUIRES_NEW) public int countRows() { String SQL = "select count(id_program) from program"; int rows=getJdbcTemplate().queryForObject(SQL, Integer.class); return rows; } @Override @Transactional(readOnly = true, propagation = Propagation.REQUIRES_NEW) public List<Program> listPrograms() { String SQL = "select * from program"; List<Program> programs = getJdbcTemplate().query(SQL, new ProgramMapper()); return programs; } }
UTF-8
Java
3,407
java
ProgramJdbcDaoSupport.java
Java
[ { "context": "online.interfaces.impl.ProgramImpl;\n\n/*\n * Author: Tim Wallace\n * Date: 04/11/14\n * \n * Description: Program Jdb", "end": 665, "score": 0.9998418688774109, "start": 654, "tag": "NAME", "value": "Tim Wallace" } ]
null
[]
package com.citonline.db.interfaces.impl; import java.util.ArrayList; import java.util.List; import javax.annotation.PostConstruct; import javax.sql.DataSource; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.support.JdbcDaoSupport; import org.springframework.stereotype.Repository; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; import com.citonline.db.interfaces.ProgramDAO; import com.citonline.domain.Program; import com.citonline.domain.Semester; import com.citonline.interfaces.impl.ProgramImpl; /* * Author: <NAME> * Date: 04/11/14 * * Description: Program Jdbc Template * * Inputs: Program String programName, String programCode, ArrayList<Semester> semesterList * * Expected Outputs: create, delete, update, list semesters, return Program sql */ @Repository public class ProgramJdbcDaoSupport extends JdbcDaoSupport implements ProgramDAO { @Autowired private DataSource dataSource; @PostConstruct private void initialize() { setDataSource(dataSource); } @Override public void createProgram(String programName, String programCode) { String SQL = "INSERT INTO Program (program_Name, program_Code) " + "VALUES(?, ?)"; getJdbcTemplate().update(SQL, new Object[] { programName, programCode}); System.out.println("Created Program Name = " + programName + "\nProgram Code = " + programCode ); } @Override public void deleteProgram(Integer id) { String SQL = "delete from Program where id_program= ?"; getJdbcTemplate().update(SQL, new Object[] {id}); System.out.println("Deleted program where id_program = " + id ); } @Override public ArrayList<Semester> listSemesters() { String SQL = "select * from semester"; ArrayList<Semester> semesterList = (ArrayList<Semester>) getJdbcTemplate().query(SQL, new ProgramMapper()); return semesterList; } @Override public Program getProgram(Integer id) { String SQL = "select * from Program where id_program = ?"; Program program = (Program) getJdbcTemplate().queryForObject(SQL, new Object[]{id}, new ProgramMapper()); return program; } @Override public void updateProgramName(Integer id, String programName) { String SQL = "update program set program_name = ? where id_program = ?"; getJdbcTemplate().update(SQL, new Object[] {programName,id}); System.out.println("Updated program_name to " + programName + " where id_program = " + id ); } @Override public void updateProgramCode(Integer id, String programCode) { String SQL = "update program set program_code = ? where id_program = ?"; getJdbcTemplate().update(SQL, new Object[] {programCode,id}); System.out.println("Updated program_code to " + programCode + " where id_program = " + id ); } @Override @Transactional(readOnly = true, propagation = Propagation.REQUIRES_NEW) public int countRows() { String SQL = "select count(id_program) from program"; int rows=getJdbcTemplate().queryForObject(SQL, Integer.class); return rows; } @Override @Transactional(readOnly = true, propagation = Propagation.REQUIRES_NEW) public List<Program> listPrograms() { String SQL = "select * from program"; List<Program> programs = getJdbcTemplate().query(SQL, new ProgramMapper()); return programs; } }
3,402
0.729087
0.727326
113
29.150442
28.233923
94
false
false
0
0
0
0
0
0
1.60177
false
false
4
2894349ad3b15e9a517dfaa1059800af52a6cdc8
1,726,576,896,076
53de8ab37b0906fb56b3d9eeb373264bd243d406
/module_driver/src/main/java/com/rzn/module_driver/ui/joborderdetial/view/PayPopupwindow.java
8e1b166218d3c01e3ab8143c990b6d4a8c3e04bf
[]
no_license
zz164344820/RZN
https://github.com/zz164344820/RZN
d8deb236dd7c77ccb9b20efbad92c689746de60c
9a046c81e0339205010d89c05954053c59a0e839
refs/heads/master
2021-01-24T20:14:38.846000
2019-07-09T05:41:04
2019-07-09T05:41:04
123,247,961
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.rzn.module_driver.ui.joborderdetial.view; import android.content.Context; import android.graphics.drawable.ColorDrawable; import android.provider.ContactsContract; import android.view.View; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.PopupWindow; import android.widget.RelativeLayout; import android.widget.TextView; import com.rzn.module_driver.R; /** * RAY.LEE * Created by 17662on 2019/4/3. */ public class PayPopupwindow extends PopupWindow { private Context context; private View popUpWindow; private LinearLayout llZhifubao; private LinearLayout llWeixin; private ImageView ivZhifubao; private ImageView ivWeixin; private TextView tvCancel; private TextView tvSure; private String type = ""; public PayPopupwindow(Context context) { this.context = context; initLayout(); setPopupWindow(); } private void setPopupWindow() { // ColorDrawable dw = new ColorDrawable(0x30000000); // // this.setBackgroundDrawable(dw); //设置SelectPicPopupWindow的View this.setContentView(popUpWindow); //设置SelectPicPopupWindow弹出窗体的宽 this.setWidth(RelativeLayout.LayoutParams.MATCH_PARENT); //设置SelectPicPopupWindow弹出窗体的高 this.setHeight(RelativeLayout.LayoutParams.MATCH_PARENT); //设置SelectPicPopupWindow弹出窗体可点击 this.setFocusable(true); //设置SelectPicPopupWindow弹出窗体动画效果 this.setAnimationStyle(R.style.AnimBottom); // // 实例化一个ColorDrawable颜色为半透明 ColorDrawable dw = new ColorDrawable(0xb0000000); // 设置弹出窗体的背景 icon_popup_cancel_order this.setBackgroundDrawable(dw); } private void initLayout() { popUpWindow = View.inflate(context, R.layout.view_pay_popupwindow, null); llZhifubao = (LinearLayout) popUpWindow.findViewById(R.id.ll_zhifubao); llWeixin = (LinearLayout) popUpWindow.findViewById(R.id.ll_weixin); ivZhifubao = (ImageView) popUpWindow.findViewById(R.id.iv_zhifubao); ivWeixin = (ImageView) popUpWindow.findViewById(R.id.iv_weixin); tvCancel = (TextView) popUpWindow.findViewById(R.id.tv_cancel); tvSure = (TextView) popUpWindow.findViewById(R.id.tv_sure); ivZhifubao.setVisibility(View.VISIBLE); ivWeixin.setVisibility(View.GONE); type = "zhifubao"; llZhifubao.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { type = "zhifubao"; ivZhifubao.setVisibility(View.VISIBLE); ivWeixin.setVisibility(View.GONE); } }); llWeixin.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { type = "weixin"; ivZhifubao.setVisibility(View.GONE); ivWeixin.setVisibility(View.VISIBLE); } }); tvCancel.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { dismiss(); } }); tvSure.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if (onPopupClickListener != null) { onPopupClickListener.onClick(type); } } }); } private OnPopupClickListener onPopupClickListener; public interface OnPopupClickListener { void onClick(String paytype); //支付宝,微信支付type值 } public void setOnClickPopListener(OnPopupClickListener onPopupClickListener) { this.onPopupClickListener = onPopupClickListener; } }
UTF-8
Java
3,936
java
PayPopupwindow.java
Java
[ { "context": "zn.module_driver.R;\n\n/**\n * RAY.LEE\n * Created by 17662on 2019/4/3.\n */\n\npublic class PayPopupwindow exte", "end": 445, "score": 0.988359808921814, "start": 440, "tag": "USERNAME", "value": "17662" } ]
null
[]
package com.rzn.module_driver.ui.joborderdetial.view; import android.content.Context; import android.graphics.drawable.ColorDrawable; import android.provider.ContactsContract; import android.view.View; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.PopupWindow; import android.widget.RelativeLayout; import android.widget.TextView; import com.rzn.module_driver.R; /** * RAY.LEE * Created by 17662on 2019/4/3. */ public class PayPopupwindow extends PopupWindow { private Context context; private View popUpWindow; private LinearLayout llZhifubao; private LinearLayout llWeixin; private ImageView ivZhifubao; private ImageView ivWeixin; private TextView tvCancel; private TextView tvSure; private String type = ""; public PayPopupwindow(Context context) { this.context = context; initLayout(); setPopupWindow(); } private void setPopupWindow() { // ColorDrawable dw = new ColorDrawable(0x30000000); // // this.setBackgroundDrawable(dw); //设置SelectPicPopupWindow的View this.setContentView(popUpWindow); //设置SelectPicPopupWindow弹出窗体的宽 this.setWidth(RelativeLayout.LayoutParams.MATCH_PARENT); //设置SelectPicPopupWindow弹出窗体的高 this.setHeight(RelativeLayout.LayoutParams.MATCH_PARENT); //设置SelectPicPopupWindow弹出窗体可点击 this.setFocusable(true); //设置SelectPicPopupWindow弹出窗体动画效果 this.setAnimationStyle(R.style.AnimBottom); // // 实例化一个ColorDrawable颜色为半透明 ColorDrawable dw = new ColorDrawable(0xb0000000); // 设置弹出窗体的背景 icon_popup_cancel_order this.setBackgroundDrawable(dw); } private void initLayout() { popUpWindow = View.inflate(context, R.layout.view_pay_popupwindow, null); llZhifubao = (LinearLayout) popUpWindow.findViewById(R.id.ll_zhifubao); llWeixin = (LinearLayout) popUpWindow.findViewById(R.id.ll_weixin); ivZhifubao = (ImageView) popUpWindow.findViewById(R.id.iv_zhifubao); ivWeixin = (ImageView) popUpWindow.findViewById(R.id.iv_weixin); tvCancel = (TextView) popUpWindow.findViewById(R.id.tv_cancel); tvSure = (TextView) popUpWindow.findViewById(R.id.tv_sure); ivZhifubao.setVisibility(View.VISIBLE); ivWeixin.setVisibility(View.GONE); type = "zhifubao"; llZhifubao.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { type = "zhifubao"; ivZhifubao.setVisibility(View.VISIBLE); ivWeixin.setVisibility(View.GONE); } }); llWeixin.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { type = "weixin"; ivZhifubao.setVisibility(View.GONE); ivWeixin.setVisibility(View.VISIBLE); } }); tvCancel.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { dismiss(); } }); tvSure.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if (onPopupClickListener != null) { onPopupClickListener.onClick(type); } } }); } private OnPopupClickListener onPopupClickListener; public interface OnPopupClickListener { void onClick(String paytype); //支付宝,微信支付type值 } public void setOnClickPopListener(OnPopupClickListener onPopupClickListener) { this.onPopupClickListener = onPopupClickListener; } }
3,936
0.652551
0.645187
116
31.775862
22.490644
82
false
false
0
0
0
0
0
0
0.508621
false
false
4
8ccb07d5f1fcd399251ff53c93fa86136627bf4c
29,326,036,727,878
83d781a9c2ba33fde6df0c6adc3a434afa1a7f82
/MarketBusinessInterface/src/main/java/com/newco/marketplace/dto/vo/incident/AssociatedIncidentVO.java
dee0096e25f5d3f87be641f6a70c9e9179ac2819
[]
no_license
ssriha0/sl-b2b-platform
https://github.com/ssriha0/sl-b2b-platform
71ab8ef1f0ccb0a7ad58b18f28a2bf6d5737fcb6
5b4fcafa9edfe4d35c2dcf1659ac30ef58d607a2
refs/heads/master
2023-01-06T18:32:24.623000
2020-11-05T12:23:26
2020-11-05T12:23:26
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.newco.marketplace.dto.vo.incident; import java.sql.Timestamp; import org.apache.commons.lang.builder.ToStringBuilder; import org.apache.commons.lang.builder.ToStringStyle; import com.sears.os.vo.SerializableBaseVO; public class AssociatedIncidentVO extends SerializableBaseVO { private static final long serialVersionUID = 598674940772310759L; private String soId; private String incidentId; private Integer buyerId; private Integer buyerRefTypeId; private String refType; private Integer ageOfOrder; private String clientIncidentId; private Integer buyerSubstatusAssocId; private Timestamp responseSentDate; private String outputFile; public String getSoId() { return soId; } public void setSoId(String soId) { this.soId = soId; } public String getIncidentId() { return incidentId; } public void setIncidentId(String incidentId) { this.incidentId = incidentId; } public Integer getBuyerId() { return buyerId; } public void setBuyerId(Integer buyerId) { this.buyerId = buyerId; } public Integer getBuyerRefTypeId() { return buyerRefTypeId; } public void setBuyerRefTypeId(Integer buyerRefTypeId) { this.buyerRefTypeId = buyerRefTypeId; } public String getRefType() { return refType; } public void setRefType(String refType) { this.refType = refType; } public Integer getAgeOfOrder() { return ageOfOrder; } public void setAgeOfOrder(Integer ageOfOrder) { this.ageOfOrder = ageOfOrder; } public Integer getBuyerSubstatusAssocId() { return buyerSubstatusAssocId; } public void setBuyerSubstatusAssocId(Integer buyerSubstatusAssocId) { this.buyerSubstatusAssocId = buyerSubstatusAssocId; } public Timestamp getResponseSentDate() { return responseSentDate; } public void setResponseSentDate(Timestamp responseSentDate) { this.responseSentDate = responseSentDate; } @Override public String toString() { return ToStringBuilder.reflectionToString(this, ToStringStyle.SIMPLE_STYLE); } public String getClientIncidentId() { return clientIncidentId; } public void setClientIncidentId(String clientIncidentId) { this.clientIncidentId = clientIncidentId; } public String getOutputFile() { return outputFile; } public void setOutputFile(String outputFile) { this.outputFile = outputFile; } }
UTF-8
Java
2,391
java
AssociatedIncidentVO.java
Java
[]
null
[]
package com.newco.marketplace.dto.vo.incident; import java.sql.Timestamp; import org.apache.commons.lang.builder.ToStringBuilder; import org.apache.commons.lang.builder.ToStringStyle; import com.sears.os.vo.SerializableBaseVO; public class AssociatedIncidentVO extends SerializableBaseVO { private static final long serialVersionUID = 598674940772310759L; private String soId; private String incidentId; private Integer buyerId; private Integer buyerRefTypeId; private String refType; private Integer ageOfOrder; private String clientIncidentId; private Integer buyerSubstatusAssocId; private Timestamp responseSentDate; private String outputFile; public String getSoId() { return soId; } public void setSoId(String soId) { this.soId = soId; } public String getIncidentId() { return incidentId; } public void setIncidentId(String incidentId) { this.incidentId = incidentId; } public Integer getBuyerId() { return buyerId; } public void setBuyerId(Integer buyerId) { this.buyerId = buyerId; } public Integer getBuyerRefTypeId() { return buyerRefTypeId; } public void setBuyerRefTypeId(Integer buyerRefTypeId) { this.buyerRefTypeId = buyerRefTypeId; } public String getRefType() { return refType; } public void setRefType(String refType) { this.refType = refType; } public Integer getAgeOfOrder() { return ageOfOrder; } public void setAgeOfOrder(Integer ageOfOrder) { this.ageOfOrder = ageOfOrder; } public Integer getBuyerSubstatusAssocId() { return buyerSubstatusAssocId; } public void setBuyerSubstatusAssocId(Integer buyerSubstatusAssocId) { this.buyerSubstatusAssocId = buyerSubstatusAssocId; } public Timestamp getResponseSentDate() { return responseSentDate; } public void setResponseSentDate(Timestamp responseSentDate) { this.responseSentDate = responseSentDate; } @Override public String toString() { return ToStringBuilder.reflectionToString(this, ToStringStyle.SIMPLE_STYLE); } public String getClientIncidentId() { return clientIncidentId; } public void setClientIncidentId(String clientIncidentId) { this.clientIncidentId = clientIncidentId; } public String getOutputFile() { return outputFile; } public void setOutputFile(String outputFile) { this.outputFile = outputFile; } }
2,391
0.750732
0.743204
91
24.274725
20.138567
78
false
false
0
0
0
0
0
0
1.527472
false
false
4
fe68052e347442c75f92565525f11ceb711ad73c
21,732,534,560,243
7947092e159732a052dd0415b5811eed4902a760
/src/controller/themeeditor/ActionThemeSave.java
1929e96bfdb5218c1066db6f6162438f2d7499a1
[]
no_license
vuthea/TheLooking
https://github.com/vuthea/TheLooking
59509f29f09e6020c3b4f7bc9c3afb75865406cf
f8c5fb89e207a5be48833500fc7c69307e0bed18
refs/heads/master
2015-09-25T22:32:15.722000
2015-08-27T04:25:00
2015-08-27T04:25:00
41,463,898
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package controller.themeeditor; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import controller.Common_method; import controller.Action; import controller.ActionForward; public class ActionThemeSave implements Action { @Override public ActionForward execute(HttpServletRequest request, HttpServletResponse response) throws Exception { ActionForward forward = new ActionForward(); //.pro?filename=index.jsp String filename = request.getParameter("filename"); //"jsp/index.jsp" ;//+ request.getAttribute("filename").toString();//"jsp/index.jsp"; //System.out.println("FILENAME" + filename); //System.out.println(filename); String textbody = request.getParameter("code"); //System.out.println(textbody); Common_method.saveToFile(request, filename, textbody); //System.out.println("FILENAME" + filename); //request.setAttribute("filepath", filename); //request.setAttribute("readfile", Common_method.readFromFile(request, filename)); forward.setRedirect(false); forward.setPath("theme_editor.act?filename="+ filename +""); //System.out.println(forward); return forward; } }
UTF-8
Java
1,196
java
ActionThemeSave.java
Java
[]
null
[]
package controller.themeeditor; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import controller.Common_method; import controller.Action; import controller.ActionForward; public class ActionThemeSave implements Action { @Override public ActionForward execute(HttpServletRequest request, HttpServletResponse response) throws Exception { ActionForward forward = new ActionForward(); //.pro?filename=index.jsp String filename = request.getParameter("filename"); //"jsp/index.jsp" ;//+ request.getAttribute("filename").toString();//"jsp/index.jsp"; //System.out.println("FILENAME" + filename); //System.out.println(filename); String textbody = request.getParameter("code"); //System.out.println(textbody); Common_method.saveToFile(request, filename, textbody); //System.out.println("FILENAME" + filename); //request.setAttribute("filepath", filename); //request.setAttribute("readfile", Common_method.readFromFile(request, filename)); forward.setRedirect(false); forward.setPath("theme_editor.act?filename="+ filename +""); //System.out.println(forward); return forward; } }
1,196
0.737458
0.737458
38
30.473684
28.872438
140
false
false
0
0
0
0
0
0
2.552632
false
false
4
f415062e06e3756fd665cdf68b8f04ca19e2ead8
30,734,786,012,607
bef6709ff31a1d3e2b3340328605dfd5af8a076e
/src/main/java/exception/CountryExistsException.java
7ae5681ca68694dcd0aaa10d926d1f05d17e32ed
[]
no_license
alexi-s/TourManager
https://github.com/alexi-s/TourManager
0b1c2439d71340604d521f3a983aec72872a1fbd
aa5eb05be668702d9981d6752d9fd51c5f1316e7
refs/heads/master
2020-03-22T15:10:05.046000
2018-07-11T14:37:26
2018-07-11T14:37:26
140,232,954
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package exception; public class CountryExistsException extends Exception { @Override public String getMessage() { return "Country exists"; } }
UTF-8
Java
165
java
CountryExistsException.java
Java
[]
null
[]
package exception; public class CountryExistsException extends Exception { @Override public String getMessage() { return "Country exists"; } }
165
0.690909
0.690909
9
17.333334
17.913372
55
false
false
0
0
0
0
0
0
0.222222
false
false
4
f67333081985c12844acdb69eb280443bef09a41
23,046,794,552,475
293911d55f33c8269ee760c90ddefc88b570a3e2
/src/bullet/MyPlane1_Bullet.java
28e9f57b7c49e9590b7c0bd9530b29085091c1a2
[]
no_license
dhd12391/Wingman
https://github.com/dhd12391/Wingman
e8bfee073ff76cb06d0e49da9ec26a116cc63ad9
28a9402c4e413e148a5e534023bf14864a9bec39
refs/heads/master
2021-01-22T04:57:21.742000
2014-07-01T15:55:24
2014-07-01T15:55:24
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package bullet; import enemy.Enemy_Parent; import java.awt.Image; import wingman.*; /** * * @author Chidi */ public class MyPlane1_Bullet extends enemy.Enemy_Parent{ public MyPlane1_Bullet (Image img, int x, int y, int speed){ super(img,x,y,speed); } public void checkCollision(){ if(gm1942.bossArrived()){ if(gm1942.boss1.collision(x, y, sizeX, sizeY)&& show == true){ show = false; gm1942.boss1.isHit(); if(gm1942.boss1.isKilled()){ gm1942.boss1.doNotShow(); gm1942.boss1.setBoom(); gm1942.boss1.hasNotExploded(); gm1942.gameEvents.setValue("p1 boss kill"); } } } for(int i = 0; i < gm1942.enemyList.size(); i++){ if(gm1942.enemyList.get(i).collision(x,y,sizeX,sizeY) && show == true){ show = false; gm1942.enemyList.get(i).doNotShow();; gm1942.enemyList.get(i).setBoom(); gm1942.enemyList.get(i).hasNotExploded(); gm1942.gameEvents.setValue("p1 hits"); break; } } } public void update(int w, int h){ if(show){ y -= speed; checkCollision(); if(y<=0){ show = false; } } else{ if(!objectGone){ x = 1000; y = 1000; } } } }
UTF-8
Java
1,679
java
MyPlane1_Bullet.java
Java
[ { "context": "va.awt.Image;\nimport wingman.*;\n\n/**\n *\n * @author Chidi\n */\npublic class MyPlane1_Bullet extends enemy.En", "end": 209, "score": 0.9990777969360352, "start": 204, "tag": "NAME", "value": "Chidi" } ]
null
[]
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package bullet; import enemy.Enemy_Parent; import java.awt.Image; import wingman.*; /** * * @author Chidi */ public class MyPlane1_Bullet extends enemy.Enemy_Parent{ public MyPlane1_Bullet (Image img, int x, int y, int speed){ super(img,x,y,speed); } public void checkCollision(){ if(gm1942.bossArrived()){ if(gm1942.boss1.collision(x, y, sizeX, sizeY)&& show == true){ show = false; gm1942.boss1.isHit(); if(gm1942.boss1.isKilled()){ gm1942.boss1.doNotShow(); gm1942.boss1.setBoom(); gm1942.boss1.hasNotExploded(); gm1942.gameEvents.setValue("p1 boss kill"); } } } for(int i = 0; i < gm1942.enemyList.size(); i++){ if(gm1942.enemyList.get(i).collision(x,y,sizeX,sizeY) && show == true){ show = false; gm1942.enemyList.get(i).doNotShow();; gm1942.enemyList.get(i).setBoom(); gm1942.enemyList.get(i).hasNotExploded(); gm1942.gameEvents.setValue("p1 hits"); break; } } } public void update(int w, int h){ if(show){ y -= speed; checkCollision(); if(y<=0){ show = false; } } else{ if(!objectGone){ x = 1000; y = 1000; } } } }
1,679
0.464562
0.419297
62
26.080645
21.040895
83
false
false
0
0
0
0
0
0
0.645161
false
false
4
fe06e43a550dcbc1c9575fe6acfcfc30ed52303f
24,378,234,409,548
79bf96592177a5001c9f8281ca10fca23e4ccace
/src/main/java/com/cl/threadCore/chapter1/JInterruptInSleep.java
cbaa1199837f72227b2ea3a71032512b3c11b777
[]
no_license
onegreens/javaDesignPatterns
https://github.com/onegreens/javaDesignPatterns
43dab3b180e595cfedbfdbdc251afab820baf3f7
ed4c85605ee40e7a1b286af3c01c84014d4d16cf
refs/heads/master
2022-12-22T11:19:55.371000
2020-10-16T02:09:30
2020-10-16T02:09:30
94,595,359
0
0
null
false
2022-12-10T04:04:20
2017-06-17T02:25:20
2020-10-16T02:09:44
2022-12-10T04:04:19
3,001
0
0
11
Java
false
false
package com.cl.threadCore.chapter1; /** * 测试 isInterrupted */ public class JInterruptInSleep extends Thread { @Override public void run() { super.run(); try { System.out.println("run begin"); Thread.sleep(200000); System.out.println("run end"); } catch (InterruptedException e) { System.out.println("在睡眠中被停止了"); e.printStackTrace(); } } public static void main(String[] args) { try { JInterruptInSleep thread = new JInterruptInSleep(); thread.start(); Thread.sleep(100); thread.interrupt(); } catch (InterruptedException e) { System.out.println("捕捉到 main 输出的异常了"); e.printStackTrace(); } } }
UTF-8
Java
843
java
JInterruptInSleep.java
Java
[]
null
[]
package com.cl.threadCore.chapter1; /** * 测试 isInterrupted */ public class JInterruptInSleep extends Thread { @Override public void run() { super.run(); try { System.out.println("run begin"); Thread.sleep(200000); System.out.println("run end"); } catch (InterruptedException e) { System.out.println("在睡眠中被停止了"); e.printStackTrace(); } } public static void main(String[] args) { try { JInterruptInSleep thread = new JInterruptInSleep(); thread.start(); Thread.sleep(100); thread.interrupt(); } catch (InterruptedException e) { System.out.println("捕捉到 main 输出的异常了"); e.printStackTrace(); } } }
843
0.53913
0.526708
32
24.15625
17.676096
63
false
false
0
0
0
0
0
0
0.40625
false
false
4
f8454a91b71e59ca4f72be00e484a4099ca918a6
5,050,881,587,017
5a35f0f99023bba139a5129f88a88aafda84126f
/opencv-java/src/com/codeferm/opencv/Writer.java
86fc6990dbac065ef171bf313c2ed4c31399b817
[ "BSD-2-Clause-Views", "BSD-2-Clause" ]
permissive
sgjava/install-opencv
https://github.com/sgjava/install-opencv
497c446675661d7922015cb3b6cddd35129e2286
0495aaacb9cc98020ea623b8c6fa4857ca3355bf
refs/heads/master
2022-09-17T03:34:42.231000
2022-08-22T20:48:09
2022-08-22T20:48:09
15,601,171
39
16
null
false
2014-05-15T14:06:41
2014-01-03T04:27:00
2014-05-15T14:06:41
2014-05-15T14:06:41
4,579
2
2
0
Java
null
null
/* * Copyright (c) Steven P. Goldsmith. All rights reserved. * * Created by Steven P. Goldsmith on December 29, 2013 * sgjava@gmail.com */ package com.codeferm.opencv; import java.io.IOException; import java.util.logging.Level; import java.util.logging.LogManager; import java.util.logging.Logger; import org.opencv.core.Core; import org.opencv.core.Mat; import org.opencv.core.Size; import org.opencv.videoio.VideoCapture; import org.opencv.videoio.VideoWriter; import org.opencv.videoio.Videoio; /** * Example of VideoWriter class. * * args[0] = source file or will default to "../resources/traffic.mp4" if no * args passed. * * @author sgoldsmith * @version 1.0.0 * @since 1.0.0 */ final class Writer { /** * Logger. */ private static final Logger logger = Logger.getLogger(Writer.class.getName()); /* Load the OpenCV system library */ static { System.loadLibrary(Core.NATIVE_LIBRARY_NAME); } /** * Suppress default constructor for noninstantiability. */ private Writer() { throw new AssertionError(); } /** * Main method. * * args[0] = source file or will default to "../resources/traffic.mp4" if no * args passed. * * @param args * Arguments passed. */ public static void main(final String... args) { String url = null; final var outputFile = "../output/writer-java.avi"; // Check how many arguments were passed in if (args.length == 0) { // If no arguments were passed then default to // ../resources/traffic.mp4 url = "../resources/traffic.mp4"; } else { url = args[0]; } // Custom logging properties via class loader try { LogManager.getLogManager() .readConfiguration(Writer.class.getClassLoader().getResourceAsStream("logging.properties")); } catch (SecurityException | IOException e) { e.printStackTrace(); } logger.log(Level.INFO, String.format("OpenCV %s", Core.VERSION)); logger.log(Level.INFO, String.format("Input file: %s", url)); logger.log(Level.INFO, String.format("Output file: %s", outputFile)); final var videoCapture = new VideoCapture(); videoCapture.open(url); final var frameSize = new Size((int) videoCapture.get(Videoio.CAP_PROP_FRAME_WIDTH), (int) videoCapture.get(Videoio.CAP_PROP_FRAME_HEIGHT)); logger.log(Level.INFO, String.format("Resolution: %s", frameSize)); final var fourCC = new FourCC("X264"); final var videoWriter = new VideoWriter(outputFile, fourCC.toInt(), videoCapture.get(Videoio.CAP_PROP_FPS), frameSize, true); final var mat = new Mat(); int frames = 0; final var startTime = System.currentTimeMillis(); while (videoCapture.read(mat)) { videoWriter.write(mat); frames++; } final var estimatedTime = System.currentTimeMillis() - startTime; final var seconds = (double) estimatedTime / 1000; logger.log(Level.INFO, String.format("%d frames", frames)); logger.log(Level.INFO, String.format("%4.1f FPS, elapsed time: %4.2f seconds", frames / seconds, seconds)); // Release native memory videoCapture.release(); videoWriter.release(); mat.release(); } }
UTF-8
Java
3,453
java
Writer.java
Java
[ { "context": "/*\n * Copyright (c) Steven P. Goldsmith. All rights reserved.\n *\n * Created by Steven P. ", "end": 39, "score": 0.9998860955238342, "start": 20, "tag": "NAME", "value": "Steven P. Goldsmith" }, { "context": ". Goldsmith. All rights reserved.\n *\n * Created by Steven P. Goldsmith on December 29, 2013\n * sgjava@gmail.com\n */\npack", "end": 98, "score": 0.9998858571052551, "start": 79, "tag": "NAME", "value": "Steven P. Goldsmith" }, { "context": "ted by Steven P. Goldsmith on December 29, 2013\n * sgjava@gmail.com\n */\npackage com.codeferm.opencv;\n\nimport java.io.", "end": 139, "score": 0.9999201893806458, "start": 123, "tag": "EMAIL", "value": "sgjava@gmail.com" }, { "context": "s/traffic.mp4\" if no\n * args passed.\n *\n * @author sgoldsmith\n * @version 1.0.0\n * @since 1.0.0\n */\nfinal class", "end": 663, "score": 0.9995405673980713, "start": 653, "tag": "USERNAME", "value": "sgoldsmith" } ]
null
[]
/* * Copyright (c) <NAME>. All rights reserved. * * Created by <NAME> on December 29, 2013 * <EMAIL> */ package com.codeferm.opencv; import java.io.IOException; import java.util.logging.Level; import java.util.logging.LogManager; import java.util.logging.Logger; import org.opencv.core.Core; import org.opencv.core.Mat; import org.opencv.core.Size; import org.opencv.videoio.VideoCapture; import org.opencv.videoio.VideoWriter; import org.opencv.videoio.Videoio; /** * Example of VideoWriter class. * * args[0] = source file or will default to "../resources/traffic.mp4" if no * args passed. * * @author sgoldsmith * @version 1.0.0 * @since 1.0.0 */ final class Writer { /** * Logger. */ private static final Logger logger = Logger.getLogger(Writer.class.getName()); /* Load the OpenCV system library */ static { System.loadLibrary(Core.NATIVE_LIBRARY_NAME); } /** * Suppress default constructor for noninstantiability. */ private Writer() { throw new AssertionError(); } /** * Main method. * * args[0] = source file or will default to "../resources/traffic.mp4" if no * args passed. * * @param args * Arguments passed. */ public static void main(final String... args) { String url = null; final var outputFile = "../output/writer-java.avi"; // Check how many arguments were passed in if (args.length == 0) { // If no arguments were passed then default to // ../resources/traffic.mp4 url = "../resources/traffic.mp4"; } else { url = args[0]; } // Custom logging properties via class loader try { LogManager.getLogManager() .readConfiguration(Writer.class.getClassLoader().getResourceAsStream("logging.properties")); } catch (SecurityException | IOException e) { e.printStackTrace(); } logger.log(Level.INFO, String.format("OpenCV %s", Core.VERSION)); logger.log(Level.INFO, String.format("Input file: %s", url)); logger.log(Level.INFO, String.format("Output file: %s", outputFile)); final var videoCapture = new VideoCapture(); videoCapture.open(url); final var frameSize = new Size((int) videoCapture.get(Videoio.CAP_PROP_FRAME_WIDTH), (int) videoCapture.get(Videoio.CAP_PROP_FRAME_HEIGHT)); logger.log(Level.INFO, String.format("Resolution: %s", frameSize)); final var fourCC = new FourCC("X264"); final var videoWriter = new VideoWriter(outputFile, fourCC.toInt(), videoCapture.get(Videoio.CAP_PROP_FPS), frameSize, true); final var mat = new Mat(); int frames = 0; final var startTime = System.currentTimeMillis(); while (videoCapture.read(mat)) { videoWriter.write(mat); frames++; } final var estimatedTime = System.currentTimeMillis() - startTime; final var seconds = (double) estimatedTime / 1000; logger.log(Level.INFO, String.format("%d frames", frames)); logger.log(Level.INFO, String.format("%4.1f FPS, elapsed time: %4.2f seconds", frames / seconds, seconds)); // Release native memory videoCapture.release(); videoWriter.release(); mat.release(); } }
3,418
0.618013
0.608746
102
32.85294
26.369322
115
false
false
0
0
0
0
0
0
0.607843
false
false
4
85a797572697641c5cda39cbb3b3da52eaf25a6f
22,007,412,464,795
50027d5906c61a908bbed54b844ff2b4fcbb0e78
/src/nl/eriba/mzidentml/identification/filereader/MzIdFileReader.java
0cb73d0cdb057c91b45b082c2192dc1c2a132e86
[]
no_license
vnijenhuis/MzIdentMlConvert
https://github.com/vnijenhuis/MzIdentMlConvert
02beb66c6e9e3b8f3bf85330655fdc2a3b302652
9c046834b5a03bae3c1dea99e66f0e8ebc3dc664
refs/heads/master
2020-06-14T23:32:36.852000
2016-12-09T21:36:46
2016-12-09T21:36:46
75,399,392
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * @author Vikthor Nijenhuis * @project PeptideItem mzIdentML Identfication Module * */ package nl.eriba.mzidentml.identification.filereader; import nl.eriba.mzidentml.identification.collections.mzid.MzIdProteinPeptideCollection; import nl.eriba.mzidentml.identification.collections.output.DatabaseSearchPsmOutputCollection; import nl.eriba.mzidentml.identification.collections.mzid.MzIdDatabaseSequenceCollection; import nl.eriba.mzidentml.identification.collections.output.ScanIdOutputCollection; import nl.eriba.mzidentml.identification.collections.mzid.MzIdPeptideCollection; import nl.eriba.mzidentml.identification.collections.output.PeptideOutputCollection; import nl.eriba.mzidentml.identification.collections.mzid.MzIdPeptideEvidenceCollection; import nl.eriba.mzidentml.identification.collections.mzid.MzIdProteinDetectionHypothesisCollection; import nl.eriba.mzidentml.identification.collections.output.ProteinPeptideOutputCollection; import nl.eriba.mzidentml.identification.collections.mzid.MzIdMainElementCollection; import nl.eriba.mzidentml.identification.collections.general.CombinedPeptideEntryCollection; import nl.eriba.mzidentml.identification.dataprocessing.sorting.SortSpectrumResultBySequence; import nl.eriba.mzidentml.identification.dataprocessing.sorting.SortPeptideEvidenceCollectionOnSequence; import nl.eriba.mzidentml.identification.dataprocessing.spectra.MzIdUnmarshaller; import nl.eriba.mzidentml.identification.dataprocessing.spectra.SingleSpectrumDataCollector; import nl.eriba.mzidentml.identification.objects.output.DatabaseSearchPsmOutput; import nl.eriba.mzidentml.identification.objects.mzid.MzIdCvParam; import nl.eriba.mzidentml.identification.objects.mzid.MzIdDatabaseSequence; import nl.eriba.mzidentml.identification.objects.mzid.MzIdModification; import nl.eriba.mzidentml.identification.objects.mzid.MzIdPeptide; import nl.eriba.mzidentml.identification.objects.mzid.MzIdPeptideEvidence; import nl.eriba.mzidentml.identification.objects.mzid.MzIdProteinDetectionHypothesis; import nl.eriba.mzidentml.identification.objects.mzid.MzIdSubstituteModification; import nl.eriba.mzidentml.identification.objects.output.PeptideOutput; import nl.eriba.mzidentml.identification.objects.output.ProteinPeptideOutput; import nl.eriba.mzidentml.identification.objects.output.ScanIdOutput; import nl.eriba.mzidentml.identification.objects.general.MatchedIonSeries; import nl.eriba.mzidentml.identification.objects.general.ProteinPeptideEntry; import nl.eriba.mzidentml.identification.objects.mzid.MzIdIonFragment; import nl.eriba.mzidentml.identification.objects.general.PeptideEntry; import nl.eriba.mzidentml.identification.objects.general.BestSpectrumEntry; import nl.eriba.mzidentml.identification.objects.general.SpectrumIdentificationItemEntry; import nl.eriba.mzidentml.identification.objects.general.SpectrumIdentificationResultEntry; import nl.eriba.mzidentml.identification.collections.general.CombinedDatabaseReferenceCollection; import nl.eriba.mzidentml.identification.collections.general.SingleDatabaseReferenceCollection; import nl.eriba.mzidentml.identification.objects.general.SingleDatabaseReference; import nl.eriba.mzidentml.identification.objects.general.CombinedPeptideEntry; import nl.eriba.mzidentml.tools.CalculationTools; import uk.ac.ebi.jmzidml.model.mzidml.PeptideEvidence; import uk.ac.ebi.jmzidml.model.mzidml.SpectrumIdentificationItem; import uk.ac.ebi.jmzidml.model.mzidml.SpectrumIdentificationList; import uk.ac.ebi.jmzidml.model.mzidml.SpectrumIdentificationResult; import uk.ac.ebi.jmzidml.model.mzidml.CvParam; import uk.ac.ebi.jmzidml.model.mzidml.DBSequence; import uk.ac.ebi.jmzidml.model.mzidml.Modification; import uk.ac.ebi.jmzidml.model.mzidml.Peptide; import uk.ac.ebi.jmzidml.model.mzidml.PeptideHypothesis; import uk.ac.ebi.jmzidml.model.mzidml.ProteinAmbiguityGroup; import uk.ac.ebi.jmzidml.model.mzidml.ProteinDetectionHypothesis; import uk.ac.ebi.jmzidml.model.mzidml.ProteinDetectionList; import uk.ac.ebi.jmzidml.model.mzidml.SequenceCollection; import uk.ac.ebi.jmzidml.model.mzidml.SpectrumIdentificationItemRef; import uk.ac.ebi.jmzidml.model.mzidml.SubstitutionModification; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Objects; import nl.eriba.mzidentml.identification.collections.general.MatchedIonSeriesCollection; import nl.eriba.mzidentml.identification.dataprocessing.spectra.CombineDatabaseReferenceInformation; import nl.eriba.mzidentml.identification.objects.mzid.MzIdProteinPeptide; import uk.ac.ebi.jmzidml.model.mzidml.FragmentArray; import uk.ac.ebi.jmzidml.model.mzidml.IonType; /** * Reads files with the .mzid extension and xml layout. * * @author vnijenhuis */ public class MzIdFileReader implements Callable { /** * Collection of ScanID objects. */ private final ScanIdOutputCollection scanCollection; /** * Current index of the dataset list. */ private final Integer currentIndex; /** * Total index of the dataset list. */ private final Integer maximumIndex; /** * Object that contains SpectrumIdentificationResult parameter data from the mzid file. */ private final SpectrumIdentificationResult spectrumResultItem; /** * Collection of MzIdPeptide objects. */ private final MzIdPeptideCollection peptideCollection; /** * List of file numbers that were entered to create output files. */ private final ArrayList<Integer> numbers; /** * Map of spectra counts of each peptide sequence. */ private final HashMap<String, Integer> spectrumCountMap; /** * Collection of MzIdProteinDetectionHypothesis objects. */ private final MzIdProteinPeptideCollection proteinPeptideCollection; /** * Intensity threshold used to filter low intensity peaks. */ private final Double intensityThreshold; /** * Map of sequences and the corresponding higest scoring sequence. */ private final ArrayList<BestSpectrumEntry> bestSpectrumList; /** * Collection of CombinedPeptideEntry objects. */ private final CombinedPeptideEntryCollection combinedPeptideEntryCollection; /** * Contains a set of tools designed for calculation purposes. */ private CalculationTools toolSet; /** * SpectrumIdentificationItem parameter from the mzid file. */ private final SpectrumIdentificationItem spectrumIdItem; /** * mzid format file reader. * * @param spectrumResultItem SpectrumIdentificationResult parameter from the mzid file. * @param spectrumIdItem SpectrumIdentificationItem parameter from the mzid file. * @param peptideCollection collection of MzIdPeptid objects. * @param combinedProteinPeptideCollection collection of MzIdCombinedProteinPeptide objects. * @param collection ScanIdCollection to store ScanID objects. * @param combinedPeptideEntryCollection collection of CombinedPeptideEntry objects. * @param spectraCountMap HashMap containing the amount of spectra per peptide sequence. * @param inputNumbers input numbers that determin which data should be processed. * @param bestSpectrumList list with the highest spectrum score per peptide sequence. * @param maximumIndex maximum index of the dataset list. * @param currentIndex current index of the dataset list. * @param intensityThreshold standard or user specified intensity threshold value. */ public MzIdFileReader(final SpectrumIdentificationResult spectrumResultItem, final SpectrumIdentificationItem spectrumIdItem, final MzIdPeptideCollection peptideCollection, MzIdProteinPeptideCollection combinedProteinPeptideCollection, final ScanIdOutputCollection collection, final CombinedPeptideEntryCollection combinedPeptideEntryCollection, final HashMap<String, Integer> spectraCountMap, ArrayList<BestSpectrumEntry> bestSpectrumList, final ArrayList<Integer> inputNumbers, final Integer currentIndex, final Integer maximumIndex, Double intensityThreshold) { this.spectrumIdItem = spectrumIdItem; this.spectrumResultItem = spectrumResultItem; this.peptideCollection = peptideCollection; this.scanCollection = collection; this.spectrumCountMap = spectraCountMap; this.currentIndex = currentIndex; this.maximumIndex = maximumIndex; this.numbers = inputNumbers; this.proteinPeptideCollection = combinedProteinPeptideCollection; this.combinedPeptideEntryCollection = combinedPeptideEntryCollection; this.intensityThreshold = intensityThreshold; this.bestSpectrumList = bestSpectrumList; } /** * Collects mzid data by storing the data into a collection of ScanID objects. * * @param mzidFile file to read the data from. * @param inputNumbers input numbers that determin which data should be processed. * @param scanIdEntryCollection collection of ScanIdEntry objets. * @param currentIndex current index of the dataset list. * @param totalIndex total index of the dataset index. * @param threads amount of threads used for the program. * @param intensityThreshold standard or user specified intensity threshold value. * @return returns a collection of ScanID objects. * @throws InterruptedException process was interrupted by another process. * @throws ExecutionException an error was encountered which prevents the execution. */ public ArrayList<Object> collectPeptideShakerScanIDs(final String mzidFile,ScanIdOutputCollection scanIdEntryCollection, final ArrayList<Integer> inputNumbers, final Integer currentIndex, final Integer totalIndex, final Integer threads, final Double intensityThreshold) throws InterruptedException, ExecutionException { System.out.println("Reading " + mzidFile); MzIdUnmarshaller unmarshalMzIdFile = new MzIdUnmarshaller(); MzIdMainElementCollection unmarshalCollection = unmarshalMzIdFile.unmarshalMzIdFile(mzidFile); //Unmarshaller that transforms storage data format to a memory format DatabaseSearchPsmOutputCollection searchPsmEntryCollection = new DatabaseSearchPsmOutputCollection(); ProteinPeptideOutputCollection proteinPeptideEntryCollection = new ProteinPeptideOutputCollection(); PeptideOutputCollection peptideOutputCollection = new PeptideOutputCollection(); MatchedIonSeriesCollection matchedIonSeriesCollection = new MatchedIonSeriesCollection(); //Get spectrum identification data SpectrumIdentificationList spectrumIdList = unmarshalCollection.getSpectrumIdentificationList(); //Remove low threshold entries. ArrayList<BestSpectrumEntry> generateBestSpectrumList = generateBestSpectrumList(spectrumIdList); //Get sequence data SequenceCollection sequenceCollection = unmarshalCollection.getSequenceCollection(); //Get peptide data MzIdPeptideCollection peptides = createPeptideCollection(sequenceCollection.getPeptide()); //Get peptide evidence data List<PeptideEvidence> peptideEvidenceList = sequenceCollection.getPeptideEvidence(); MzIdPeptideEvidenceCollection evidenceCollection = createPeptideEvidenceCollection(peptideEvidenceList); //Group data of database sequence objects into different collections MzIdDatabaseSequenceCollection dbSequenceCollection = createDatabaseSequenceCollection(sequenceCollection.getDBSequence()); //Create SingleDatabaseReference objects that are used to create the CombinedPeptidEntry and CombinedDatabaseReference collections. SingleDatabaseReferenceCollection singleDatabaseReferenceCollection = createSingleDatabaseReferenceCollection(peptideEvidenceList, peptides); CombinedPeptideEntryCollection combinedPeptides = createCombinedPeptideCollection(singleDatabaseReferenceCollection); //Combined SingleDatabaseReference objects to represent all unique protein hits per peptide sequence. CombineDatabaseReferenceInformation combineInformation = new CombineDatabaseReferenceInformation(null, null); CombinedDatabaseReferenceCollection combinedDatabaseReferenceCollection = combineInformation.combineDatabaseReferenceData(singleDatabaseReferenceCollection, dbSequenceCollection, combinedPeptides, threads); //Create map with spectra counts per sequence HashMap<String, Integer> spectraCountMap = determineSpectraCounts(peptideEvidenceList); //Get protein hypothesis data ProteinDetectionList proteinHypothesisList = unmarshalCollection.getProteinHypothesisCollection(); MzIdProteinDetectionHypothesisCollection proteinHypothesisCollection = createProteinHypothesisCollection(proteinHypothesisList); MzIdProteinPeptideCollection mzidProteinPeptideCollection = combineProteinHypothesisWithPeptideEvidence(evidenceCollection, proteinHypothesisCollection); //Remove hits that didn't pass the initial threshold and hits that are tagged as a decoy sequence. mzidProteinPeptideCollection = removeLowThresholdSequences(mzidProteinPeptideCollection); mzidProteinPeptideCollection = removeDecoySequences(mzidProteinPeptideCollection); mzidProteinPeptideCollection.sortOnPeptideSequence(); //Filter evidence collection based on evidences present in protein hypotheses Collections.sort(spectrumIdList.getSpectrumIdentificationResult(), new SortSpectrumResultBySequence()); ExecutorService executor = Executors.newFixedThreadPool(threads); Integer count = 0; System.out.println("Starting identification of spectrum results."); for (SpectrumIdentificationResult spectrumIdResult : spectrumIdList.getSpectrumIdentificationResult()) { count++; for (SpectrumIdentificationItem spectrumIdentificationItem: spectrumIdResult.getSpectrumIdentificationItem()) { //Test if the initial threshold is passed. if (spectrumIdentificationItem.isPassThreshold()) { Callable<ArrayList<Object>> callable = new MzIdFileReader(spectrumIdResult, spectrumIdentificationItem, peptides, mzidProteinPeptideCollection, scanIdEntryCollection, combinedPeptides, spectraCountMap, generateBestSpectrumList, inputNumbers, currentIndex, totalIndex, intensityThreshold); //Collects the output from the call function Future<ArrayList<Object>> future = executor.submit(callable); scanIdEntryCollection = (ScanIdOutputCollection) future.get().get(0); for (Integer number : numbers) { //Add data to respective collection if number is present. if (number != null) { switch (number) { case 1: //Gathers DatabaseSearchPsm objects to define peptide spectrum match data. DatabaseSearchPsmOutputCollection psmObjects = (DatabaseSearchPsmOutputCollection) future.get().get(1); for (DatabaseSearchPsmOutput object : psmObjects.getDatabaseSearchPsmEntryList()) { searchPsmEntryCollection.addDatabaseSearchPsmEntry(object); } break; case 2: //Gathers PeptideOutput objects to define peptide data. PeptideOutputCollection peptideObjects = (PeptideOutputCollection) future.get().get(2); for (PeptideOutput object : peptideObjects.getPeptideEntryList()) { peptideOutputCollection.addPeptideEntry(object); } //Gathers MatchedIonSeries objects to define the ion series and quality of the best spectrum matches. MatchedIonSeriesCollection matchedIonSeries = (MatchedIonSeriesCollection) future.get().get(3); for (MatchedIonSeries ionSeries: matchedIonSeries.getMatchedIonSeriesList()) { matchedIonSeriesCollection.addMatchedIonSeries(ionSeries); } break; case 3: //Gathers ProteinPeptideOutput objects to define protein-peptide data. ProteinPeptideOutputCollection proteinPeptideObjects = (ProteinPeptideOutputCollection) future.get().get(4); mzidProteinPeptideCollection = (MzIdProteinPeptideCollection) future.get().get(5); for (ProteinPeptideOutput object : proteinPeptideObjects.getProteinPeptideEntryList()) { proteinPeptideEntryCollection.addProteinPeptideEntry(object); } break; default: break; } } } } } if (count % 2000 == 0) { System.out.println("Matched data for " + count + " entries."); } } System.out.println("Matched data for " + count + " entries."); //Sort collections System.out.println("Sorting collections..."); searchPsmEntryCollection.sortOnPeptideScore(); proteinPeptideEntryCollection.sortOnProteinGroup(); peptideOutputCollection.sortOnPeptideScore(); combinedDatabaseReferenceCollection.sortOnAccession(); //Add collections to list. ArrayList<Object> collections = new ArrayList<>(); collections.add(scanIdEntryCollection); collections.add(searchPsmEntryCollection); collections.add(peptideOutputCollection); collections.add(matchedIonSeriesCollection); collections.add(proteinPeptideEntryCollection); collections.add(proteinHypothesisCollection); collections.add(combinedDatabaseReferenceCollection); //Shutdown executor to remove the created threadpool. executor.shutdown(); return collections; } /** * Call function that is used by a thread to process SpectrumIdentificationResult objects. * * @return return ScanIdCollection with added/updated ScanID object. * @throws java.lang.InterruptedException process was interrupted. * @throws java.util.concurrent.ExecutionException any exception encountered during execution. */ @Override public Object call() throws InterruptedException, ExecutionException { //Call class that can gather data from single spectra. SingleSpectrumDataCollector collector = new SingleSpectrumDataCollector(); //Gather data from SpectrumIdentificationItem. SpectrumIdentificationItemEntry spectrumItemData = collector.getSpectrumIdentificationItemData(spectrumResultItem, spectrumIdItem); String sequence = spectrumItemData.getPeptideSequence(); String score = spectrumItemData.getPsmScore(); Double peptideScore = Double.parseDouble(score); Double calculatedMassToCharge = spectrumItemData.getCalculatedMassToCharge(); Double experimentalMassToCharge = spectrumItemData.getExperimentalMassToCharge(); Double theoreticalMassToCharge = spectrumItemData.getTheoreticalMassToCharge(); Integer length = spectrumItemData.getSequenceLength(); //Gather data from SpectrumIdentificationResult item. SpectrumIdentificationResultEntry resultItemData = collector.getSpectrumIdentificationResultData(spectrumResultItem); // Integer index = resultItemData.getIndex(); String retentionTime = resultItemData.getRetentionTime(); String scanNumber = resultItemData.getScanNumber(); String scanId = resultItemData.getScanId(); // String scanID = resultItemData.getScanID(); Double partsPerMillion = ((calculatedMassToCharge - experimentalMassToCharge) / calculatedMassToCharge) * 1000000; toolSet = new CalculationTools(); partsPerMillion = toolSet.roundDouble(partsPerMillion, 2); //Gther data from Peptide item. PeptideEntry peptideData = collector.getPeptideCollectionData(peptideCollection, sequence); String aScore = peptideData.getAScore(); String modifiedSequence = peptideData.getModifiedSequence(); String postTranslationalModification = peptideData.getPostTranslationalModification(); //Create lists for each object. ArrayList<Object> collectionList = new ArrayList<>(); ProteinPeptideOutputCollection proteinPeptideList = new ProteinPeptideOutputCollection(); DatabaseSearchPsmOutputCollection databaseSearchPsmList = new DatabaseSearchPsmOutputCollection(); PeptideOutputCollection peptideOutputCollection = new PeptideOutputCollection(); MatchedIonSeriesCollection matchedIonSeriesCollection = new MatchedIonSeriesCollection(); //Adds ScanID entry to the scanCollection if (numbers.contains(1)) { addEntryToScanCollection(scanId, sequence, peptideScore); } //If one of the file numbers corresponds to ProteinPeptideEntry proteinPeptideData = matchProteinPeptideData(sequence); String accessions = proteinPeptideData.getAccessions(); String unique = proteinPeptideData.getUniqueness(); //Match sequence to protein peptide data. Integer spectraCount = spectrumCountMap.get(sequence); if (numbers.contains(2)) { DatabaseSearchPsmOutput dbsObject = new DatabaseSearchPsmOutput(modifiedSequence, peptideScore, theoreticalMassToCharge, length, partsPerMillion, calculatedMassToCharge, retentionTime, scanNumber, accessions, postTranslationalModification, aScore, spectraCount); databaseSearchPsmList.addDatabaseSearchPsmEntry(dbsObject); } Double highestScore = 0.0; for (BestSpectrumEntry spectrum : bestSpectrumList) { if (spectrum.getSequence().equals(sequence) && !spectrum.getFlag()) { highestScore = spectrum.getScore(); spectrum.setFlag(true); break; } } if (numbers.contains(3)) { if (Objects.equals(peptideScore, highestScore)) { MatchedIonSeries matchedIonSeries = createFragmentIndexList(spectrumResultItem, spectrumIdItem, intensityThreshold, sequence, peptideScore, accessions); matchedIonSeriesCollection.getMatchedIonSeriesList().add(matchedIonSeries); // 0 not complete coverage of sequence, 1 = y-ion coverage, 2 = b-ion coverage 3 = combined ion coverage PeptideOutput peptideObject = new PeptideOutput(modifiedSequence, peptideScore, theoreticalMassToCharge, length, partsPerMillion, calculatedMassToCharge, retentionTime, scanNumber, accessions, spectraCount, postTranslationalModification, aScore); peptideOutputCollection.addPeptideEntry(peptideObject); } } if (numbers.contains(4)) { if (Objects.equals(peptideScore, highestScore)) { ArrayList<MzIdProteinPeptide> removeableEvidence = new ArrayList<>(); Boolean allowMismatch = false; for (MzIdProteinPeptide proteinPeptide: proteinPeptideCollection.getProteinPeptideList()) { if (proteinPeptide.getPeptideSequence().equals(sequence)) { removeableEvidence.add(proteinPeptide); Integer start = proteinPeptide.getStartIndex(); Integer end = proteinPeptide.getEndIndex(); String pre = proteinPeptide.getPreAminoAcid(); String post = proteinPeptide.getPostAminoAcid(); Integer proteinGroup = proteinPeptide.getProteinGroup(); String proteinId = proteinPeptide.getProteinId(); String finalSequence = ""; if (finalSequence.isEmpty()) { if (!pre.matches("[A-Z]")) { finalSequence = modifiedSequence + "." + post; } else if (!post.matches("[A-Z]")) { finalSequence = pre + "." + modifiedSequence; } else { finalSequence = pre + "." + modifiedSequence + "." + post; } } String accession = proteinPeptide.getProteinAccession(); ProteinPeptideOutput proteinPeptideObject = new ProteinPeptideOutput(proteinGroup, proteinId, accession, finalSequence, unique, peptideScore, theoreticalMassToCharge, calculatedMassToCharge, length, partsPerMillion, retentionTime, scanNumber, spectraCount, start, end, postTranslationalModification, aScore); proteinPeptideList.addProteinPeptideEntry(proteinPeptideObject); allowMismatch = true; } else if (allowMismatch) { break; } } for (MzIdProteinPeptide entry: removeableEvidence) { proteinPeptideCollection.removeProteinPeptide(entry); } } } collectionList.add(scanCollection); collectionList.add(databaseSearchPsmList); collectionList.add(peptideOutputCollection); collectionList.add(matchedIonSeriesCollection); collectionList.add(proteinPeptideList); collectionList.add(proteinPeptideCollection); return collectionList; } /** * Creates a collection of MzIdDatabaseSequence objects. * * @param dbSequenceList list of DatabaseSequence objects. * @return collection of MzIdDatabaseSequence objects. */ private MzIdDatabaseSequenceCollection createDatabaseSequenceCollection(final List<DBSequence> dbSequenceList) { System.out.println("Creating MzIdDatabaseSequence object collection..."); MzIdDatabaseSequenceCollection databaseSequenceCollection = new MzIdDatabaseSequenceCollection(); for (int index = 0; index < dbSequenceList.size() - 1; index++) { DBSequence databaseSequence = dbSequenceList.get(index); String id = databaseSequence.getId(); String proteinAccession = databaseSequence.getAccession(); String databaseReference = databaseSequence.getSearchDatabaseRef(); String description = ""; String reversedDescription = ""; String paramValue = databaseSequence.getCvParam().get(0).getValue(); if (paramValue != null) { description = paramValue; } index++; DBSequence reveresedDatabaseSequence = dbSequenceList.get(index); String reversedProteinAccession = reveresedDatabaseSequence.getAccession(); paramValue = databaseSequence.getCvParam().get(0).getValue(); if (paramValue != null) { reversedDescription = paramValue; } description = description.replaceAll(",", "."); reversedDescription = reversedDescription.replaceAll(",", "."); MzIdDatabaseSequence mzidDatabaseSequence = new MzIdDatabaseSequence(id, proteinAccession, reversedProteinAccession, databaseReference, description, reversedDescription); databaseSequenceCollection.addDatabaseSequence(mzidDatabaseSequence); } return databaseSequenceCollection; } /** * Creates a SingleDatabaseReferenceCollection containing data of single entry hits. * * @param peptideEvidenceList list of PeptideEvidence objects. * @param peptideCollection list of MzIdPeptide objects. * @return collection of SingleDatabaseReference objects. */ private SingleDatabaseReferenceCollection createSingleDatabaseReferenceCollection(final List<PeptideEvidence> peptideEvidenceList, final MzIdPeptideCollection peptideCollection) { System.out.println("Creating SequenceDatabaseReference object collection..."); SingleDatabaseReferenceCollection sequenceDatabaseReferenceCollection = new SingleDatabaseReferenceCollection(); Collections.sort(peptideEvidenceList, new SortPeptideEvidenceCollectionOnSequence()); peptideCollection.sortOnPeptideSequence(); for (PeptideEvidence peptideEvidence : peptideEvidenceList) { if (!peptideEvidence.isIsDecoy()) { ArrayList<MzIdPeptide> removeablePeptideEntries = new ArrayList<>(); String proteinAccession = peptideEvidence.getDBSequenceRef(); Integer start = peptideEvidence.getStart(); Integer end = peptideEvidence.getEnd(); String peptideSequence = peptideEvidence.getPeptideRef(); String pre = peptideEvidence.getPre(); String post = peptideEvidence.getPost(); String id = peptideEvidence.getId().split("_")[1]; Integer evidenceId = Integer.parseInt(id); MzIdPeptide newEntry = null; ArrayList<String> modifications = new ArrayList<>(); for (MzIdPeptide entry: peptideCollection.getPeptides()) { if (entry.getModifications().isEmpty() && entry.getSubstituteModifications().isEmpty()) { removeablePeptideEntries.add(entry); } else if (entry.getPeptideSequence().equals(peptideSequence)) { newEntry = entry; for (MzIdModification modification: entry.getModifications()) { for (String name: modification.getNames()) { if (!modifications.contains(name)) { modifications.add(name); } } } } } removeablePeptideEntries.add(newEntry); for (MzIdPeptide x: removeablePeptideEntries) { peptideCollection.getPeptides().remove(x); } SingleDatabaseReference sequenceDatabaseReference = new SingleDatabaseReference(proteinAccession, evidenceId, peptideSequence, start, end, pre, post, modifications); sequenceDatabaseReferenceCollection.addDatabaseReference(sequenceDatabaseReference); } } return sequenceDatabaseReferenceCollection; } /** * Creates a collection of CombinedPeptideEntry objects. * * @param singleDatabaseReferenceCollection collection of SingleDatabaseReference objects. * @return collection of CombinedPeptideEntry objects. */ private CombinedPeptideEntryCollection createCombinedPeptideCollection(final SingleDatabaseReferenceCollection singleDatabaseReferenceCollection) { System.out.println("Creating list for peptide data objects."); //Determine if a sequence is unique to one accession. CombinedPeptideEntryCollection combinedPeptideCollection = new CombinedPeptideEntryCollection(); //Sort collections on sequence. This causes UniquePeptideEntry list to be sorted on sequence as well. singleDatabaseReferenceCollection.sortOnPeptideSequence(); //Get first entry sequence. ArrayList<String> accessionList = new ArrayList<>(); String targetSequence = singleDatabaseReferenceCollection.getDatabaseSequenceReferenceList().get(0).getPeptideSequence(); for (SingleDatabaseReference databaseReference: singleDatabaseReferenceCollection.getDatabaseSequenceReferenceList()) { //Check if current sequence matches the targetSequence and add accession to given sequence. if (databaseReference.getPeptideSequence().equals(targetSequence)) { //if accession is not present add it to the list. Duplicate accessions are not necessary. if (!accessionList.contains(databaseReference.getProteinAccession())) { accessionList.add(databaseReference.getProteinAccession()); } if (!accessionList.contains(databaseReference.getProteinAccession())) { accessionList.add(databaseReference.getProteinAccession()); } } else { //UniquePeptideAccessionCount object is created that contains the target sequence and the list of accession ids. Collections.sort(accessionList); CombinedPeptideEntry combinedPeptide = new CombinedPeptideEntry(targetSequence, accessionList); combinedPeptideCollection.addCombinedPeptideEntry(combinedPeptide); accessionList = new ArrayList<>(); accessionList.add(databaseReference.getProteinAccession()); targetSequence = databaseReference.getPeptideSequence(); } } return combinedPeptideCollection; } /** * Determines the spectra count per peptide sequence by coutning the peptide evidences per peptide sequence. * * @param peptideEvidenceList determines the amount of peptide spectra of each peptide sequence. * @return HashMap with peptide sequence as key and count as value. */ private HashMap<String, Integer> determineSpectraCounts(final List<PeptideEvidence> peptideEvidenceList) { System.out.println("Creating spectra count map..."); HashMap<String, Integer> spectraCountMap = new HashMap<>(); //Loops through list of PeptideEvidence objects. for (PeptideEvidence peptideEvidence : peptideEvidenceList) { String peptideRef = peptideEvidence.getPeptideRef(); if (!spectraCountMap.isEmpty() && spectraCountMap.containsKey(peptideRef)) { Integer spectraCount = spectraCountMap.get(peptideRef) + 1; spectraCountMap.put(peptideRef, spectraCount); } else { spectraCountMap.put(peptideRef, 1); } } return spectraCountMap; } /** * Creates a collection of MzIdPeptide objects. * * @param peptides list of PeptideItem objects. * @return collection of MzIdPeptide objects. */ private MzIdPeptideCollection createPeptideCollection(final List<Peptide> peptides) { System.out.println("Creating MzIdPeptide object collection..."); MzIdPeptideCollection newPeptideCollection = new MzIdPeptideCollection(); //Loops through list of all PeptideItem objects. for (Peptide peptide : peptides) { String id = peptide.getId(); String sequence = peptide.getPeptideSequence(); List<Modification> mods = peptide.getModification(); List<SubstitutionModification> subMods = peptide.getSubstitutionModification(); ArrayList<MzIdSubstituteModification> subModificationList = new ArrayList<>(); ArrayList<MzIdModification> modificationList = new ArrayList<>(); //Create list of Modification objects. for (Modification modification : mods) { Integer location = modification.getLocation(); ArrayList<String> nameList = new ArrayList<>(); for (CvParam param : modification.getCvParam()) { String name = param.getName(); nameList.add(name); } Double monoMassDelta = modification.getMonoisotopicMassDelta(); List<String> modResidues = modification.getResidues(); ArrayList<String> residueList = new ArrayList<>(); for (String residue : modResidues) { residueList.add(residue); } //Stores data in new Modification object. MzIdModification modificationObject = new MzIdModification(monoMassDelta, location, residueList, nameList); //Adds objects to the list. modificationList.add(modificationObject); } //Create list of SubstituteModification objects. for (SubstitutionModification subModification : subMods) { Double monoMassDelta = subModification.getMonoisotopicMassDelta(); Integer location = subModification.getLocation(); String originalResidue = subModification.getOriginalResidue(); String replacedResidue = subModification.getReplacementResidue(); //Stores data in new SubstituteModification object. MzIdSubstituteModification subModificationObject = new MzIdSubstituteModification(monoMassDelta, location, originalResidue, replacedResidue); //Adds objects to the list. subModificationList.add(subModificationObject); } //Stores data in new PeptideItem object. MzIdPeptide peptideObject = new MzIdPeptide(id, sequence, modificationList, subModificationList); //Adds objects to the MzIdPeptideCollection. newPeptideCollection.addPeptide(peptideObject); } return newPeptideCollection; } /** * Creates a collection of MzIdPeptideHypothesis objects. * * @param hypothesisList list of PeptideHypothesis parameters from the MzIdentML data. * @return list of MzIdPeptideHypothesis objects. */ private MzIdProteinDetectionHypothesisCollection createProteinHypothesisCollection(final ProteinDetectionList proteinHypothesisList) { System.out.println("Creating MzIdProteinDetectionHypothesis object collection..."); MzIdProteinDetectionHypothesisCollection proteinHypothesisCollection = new MzIdProteinDetectionHypothesisCollection(); //Loops throughe list of ProteinDetectionHypothesis objects. List<ProteinAmbiguityGroup> proteinAmbiguityGroup = proteinHypothesisList.getProteinAmbiguityGroup(); for (ProteinAmbiguityGroup ambiguity : proteinAmbiguityGroup) { String ambiguityId = ambiguity.getId(); String group = ambiguityId.split("_")[1]; Integer proteinGroup = Integer.parseInt(group); String score = ambiguity.getCvParam().get(0).getValue(); Double proteinscore = Double.parseDouble(score); for (ProteinDetectionHypothesis proteinHypothesis : ambiguity.getProteinDetectionHypothesis()) { String proteinId = proteinHypothesis.getId(); String dbSeqRef = proteinHypothesis.getDBSequenceRef(); Boolean passThreshold = proteinHypothesis.isPassThreshold(); Double sequenceCoverage = 0.0; List<CvParam> paramList = ambiguity.getCvParam(); for (CvParam parameter: paramList) { //Gets sequence coverage if available. if (parameter.getName().contains("coverage")) { sequenceCoverage = Double.parseDouble(parameter.getValue()); } } ArrayList<MzIdCvParam> mzIdParamList = new ArrayList<>(); //Creates list of cvParam objects. for (CvParam param : paramList) { String accession = param.getAccession(); String name = param.getName(); String value = param.getValue(); //Stores data in new cvParam object. MzIdCvParam mzIdCvParam = new MzIdCvParam(name, accession, value); mzIdParamList.add(mzIdCvParam); } //Creates list of PeptideHypothesis objects. for (PeptideHypothesis peptideHypothesis : proteinHypothesis.getPeptideHypothesis()) { String peptideEvidenceRef = peptideHypothesis.getPeptideEvidenceRef(); Integer peptideEvidenceId = Integer.parseInt(peptideEvidenceRef.split("_")[1]); List<SpectrumIdentificationItemRef> spectrumItemRefList = peptideHypothesis.getSpectrumIdentificationItemRef(); ArrayList<String> idReferenceList = new ArrayList<>(); //Creates a list of SpectrumReference objects. for (SpectrumIdentificationItemRef spectrumItemRef : spectrumItemRefList) { idReferenceList.add(spectrumItemRef.getSpectrumIdentificationItemRef()); } MzIdProteinDetectionHypothesis proteinDetectionHypothesis = new MzIdProteinDetectionHypothesis(passThreshold, proteinId, proteinGroup, dbSeqRef, peptideEvidenceId, proteinscore, sequenceCoverage, idReferenceList, mzIdParamList); proteinHypothesisCollection.addProteinDetectionHypothesis(proteinDetectionHypothesis); } } } //Sorts the ProteinDetectionList based on the PeptideEvidence id. proteinHypothesisCollection.sortOnPeptideEvidence(); return proteinHypothesisCollection; } /** * Creates and adds a ScanID object to the ScanIdCollection. * * @param scanID ID of the scan. * @param sequence peptide amino acid sequence. * @param psmScore peptide score (-10LogP). */ public final void addEntryToScanCollection(final String scanID, final String sequence, final Double psmScore) { ArrayList<String> sequences = new ArrayList(maximumIndex); ArrayList<Double> psmScores = new ArrayList(maximumIndex); ArrayList<String> databaseFlags = new ArrayList<>(maximumIndex); for (int i = 0; i <= maximumIndex; i++) { if (i == currentIndex) { sequences.add(sequence); psmScores.add(psmScore); databaseFlags.add(""); } else { sequences.add(""); psmScores.add(0.0); databaseFlags.add(""); } } Boolean newScanID = true; if (!scanCollection.getScanIdEntryList().isEmpty()) { //Loop through entries of the HashMap. if (currentIndex != 0) { for (ScanIdOutput object : scanCollection.getScanIdEntryList()) { //Check for duplicates. if (object.getScanId().equals(scanID)) { object.getPeptideSequenceList().set(currentIndex, sequence); object.getPsmScoreList().set(currentIndex, psmScore); newScanID = false; break; } } } } //Add a new entry to the collection. if (newScanID) { ScanIdOutput scanObject = new ScanIdOutput(scanID, sequences, psmScores, databaseFlags); scanCollection.addScanIdEntry(scanObject); } } /** * Gathers all accessions per peptide sequence and determines if the peptide is unique to a protein sequence. * * @param sequence peptide sequence. * @return EvidenceData with a list of accessions and uniqueness flag. */ public final ProteinPeptideEntry matchProteinPeptideData(final String sequence) { String accessions = ""; String unique = "N"; for (CombinedPeptideEntry peptide : combinedPeptideEntryCollection.getUniquePeptideList()) { if (peptide.getSequence().equals(sequence)) { if (peptide.getAccessionList().size() == 1) { unique = "Y"; } for (String accession : peptide.getAccessionList()) { if (accessions.isEmpty()) { accessions += accession; } else { accessions += ":" + accession; } } break; } } ProteinPeptideEntry matchedProteinPeptide = new ProteinPeptideEntry(sequence, accessions, unique); return matchedProteinPeptide; } /** * Creates a list of peptide ion fragments and the covered ion indices. * * @param spectrumItemData contains SpectrumItemData. * @param sequence peptide sequence. * @return IndexItemData consisting of a list of ion fragment indices and the given ionSerieFlag. */ private MatchedIonSeries createFragmentIndexList(final SpectrumIdentificationResult spectrumIdentificationResult, final SpectrumIdentificationItem spectrumItem, Double userIntensityThreshold, final String peptideSequence, final Double peptideScore, final String accessions) { ArrayList<MzIdIonFragment> ionFragmentList = new ArrayList<>(); List<IonType> fragmentList = spectrumItem.getFragmentation().getIonType(); //Process all ion fragments of the given peptide amino acid sequence. for (IonType ionType : fragmentList) { List<Integer> indexList = ionType.getIndex(); ArrayList<Double> measuredMassToChargeValues = new ArrayList<>(); ArrayList<Boolean> passedIntensityThreshold = new ArrayList<>(); FragmentArray fragmentArray = ionType.getFragmentArray().get(0); //Gathers measured mass to charge values of each fragment array. for (float fragmentValue : fragmentArray.getValues()) { double measuredMassToCharge = fragmentValue; measuredMassToChargeValues.add(measuredMassToCharge); } //Set standard threshold to 5%. Double standardThreshold = 0.05; // Calculate the user defined intensity threshold value per peptide sequence. FragmentArray measureIntensity = ionType.getFragmentArray().get(1); if (userIntensityThreshold >= standardThreshold) { standardThreshold = userIntensityThreshold; } Double highestPeakIntensity = 0.0; //Test peakIntensity versus the specified threshold. for (Float intensityValue : measureIntensity.getValues()) { double intensity = intensityValue; Double peakIntensity = intensity * standardThreshold; if (peakIntensity > highestPeakIntensity) { highestPeakIntensity = peakIntensity; } } //Test if ion intensity passes the user specified threshold. for (Float intensityValue : measureIntensity.getValues()) { double intensity = intensityValue; if (intensity >= highestPeakIntensity) { passedIntensityThreshold.add(true); } else { passedIntensityThreshold.add(false); } } //Create MzIdIonFragment object containing the name, indices, m/z values and a true/false list for passing the intensity threshold. String name = ionType.getCvParam().getName(); MzIdIonFragment fragment = new MzIdIonFragment(name, indexList, measuredMassToChargeValues, passedIntensityThreshold); ionFragmentList.add(fragment); } Integer sequenceLength = peptideSequence.length(); ArrayList<Integer> bIonIndices = new ArrayList<>(sequenceLength); ArrayList<Integer> yIonIndices = new ArrayList<>(sequenceLength); ArrayList<Integer> combinedIonIndices = new ArrayList<>(sequenceLength); ArrayList<Integer> combinedAllIonIndices = new ArrayList<>(); ArrayList<Integer> finalIndexList = new ArrayList<>(); for (MzIdIonFragment ionFragment : ionFragmentList) { String name = ionFragment.getName(); List<Integer> indexList = ionFragment.getIndexList(); ArrayList<Boolean> intensityValues = ionFragment.getItensityValues(); //Removes hits with different index and intensity counts. (size should be the same to process data. if (intensityValues.size() == indexList.size()) { for (int i = 0; i < indexList.size(); i++) { Integer listIndex = indexList.get(i); Integer sequenceIndex = listIndex; if (intensityValues.get(i)) { if (name.matches("frag: y ion")) { if (!yIonIndices.contains(sequenceIndex)) { yIonIndices.add(sequenceIndex); } if (!combinedAllIonIndices.contains(sequenceIndex)) { combinedAllIonIndices.add(sequenceIndex); } } else if (name.matches("(frag: y ion -).*")) { if (!combinedIonIndices.contains(sequenceIndex)) { combinedIonIndices.add(sequenceIndex); } if (!combinedAllIonIndices.contains(sequenceIndex)) { combinedAllIonIndices.add(sequenceIndex); } } else if (name.matches("frag: b ion")) { sequenceIndex = sequenceLength - listIndex; if (!bIonIndices.contains(sequenceIndex)) { bIonIndices.add(sequenceIndex); } if (!combinedAllIonIndices.contains(sequenceIndex)) { combinedAllIonIndices.add(sequenceIndex); } } else if (name.matches("(frag: b ion -).*")) { if (!combinedIonIndices.contains(sequenceIndex)) { combinedIonIndices.add(sequenceIndex); } if (!combinedAllIonIndices.contains(sequenceIndex)) { combinedAllIonIndices.add(sequenceIndex); } } else if (name.contains("immonium")) { if (!combinedIonIndices.contains(sequenceIndex)) { combinedIonIndices.add(sequenceIndex); } if (!combinedAllIonIndices.contains(sequenceIndex)) { combinedAllIonIndices.add(sequenceIndex); } } } } } } //Flag 0 for incomplete ion serie, flag 1 for complete b ion serie, flag 2 for complete y ion serie, flag 3 for combined ion series (includes immonium) Integer ionSerieFlag = 0; sequenceLength--; if (sequenceLength == bIonIndices.size()) { ionSerieFlag = 1; finalIndexList = bIonIndices; } else if (sequenceLength == yIonIndices.size()) { ionSerieFlag = 2; finalIndexList = yIonIndices; } else if (sequenceLength == combinedIonIndices.size()) { ionSerieFlag = 3; finalIndexList = combinedIonIndices; } else if (sequenceLength == combinedAllIonIndices.size()) { ionSerieFlag = 4; finalIndexList = combinedAllIonIndices; } Collections.sort(finalIndexList); MatchedIonSeries ionSeries = new MatchedIonSeries(peptideSequence, peptideScore, accessions, combinedIonIndices, bIonIndices, yIonIndices, combinedAllIonIndices, finalIndexList, ionSerieFlag); return ionSeries; } /** * Generates a list of BestSpectrumEntry objects that define the highest scoring peptide spectrum per peptide sequence. * * @param spectrumIdList list of SpectrumIdentificationResult items. * @return returns a list containing BestSpectrumEntry objects. */ private ArrayList<BestSpectrumEntry> generateBestSpectrumList(SpectrumIdentificationList spectrumIdList) { System.out.println("Generating spectrum ID map"); ArrayList<BestSpectrumEntry> spectrumScoreList = new ArrayList<>(); for (SpectrumIdentificationResult spectrumIdResult : spectrumIdList.getSpectrumIdentificationResult()) { for (SpectrumIdentificationItem spectrumIdentificationItem : spectrumIdResult.getSpectrumIdentificationItem()) { Boolean isPassThreshold = spectrumIdentificationItem.isPassThreshold(); //If an item passes the threshol the call() function is executed by a thread from the threadpool Double psmScore = 0.0; if (isPassThreshold) { String peptideSequence = spectrumIdentificationItem.getPeptideRef(); Boolean newReference = true; List<CvParam> paramList = spectrumIdentificationItem.getCvParam(); for (CvParam param : paramList) { if (param.getName().contains("PSM score")) { psmScore = Double.parseDouble(param.getValue()); } } for (BestSpectrumEntry spectrum : spectrumScoreList) { if (spectrum.getSequence().equals(peptideSequence)) { if (spectrum.getScore() > psmScore) { spectrumScoreList.remove(spectrum); spectrum.setScore(psmScore); spectrum.setFlag(false); spectrumScoreList.add(spectrum); } break; } } //New peptide sequence and highest score. if (newReference) { BestSpectrumEntry spectrum = new BestSpectrumEntry(peptideSequence, psmScore, false); spectrumScoreList.add(spectrum); } } } } return spectrumScoreList; } /** * Combines data from MzIdProteinHypothesis with MzIdPeptideEvidence. * * @param mzIdPeptideEvidenceCollection collection of MzIdPeptideEvidence objects. * @param mzIdProteinHypothesisCollection collection of MzIdProteinHypothesis objects. * @return MzIdProteinPeptideCollection containing MzIdProteinPeptide objects. */ public final MzIdProteinPeptideCollection combineProteinHypothesisWithPeptideEvidence(MzIdPeptideEvidenceCollection mzIdPeptideEvidenceCollection, MzIdProteinDetectionHypothesisCollection mzIdProteinHypothesisCollection) { System.out.println("combining protein hypothesis data with peptide evidence data..."); MzIdProteinPeptideCollection mzidProteinPeptideCollection = new MzIdProteinPeptideCollection(); for (MzIdProteinDetectionHypothesis mzIdProteinDetectionHypothesis : mzIdProteinHypothesisCollection.getProteinDetectionHypothesisList()) { Integer id = mzIdProteinDetectionHypothesis.getPeptideEvidenceId(); Integer indexOfEvidenceId = id - 1; MzIdPeptideEvidence evidence = mzIdPeptideEvidenceCollection.getPeptideEvidenceItems().get(indexOfEvidenceId); String peptideSequence = evidence.getPeptideSequence(); Boolean isDecoySequence = evidence.isDecoySequence(); Boolean isPassThreshold = mzIdProteinDetectionHypothesis.isPassThreshold(); Integer endIndex = evidence.getEndIndex(); Integer startIndex = evidence.getStartIndex(); String preAminoAcid = evidence.getPreAminoAcid(); String postAminoAcid = evidence.getPostAminoAcid(); String proteinAccession = mzIdProteinDetectionHypothesis.getProteinAccession(); Integer proteinGroup = mzIdProteinDetectionHypothesis.getProteinGroup(); String proteinId = proteinGroup + "_" + mzIdProteinDetectionHypothesis.getProteinId().split("_")[2]; Double proteinGroupScore = mzIdProteinDetectionHypothesis.getProteinScore(); MzIdProteinPeptide proteinPeptide = new MzIdProteinPeptide(id, peptideSequence, proteinAccession, proteinGroup, proteinId, isDecoySequence, isPassThreshold, startIndex, endIndex, preAminoAcid, postAminoAcid, proteinGroupScore); mzidProteinPeptideCollection.addProteinPeptide(proteinPeptide); } return mzidProteinPeptideCollection; } /** * Creates a collection of MzIdPeptideEvidence objects using the PeptideEvidence list of the mzid file. * * @param peptideEvidenceList list of PeptideEvidence objects. * @return returns the MzIdPeptideEvidenceCollection. */ private MzIdPeptideEvidenceCollection createPeptideEvidenceCollection(List<PeptideEvidence> peptideEvidenceList) { System.out.println("Creating peptide evidence collection..."); MzIdPeptideEvidenceCollection mzIdPeptideEvidenceCollection = new MzIdPeptideEvidenceCollection(); for (PeptideEvidence peptideEvidence: peptideEvidenceList) { String id = peptideEvidence.getId().split("_")[1]; Integer isAsInteger = Integer.parseInt(id); Boolean isDecoySequence = peptideEvidence.isIsDecoy(); String proteinAccession = peptideEvidence.getDBSequenceRef(); Integer startIndex = peptideEvidence.getStart(); Integer endIndex = peptideEvidence.getEnd(); String preAminoAcid = peptideEvidence.getPre(); String postAminoAcid = peptideEvidence.getPost(); String peptideSequence = peptideEvidence.getPeptideRef(); MzIdPeptideEvidence mzIdPeptideEvidence = new MzIdPeptideEvidence(isAsInteger, proteinAccession, peptideSequence, isDecoySequence, startIndex, endIndex, preAminoAcid, postAminoAcid); mzIdPeptideEvidenceCollection.addPeptideEvidence(mzIdPeptideEvidence); } return mzIdPeptideEvidenceCollection; } /** * Removes MzIdProteinPeptide entries that do not pass the threshold * * @param mzIdProteinPeptideCollection collection of MzIdProteinPeptide objects. * @return returns the filtered MzIdProteinPeptideCollection. */ private MzIdProteinPeptideCollection removeLowThresholdSequences(MzIdProteinPeptideCollection mzIdProteinPeptideCollection) { System.out.println("Removing low threshold and decoy sequences..."); MzIdProteinPeptideCollection filteredMzIdProteinPeptideCollection = new MzIdProteinPeptideCollection(); for (MzIdProteinPeptide proteinPeptide: mzIdProteinPeptideCollection.getProteinPeptideList()) { //Remove low threshold and decoy if (proteinPeptide.isPassThreshold()) { filteredMzIdProteinPeptideCollection.addProteinPeptide(proteinPeptide); } } return filteredMzIdProteinPeptideCollection; } /** * Removes MzIdProteinPeptide entries that qualify as a decoy sequence. * * @param mzIdProteinPeptideCollection collection of MzIdProteinPeptide objects. * @return returns the filtered MzIdProteinPeptideCollection. */ private MzIdProteinPeptideCollection removeDecoySequences(MzIdProteinPeptideCollection mzIdProteinPeptideCollection) { System.out.println("Removing low threshold and decoy sequences..."); MzIdProteinPeptideCollection filteredMzIdProteinPeptideCollection = new MzIdProteinPeptideCollection(); for (MzIdProteinPeptide proteinPeptide: mzIdProteinPeptideCollection.getProteinPeptideList()) { //Remove low threshold and decoy if (!proteinPeptide.isDecoySequence()) { filteredMzIdProteinPeptideCollection.addProteinPeptide(proteinPeptide); } } return filteredMzIdProteinPeptideCollection; } }
UTF-8
Java
61,875
java
MzIdFileReader.java
Java
[ { "context": "/*\r\n * @author Vikthor Nijenhuis\r\n * @project PeptideItem mzIdentML Identfication ", "end": 32, "score": 0.9998657703399658, "start": 15, "tag": "NAME", "value": "Vikthor Nijenhuis" }, { "context": "he .mzid extension and xml layout.\r\n *\r\n * @author vnijenhuis\r\n */\r\npublic class MzIdFileReader implements Callab", "end": 5070, "score": 0.8998355269432068, "start": 5060, "tag": "USERNAME", "value": "vnijenhuis" } ]
null
[]
/* * @author <NAME> * @project PeptideItem mzIdentML Identfication Module * */ package nl.eriba.mzidentml.identification.filereader; import nl.eriba.mzidentml.identification.collections.mzid.MzIdProteinPeptideCollection; import nl.eriba.mzidentml.identification.collections.output.DatabaseSearchPsmOutputCollection; import nl.eriba.mzidentml.identification.collections.mzid.MzIdDatabaseSequenceCollection; import nl.eriba.mzidentml.identification.collections.output.ScanIdOutputCollection; import nl.eriba.mzidentml.identification.collections.mzid.MzIdPeptideCollection; import nl.eriba.mzidentml.identification.collections.output.PeptideOutputCollection; import nl.eriba.mzidentml.identification.collections.mzid.MzIdPeptideEvidenceCollection; import nl.eriba.mzidentml.identification.collections.mzid.MzIdProteinDetectionHypothesisCollection; import nl.eriba.mzidentml.identification.collections.output.ProteinPeptideOutputCollection; import nl.eriba.mzidentml.identification.collections.mzid.MzIdMainElementCollection; import nl.eriba.mzidentml.identification.collections.general.CombinedPeptideEntryCollection; import nl.eriba.mzidentml.identification.dataprocessing.sorting.SortSpectrumResultBySequence; import nl.eriba.mzidentml.identification.dataprocessing.sorting.SortPeptideEvidenceCollectionOnSequence; import nl.eriba.mzidentml.identification.dataprocessing.spectra.MzIdUnmarshaller; import nl.eriba.mzidentml.identification.dataprocessing.spectra.SingleSpectrumDataCollector; import nl.eriba.mzidentml.identification.objects.output.DatabaseSearchPsmOutput; import nl.eriba.mzidentml.identification.objects.mzid.MzIdCvParam; import nl.eriba.mzidentml.identification.objects.mzid.MzIdDatabaseSequence; import nl.eriba.mzidentml.identification.objects.mzid.MzIdModification; import nl.eriba.mzidentml.identification.objects.mzid.MzIdPeptide; import nl.eriba.mzidentml.identification.objects.mzid.MzIdPeptideEvidence; import nl.eriba.mzidentml.identification.objects.mzid.MzIdProteinDetectionHypothesis; import nl.eriba.mzidentml.identification.objects.mzid.MzIdSubstituteModification; import nl.eriba.mzidentml.identification.objects.output.PeptideOutput; import nl.eriba.mzidentml.identification.objects.output.ProteinPeptideOutput; import nl.eriba.mzidentml.identification.objects.output.ScanIdOutput; import nl.eriba.mzidentml.identification.objects.general.MatchedIonSeries; import nl.eriba.mzidentml.identification.objects.general.ProteinPeptideEntry; import nl.eriba.mzidentml.identification.objects.mzid.MzIdIonFragment; import nl.eriba.mzidentml.identification.objects.general.PeptideEntry; import nl.eriba.mzidentml.identification.objects.general.BestSpectrumEntry; import nl.eriba.mzidentml.identification.objects.general.SpectrumIdentificationItemEntry; import nl.eriba.mzidentml.identification.objects.general.SpectrumIdentificationResultEntry; import nl.eriba.mzidentml.identification.collections.general.CombinedDatabaseReferenceCollection; import nl.eriba.mzidentml.identification.collections.general.SingleDatabaseReferenceCollection; import nl.eriba.mzidentml.identification.objects.general.SingleDatabaseReference; import nl.eriba.mzidentml.identification.objects.general.CombinedPeptideEntry; import nl.eriba.mzidentml.tools.CalculationTools; import uk.ac.ebi.jmzidml.model.mzidml.PeptideEvidence; import uk.ac.ebi.jmzidml.model.mzidml.SpectrumIdentificationItem; import uk.ac.ebi.jmzidml.model.mzidml.SpectrumIdentificationList; import uk.ac.ebi.jmzidml.model.mzidml.SpectrumIdentificationResult; import uk.ac.ebi.jmzidml.model.mzidml.CvParam; import uk.ac.ebi.jmzidml.model.mzidml.DBSequence; import uk.ac.ebi.jmzidml.model.mzidml.Modification; import uk.ac.ebi.jmzidml.model.mzidml.Peptide; import uk.ac.ebi.jmzidml.model.mzidml.PeptideHypothesis; import uk.ac.ebi.jmzidml.model.mzidml.ProteinAmbiguityGroup; import uk.ac.ebi.jmzidml.model.mzidml.ProteinDetectionHypothesis; import uk.ac.ebi.jmzidml.model.mzidml.ProteinDetectionList; import uk.ac.ebi.jmzidml.model.mzidml.SequenceCollection; import uk.ac.ebi.jmzidml.model.mzidml.SpectrumIdentificationItemRef; import uk.ac.ebi.jmzidml.model.mzidml.SubstitutionModification; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Objects; import nl.eriba.mzidentml.identification.collections.general.MatchedIonSeriesCollection; import nl.eriba.mzidentml.identification.dataprocessing.spectra.CombineDatabaseReferenceInformation; import nl.eriba.mzidentml.identification.objects.mzid.MzIdProteinPeptide; import uk.ac.ebi.jmzidml.model.mzidml.FragmentArray; import uk.ac.ebi.jmzidml.model.mzidml.IonType; /** * Reads files with the .mzid extension and xml layout. * * @author vnijenhuis */ public class MzIdFileReader implements Callable { /** * Collection of ScanID objects. */ private final ScanIdOutputCollection scanCollection; /** * Current index of the dataset list. */ private final Integer currentIndex; /** * Total index of the dataset list. */ private final Integer maximumIndex; /** * Object that contains SpectrumIdentificationResult parameter data from the mzid file. */ private final SpectrumIdentificationResult spectrumResultItem; /** * Collection of MzIdPeptide objects. */ private final MzIdPeptideCollection peptideCollection; /** * List of file numbers that were entered to create output files. */ private final ArrayList<Integer> numbers; /** * Map of spectra counts of each peptide sequence. */ private final HashMap<String, Integer> spectrumCountMap; /** * Collection of MzIdProteinDetectionHypothesis objects. */ private final MzIdProteinPeptideCollection proteinPeptideCollection; /** * Intensity threshold used to filter low intensity peaks. */ private final Double intensityThreshold; /** * Map of sequences and the corresponding higest scoring sequence. */ private final ArrayList<BestSpectrumEntry> bestSpectrumList; /** * Collection of CombinedPeptideEntry objects. */ private final CombinedPeptideEntryCollection combinedPeptideEntryCollection; /** * Contains a set of tools designed for calculation purposes. */ private CalculationTools toolSet; /** * SpectrumIdentificationItem parameter from the mzid file. */ private final SpectrumIdentificationItem spectrumIdItem; /** * mzid format file reader. * * @param spectrumResultItem SpectrumIdentificationResult parameter from the mzid file. * @param spectrumIdItem SpectrumIdentificationItem parameter from the mzid file. * @param peptideCollection collection of MzIdPeptid objects. * @param combinedProteinPeptideCollection collection of MzIdCombinedProteinPeptide objects. * @param collection ScanIdCollection to store ScanID objects. * @param combinedPeptideEntryCollection collection of CombinedPeptideEntry objects. * @param spectraCountMap HashMap containing the amount of spectra per peptide sequence. * @param inputNumbers input numbers that determin which data should be processed. * @param bestSpectrumList list with the highest spectrum score per peptide sequence. * @param maximumIndex maximum index of the dataset list. * @param currentIndex current index of the dataset list. * @param intensityThreshold standard or user specified intensity threshold value. */ public MzIdFileReader(final SpectrumIdentificationResult spectrumResultItem, final SpectrumIdentificationItem spectrumIdItem, final MzIdPeptideCollection peptideCollection, MzIdProteinPeptideCollection combinedProteinPeptideCollection, final ScanIdOutputCollection collection, final CombinedPeptideEntryCollection combinedPeptideEntryCollection, final HashMap<String, Integer> spectraCountMap, ArrayList<BestSpectrumEntry> bestSpectrumList, final ArrayList<Integer> inputNumbers, final Integer currentIndex, final Integer maximumIndex, Double intensityThreshold) { this.spectrumIdItem = spectrumIdItem; this.spectrumResultItem = spectrumResultItem; this.peptideCollection = peptideCollection; this.scanCollection = collection; this.spectrumCountMap = spectraCountMap; this.currentIndex = currentIndex; this.maximumIndex = maximumIndex; this.numbers = inputNumbers; this.proteinPeptideCollection = combinedProteinPeptideCollection; this.combinedPeptideEntryCollection = combinedPeptideEntryCollection; this.intensityThreshold = intensityThreshold; this.bestSpectrumList = bestSpectrumList; } /** * Collects mzid data by storing the data into a collection of ScanID objects. * * @param mzidFile file to read the data from. * @param inputNumbers input numbers that determin which data should be processed. * @param scanIdEntryCollection collection of ScanIdEntry objets. * @param currentIndex current index of the dataset list. * @param totalIndex total index of the dataset index. * @param threads amount of threads used for the program. * @param intensityThreshold standard or user specified intensity threshold value. * @return returns a collection of ScanID objects. * @throws InterruptedException process was interrupted by another process. * @throws ExecutionException an error was encountered which prevents the execution. */ public ArrayList<Object> collectPeptideShakerScanIDs(final String mzidFile,ScanIdOutputCollection scanIdEntryCollection, final ArrayList<Integer> inputNumbers, final Integer currentIndex, final Integer totalIndex, final Integer threads, final Double intensityThreshold) throws InterruptedException, ExecutionException { System.out.println("Reading " + mzidFile); MzIdUnmarshaller unmarshalMzIdFile = new MzIdUnmarshaller(); MzIdMainElementCollection unmarshalCollection = unmarshalMzIdFile.unmarshalMzIdFile(mzidFile); //Unmarshaller that transforms storage data format to a memory format DatabaseSearchPsmOutputCollection searchPsmEntryCollection = new DatabaseSearchPsmOutputCollection(); ProteinPeptideOutputCollection proteinPeptideEntryCollection = new ProteinPeptideOutputCollection(); PeptideOutputCollection peptideOutputCollection = new PeptideOutputCollection(); MatchedIonSeriesCollection matchedIonSeriesCollection = new MatchedIonSeriesCollection(); //Get spectrum identification data SpectrumIdentificationList spectrumIdList = unmarshalCollection.getSpectrumIdentificationList(); //Remove low threshold entries. ArrayList<BestSpectrumEntry> generateBestSpectrumList = generateBestSpectrumList(spectrumIdList); //Get sequence data SequenceCollection sequenceCollection = unmarshalCollection.getSequenceCollection(); //Get peptide data MzIdPeptideCollection peptides = createPeptideCollection(sequenceCollection.getPeptide()); //Get peptide evidence data List<PeptideEvidence> peptideEvidenceList = sequenceCollection.getPeptideEvidence(); MzIdPeptideEvidenceCollection evidenceCollection = createPeptideEvidenceCollection(peptideEvidenceList); //Group data of database sequence objects into different collections MzIdDatabaseSequenceCollection dbSequenceCollection = createDatabaseSequenceCollection(sequenceCollection.getDBSequence()); //Create SingleDatabaseReference objects that are used to create the CombinedPeptidEntry and CombinedDatabaseReference collections. SingleDatabaseReferenceCollection singleDatabaseReferenceCollection = createSingleDatabaseReferenceCollection(peptideEvidenceList, peptides); CombinedPeptideEntryCollection combinedPeptides = createCombinedPeptideCollection(singleDatabaseReferenceCollection); //Combined SingleDatabaseReference objects to represent all unique protein hits per peptide sequence. CombineDatabaseReferenceInformation combineInformation = new CombineDatabaseReferenceInformation(null, null); CombinedDatabaseReferenceCollection combinedDatabaseReferenceCollection = combineInformation.combineDatabaseReferenceData(singleDatabaseReferenceCollection, dbSequenceCollection, combinedPeptides, threads); //Create map with spectra counts per sequence HashMap<String, Integer> spectraCountMap = determineSpectraCounts(peptideEvidenceList); //Get protein hypothesis data ProteinDetectionList proteinHypothesisList = unmarshalCollection.getProteinHypothesisCollection(); MzIdProteinDetectionHypothesisCollection proteinHypothesisCollection = createProteinHypothesisCollection(proteinHypothesisList); MzIdProteinPeptideCollection mzidProteinPeptideCollection = combineProteinHypothesisWithPeptideEvidence(evidenceCollection, proteinHypothesisCollection); //Remove hits that didn't pass the initial threshold and hits that are tagged as a decoy sequence. mzidProteinPeptideCollection = removeLowThresholdSequences(mzidProteinPeptideCollection); mzidProteinPeptideCollection = removeDecoySequences(mzidProteinPeptideCollection); mzidProteinPeptideCollection.sortOnPeptideSequence(); //Filter evidence collection based on evidences present in protein hypotheses Collections.sort(spectrumIdList.getSpectrumIdentificationResult(), new SortSpectrumResultBySequence()); ExecutorService executor = Executors.newFixedThreadPool(threads); Integer count = 0; System.out.println("Starting identification of spectrum results."); for (SpectrumIdentificationResult spectrumIdResult : spectrumIdList.getSpectrumIdentificationResult()) { count++; for (SpectrumIdentificationItem spectrumIdentificationItem: spectrumIdResult.getSpectrumIdentificationItem()) { //Test if the initial threshold is passed. if (spectrumIdentificationItem.isPassThreshold()) { Callable<ArrayList<Object>> callable = new MzIdFileReader(spectrumIdResult, spectrumIdentificationItem, peptides, mzidProteinPeptideCollection, scanIdEntryCollection, combinedPeptides, spectraCountMap, generateBestSpectrumList, inputNumbers, currentIndex, totalIndex, intensityThreshold); //Collects the output from the call function Future<ArrayList<Object>> future = executor.submit(callable); scanIdEntryCollection = (ScanIdOutputCollection) future.get().get(0); for (Integer number : numbers) { //Add data to respective collection if number is present. if (number != null) { switch (number) { case 1: //Gathers DatabaseSearchPsm objects to define peptide spectrum match data. DatabaseSearchPsmOutputCollection psmObjects = (DatabaseSearchPsmOutputCollection) future.get().get(1); for (DatabaseSearchPsmOutput object : psmObjects.getDatabaseSearchPsmEntryList()) { searchPsmEntryCollection.addDatabaseSearchPsmEntry(object); } break; case 2: //Gathers PeptideOutput objects to define peptide data. PeptideOutputCollection peptideObjects = (PeptideOutputCollection) future.get().get(2); for (PeptideOutput object : peptideObjects.getPeptideEntryList()) { peptideOutputCollection.addPeptideEntry(object); } //Gathers MatchedIonSeries objects to define the ion series and quality of the best spectrum matches. MatchedIonSeriesCollection matchedIonSeries = (MatchedIonSeriesCollection) future.get().get(3); for (MatchedIonSeries ionSeries: matchedIonSeries.getMatchedIonSeriesList()) { matchedIonSeriesCollection.addMatchedIonSeries(ionSeries); } break; case 3: //Gathers ProteinPeptideOutput objects to define protein-peptide data. ProteinPeptideOutputCollection proteinPeptideObjects = (ProteinPeptideOutputCollection) future.get().get(4); mzidProteinPeptideCollection = (MzIdProteinPeptideCollection) future.get().get(5); for (ProteinPeptideOutput object : proteinPeptideObjects.getProteinPeptideEntryList()) { proteinPeptideEntryCollection.addProteinPeptideEntry(object); } break; default: break; } } } } } if (count % 2000 == 0) { System.out.println("Matched data for " + count + " entries."); } } System.out.println("Matched data for " + count + " entries."); //Sort collections System.out.println("Sorting collections..."); searchPsmEntryCollection.sortOnPeptideScore(); proteinPeptideEntryCollection.sortOnProteinGroup(); peptideOutputCollection.sortOnPeptideScore(); combinedDatabaseReferenceCollection.sortOnAccession(); //Add collections to list. ArrayList<Object> collections = new ArrayList<>(); collections.add(scanIdEntryCollection); collections.add(searchPsmEntryCollection); collections.add(peptideOutputCollection); collections.add(matchedIonSeriesCollection); collections.add(proteinPeptideEntryCollection); collections.add(proteinHypothesisCollection); collections.add(combinedDatabaseReferenceCollection); //Shutdown executor to remove the created threadpool. executor.shutdown(); return collections; } /** * Call function that is used by a thread to process SpectrumIdentificationResult objects. * * @return return ScanIdCollection with added/updated ScanID object. * @throws java.lang.InterruptedException process was interrupted. * @throws java.util.concurrent.ExecutionException any exception encountered during execution. */ @Override public Object call() throws InterruptedException, ExecutionException { //Call class that can gather data from single spectra. SingleSpectrumDataCollector collector = new SingleSpectrumDataCollector(); //Gather data from SpectrumIdentificationItem. SpectrumIdentificationItemEntry spectrumItemData = collector.getSpectrumIdentificationItemData(spectrumResultItem, spectrumIdItem); String sequence = spectrumItemData.getPeptideSequence(); String score = spectrumItemData.getPsmScore(); Double peptideScore = Double.parseDouble(score); Double calculatedMassToCharge = spectrumItemData.getCalculatedMassToCharge(); Double experimentalMassToCharge = spectrumItemData.getExperimentalMassToCharge(); Double theoreticalMassToCharge = spectrumItemData.getTheoreticalMassToCharge(); Integer length = spectrumItemData.getSequenceLength(); //Gather data from SpectrumIdentificationResult item. SpectrumIdentificationResultEntry resultItemData = collector.getSpectrumIdentificationResultData(spectrumResultItem); // Integer index = resultItemData.getIndex(); String retentionTime = resultItemData.getRetentionTime(); String scanNumber = resultItemData.getScanNumber(); String scanId = resultItemData.getScanId(); // String scanID = resultItemData.getScanID(); Double partsPerMillion = ((calculatedMassToCharge - experimentalMassToCharge) / calculatedMassToCharge) * 1000000; toolSet = new CalculationTools(); partsPerMillion = toolSet.roundDouble(partsPerMillion, 2); //Gther data from Peptide item. PeptideEntry peptideData = collector.getPeptideCollectionData(peptideCollection, sequence); String aScore = peptideData.getAScore(); String modifiedSequence = peptideData.getModifiedSequence(); String postTranslationalModification = peptideData.getPostTranslationalModification(); //Create lists for each object. ArrayList<Object> collectionList = new ArrayList<>(); ProteinPeptideOutputCollection proteinPeptideList = new ProteinPeptideOutputCollection(); DatabaseSearchPsmOutputCollection databaseSearchPsmList = new DatabaseSearchPsmOutputCollection(); PeptideOutputCollection peptideOutputCollection = new PeptideOutputCollection(); MatchedIonSeriesCollection matchedIonSeriesCollection = new MatchedIonSeriesCollection(); //Adds ScanID entry to the scanCollection if (numbers.contains(1)) { addEntryToScanCollection(scanId, sequence, peptideScore); } //If one of the file numbers corresponds to ProteinPeptideEntry proteinPeptideData = matchProteinPeptideData(sequence); String accessions = proteinPeptideData.getAccessions(); String unique = proteinPeptideData.getUniqueness(); //Match sequence to protein peptide data. Integer spectraCount = spectrumCountMap.get(sequence); if (numbers.contains(2)) { DatabaseSearchPsmOutput dbsObject = new DatabaseSearchPsmOutput(modifiedSequence, peptideScore, theoreticalMassToCharge, length, partsPerMillion, calculatedMassToCharge, retentionTime, scanNumber, accessions, postTranslationalModification, aScore, spectraCount); databaseSearchPsmList.addDatabaseSearchPsmEntry(dbsObject); } Double highestScore = 0.0; for (BestSpectrumEntry spectrum : bestSpectrumList) { if (spectrum.getSequence().equals(sequence) && !spectrum.getFlag()) { highestScore = spectrum.getScore(); spectrum.setFlag(true); break; } } if (numbers.contains(3)) { if (Objects.equals(peptideScore, highestScore)) { MatchedIonSeries matchedIonSeries = createFragmentIndexList(spectrumResultItem, spectrumIdItem, intensityThreshold, sequence, peptideScore, accessions); matchedIonSeriesCollection.getMatchedIonSeriesList().add(matchedIonSeries); // 0 not complete coverage of sequence, 1 = y-ion coverage, 2 = b-ion coverage 3 = combined ion coverage PeptideOutput peptideObject = new PeptideOutput(modifiedSequence, peptideScore, theoreticalMassToCharge, length, partsPerMillion, calculatedMassToCharge, retentionTime, scanNumber, accessions, spectraCount, postTranslationalModification, aScore); peptideOutputCollection.addPeptideEntry(peptideObject); } } if (numbers.contains(4)) { if (Objects.equals(peptideScore, highestScore)) { ArrayList<MzIdProteinPeptide> removeableEvidence = new ArrayList<>(); Boolean allowMismatch = false; for (MzIdProteinPeptide proteinPeptide: proteinPeptideCollection.getProteinPeptideList()) { if (proteinPeptide.getPeptideSequence().equals(sequence)) { removeableEvidence.add(proteinPeptide); Integer start = proteinPeptide.getStartIndex(); Integer end = proteinPeptide.getEndIndex(); String pre = proteinPeptide.getPreAminoAcid(); String post = proteinPeptide.getPostAminoAcid(); Integer proteinGroup = proteinPeptide.getProteinGroup(); String proteinId = proteinPeptide.getProteinId(); String finalSequence = ""; if (finalSequence.isEmpty()) { if (!pre.matches("[A-Z]")) { finalSequence = modifiedSequence + "." + post; } else if (!post.matches("[A-Z]")) { finalSequence = pre + "." + modifiedSequence; } else { finalSequence = pre + "." + modifiedSequence + "." + post; } } String accession = proteinPeptide.getProteinAccession(); ProteinPeptideOutput proteinPeptideObject = new ProteinPeptideOutput(proteinGroup, proteinId, accession, finalSequence, unique, peptideScore, theoreticalMassToCharge, calculatedMassToCharge, length, partsPerMillion, retentionTime, scanNumber, spectraCount, start, end, postTranslationalModification, aScore); proteinPeptideList.addProteinPeptideEntry(proteinPeptideObject); allowMismatch = true; } else if (allowMismatch) { break; } } for (MzIdProteinPeptide entry: removeableEvidence) { proteinPeptideCollection.removeProteinPeptide(entry); } } } collectionList.add(scanCollection); collectionList.add(databaseSearchPsmList); collectionList.add(peptideOutputCollection); collectionList.add(matchedIonSeriesCollection); collectionList.add(proteinPeptideList); collectionList.add(proteinPeptideCollection); return collectionList; } /** * Creates a collection of MzIdDatabaseSequence objects. * * @param dbSequenceList list of DatabaseSequence objects. * @return collection of MzIdDatabaseSequence objects. */ private MzIdDatabaseSequenceCollection createDatabaseSequenceCollection(final List<DBSequence> dbSequenceList) { System.out.println("Creating MzIdDatabaseSequence object collection..."); MzIdDatabaseSequenceCollection databaseSequenceCollection = new MzIdDatabaseSequenceCollection(); for (int index = 0; index < dbSequenceList.size() - 1; index++) { DBSequence databaseSequence = dbSequenceList.get(index); String id = databaseSequence.getId(); String proteinAccession = databaseSequence.getAccession(); String databaseReference = databaseSequence.getSearchDatabaseRef(); String description = ""; String reversedDescription = ""; String paramValue = databaseSequence.getCvParam().get(0).getValue(); if (paramValue != null) { description = paramValue; } index++; DBSequence reveresedDatabaseSequence = dbSequenceList.get(index); String reversedProteinAccession = reveresedDatabaseSequence.getAccession(); paramValue = databaseSequence.getCvParam().get(0).getValue(); if (paramValue != null) { reversedDescription = paramValue; } description = description.replaceAll(",", "."); reversedDescription = reversedDescription.replaceAll(",", "."); MzIdDatabaseSequence mzidDatabaseSequence = new MzIdDatabaseSequence(id, proteinAccession, reversedProteinAccession, databaseReference, description, reversedDescription); databaseSequenceCollection.addDatabaseSequence(mzidDatabaseSequence); } return databaseSequenceCollection; } /** * Creates a SingleDatabaseReferenceCollection containing data of single entry hits. * * @param peptideEvidenceList list of PeptideEvidence objects. * @param peptideCollection list of MzIdPeptide objects. * @return collection of SingleDatabaseReference objects. */ private SingleDatabaseReferenceCollection createSingleDatabaseReferenceCollection(final List<PeptideEvidence> peptideEvidenceList, final MzIdPeptideCollection peptideCollection) { System.out.println("Creating SequenceDatabaseReference object collection..."); SingleDatabaseReferenceCollection sequenceDatabaseReferenceCollection = new SingleDatabaseReferenceCollection(); Collections.sort(peptideEvidenceList, new SortPeptideEvidenceCollectionOnSequence()); peptideCollection.sortOnPeptideSequence(); for (PeptideEvidence peptideEvidence : peptideEvidenceList) { if (!peptideEvidence.isIsDecoy()) { ArrayList<MzIdPeptide> removeablePeptideEntries = new ArrayList<>(); String proteinAccession = peptideEvidence.getDBSequenceRef(); Integer start = peptideEvidence.getStart(); Integer end = peptideEvidence.getEnd(); String peptideSequence = peptideEvidence.getPeptideRef(); String pre = peptideEvidence.getPre(); String post = peptideEvidence.getPost(); String id = peptideEvidence.getId().split("_")[1]; Integer evidenceId = Integer.parseInt(id); MzIdPeptide newEntry = null; ArrayList<String> modifications = new ArrayList<>(); for (MzIdPeptide entry: peptideCollection.getPeptides()) { if (entry.getModifications().isEmpty() && entry.getSubstituteModifications().isEmpty()) { removeablePeptideEntries.add(entry); } else if (entry.getPeptideSequence().equals(peptideSequence)) { newEntry = entry; for (MzIdModification modification: entry.getModifications()) { for (String name: modification.getNames()) { if (!modifications.contains(name)) { modifications.add(name); } } } } } removeablePeptideEntries.add(newEntry); for (MzIdPeptide x: removeablePeptideEntries) { peptideCollection.getPeptides().remove(x); } SingleDatabaseReference sequenceDatabaseReference = new SingleDatabaseReference(proteinAccession, evidenceId, peptideSequence, start, end, pre, post, modifications); sequenceDatabaseReferenceCollection.addDatabaseReference(sequenceDatabaseReference); } } return sequenceDatabaseReferenceCollection; } /** * Creates a collection of CombinedPeptideEntry objects. * * @param singleDatabaseReferenceCollection collection of SingleDatabaseReference objects. * @return collection of CombinedPeptideEntry objects. */ private CombinedPeptideEntryCollection createCombinedPeptideCollection(final SingleDatabaseReferenceCollection singleDatabaseReferenceCollection) { System.out.println("Creating list for peptide data objects."); //Determine if a sequence is unique to one accession. CombinedPeptideEntryCollection combinedPeptideCollection = new CombinedPeptideEntryCollection(); //Sort collections on sequence. This causes UniquePeptideEntry list to be sorted on sequence as well. singleDatabaseReferenceCollection.sortOnPeptideSequence(); //Get first entry sequence. ArrayList<String> accessionList = new ArrayList<>(); String targetSequence = singleDatabaseReferenceCollection.getDatabaseSequenceReferenceList().get(0).getPeptideSequence(); for (SingleDatabaseReference databaseReference: singleDatabaseReferenceCollection.getDatabaseSequenceReferenceList()) { //Check if current sequence matches the targetSequence and add accession to given sequence. if (databaseReference.getPeptideSequence().equals(targetSequence)) { //if accession is not present add it to the list. Duplicate accessions are not necessary. if (!accessionList.contains(databaseReference.getProteinAccession())) { accessionList.add(databaseReference.getProteinAccession()); } if (!accessionList.contains(databaseReference.getProteinAccession())) { accessionList.add(databaseReference.getProteinAccession()); } } else { //UniquePeptideAccessionCount object is created that contains the target sequence and the list of accession ids. Collections.sort(accessionList); CombinedPeptideEntry combinedPeptide = new CombinedPeptideEntry(targetSequence, accessionList); combinedPeptideCollection.addCombinedPeptideEntry(combinedPeptide); accessionList = new ArrayList<>(); accessionList.add(databaseReference.getProteinAccession()); targetSequence = databaseReference.getPeptideSequence(); } } return combinedPeptideCollection; } /** * Determines the spectra count per peptide sequence by coutning the peptide evidences per peptide sequence. * * @param peptideEvidenceList determines the amount of peptide spectra of each peptide sequence. * @return HashMap with peptide sequence as key and count as value. */ private HashMap<String, Integer> determineSpectraCounts(final List<PeptideEvidence> peptideEvidenceList) { System.out.println("Creating spectra count map..."); HashMap<String, Integer> spectraCountMap = new HashMap<>(); //Loops through list of PeptideEvidence objects. for (PeptideEvidence peptideEvidence : peptideEvidenceList) { String peptideRef = peptideEvidence.getPeptideRef(); if (!spectraCountMap.isEmpty() && spectraCountMap.containsKey(peptideRef)) { Integer spectraCount = spectraCountMap.get(peptideRef) + 1; spectraCountMap.put(peptideRef, spectraCount); } else { spectraCountMap.put(peptideRef, 1); } } return spectraCountMap; } /** * Creates a collection of MzIdPeptide objects. * * @param peptides list of PeptideItem objects. * @return collection of MzIdPeptide objects. */ private MzIdPeptideCollection createPeptideCollection(final List<Peptide> peptides) { System.out.println("Creating MzIdPeptide object collection..."); MzIdPeptideCollection newPeptideCollection = new MzIdPeptideCollection(); //Loops through list of all PeptideItem objects. for (Peptide peptide : peptides) { String id = peptide.getId(); String sequence = peptide.getPeptideSequence(); List<Modification> mods = peptide.getModification(); List<SubstitutionModification> subMods = peptide.getSubstitutionModification(); ArrayList<MzIdSubstituteModification> subModificationList = new ArrayList<>(); ArrayList<MzIdModification> modificationList = new ArrayList<>(); //Create list of Modification objects. for (Modification modification : mods) { Integer location = modification.getLocation(); ArrayList<String> nameList = new ArrayList<>(); for (CvParam param : modification.getCvParam()) { String name = param.getName(); nameList.add(name); } Double monoMassDelta = modification.getMonoisotopicMassDelta(); List<String> modResidues = modification.getResidues(); ArrayList<String> residueList = new ArrayList<>(); for (String residue : modResidues) { residueList.add(residue); } //Stores data in new Modification object. MzIdModification modificationObject = new MzIdModification(monoMassDelta, location, residueList, nameList); //Adds objects to the list. modificationList.add(modificationObject); } //Create list of SubstituteModification objects. for (SubstitutionModification subModification : subMods) { Double monoMassDelta = subModification.getMonoisotopicMassDelta(); Integer location = subModification.getLocation(); String originalResidue = subModification.getOriginalResidue(); String replacedResidue = subModification.getReplacementResidue(); //Stores data in new SubstituteModification object. MzIdSubstituteModification subModificationObject = new MzIdSubstituteModification(monoMassDelta, location, originalResidue, replacedResidue); //Adds objects to the list. subModificationList.add(subModificationObject); } //Stores data in new PeptideItem object. MzIdPeptide peptideObject = new MzIdPeptide(id, sequence, modificationList, subModificationList); //Adds objects to the MzIdPeptideCollection. newPeptideCollection.addPeptide(peptideObject); } return newPeptideCollection; } /** * Creates a collection of MzIdPeptideHypothesis objects. * * @param hypothesisList list of PeptideHypothesis parameters from the MzIdentML data. * @return list of MzIdPeptideHypothesis objects. */ private MzIdProteinDetectionHypothesisCollection createProteinHypothesisCollection(final ProteinDetectionList proteinHypothesisList) { System.out.println("Creating MzIdProteinDetectionHypothesis object collection..."); MzIdProteinDetectionHypothesisCollection proteinHypothesisCollection = new MzIdProteinDetectionHypothesisCollection(); //Loops throughe list of ProteinDetectionHypothesis objects. List<ProteinAmbiguityGroup> proteinAmbiguityGroup = proteinHypothesisList.getProteinAmbiguityGroup(); for (ProteinAmbiguityGroup ambiguity : proteinAmbiguityGroup) { String ambiguityId = ambiguity.getId(); String group = ambiguityId.split("_")[1]; Integer proteinGroup = Integer.parseInt(group); String score = ambiguity.getCvParam().get(0).getValue(); Double proteinscore = Double.parseDouble(score); for (ProteinDetectionHypothesis proteinHypothesis : ambiguity.getProteinDetectionHypothesis()) { String proteinId = proteinHypothesis.getId(); String dbSeqRef = proteinHypothesis.getDBSequenceRef(); Boolean passThreshold = proteinHypothesis.isPassThreshold(); Double sequenceCoverage = 0.0; List<CvParam> paramList = ambiguity.getCvParam(); for (CvParam parameter: paramList) { //Gets sequence coverage if available. if (parameter.getName().contains("coverage")) { sequenceCoverage = Double.parseDouble(parameter.getValue()); } } ArrayList<MzIdCvParam> mzIdParamList = new ArrayList<>(); //Creates list of cvParam objects. for (CvParam param : paramList) { String accession = param.getAccession(); String name = param.getName(); String value = param.getValue(); //Stores data in new cvParam object. MzIdCvParam mzIdCvParam = new MzIdCvParam(name, accession, value); mzIdParamList.add(mzIdCvParam); } //Creates list of PeptideHypothesis objects. for (PeptideHypothesis peptideHypothesis : proteinHypothesis.getPeptideHypothesis()) { String peptideEvidenceRef = peptideHypothesis.getPeptideEvidenceRef(); Integer peptideEvidenceId = Integer.parseInt(peptideEvidenceRef.split("_")[1]); List<SpectrumIdentificationItemRef> spectrumItemRefList = peptideHypothesis.getSpectrumIdentificationItemRef(); ArrayList<String> idReferenceList = new ArrayList<>(); //Creates a list of SpectrumReference objects. for (SpectrumIdentificationItemRef spectrumItemRef : spectrumItemRefList) { idReferenceList.add(spectrumItemRef.getSpectrumIdentificationItemRef()); } MzIdProteinDetectionHypothesis proteinDetectionHypothesis = new MzIdProteinDetectionHypothesis(passThreshold, proteinId, proteinGroup, dbSeqRef, peptideEvidenceId, proteinscore, sequenceCoverage, idReferenceList, mzIdParamList); proteinHypothesisCollection.addProteinDetectionHypothesis(proteinDetectionHypothesis); } } } //Sorts the ProteinDetectionList based on the PeptideEvidence id. proteinHypothesisCollection.sortOnPeptideEvidence(); return proteinHypothesisCollection; } /** * Creates and adds a ScanID object to the ScanIdCollection. * * @param scanID ID of the scan. * @param sequence peptide amino acid sequence. * @param psmScore peptide score (-10LogP). */ public final void addEntryToScanCollection(final String scanID, final String sequence, final Double psmScore) { ArrayList<String> sequences = new ArrayList(maximumIndex); ArrayList<Double> psmScores = new ArrayList(maximumIndex); ArrayList<String> databaseFlags = new ArrayList<>(maximumIndex); for (int i = 0; i <= maximumIndex; i++) { if (i == currentIndex) { sequences.add(sequence); psmScores.add(psmScore); databaseFlags.add(""); } else { sequences.add(""); psmScores.add(0.0); databaseFlags.add(""); } } Boolean newScanID = true; if (!scanCollection.getScanIdEntryList().isEmpty()) { //Loop through entries of the HashMap. if (currentIndex != 0) { for (ScanIdOutput object : scanCollection.getScanIdEntryList()) { //Check for duplicates. if (object.getScanId().equals(scanID)) { object.getPeptideSequenceList().set(currentIndex, sequence); object.getPsmScoreList().set(currentIndex, psmScore); newScanID = false; break; } } } } //Add a new entry to the collection. if (newScanID) { ScanIdOutput scanObject = new ScanIdOutput(scanID, sequences, psmScores, databaseFlags); scanCollection.addScanIdEntry(scanObject); } } /** * Gathers all accessions per peptide sequence and determines if the peptide is unique to a protein sequence. * * @param sequence peptide sequence. * @return EvidenceData with a list of accessions and uniqueness flag. */ public final ProteinPeptideEntry matchProteinPeptideData(final String sequence) { String accessions = ""; String unique = "N"; for (CombinedPeptideEntry peptide : combinedPeptideEntryCollection.getUniquePeptideList()) { if (peptide.getSequence().equals(sequence)) { if (peptide.getAccessionList().size() == 1) { unique = "Y"; } for (String accession : peptide.getAccessionList()) { if (accessions.isEmpty()) { accessions += accession; } else { accessions += ":" + accession; } } break; } } ProteinPeptideEntry matchedProteinPeptide = new ProteinPeptideEntry(sequence, accessions, unique); return matchedProteinPeptide; } /** * Creates a list of peptide ion fragments and the covered ion indices. * * @param spectrumItemData contains SpectrumItemData. * @param sequence peptide sequence. * @return IndexItemData consisting of a list of ion fragment indices and the given ionSerieFlag. */ private MatchedIonSeries createFragmentIndexList(final SpectrumIdentificationResult spectrumIdentificationResult, final SpectrumIdentificationItem spectrumItem, Double userIntensityThreshold, final String peptideSequence, final Double peptideScore, final String accessions) { ArrayList<MzIdIonFragment> ionFragmentList = new ArrayList<>(); List<IonType> fragmentList = spectrumItem.getFragmentation().getIonType(); //Process all ion fragments of the given peptide amino acid sequence. for (IonType ionType : fragmentList) { List<Integer> indexList = ionType.getIndex(); ArrayList<Double> measuredMassToChargeValues = new ArrayList<>(); ArrayList<Boolean> passedIntensityThreshold = new ArrayList<>(); FragmentArray fragmentArray = ionType.getFragmentArray().get(0); //Gathers measured mass to charge values of each fragment array. for (float fragmentValue : fragmentArray.getValues()) { double measuredMassToCharge = fragmentValue; measuredMassToChargeValues.add(measuredMassToCharge); } //Set standard threshold to 5%. Double standardThreshold = 0.05; // Calculate the user defined intensity threshold value per peptide sequence. FragmentArray measureIntensity = ionType.getFragmentArray().get(1); if (userIntensityThreshold >= standardThreshold) { standardThreshold = userIntensityThreshold; } Double highestPeakIntensity = 0.0; //Test peakIntensity versus the specified threshold. for (Float intensityValue : measureIntensity.getValues()) { double intensity = intensityValue; Double peakIntensity = intensity * standardThreshold; if (peakIntensity > highestPeakIntensity) { highestPeakIntensity = peakIntensity; } } //Test if ion intensity passes the user specified threshold. for (Float intensityValue : measureIntensity.getValues()) { double intensity = intensityValue; if (intensity >= highestPeakIntensity) { passedIntensityThreshold.add(true); } else { passedIntensityThreshold.add(false); } } //Create MzIdIonFragment object containing the name, indices, m/z values and a true/false list for passing the intensity threshold. String name = ionType.getCvParam().getName(); MzIdIonFragment fragment = new MzIdIonFragment(name, indexList, measuredMassToChargeValues, passedIntensityThreshold); ionFragmentList.add(fragment); } Integer sequenceLength = peptideSequence.length(); ArrayList<Integer> bIonIndices = new ArrayList<>(sequenceLength); ArrayList<Integer> yIonIndices = new ArrayList<>(sequenceLength); ArrayList<Integer> combinedIonIndices = new ArrayList<>(sequenceLength); ArrayList<Integer> combinedAllIonIndices = new ArrayList<>(); ArrayList<Integer> finalIndexList = new ArrayList<>(); for (MzIdIonFragment ionFragment : ionFragmentList) { String name = ionFragment.getName(); List<Integer> indexList = ionFragment.getIndexList(); ArrayList<Boolean> intensityValues = ionFragment.getItensityValues(); //Removes hits with different index and intensity counts. (size should be the same to process data. if (intensityValues.size() == indexList.size()) { for (int i = 0; i < indexList.size(); i++) { Integer listIndex = indexList.get(i); Integer sequenceIndex = listIndex; if (intensityValues.get(i)) { if (name.matches("frag: y ion")) { if (!yIonIndices.contains(sequenceIndex)) { yIonIndices.add(sequenceIndex); } if (!combinedAllIonIndices.contains(sequenceIndex)) { combinedAllIonIndices.add(sequenceIndex); } } else if (name.matches("(frag: y ion -).*")) { if (!combinedIonIndices.contains(sequenceIndex)) { combinedIonIndices.add(sequenceIndex); } if (!combinedAllIonIndices.contains(sequenceIndex)) { combinedAllIonIndices.add(sequenceIndex); } } else if (name.matches("frag: b ion")) { sequenceIndex = sequenceLength - listIndex; if (!bIonIndices.contains(sequenceIndex)) { bIonIndices.add(sequenceIndex); } if (!combinedAllIonIndices.contains(sequenceIndex)) { combinedAllIonIndices.add(sequenceIndex); } } else if (name.matches("(frag: b ion -).*")) { if (!combinedIonIndices.contains(sequenceIndex)) { combinedIonIndices.add(sequenceIndex); } if (!combinedAllIonIndices.contains(sequenceIndex)) { combinedAllIonIndices.add(sequenceIndex); } } else if (name.contains("immonium")) { if (!combinedIonIndices.contains(sequenceIndex)) { combinedIonIndices.add(sequenceIndex); } if (!combinedAllIonIndices.contains(sequenceIndex)) { combinedAllIonIndices.add(sequenceIndex); } } } } } } //Flag 0 for incomplete ion serie, flag 1 for complete b ion serie, flag 2 for complete y ion serie, flag 3 for combined ion series (includes immonium) Integer ionSerieFlag = 0; sequenceLength--; if (sequenceLength == bIonIndices.size()) { ionSerieFlag = 1; finalIndexList = bIonIndices; } else if (sequenceLength == yIonIndices.size()) { ionSerieFlag = 2; finalIndexList = yIonIndices; } else if (sequenceLength == combinedIonIndices.size()) { ionSerieFlag = 3; finalIndexList = combinedIonIndices; } else if (sequenceLength == combinedAllIonIndices.size()) { ionSerieFlag = 4; finalIndexList = combinedAllIonIndices; } Collections.sort(finalIndexList); MatchedIonSeries ionSeries = new MatchedIonSeries(peptideSequence, peptideScore, accessions, combinedIonIndices, bIonIndices, yIonIndices, combinedAllIonIndices, finalIndexList, ionSerieFlag); return ionSeries; } /** * Generates a list of BestSpectrumEntry objects that define the highest scoring peptide spectrum per peptide sequence. * * @param spectrumIdList list of SpectrumIdentificationResult items. * @return returns a list containing BestSpectrumEntry objects. */ private ArrayList<BestSpectrumEntry> generateBestSpectrumList(SpectrumIdentificationList spectrumIdList) { System.out.println("Generating spectrum ID map"); ArrayList<BestSpectrumEntry> spectrumScoreList = new ArrayList<>(); for (SpectrumIdentificationResult spectrumIdResult : spectrumIdList.getSpectrumIdentificationResult()) { for (SpectrumIdentificationItem spectrumIdentificationItem : spectrumIdResult.getSpectrumIdentificationItem()) { Boolean isPassThreshold = spectrumIdentificationItem.isPassThreshold(); //If an item passes the threshol the call() function is executed by a thread from the threadpool Double psmScore = 0.0; if (isPassThreshold) { String peptideSequence = spectrumIdentificationItem.getPeptideRef(); Boolean newReference = true; List<CvParam> paramList = spectrumIdentificationItem.getCvParam(); for (CvParam param : paramList) { if (param.getName().contains("PSM score")) { psmScore = Double.parseDouble(param.getValue()); } } for (BestSpectrumEntry spectrum : spectrumScoreList) { if (spectrum.getSequence().equals(peptideSequence)) { if (spectrum.getScore() > psmScore) { spectrumScoreList.remove(spectrum); spectrum.setScore(psmScore); spectrum.setFlag(false); spectrumScoreList.add(spectrum); } break; } } //New peptide sequence and highest score. if (newReference) { BestSpectrumEntry spectrum = new BestSpectrumEntry(peptideSequence, psmScore, false); spectrumScoreList.add(spectrum); } } } } return spectrumScoreList; } /** * Combines data from MzIdProteinHypothesis with MzIdPeptideEvidence. * * @param mzIdPeptideEvidenceCollection collection of MzIdPeptideEvidence objects. * @param mzIdProteinHypothesisCollection collection of MzIdProteinHypothesis objects. * @return MzIdProteinPeptideCollection containing MzIdProteinPeptide objects. */ public final MzIdProteinPeptideCollection combineProteinHypothesisWithPeptideEvidence(MzIdPeptideEvidenceCollection mzIdPeptideEvidenceCollection, MzIdProteinDetectionHypothesisCollection mzIdProteinHypothesisCollection) { System.out.println("combining protein hypothesis data with peptide evidence data..."); MzIdProteinPeptideCollection mzidProteinPeptideCollection = new MzIdProteinPeptideCollection(); for (MzIdProteinDetectionHypothesis mzIdProteinDetectionHypothesis : mzIdProteinHypothesisCollection.getProteinDetectionHypothesisList()) { Integer id = mzIdProteinDetectionHypothesis.getPeptideEvidenceId(); Integer indexOfEvidenceId = id - 1; MzIdPeptideEvidence evidence = mzIdPeptideEvidenceCollection.getPeptideEvidenceItems().get(indexOfEvidenceId); String peptideSequence = evidence.getPeptideSequence(); Boolean isDecoySequence = evidence.isDecoySequence(); Boolean isPassThreshold = mzIdProteinDetectionHypothesis.isPassThreshold(); Integer endIndex = evidence.getEndIndex(); Integer startIndex = evidence.getStartIndex(); String preAminoAcid = evidence.getPreAminoAcid(); String postAminoAcid = evidence.getPostAminoAcid(); String proteinAccession = mzIdProteinDetectionHypothesis.getProteinAccession(); Integer proteinGroup = mzIdProteinDetectionHypothesis.getProteinGroup(); String proteinId = proteinGroup + "_" + mzIdProteinDetectionHypothesis.getProteinId().split("_")[2]; Double proteinGroupScore = mzIdProteinDetectionHypothesis.getProteinScore(); MzIdProteinPeptide proteinPeptide = new MzIdProteinPeptide(id, peptideSequence, proteinAccession, proteinGroup, proteinId, isDecoySequence, isPassThreshold, startIndex, endIndex, preAminoAcid, postAminoAcid, proteinGroupScore); mzidProteinPeptideCollection.addProteinPeptide(proteinPeptide); } return mzidProteinPeptideCollection; } /** * Creates a collection of MzIdPeptideEvidence objects using the PeptideEvidence list of the mzid file. * * @param peptideEvidenceList list of PeptideEvidence objects. * @return returns the MzIdPeptideEvidenceCollection. */ private MzIdPeptideEvidenceCollection createPeptideEvidenceCollection(List<PeptideEvidence> peptideEvidenceList) { System.out.println("Creating peptide evidence collection..."); MzIdPeptideEvidenceCollection mzIdPeptideEvidenceCollection = new MzIdPeptideEvidenceCollection(); for (PeptideEvidence peptideEvidence: peptideEvidenceList) { String id = peptideEvidence.getId().split("_")[1]; Integer isAsInteger = Integer.parseInt(id); Boolean isDecoySequence = peptideEvidence.isIsDecoy(); String proteinAccession = peptideEvidence.getDBSequenceRef(); Integer startIndex = peptideEvidence.getStart(); Integer endIndex = peptideEvidence.getEnd(); String preAminoAcid = peptideEvidence.getPre(); String postAminoAcid = peptideEvidence.getPost(); String peptideSequence = peptideEvidence.getPeptideRef(); MzIdPeptideEvidence mzIdPeptideEvidence = new MzIdPeptideEvidence(isAsInteger, proteinAccession, peptideSequence, isDecoySequence, startIndex, endIndex, preAminoAcid, postAminoAcid); mzIdPeptideEvidenceCollection.addPeptideEvidence(mzIdPeptideEvidence); } return mzIdPeptideEvidenceCollection; } /** * Removes MzIdProteinPeptide entries that do not pass the threshold * * @param mzIdProteinPeptideCollection collection of MzIdProteinPeptide objects. * @return returns the filtered MzIdProteinPeptideCollection. */ private MzIdProteinPeptideCollection removeLowThresholdSequences(MzIdProteinPeptideCollection mzIdProteinPeptideCollection) { System.out.println("Removing low threshold and decoy sequences..."); MzIdProteinPeptideCollection filteredMzIdProteinPeptideCollection = new MzIdProteinPeptideCollection(); for (MzIdProteinPeptide proteinPeptide: mzIdProteinPeptideCollection.getProteinPeptideList()) { //Remove low threshold and decoy if (proteinPeptide.isPassThreshold()) { filteredMzIdProteinPeptideCollection.addProteinPeptide(proteinPeptide); } } return filteredMzIdProteinPeptideCollection; } /** * Removes MzIdProteinPeptide entries that qualify as a decoy sequence. * * @param mzIdProteinPeptideCollection collection of MzIdProteinPeptide objects. * @return returns the filtered MzIdProteinPeptideCollection. */ private MzIdProteinPeptideCollection removeDecoySequences(MzIdProteinPeptideCollection mzIdProteinPeptideCollection) { System.out.println("Removing low threshold and decoy sequences..."); MzIdProteinPeptideCollection filteredMzIdProteinPeptideCollection = new MzIdProteinPeptideCollection(); for (MzIdProteinPeptide proteinPeptide: mzIdProteinPeptideCollection.getProteinPeptideList()) { //Remove low threshold and decoy if (!proteinPeptide.isDecoySequence()) { filteredMzIdProteinPeptideCollection.addProteinPeptide(proteinPeptide); } } return filteredMzIdProteinPeptideCollection; } }
61,864
0.661996
0.660768
1,025
58.365852
40.981731
332
false
false
0
0
0
0
0
0
0.657561
false
false
4
f8144aa8fe9c16c801d3c3d881fe7fadc932404f
773,094,164,977
9d534dc8296c1e8fe490c7067c24a6f63ab8c0aa
/PWoutput.java
acec3ab75ba768699ab05a712a8a407f9d18d1c5
[]
no_license
Anniebhalla10/Java-Codes
https://github.com/Anniebhalla10/Java-Codes
ebba24d227e47d8abb7cc205329a4c6932b6c6e9
aed9aea36e9f64571834313eed4f4e1b98f961a0
refs/heads/master
2021-01-06T14:07:30.857000
2020-03-24T14:05:26
2020-03-24T14:05:26
241,354,246
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * 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 Java; import java.io.*; /** * * @author Admin */ public class PWoutput { public static void main(String[] args) { PrintWriter obj = new PrintWriter(System.out, true); obj.println("This is a string"); int i=-3; obj.println(i); double d= 4.5e-7; obj.println(d); } }
UTF-8
Java
540
java
PWoutput.java
Java
[ { "context": "ge Java;\r\nimport java.io.*;\r\n\r\n/**\r\n *\r\n * @author Admin\r\n */\r\npublic class PWoutput {\r\n public static ", "end": 251, "score": 0.7158908843994141, "start": 246, "tag": "USERNAME", "value": "Admin" } ]
null
[]
/* * 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 Java; import java.io.*; /** * * @author Admin */ public class PWoutput { public static void main(String[] args) { PrintWriter obj = new PrintWriter(System.out, true); obj.println("This is a string"); int i=-3; obj.println(i); double d= 4.5e-7; obj.println(d); } }
540
0.596296
0.588889
22
22.545454
21.660032
79
false
false
0
0
0
0
0
0
0.545455
false
false
4
e72edb52d0c74e1b16df914e125c5eba0f4f7c5b
13,005,161,014,120
de5726cd066ae7673190d5485163a80d20fa87b6
/src/main/java/com/brewduck/web/recipe/dao/RecipeDaoImpl.java
97818adda3091249c711d29115e099892f166870
[]
no_license
freepow/brewduck-1
https://github.com/freepow/brewduck-1
8c55de41f2847e7dddd7d9bf6fc9939dcf806b98
0f92f9579a8ecaea7c077c2a5f9a85e0a674b6a5
refs/heads/master
2020-12-07T17:14:52.342000
2014-05-19T00:33:15
2014-05-19T00:33:15
19,988,840
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.brewduck.web.recipe.dao; import com.brewduck.web.domain.Recipe; import org.apache.ibatis.session.SqlSession; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; import java.util.List; /** * <pre> * 맥주 레시피 DAO 구현체. * </pre> * * @author jaeger * @version 1.0, 2014.02.20 */ @Repository("recipeDao") public class RecipeDaoImpl implements RecipeDao { private static final Logger logger = LoggerFactory.getLogger(RecipeDaoImpl.class); /** * Mybatis SQL Session Dependency Injection. */ @Autowired private SqlSession sqlSession; @Override public List<Recipe> selectRecipeList(Recipe recipe) { return sqlSession.selectList("Recipe.selectRecipeList", recipe); } @Override public Recipe selectRecipeDetail(Recipe recipe) { return sqlSession.selectOne("Recipe.selectRecipeDetail", recipe); } @Override public Integer insertRecipe(Recipe recipe) { return sqlSession.update("Recipe.insertRecipe", recipe); } @Override public Integer updateRecipe(Recipe recipe) { return sqlSession.update("Recipe.updateRecipe", recipe); } @Override public Integer deleteRecipe(Recipe recipe) { return sqlSession.update("Recipe.deleteRecipe", recipe); } }
UTF-8
Java
1,415
java
RecipeDaoImpl.java
Java
[ { "context": "* <pre>\n * 맥주 레시피 DAO 구현체.\n * </pre>\n *\n * @author jaeger\n * @version 1.0, 2014.02.20\n */\n@Repository(\"reci", "end": 380, "score": 0.9994996190071106, "start": 374, "tag": "USERNAME", "value": "jaeger" } ]
null
[]
package com.brewduck.web.recipe.dao; import com.brewduck.web.domain.Recipe; import org.apache.ibatis.session.SqlSession; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; import java.util.List; /** * <pre> * 맥주 레시피 DAO 구현체. * </pre> * * @author jaeger * @version 1.0, 2014.02.20 */ @Repository("recipeDao") public class RecipeDaoImpl implements RecipeDao { private static final Logger logger = LoggerFactory.getLogger(RecipeDaoImpl.class); /** * Mybatis SQL Session Dependency Injection. */ @Autowired private SqlSession sqlSession; @Override public List<Recipe> selectRecipeList(Recipe recipe) { return sqlSession.selectList("Recipe.selectRecipeList", recipe); } @Override public Recipe selectRecipeDetail(Recipe recipe) { return sqlSession.selectOne("Recipe.selectRecipeDetail", recipe); } @Override public Integer insertRecipe(Recipe recipe) { return sqlSession.update("Recipe.insertRecipe", recipe); } @Override public Integer updateRecipe(Recipe recipe) { return sqlSession.update("Recipe.updateRecipe", recipe); } @Override public Integer deleteRecipe(Recipe recipe) { return sqlSession.update("Recipe.deleteRecipe", recipe); } }
1,415
0.713367
0.704789
56
24
24.298737
86
false
false
0
0
0
0
0
0
0.375
false
false
4
a061896792f23bcb32bbd8d64e8c4813e2060b01
32,667,521,293,662
3cb1995df9d71aa12f67d73fc938470289e82191
/class design/Matrix.java
743ece02348b82033f6f15f7297de3a58e15d7dc
[ "MIT" ]
permissive
dinhnhat0401/OCP
https://github.com/dinhnhat0401/OCP
ef7f9424ed68e7b24b3ae0fd26815ade6f440bc0
abcd89192e7fbcefbb37c5e8e0c74dbb58be9355
refs/heads/master
2020-04-17T11:36:04.945000
2019-06-21T13:56:58
2019-06-21T14:03:41
166,546,846
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
//package world; public class Matrix { private int level = 1; class Deep { private int level = 2; class Deeper { private int level = 5; public void printReality() { System.out.print(level); System.out.print(" "+Matrix.Deep.this.level); System.out.print(" "+Deep.this.level); System.out.print(" " + Matrix.this.level); } } } public static void main(String[] bots) { Matrix.Deep.Deeper simulation = new Matrix().new Deep().new Deeper(); simulation.printReality(); } }
UTF-8
Java
586
java
Matrix.java
Java
[]
null
[]
//package world; public class Matrix { private int level = 1; class Deep { private int level = 2; class Deeper { private int level = 5; public void printReality() { System.out.print(level); System.out.print(" "+Matrix.Deep.this.level); System.out.print(" "+Deep.this.level); System.out.print(" " + Matrix.this.level); } } } public static void main(String[] bots) { Matrix.Deep.Deeper simulation = new Matrix().new Deep().new Deeper(); simulation.printReality(); } }
586
0.56314
0.55802
20
28.299999
19.601276
75
false
false
0
0
0
0
0
0
0.5
false
false
4
325d984e59cbee3d93951e5a1ca2ef3640e6153f
3,968,549,829,855
1fa996ace97bf1f560d3b3479dce7c4f7c815c89
/MyMVCFrameWork/src/com/hugeyurt/mvc/RequestDataHandler.java
0f94bf3626db13320fc1b89c7037ce54de1430a0
[]
no_license
Creator-Youth/mystudent
https://github.com/Creator-Youth/mystudent
f4d432649893f3f7f35f0d9dd017da8c86927a81
c52dd8937437edb9ae67b1885f57cddbbc3a3751
refs/heads/master
2023-08-04T08:42:06.072000
2020-02-06T09:05:54
2020-02-06T09:05:54
238,636,619
0
0
null
false
2023-07-23T04:47:06
2020-02-06T08:01:25
2020-02-06T09:09:48
2023-07-23T04:47:05
129,639
0
0
2
JavaScript
false
false
package com.hugeyurt.mvc; import java.lang.reflect.Field; import java.util.Enumeration; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class RequestDataHandler { public static Object[] handlerRequest(HttpServletRequest request, HttpServletResponse response, Class paramTypes[],String[] paramNames) { Object values[]=new Object[paramTypes.length]; for(int i=0;i<paramTypes.length;i++) { if(checkInterface(paramTypes[i],request.getClass().getInterfaces())) values[i]=request; else if(checkInterface(paramTypes[i],request.getSession().getClass().getInterfaces())) values[i]=request.getSession(); else if(checkInterface(paramTypes[i],response.getClass().getInterfaces())) values[i]=response; else if(paramTypes[i]==String.class) values[i]=(String) request.getParameter(paramNames[i]); else if(paramTypes[i]==Integer.class) values[i]=Integer.valueOf((String) request.getParameter(paramNames[i])); else if(paramTypes[i]==Double.class) values[i]=Double.valueOf((String) request.getParameter(paramNames[i])); else if(paramTypes[i]==Boolean.class) values[i]=Boolean.valueOf((String) request.getParameter(paramNames[i])); else { values[i]=toObject(paramTypes[i],request); } } return values; } private static boolean checkInterface(Class clz, Class interfaces[]) { if(clz==null||interfaces==null) return false; for(int i=0;i<interfaces.length;i++) if(clz==interfaces[i]) return true; return false; } private static Object toObject(Class clz, HttpServletRequest request) { Object object=null; Enumeration<String> names=request.getParameterNames(); try{ object=clz.newInstance(); while(names.hasMoreElements()) { String paramName=names.nextElement(); Field field=null; try{ field=clz.getDeclaredField(paramName); }catch(Exception e) { e.printStackTrace(); } if(field==null) continue; field.setAccessible(true); String value=(String)request.getParameter(paramName); if(field.getType()==Integer.class|| field.getType()==Integer.TYPE) field.set(object, Integer.parseInt(value)); else if(field.getType()==Double.class|| field.getType()==Double.TYPE) field.set(object, Double.parseDouble(value)); else field.set(object, value); } }catch(Exception e) { e.printStackTrace(); } return object; } }
UTF-8
Java
2,637
java
RequestDataHandler.java
Java
[]
null
[]
package com.hugeyurt.mvc; import java.lang.reflect.Field; import java.util.Enumeration; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class RequestDataHandler { public static Object[] handlerRequest(HttpServletRequest request, HttpServletResponse response, Class paramTypes[],String[] paramNames) { Object values[]=new Object[paramTypes.length]; for(int i=0;i<paramTypes.length;i++) { if(checkInterface(paramTypes[i],request.getClass().getInterfaces())) values[i]=request; else if(checkInterface(paramTypes[i],request.getSession().getClass().getInterfaces())) values[i]=request.getSession(); else if(checkInterface(paramTypes[i],response.getClass().getInterfaces())) values[i]=response; else if(paramTypes[i]==String.class) values[i]=(String) request.getParameter(paramNames[i]); else if(paramTypes[i]==Integer.class) values[i]=Integer.valueOf((String) request.getParameter(paramNames[i])); else if(paramTypes[i]==Double.class) values[i]=Double.valueOf((String) request.getParameter(paramNames[i])); else if(paramTypes[i]==Boolean.class) values[i]=Boolean.valueOf((String) request.getParameter(paramNames[i])); else { values[i]=toObject(paramTypes[i],request); } } return values; } private static boolean checkInterface(Class clz, Class interfaces[]) { if(clz==null||interfaces==null) return false; for(int i=0;i<interfaces.length;i++) if(clz==interfaces[i]) return true; return false; } private static Object toObject(Class clz, HttpServletRequest request) { Object object=null; Enumeration<String> names=request.getParameterNames(); try{ object=clz.newInstance(); while(names.hasMoreElements()) { String paramName=names.nextElement(); Field field=null; try{ field=clz.getDeclaredField(paramName); }catch(Exception e) { e.printStackTrace(); } if(field==null) continue; field.setAccessible(true); String value=(String)request.getParameter(paramName); if(field.getType()==Integer.class|| field.getType()==Integer.TYPE) field.set(object, Integer.parseInt(value)); else if(field.getType()==Double.class|| field.getType()==Double.TYPE) field.set(object, Double.parseDouble(value)); else field.set(object, value); } }catch(Exception e) { e.printStackTrace(); } return object; } }
2,637
0.656428
0.655669
86
29.66279
24.008532
97
false
false
0
0
0
0
0
0
2.697675
false
false
4
ab2dce359029af74e02096eece41291ab57a4b04
11,295,764,034,209
5985e8d20eb0814c9ef52ee0a4cda3e85a7d2e42
/codingbat/java/src/array-1/makeMiddle.java
fb91631e0a57b695f7536e6b25954883d84eb0c8
[]
no_license
liampuk/code-practice
https://github.com/liampuk/code-practice
459db92bb02ea61c6f9d58d7a631f566234d6614
ea9b76713192f00a8c912234ad56e206d2a709d1
refs/heads/master
2021-07-09T18:41:04.129000
2020-06-19T12:02:01
2020-06-19T12:02:01
144,829,996
0
0
null
false
2020-06-19T12:02:02
2018-08-15T08:56:49
2020-06-19T11:54:21
2020-06-19T12:02:01
402
0
0
0
Java
false
false
public int[] makeMiddle(int[] nums) { return new int[]{nums[nums.length/2-1],nums[nums.length/2]}; }
UTF-8
Java
103
java
makeMiddle.java
Java
[]
null
[]
public int[] makeMiddle(int[] nums) { return new int[]{nums[nums.length/2-1],nums[nums.length/2]}; }
103
0.669903
0.640777
3
33.333332
25.037748
62
false
false
0
0
0
0
0
0
0.666667
false
false
4
c8350bd773cac331e468d1dc627601669fcaecd1
29,162,827,990,350
b71d34573d9383106187bc662ef73a4938dcf0ab
/src/main/java/br/com/camtwo/reunioes/config/springdata/DefaultRepository.java
ae4a30bb205bb2ece3dda61c8e6c469d1635cc35
[]
no_license
vitorzachi/reunioes
https://github.com/vitorzachi/reunioes
3b8138dbad323d31afa804d57d2d8ff15593fa76
a344cf5902a4ac3c12119e39772ba8655a7d856a
refs/heads/master
2021-01-10T01:29:41.565000
2016-02-12T23:27:24
2016-02-12T23:27:24
51,623,142
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package br.com.camtwo.reunioes.config.springdata; import br.com.camtwo.reunioes.model.basic.Id; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaSpecificationExecutor; import org.springframework.data.repository.NoRepositoryBean; /** * @author Vitor Zachi Junior * @since 09/02/16 */ @NoRepositoryBean public interface DefaultRepository<T> extends JpaRepository<T, Id>, JpaSpecificationExecutor<T> { }
UTF-8
Java
469
java
DefaultRepository.java
Java
[ { "context": ".data.repository.NoRepositoryBean;\n\n/**\n * @author Vitor Zachi Junior\n * @since 09/02/16\n */\n@NoRepositoryBean\npublic i", "end": 327, "score": 0.9998802542686462, "start": 309, "tag": "NAME", "value": "Vitor Zachi Junior" } ]
null
[]
package br.com.camtwo.reunioes.config.springdata; import br.com.camtwo.reunioes.model.basic.Id; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaSpecificationExecutor; import org.springframework.data.repository.NoRepositoryBean; /** * @author <NAME> * @since 09/02/16 */ @NoRepositoryBean public interface DefaultRepository<T> extends JpaRepository<T, Id>, JpaSpecificationExecutor<T> { }
457
0.814499
0.801706
14
32.5
30.502342
97
false
false
0
0
0
0
0
0
0.5
false
false
4
bc03eca26796cd96649215b3c724d29477d35b2f
8,134,668,109,525
b8f3e317e922c9bca72c63cc47cbc556104163a7
/src/main/java/vmware/samples/vcenter/vcha/VchaClient.java
0d689e1d9a864b704de3250fb511aa61f4bae0fe
[ "MIT" ]
permissive
Onebooming/vsphere-automation-sdk-java
https://github.com/Onebooming/vsphere-automation-sdk-java
86d93420135f3c66bb3467da28d930a435869946
e24b7a85dbe5d03af34e8655ccc9b4d6128c58ce
refs/heads/master
2020-09-21T09:18:58.561000
2019-11-27T05:55:05
2019-11-27T05:55:05
224,751,791
1
0
MIT
true
2019-11-29T01:01:07
2019-11-29T01:01:06
2019-11-27T05:55:08
2019-11-27T05:55:06
630,572
0
0
0
null
false
false
/* * ******************************************************* * Copyright VMware, Inc. 2018. All Rights Reserved. * SPDX-License-Identifier: MIT * ******************************************************* * * DISCLAIMER. THIS PROGRAM IS PROVIDED TO YOU "AS IS" WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, WHETHER ORAL OR WRITTEN, * EXPRESS OR IMPLIED. THE AUTHOR SPECIFICALLY DISCLAIMS ANY IMPLIED * WARRANTIES OR CONDITIONS OF MERCHANTABILITY, SATISFACTORY QUALITY, * NON-INFRINGEMENT AND FITNESS FOR A PARTICULAR PURPOSE. */ package vmware.samples.vcenter.vcha; import java.util.Arrays; import java.util.List; import com.vmware.vcenter.vcha.CredentialsSpec; import com.vmware.vcenter.vcha.Cluster; import com.vmware.vcenter.vcha.cluster.Active; import com.vmware.vcenter.vcha.cluster.Mode; import org.apache.commons.cli.Option; import vmware.samples.common.SamplesAbstractBase; import vmware.samples.vcenter.vcha.helpers.SpecHelper; import vmware.samples.vcenter.vcha.helpers.ArgumentsHelper; /** * Description: Demonstrates listing active node information, vCenter HA cluster information and vCenter HA cluster mode * * Step 1: List active node information * Step 2: List vCenter HA cluster information * Step 3: List vCenter HA cluster mode * Author: VMware, Inc. * Sample Prerequisites: The sample requires a configured vCenter HA cluster * */ public class VchaClient extends SamplesAbstractBase { private String vcSpecActiveLocationHostname; private String vcSpecActiveLocationUsername; private String vcSpecActiveLocationPassword; private String vcSpecActiveLocationSSLThumbprint; private CredentialsSpec mgmtVcCredentialsSpec; private Cluster clusterService; private Active activeService; private Mode modeService; /** * Define the options specific to this sample and configure the sample using * command-line arguments or a config file * * @param args command line arguments passed to the sample */ protected void parseArgs(String[] args) { Option mgmtHostnameOption = Option.builder() .longOpt(ArgumentsHelper.VC_SPEC_ACTIVE_LOCATION_HOSTNAME) .desc("hostname of the Management vCenter Server. Leave blank if it's a self-managed VC") .argName("MGMT VC HOST") .required(false) .hasArg() .build(); Option mgmtUsernameOption = Option.builder() .longOpt(ArgumentsHelper.VC_SPEC_ACTIVE_LOCATION_USERNAME) .desc("username to login to the Management vCenter Server. Leave blank if it's a self-managed VC") .argName("MGMT VC USERNAME") .required(false) .hasArg() .build(); Option mgmtPasswordOption = Option.builder() .longOpt(ArgumentsHelper.VC_SPEC_ACTIVE_LOCATION_PASSWORD) .desc("password to login to the Management vCenter Server. Leave blank if it's a self-managed VC") .argName("MGMT VC PASSWORD") .required(false) .hasArg() .build(); Option mgmtVcSSLThumbprintOption = Option.builder() .longOpt(ArgumentsHelper.VC_SPEC_ACTIVE_LOCATION_SSL_THUMBPRINT) .desc("SSL Thumbprint of Management vCenter Server.") .argName("MGMT VC SSL THUMBPRINT") .required(true) .hasArg() .build(); List<Option> optionList = Arrays.asList(mgmtHostnameOption, mgmtUsernameOption, mgmtPasswordOption, mgmtVcSSLThumbprintOption); super.parseArgs(optionList, args); this.vcSpecActiveLocationHostname = ArgumentsHelper.getStringArg(parsedOptions, ArgumentsHelper.VC_SPEC_ACTIVE_LOCATION_HOSTNAME); if(this.vcSpecActiveLocationHostname == null) this.vcSpecActiveLocationHostname = this.getServer(); this.vcSpecActiveLocationUsername = ArgumentsHelper.getStringArg(parsedOptions, ArgumentsHelper.VC_SPEC_ACTIVE_LOCATION_USERNAME); if(this.vcSpecActiveLocationUsername == null) this.vcSpecActiveLocationUsername = this.getUsername(); this.vcSpecActiveLocationPassword = ArgumentsHelper.getStringArg(parsedOptions, ArgumentsHelper.VC_SPEC_ACTIVE_LOCATION_PASSWORD); if(this.vcSpecActiveLocationPassword == null) this.vcSpecActiveLocationPassword = this.getPassword(); this.vcSpecActiveLocationSSLThumbprint = ArgumentsHelper.getStringArg(parsedOptions, ArgumentsHelper.VC_SPEC_ACTIVE_LOCATION_SSL_THUMBPRINT); } protected void setup() throws Exception { this.clusterService = this.vapiAuthHelper.getStubFactory().createStub(Cluster.class, this.sessionStubConfig); this.activeService = this.vapiAuthHelper.getStubFactory().createStub(Active.class, this.sessionStubConfig); this.modeService = this.vapiAuthHelper.getStubFactory().createStub(Mode.class, this.sessionStubConfig); this.mgmtVcCredentialsSpec = SpecHelper.createCredentialsSpec(this.vcSpecActiveLocationHostname, this.vcSpecActiveLocationUsername, this.vcSpecActiveLocationPassword, this.vcSpecActiveLocationSSLThumbprint); } protected void run() throws Exception { // List active node info, vCenter HA cluster info and cluster mode final String LINE_SEPARATOR = "--------------------------------------------------------------------"; System.out.println(LINE_SEPARATOR); System.out.println("ACTIVE NODE INFO"); System.out.println(LINE_SEPARATOR); System.out.println(this.activeService.get(this.mgmtVcCredentialsSpec, false).toString()); System.out.println(LINE_SEPARATOR); System.out.println("CLUSTER INFO"); System.out.println(LINE_SEPARATOR); System.out.println(this.clusterService.get(this.mgmtVcCredentialsSpec, false).toString()); System.out.println(LINE_SEPARATOR); System.out.println("CLUSTER MODE"); System.out.println(LINE_SEPARATOR); System.out.println(this.modeService.get().toString()); } protected void cleanup() throws Exception { // No cleanup required } public static void main(String[] args) throws Exception { /* * Execute the sample using the command line arguments or parameters * from the configuration file. This executes the following steps: * 1. Parse the arguments required by the sample * 2. Login to the server * 3. Setup any resources required by the sample run * 4. Run the sample * 5. Cleanup any data created by the sample run, if cleanup=true * 6. Logout of the server */ new VchaClient().execute(args); } }
UTF-8
Java
7,223
java
VchaClient.java
Java
[]
null
[]
/* * ******************************************************* * Copyright VMware, Inc. 2018. All Rights Reserved. * SPDX-License-Identifier: MIT * ******************************************************* * * DISCLAIMER. THIS PROGRAM IS PROVIDED TO YOU "AS IS" WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, WHETHER ORAL OR WRITTEN, * EXPRESS OR IMPLIED. THE AUTHOR SPECIFICALLY DISCLAIMS ANY IMPLIED * WARRANTIES OR CONDITIONS OF MERCHANTABILITY, SATISFACTORY QUALITY, * NON-INFRINGEMENT AND FITNESS FOR A PARTICULAR PURPOSE. */ package vmware.samples.vcenter.vcha; import java.util.Arrays; import java.util.List; import com.vmware.vcenter.vcha.CredentialsSpec; import com.vmware.vcenter.vcha.Cluster; import com.vmware.vcenter.vcha.cluster.Active; import com.vmware.vcenter.vcha.cluster.Mode; import org.apache.commons.cli.Option; import vmware.samples.common.SamplesAbstractBase; import vmware.samples.vcenter.vcha.helpers.SpecHelper; import vmware.samples.vcenter.vcha.helpers.ArgumentsHelper; /** * Description: Demonstrates listing active node information, vCenter HA cluster information and vCenter HA cluster mode * * Step 1: List active node information * Step 2: List vCenter HA cluster information * Step 3: List vCenter HA cluster mode * Author: VMware, Inc. * Sample Prerequisites: The sample requires a configured vCenter HA cluster * */ public class VchaClient extends SamplesAbstractBase { private String vcSpecActiveLocationHostname; private String vcSpecActiveLocationUsername; private String vcSpecActiveLocationPassword; private String vcSpecActiveLocationSSLThumbprint; private CredentialsSpec mgmtVcCredentialsSpec; private Cluster clusterService; private Active activeService; private Mode modeService; /** * Define the options specific to this sample and configure the sample using * command-line arguments or a config file * * @param args command line arguments passed to the sample */ protected void parseArgs(String[] args) { Option mgmtHostnameOption = Option.builder() .longOpt(ArgumentsHelper.VC_SPEC_ACTIVE_LOCATION_HOSTNAME) .desc("hostname of the Management vCenter Server. Leave blank if it's a self-managed VC") .argName("MGMT VC HOST") .required(false) .hasArg() .build(); Option mgmtUsernameOption = Option.builder() .longOpt(ArgumentsHelper.VC_SPEC_ACTIVE_LOCATION_USERNAME) .desc("username to login to the Management vCenter Server. Leave blank if it's a self-managed VC") .argName("MGMT VC USERNAME") .required(false) .hasArg() .build(); Option mgmtPasswordOption = Option.builder() .longOpt(ArgumentsHelper.VC_SPEC_ACTIVE_LOCATION_PASSWORD) .desc("password to login to the Management vCenter Server. Leave blank if it's a self-managed VC") .argName("MGMT VC PASSWORD") .required(false) .hasArg() .build(); Option mgmtVcSSLThumbprintOption = Option.builder() .longOpt(ArgumentsHelper.VC_SPEC_ACTIVE_LOCATION_SSL_THUMBPRINT) .desc("SSL Thumbprint of Management vCenter Server.") .argName("MGMT VC SSL THUMBPRINT") .required(true) .hasArg() .build(); List<Option> optionList = Arrays.asList(mgmtHostnameOption, mgmtUsernameOption, mgmtPasswordOption, mgmtVcSSLThumbprintOption); super.parseArgs(optionList, args); this.vcSpecActiveLocationHostname = ArgumentsHelper.getStringArg(parsedOptions, ArgumentsHelper.VC_SPEC_ACTIVE_LOCATION_HOSTNAME); if(this.vcSpecActiveLocationHostname == null) this.vcSpecActiveLocationHostname = this.getServer(); this.vcSpecActiveLocationUsername = ArgumentsHelper.getStringArg(parsedOptions, ArgumentsHelper.VC_SPEC_ACTIVE_LOCATION_USERNAME); if(this.vcSpecActiveLocationUsername == null) this.vcSpecActiveLocationUsername = this.getUsername(); this.vcSpecActiveLocationPassword = ArgumentsHelper.getStringArg(parsedOptions, ArgumentsHelper.VC_SPEC_ACTIVE_LOCATION_PASSWORD); if(this.vcSpecActiveLocationPassword == null) this.vcSpecActiveLocationPassword = this.getPassword(); this.vcSpecActiveLocationSSLThumbprint = ArgumentsHelper.getStringArg(parsedOptions, ArgumentsHelper.VC_SPEC_ACTIVE_LOCATION_SSL_THUMBPRINT); } protected void setup() throws Exception { this.clusterService = this.vapiAuthHelper.getStubFactory().createStub(Cluster.class, this.sessionStubConfig); this.activeService = this.vapiAuthHelper.getStubFactory().createStub(Active.class, this.sessionStubConfig); this.modeService = this.vapiAuthHelper.getStubFactory().createStub(Mode.class, this.sessionStubConfig); this.mgmtVcCredentialsSpec = SpecHelper.createCredentialsSpec(this.vcSpecActiveLocationHostname, this.vcSpecActiveLocationUsername, this.vcSpecActiveLocationPassword, this.vcSpecActiveLocationSSLThumbprint); } protected void run() throws Exception { // List active node info, vCenter HA cluster info and cluster mode final String LINE_SEPARATOR = "--------------------------------------------------------------------"; System.out.println(LINE_SEPARATOR); System.out.println("ACTIVE NODE INFO"); System.out.println(LINE_SEPARATOR); System.out.println(this.activeService.get(this.mgmtVcCredentialsSpec, false).toString()); System.out.println(LINE_SEPARATOR); System.out.println("CLUSTER INFO"); System.out.println(LINE_SEPARATOR); System.out.println(this.clusterService.get(this.mgmtVcCredentialsSpec, false).toString()); System.out.println(LINE_SEPARATOR); System.out.println("CLUSTER MODE"); System.out.println(LINE_SEPARATOR); System.out.println(this.modeService.get().toString()); } protected void cleanup() throws Exception { // No cleanup required } public static void main(String[] args) throws Exception { /* * Execute the sample using the command line arguments or parameters * from the configuration file. This executes the following steps: * 1. Parse the arguments required by the sample * 2. Login to the server * 3. Setup any resources required by the sample run * 4. Run the sample * 5. Cleanup any data created by the sample run, if cleanup=true * 6. Logout of the server */ new VchaClient().execute(args); } }
7,223
0.638793
0.636993
152
46.519737
29.971691
120
false
false
0
0
0
0
0
0
0.552632
false
false
4
c676c670665fd84f38ee7595ee17b7124c45cd54
15,109,694,998,146
0a8f81fe4d99f05e58fbd3f923d34eca52002f35
/JavaWorld/src/byui/cit260/thegame/view/AfterStatusAndInventory.java
8c53a191417386608836d217beb60858dda16e0a
[]
no_license
erikfenriz/JavaWorldCIT260
https://github.com/erikfenriz/JavaWorldCIT260
85202416cb81c0b7190bbab14c30c6203cc705e9
2a60b019536e2059525063aaeb609ef66fca7761
refs/heads/master
2021-05-08T22:04:10.226000
2018-04-07T03:07:01
2018-04-07T03:07:01
119,662,056
0
0
null
false
2018-04-06T14:56:27
2018-01-31T09:04:10
2018-04-06T03:37:02
2018-04-06T14:56:27
171
0
0
0
Java
false
null
/* * 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 byui.cit260.thegame.view; /** * * @author Erik Rybalkin */ public class AfterStatusAndInventory extends View{ public AfterStatusAndInventory(){ super("Slightly visible lights of the tall buildings in a distance.\n" + " The train is slowing its speed and soon will stop.\n" +" \n" +"Almost there...\n" +"1. continue..."); } @Override public boolean doAction(String value){ char choice = Character.toUpperCase(value.charAt(0)); switch(choice){ case '1': FirstArrivalView firstArrivalView = new FirstArrivalView(); firstArrivalView.display(); break; default: ErrorView.display(this.getClass().getName(), "Invalid Choice"); break; } return false; } }
UTF-8
Java
1,049
java
AfterStatusAndInventory.java
Java
[ { "context": "ckage byui.cit260.thegame.view;\n\n/**\n *\n * @author Erik Rybalkin\n */\npublic class AfterStatusAndInventory extends ", "end": 251, "score": 0.9998929500579834, "start": 238, "tag": "NAME", "value": "Erik Rybalkin" } ]
null
[]
/* * 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 byui.cit260.thegame.view; /** * * @author <NAME> */ public class AfterStatusAndInventory extends View{ public AfterStatusAndInventory(){ super("Slightly visible lights of the tall buildings in a distance.\n" + " The train is slowing its speed and soon will stop.\n" +" \n" +"Almost there...\n" +"1. continue..."); } @Override public boolean doAction(String value){ char choice = Character.toUpperCase(value.charAt(0)); switch(choice){ case '1': FirstArrivalView firstArrivalView = new FirstArrivalView(); firstArrivalView.display(); break; default: ErrorView.display(this.getClass().getName(), "Invalid Choice"); break; } return false; } }
1,042
0.595806
0.590086
37
27.378378
26.14032
84
false
false
0
0
0
0
0
0
0.351351
false
false
4
aca4da524321edc92f1ff98191a7935c706c252a
25,426,206,447,534
067ee1d2d21add6388d407b22443c018262c2141
/WqComponent/src/main/java/com/weqia/wq/component/view/BottomLinesNumView.java
bfc52c57f156966abf2860e0d0e89cc076e8188a
[]
no_license
luoguofu/ccbimpoi
https://github.com/luoguofu/ccbimpoi
2c86e046f32124ddaf90810e75b6ebcd7cfc6111
8a33078ddacf6d7dfd4b3fcc9714b9f5117395cc
refs/heads/master
2020-04-28T16:45:41.308000
2019-11-13T03:24:06
2019-11-13T03:24:06
175,422,913
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.weqia.wq.component.view; import android.content.Context; import android.util.AttributeSet; import android.view.LayoutInflater; import android.view.View; import android.widget.LinearLayout; import android.widget.TextView; import com.weqia.wq.R; /** * Created by ML on 2016/10/13. */ public class BottomLinesNumView extends LinearLayout { private TextView tvLine; private Context ctx; //上下文对象! private TextView tvBottomTitle; public BottomLinesNumView(Context context) { super(context); } public BottomLinesNumView(Context context, AttributeSet attrs) { super(context, attrs); this.ctx = context; initView(); } public void setTvLine(TextView tvLine) { this.tvLine = tvLine; } public TextView getTvLine() { return tvLine; } public void setCtx(Context ctx) { this.ctx = ctx; } public Context getCtx() { return ctx; } public void initView(){ if (isInEditMode()) { //if (isInEditMode()) { return; },防止可视化编辑报错 return; } LayoutInflater inflater = LayoutInflater.from(getCtx()); LinearLayout layout = new LinearLayout(getCtx()); View view = inflater.inflate(R.layout.view_bottom_num_line,layout); if (view != null) { setTvBottomTitle((TextView) view.findViewById(R.id.tv_bottom_title_line)); setTvLine((TextView)view.findViewById(R.id.tv_bottom_line)); } LayoutParams layoutParams =new LayoutParams( LinearLayout.LayoutParams.MATCH_PARENT,LinearLayout.LayoutParams.MATCH_PARENT); layout.setLayoutParams(layoutParams); //配置View的大小! this.addView(layout); } @Override public void setSelected(boolean selected) { super.setSelected(selected); if (selected) { getTvBottomTitle().setTextColor(getResources().getColor(R.color.main_color)); getTvLine().setBackgroundColor(getResources().getColor(R.color.main_color)); } else { getTvBottomTitle().setTextColor(getResources().getColor(R.color.black_font)); getTvLine().setBackgroundColor(getResources().getColor(R.color.white)); } } public TextView getTvBottomTitle() { return tvBottomTitle; } public void setTvBottomTitle(TextView tvBottomTitle) { this.tvBottomTitle = tvBottomTitle; } public void setText(String text) { this.tvBottomTitle.setText(text); } public void setText(int id) { this.tvBottomTitle.setText(ctx.getText(id)); } }
UTF-8
Java
2,663
java
BottomLinesNumView.java
Java
[ { "context": "xtView;\n\nimport com.weqia.wq.R;\n\n/**\n * Created by ML on 2016/10/13.\n */\n\npublic class BottomLinesNumVi", "end": 279, "score": 0.9820029735565186, "start": 277, "tag": "USERNAME", "value": "ML" } ]
null
[]
package com.weqia.wq.component.view; import android.content.Context; import android.util.AttributeSet; import android.view.LayoutInflater; import android.view.View; import android.widget.LinearLayout; import android.widget.TextView; import com.weqia.wq.R; /** * Created by ML on 2016/10/13. */ public class BottomLinesNumView extends LinearLayout { private TextView tvLine; private Context ctx; //上下文对象! private TextView tvBottomTitle; public BottomLinesNumView(Context context) { super(context); } public BottomLinesNumView(Context context, AttributeSet attrs) { super(context, attrs); this.ctx = context; initView(); } public void setTvLine(TextView tvLine) { this.tvLine = tvLine; } public TextView getTvLine() { return tvLine; } public void setCtx(Context ctx) { this.ctx = ctx; } public Context getCtx() { return ctx; } public void initView(){ if (isInEditMode()) { //if (isInEditMode()) { return; },防止可视化编辑报错 return; } LayoutInflater inflater = LayoutInflater.from(getCtx()); LinearLayout layout = new LinearLayout(getCtx()); View view = inflater.inflate(R.layout.view_bottom_num_line,layout); if (view != null) { setTvBottomTitle((TextView) view.findViewById(R.id.tv_bottom_title_line)); setTvLine((TextView)view.findViewById(R.id.tv_bottom_line)); } LayoutParams layoutParams =new LayoutParams( LinearLayout.LayoutParams.MATCH_PARENT,LinearLayout.LayoutParams.MATCH_PARENT); layout.setLayoutParams(layoutParams); //配置View的大小! this.addView(layout); } @Override public void setSelected(boolean selected) { super.setSelected(selected); if (selected) { getTvBottomTitle().setTextColor(getResources().getColor(R.color.main_color)); getTvLine().setBackgroundColor(getResources().getColor(R.color.main_color)); } else { getTvBottomTitle().setTextColor(getResources().getColor(R.color.black_font)); getTvLine().setBackgroundColor(getResources().getColor(R.color.white)); } } public TextView getTvBottomTitle() { return tvBottomTitle; } public void setTvBottomTitle(TextView tvBottomTitle) { this.tvBottomTitle = tvBottomTitle; } public void setText(String text) { this.tvBottomTitle.setText(text); } public void setText(int id) { this.tvBottomTitle.setText(ctx.getText(id)); } }
2,663
0.650248
0.647194
95
26.56842
26.713943
132
false
false
0
0
0
0
0
0
0.442105
false
false
4
52fc101dd544c85d7ff6593a7a7831d3e5d287bc
7,722,351,246,973
b77b29c5684983c9117a781a0612bbdbfd147b6e
/src/main/java/com/huawei/hostingtrial/repository/OauthAccessTokenRepository.java
5fe5e14163c70e7b8400c8576b7581fe7838c988
[]
no_license
pologood/spring-oauth
https://github.com/pologood/spring-oauth
3aee6b47945c168ee2e1e01c7bad1749ae16a2fe
5aa589d9ea43816c7397cb9c1460b6710d51d52d
refs/heads/master
2021-01-20T01:38:44.379000
2014-03-07T03:16:59
2014-03-07T03:16:59
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.huawei.hostingtrial.repository; import java.util.List; import com.huawei.hostingtrial.domain.OauthAccessToken; import org.springframework.data.jpa.repository.JpaRepository; public interface OauthAccessTokenRepository extends JpaRepository<OauthAccessToken, String>{ List<OauthAccessToken> findByClientId(String clientId); int countByClientId(String clientId); }
UTF-8
Java
384
java
OauthAccessTokenRepository.java
Java
[]
null
[]
package com.huawei.hostingtrial.repository; import java.util.List; import com.huawei.hostingtrial.domain.OauthAccessToken; import org.springframework.data.jpa.repository.JpaRepository; public interface OauthAccessTokenRepository extends JpaRepository<OauthAccessToken, String>{ List<OauthAccessToken> findByClientId(String clientId); int countByClientId(String clientId); }
384
0.838542
0.838542
14
26.428572
29.697798
92
false
false
0
0
0
0
0
0
0.785714
false
false
4
233bd5235f8eed8648635323768b1a71e3d8565a
16,088,947,548,353
a393af502e20cec6b9463ea6b16cbf2c40698c03
/src/LinkedlistSolve.java
822eb606f7740c5968b2730bd1f02189eea9b8a8
[]
no_license
xlwwww/leetcode
https://github.com/xlwwww/leetcode
c138676ceb97b9340f7b63cf648cdb91b220b804
1b09e8e327b86d642822503eb92ccc65cdaa65e0
refs/heads/master
2022-12-16T23:46:51.561000
2020-09-09T13:40:20
2020-09-09T13:40:20
284,383,090
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import Tree.TreeNode; /** * @author cutiewang * @date 2020/2/25 21:01 */ public class LinkedlistSolve { public TreeNode sortedListToBST(ListNode head) { if(head == null) return null; if(head.next == null) return new TreeNode(head.val); ListNode p= head,q=head,pre=head; while(q.next!=null && q.next.next!=null) { pre = p; p = p.next; q = q.next.next; } //q = p.next; pre.next = null; TreeNode root = new TreeNode(p.val); root.left = sortedListToBST(head); root.right = sortedListToBST(p.next); return root; } }
UTF-8
Java
648
java
LinkedlistSolve.java
Java
[ { "context": "import Tree.TreeNode;\n\n/**\n * @author cutiewang\n * @date 2020/2/25 21:01\n */\npublic class Linkedl", "end": 47, "score": 0.9898459315299988, "start": 38, "tag": "USERNAME", "value": "cutiewang" } ]
null
[]
import Tree.TreeNode; /** * @author cutiewang * @date 2020/2/25 21:01 */ public class LinkedlistSolve { public TreeNode sortedListToBST(ListNode head) { if(head == null) return null; if(head.next == null) return new TreeNode(head.val); ListNode p= head,q=head,pre=head; while(q.next!=null && q.next.next!=null) { pre = p; p = p.next; q = q.next.next; } //q = p.next; pre.next = null; TreeNode root = new TreeNode(p.val); root.left = sortedListToBST(head); root.right = sortedListToBST(p.next); return root; } }
648
0.54784
0.530864
25
24.92
17.465212
60
false
false
0
0
0
0
0
0
0.6
false
false
4
8b68f39ee80f492c448072d681f8a7a351de9526
13,563,506,789,714
53d92aa8844e76a2349741e766d4693362ecba3f
/src/Reaction.java
5f47f7b2547c6ab57a2f19e504f660b50d8eb66c
[]
no_license
JacobAriCoefficientGames/EventsTest
https://github.com/JacobAriCoefficientGames/EventsTest
8ef2431c663138d422a46d34de72ce5792d7e7bb
0994b7e02c0001ccaa85550964b7d676213141c7
refs/heads/master
2016-09-05T20:29:56.746000
2015-03-04T22:14:44
2015-03-04T22:14:44
31,346,857
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/** * * @author Jacob * * @param <E> the type of Event that this reacts to * * this represents a function that gets run when the E event type happens */ @FunctionalInterface public interface Reaction<E extends Event> { /** * * @param event the event that triggered this reaction * @return weather reaction should be kept in pool * @return if false, then removed. if true, then kept. * * This function gets run whenever there is an event of type E. */ public boolean react(E event, EventPool pool); }
UTF-8
Java
527
java
Reaction.java
Java
[ { "context": "/**\n * \n * @author Jacob\n *\n * @param <E> the type of Event that this reac", "end": 24, "score": 0.9995691776275635, "start": 19, "tag": "NAME", "value": "Jacob" } ]
null
[]
/** * * @author Jacob * * @param <E> the type of Event that this reacts to * * this represents a function that gets run when the E event type happens */ @FunctionalInterface public interface Reaction<E extends Event> { /** * * @param event the event that triggered this reaction * @return weather reaction should be kept in pool * @return if false, then removed. if true, then kept. * * This function gets run whenever there is an event of type E. */ public boolean react(E event, EventPool pool); }
527
0.6926
0.6926
20
25.35
25.229496
73
false
false
0
0
0
0
0
0
0.65
false
false
4
13f21a4e780281f3c69530607ecc8ee61e4ab622
33,526,514,769,871
84097bc944e1d2058011a8d94719efa4116f2629
/src/maze/State.java
689aaecc22c91c6f676dc9e251af3c8a4f0354b2
[]
no_license
pybae/maze
https://github.com/pybae/maze
c5d9fdc2a64bc989e382d1a5f0605c3587e37287
df3628baa5065bd3b8b7c6e7297ff099224858fa
refs/heads/master
2020-05-27T02:49:44.255000
2015-05-14T19:07:22
2015-05-14T19:07:22
33,505,673
2
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package maze; public enum State { NOT_SET, WALL, OPEN, DOOR, DEBUG }
UTF-8
Java
90
java
State.java
Java
[]
null
[]
package maze; public enum State { NOT_SET, WALL, OPEN, DOOR, DEBUG }
90
0.544444
0.544444
9
9
5.477226
19
false
false
0
0
0
0
0
0
0.555556
false
false
4
adcceb9c16673a6727f429a4d14c713ea5abc447
6,158,983,172,195
41ff3ba1a373d77a963588c6a765dfbd7631c4f3
/baekjoon/src/bruteforce/p14501.java
3b5b1f0ef6914d2d75e92cc8a6a2e4e546914f3e
[]
no_license
hye1n/Programming
https://github.com/hye1n/Programming
50be06b49a8ae3ce2fce11753d05e65d9b6eee9b
079c15f9897b7fc97523b08b25b55417b3fd5953
refs/heads/master
2022-01-04T16:37:46.934000
2019-08-22T08:30:41
2019-08-22T08:30:41
197,872,465
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package bruteforce; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.util.StringTokenizer; public class p14501 { public static int max = 0; public static void main(String[] args) throws IOException { // TODO Auto-generated method stub BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out)); int n = Integer.parseInt(br.readLine()); int[] t = new int[n + 1]; int[] p = new int[n + 1]; StringTokenizer st; for (int i = 1; i <= n; i++) { st = new StringTokenizer(br.readLine()); t[i] = Integer.parseInt(st.nextToken()); p[i] = Integer.parseInt(st.nextToken()); } solve(n, t, p, 1, 0); bw.append(String.valueOf(max)); bw.flush(); bw.close(); } public static void solve(int n, int[] t, int[] p, int i, int sum) { if (i == n + 1) { max = Math.max(max, sum); return; } if (i > n + 1) { return; } solve(n, t, p, i + t[i], sum + p[i]); solve(n, t, p, i + 1, sum); } }
UTF-8
Java
1,141
java
p14501.java
Java
[]
null
[]
package bruteforce; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.util.StringTokenizer; public class p14501 { public static int max = 0; public static void main(String[] args) throws IOException { // TODO Auto-generated method stub BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out)); int n = Integer.parseInt(br.readLine()); int[] t = new int[n + 1]; int[] p = new int[n + 1]; StringTokenizer st; for (int i = 1; i <= n; i++) { st = new StringTokenizer(br.readLine()); t[i] = Integer.parseInt(st.nextToken()); p[i] = Integer.parseInt(st.nextToken()); } solve(n, t, p, 1, 0); bw.append(String.valueOf(max)); bw.flush(); bw.close(); } public static void solve(int n, int[] t, int[] p, int i, int sum) { if (i == n + 1) { max = Math.max(max, sum); return; } if (i > n + 1) { return; } solve(n, t, p, i + t[i], sum + p[i]); solve(n, t, p, i + 1, sum); } }
1,141
0.647677
0.635408
44
24.931818
19.871632
77
false
false
0
0
0
0
0
0
2.409091
false
false
4
669542015f0f34d3399149233b344946e2d2171e
25,400,436,647,021
7be922bdd1a1b60d8089bd09a764c33643e0af66
/app/src/main/java/com/orange/blog/net/protocol/UserFriendReuqestProcotol.java
4d1231dedeed20f7747b5ecb69eb71b2dd4277ca
[]
no_license
Tangqiketang/java-TCP-long-connection
https://github.com/Tangqiketang/java-TCP-long-connection
6acaf07051aae93f7bd811be63541d9e1a008d44
00b664a47e293d082c92d50c17d46222a40e1b27
refs/heads/master
2020-08-17T16:34:32.065000
2018-10-25T02:19:31
2018-10-25T02:19:31
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.orange.blog.net.protocol; import com.orange.blog.common.ProjectApplication; import com.orange.blog.net.ProtocolException; import java.io.ByteArrayOutputStream; import java.io.UnsupportedEncodingException; /** * Created by orange on 16/6/22. */ public class UserFriendReuqestProcotol extends BasicProtocol { public static final String USERFRIENDREQUESTCOMMEND="0003"; private String usersJson; private String selfUUID; public UserFriendReuqestProcotol(){ selfUUID= ProjectApplication.getUUID(); } @Override public String getCommend() { return USERFRIENDREQUESTCOMMEND; } @Override public byte[] getContentData() { byte[] pre=super.getContentData(); ByteArrayOutputStream baos=new ByteArrayOutputStream(); baos.write(pre,0,pre.length); baos.write(selfUUID.getBytes(),0,ChatMsgProcotol.SLEFUUID_LEN); return baos.toByteArray(); } public String getUsersJson() { return usersJson; } @Override public int parseBinary(byte[] data) throws ProtocolException { int pos=super.parseBinary(data); try { usersJson=new String(data,pos,data.length-pos,"utf-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return pos; } public void setUsersJson(String usersJson) { this.usersJson = usersJson; } }
UTF-8
Java
1,438
java
UserFriendReuqestProcotol.java
Java
[ { "context": "o.UnsupportedEncodingException;\n\n/**\n * Created by orange on 16/6/22.\n */\npublic class UserFriendReuqestPro", "end": 244, "score": 0.7397518157958984, "start": 238, "tag": "USERNAME", "value": "orange" } ]
null
[]
package com.orange.blog.net.protocol; import com.orange.blog.common.ProjectApplication; import com.orange.blog.net.ProtocolException; import java.io.ByteArrayOutputStream; import java.io.UnsupportedEncodingException; /** * Created by orange on 16/6/22. */ public class UserFriendReuqestProcotol extends BasicProtocol { public static final String USERFRIENDREQUESTCOMMEND="0003"; private String usersJson; private String selfUUID; public UserFriendReuqestProcotol(){ selfUUID= ProjectApplication.getUUID(); } @Override public String getCommend() { return USERFRIENDREQUESTCOMMEND; } @Override public byte[] getContentData() { byte[] pre=super.getContentData(); ByteArrayOutputStream baos=new ByteArrayOutputStream(); baos.write(pre,0,pre.length); baos.write(selfUUID.getBytes(),0,ChatMsgProcotol.SLEFUUID_LEN); return baos.toByteArray(); } public String getUsersJson() { return usersJson; } @Override public int parseBinary(byte[] data) throws ProtocolException { int pos=super.parseBinary(data); try { usersJson=new String(data,pos,data.length-pos,"utf-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return pos; } public void setUsersJson(String usersJson) { this.usersJson = usersJson; } }
1,438
0.675243
0.666898
57
24.228069
22.011972
71
false
false
0
0
0
0
0
0
0.491228
false
false
4
80843e900556550778734c3f67d713a1bcac6b1f
30,227,979,897,688
bf063b9feb2659830c44facd9c142444b3255864
/person/叶紫/auto2020/src/com/webtest/renzixuan/Chaxun.java
5de2d6d84cbf6dc08b57388bee46b9d3ad63786c
[]
no_license
yezi3456/ceshixiaocai-FirstProject
https://github.com/yezi3456/ceshixiaocai-FirstProject
ac3ddab35f413ea1494bb829be58394d5590d24a
2409943c7039ac22f540f4752d37609cc95d95d5
refs/heads/master
2020-09-08T09:40:04.820000
2019-12-19T02:23:05
2019-12-19T02:23:05
221,097,505
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.webtest.renzixuan; import static org.testng.Assert.assertTrue; import org.testng.annotations.BeforeClass; import org.testng.annotations.Listeners; import org.testng.annotations.Test; import com.webtest.core.BaseTest; import com.webtest.core.BaseTest1; import com.webtest.dataprovider.NSDataProvider; import com.webtest.utils.ReadProperties; @Listeners(com.webtest.core.WebTestListener.class) public class Chaxun extends BaseTest1{ @BeforeClass public void loginTest() throws Exception{ webtest.open(ReadProperties.getPropertyValue("backstage_url")); webtest.type("id=loginName", "admin"); webtest.type("id=loginPwd", "yz290315"); webtest.click("xpath=//input[@value='登录']"); Thread.sleep(3000); } @Test(description="13.订单管理的已收货订单列表里根据订单编号100000003查询订单详情") public void test1() throws Exception { webtest.click("xpath=//*[@id=\"wst-tabs\"]/div[1]/ul/li[3]"); webtest.click("xpath=//*[@id=\"wst-accordion-35\"]/div[2]/a[6]"); webtest.enterFrame("wst-lframe-35"); webtest.type("id=orderNo","100000003"); webtest.click("xpath=//*[@id=\"payType\"]/option[2]"); webtest.click("xpath=//*[@id=\"deliverType\"]/option[3]"); webtest.click("xpath=/html/body/div[1]/button"); assertTrue(webtest.isTextPresent("查询")); } @Test(description="14.订单管理的已收货订单列表里根据订单编号查询(查不到的情况)(货到付款选成自提或者输入一个根本不存在的订单号)") public void test2() throws Exception { Thread.sleep(2000); webtest.click("xpath=//*[@id=\"payType\"]/option[2]"); webtest.click("xpath=//*[@id=\"deliverType\"]/option[2]"); webtest.click("xpath=/html/body/div[1]/button"); assertTrue(webtest.isTextPresent("查询")); } @Test(description="15.订单管理的待发货订单列表里根据订单编号100000202查询订单详情") public void test3() throws Exception { webtest.leaveFrame(); //点击待发货订单 webtest.click("xpath=//*[@id=\"wst-accordion-35\"]/div[2]/a[1]"); webtest.enterFrame("wst-lframe-35"); webtest.type("id=orderNo","100000202"); Thread.sleep(2000); webtest.click("xpath=//*[@id=\"payType\"]/option[2]"); webtest.click("xpath=//*[@id=\"deliverType\"]/option[1]"); webtest.click("xpath=/html/body/div[1]/button"); assertTrue(webtest.isTextPresent("查询")); } @Test(description="16.订单管理的待发货订单列表里根据订单编号查询(查不到的情况)(货到付款选成自提或者输入一个根本不存在的订单号)") public void test4() throws Exception { Thread.sleep(2000); webtest.click("xpath=//*[@id=\"payType\"]/option[2]"); webtest.click("xpath=//*[@id=\"deliverType\"]/option[2]"); webtest.click("xpath=/html/body/div[1]/button"); assertTrue(webtest.isTextPresent("查询")); } @Test(description="16.订单管理的已发货订单列表里根据订单编号100000036查询订单详情") public void test5() throws Exception { webtest.leaveFrame(); //点击已发货订单 webtest.click("xpath=//*[@id=\"wst-accordion-35\"]/div[2]/a[3]"); Thread.sleep(2000); webtest.enterFrame("wst-lframe-35"); Thread.sleep(2000); webtest.type("id=orderNo","100000036"); Thread.sleep(2000); webtest.click("xpath=//*[@id=\"orderStatus\"]/option[2]"); webtest.click("xpath=//*[@id=\"payType\"]/option[3]"); webtest.click("xpath=/html/body/div[1]/button"); assertTrue(webtest.isTextPresent("查询")); } @Test(description="17.订单管理的已发货订单列表里根据订单编号查询(查不到的情况)(货到付款选成自提或者输入一个根本不存在的订单号)") public void test6() throws Exception { //登录后台 Thread.sleep(2000); webtest.click("xpath=//*[@id=\"orderStatus\"]/option[2]"); webtest.click("xpath=//*[@id=\"payType\"]/option[2]"); webtest.click("xpath=/html/body/div[1]/button"); assertTrue(webtest.isTextPresent("查询")); } @Test(description="18.订单管理的取消/拒收订单列表里根据订单编号100000003查询订单详情") public void test7() throws Exception { webtest.leaveFrame(); //点击取消/拒收订单 webtest.click("xpath=//*[@id=\"wst-accordion-35\"]/div[2]/a[4]"); webtest.enterFrame("wst-lframe-35"); webtest.type("id=orderNo","100000014"); Thread.sleep(2000); webtest.click("xpath=//*[@id=\"orderStatus\"]/option[2]"); webtest.click("xpath=//*[@id=\"payType\"]/option[3]"); webtest.click("xpath=/html/body/div[1]/button"); assertTrue(webtest.isTextPresent("查询")); } @Test(description="19.订单管理的取消/拒收订单列表里根据订单编号查询(查不到的情况)(货到付款选成自提或者输入一个根本不存在的订单号)") public void test8() throws Exception { //登录后台 Thread.sleep(2000); webtest.click("xpath=//*[@id=\"orderStatus\"]/option[2]"); webtest.click("xpath=//*[@id=\"payType\"]/option[2]"); webtest.click("xpath=/html/body/div[1]/button"); assertTrue(webtest.isTextPresent("查询")); } }
GB18030
Java
5,161
java
Chaxun.java
Java
[ { "context": "backstage_url\"));\n\t\twebtest.type(\"id=loginName\", \"admin\");\n\t\twebtest.type(\"id=loginPwd\", \"yz290315\");\n\t\tw", "end": 607, "score": 0.9895113110542297, "start": 602, "tag": "USERNAME", "value": "admin" }, { "context": "inName\", \"admin\");\n\t\twebtest.type(\"id=loginPwd\", \"yz290315\");\n\t\twebtest.click(\"xpath=//input[@value='登录']\");", "end": 650, "score": 0.999466598033905, "start": 642, "tag": "PASSWORD", "value": "yz290315" } ]
null
[]
package com.webtest.renzixuan; import static org.testng.Assert.assertTrue; import org.testng.annotations.BeforeClass; import org.testng.annotations.Listeners; import org.testng.annotations.Test; import com.webtest.core.BaseTest; import com.webtest.core.BaseTest1; import com.webtest.dataprovider.NSDataProvider; import com.webtest.utils.ReadProperties; @Listeners(com.webtest.core.WebTestListener.class) public class Chaxun extends BaseTest1{ @BeforeClass public void loginTest() throws Exception{ webtest.open(ReadProperties.getPropertyValue("backstage_url")); webtest.type("id=loginName", "admin"); webtest.type("id=loginPwd", "<PASSWORD>"); webtest.click("xpath=//input[@value='登录']"); Thread.sleep(3000); } @Test(description="13.订单管理的已收货订单列表里根据订单编号100000003查询订单详情") public void test1() throws Exception { webtest.click("xpath=//*[@id=\"wst-tabs\"]/div[1]/ul/li[3]"); webtest.click("xpath=//*[@id=\"wst-accordion-35\"]/div[2]/a[6]"); webtest.enterFrame("wst-lframe-35"); webtest.type("id=orderNo","100000003"); webtest.click("xpath=//*[@id=\"payType\"]/option[2]"); webtest.click("xpath=//*[@id=\"deliverType\"]/option[3]"); webtest.click("xpath=/html/body/div[1]/button"); assertTrue(webtest.isTextPresent("查询")); } @Test(description="14.订单管理的已收货订单列表里根据订单编号查询(查不到的情况)(货到付款选成自提或者输入一个根本不存在的订单号)") public void test2() throws Exception { Thread.sleep(2000); webtest.click("xpath=//*[@id=\"payType\"]/option[2]"); webtest.click("xpath=//*[@id=\"deliverType\"]/option[2]"); webtest.click("xpath=/html/body/div[1]/button"); assertTrue(webtest.isTextPresent("查询")); } @Test(description="15.订单管理的待发货订单列表里根据订单编号100000202查询订单详情") public void test3() throws Exception { webtest.leaveFrame(); //点击待发货订单 webtest.click("xpath=//*[@id=\"wst-accordion-35\"]/div[2]/a[1]"); webtest.enterFrame("wst-lframe-35"); webtest.type("id=orderNo","100000202"); Thread.sleep(2000); webtest.click("xpath=//*[@id=\"payType\"]/option[2]"); webtest.click("xpath=//*[@id=\"deliverType\"]/option[1]"); webtest.click("xpath=/html/body/div[1]/button"); assertTrue(webtest.isTextPresent("查询")); } @Test(description="16.订单管理的待发货订单列表里根据订单编号查询(查不到的情况)(货到付款选成自提或者输入一个根本不存在的订单号)") public void test4() throws Exception { Thread.sleep(2000); webtest.click("xpath=//*[@id=\"payType\"]/option[2]"); webtest.click("xpath=//*[@id=\"deliverType\"]/option[2]"); webtest.click("xpath=/html/body/div[1]/button"); assertTrue(webtest.isTextPresent("查询")); } @Test(description="16.订单管理的已发货订单列表里根据订单编号100000036查询订单详情") public void test5() throws Exception { webtest.leaveFrame(); //点击已发货订单 webtest.click("xpath=//*[@id=\"wst-accordion-35\"]/div[2]/a[3]"); Thread.sleep(2000); webtest.enterFrame("wst-lframe-35"); Thread.sleep(2000); webtest.type("id=orderNo","100000036"); Thread.sleep(2000); webtest.click("xpath=//*[@id=\"orderStatus\"]/option[2]"); webtest.click("xpath=//*[@id=\"payType\"]/option[3]"); webtest.click("xpath=/html/body/div[1]/button"); assertTrue(webtest.isTextPresent("查询")); } @Test(description="17.订单管理的已发货订单列表里根据订单编号查询(查不到的情况)(货到付款选成自提或者输入一个根本不存在的订单号)") public void test6() throws Exception { //登录后台 Thread.sleep(2000); webtest.click("xpath=//*[@id=\"orderStatus\"]/option[2]"); webtest.click("xpath=//*[@id=\"payType\"]/option[2]"); webtest.click("xpath=/html/body/div[1]/button"); assertTrue(webtest.isTextPresent("查询")); } @Test(description="18.订单管理的取消/拒收订单列表里根据订单编号100000003查询订单详情") public void test7() throws Exception { webtest.leaveFrame(); //点击取消/拒收订单 webtest.click("xpath=//*[@id=\"wst-accordion-35\"]/div[2]/a[4]"); webtest.enterFrame("wst-lframe-35"); webtest.type("id=orderNo","100000014"); Thread.sleep(2000); webtest.click("xpath=//*[@id=\"orderStatus\"]/option[2]"); webtest.click("xpath=//*[@id=\"payType\"]/option[3]"); webtest.click("xpath=/html/body/div[1]/button"); assertTrue(webtest.isTextPresent("查询")); } @Test(description="19.订单管理的取消/拒收订单列表里根据订单编号查询(查不到的情况)(货到付款选成自提或者输入一个根本不存在的订单号)") public void test8() throws Exception { //登录后台 Thread.sleep(2000); webtest.click("xpath=//*[@id=\"orderStatus\"]/option[2]"); webtest.click("xpath=//*[@id=\"payType\"]/option[2]"); webtest.click("xpath=/html/body/div[1]/button"); assertTrue(webtest.isTextPresent("查询")); } }
5,163
0.681418
0.637616
123
35.008129
22.951874
82
false
false
0
0
0
0
0
0
2.666667
false
false
4
81a8c257ac7703ef3e0923ad45b65d98a51be281
13,262,859,010,561
0b6d887a9b0eb90a822eef4ec8d274cb58610560
/aula0910 - aula 8 e 9/src/br/com/prog3/aula0910/nestedClass/Mensagem.java
afdee0c527b5941ea5508f6cdae676622c882a83
[]
no_license
sknyx/PC3
https://github.com/sknyx/PC3
5aeb9c17bc238f6013405709c0f1d88f2fdde35a
b45d89d9a9d7591f56c063f464be3339bf46b060
refs/heads/master
2020-03-13T15:51:45.494000
2018-04-26T17:03:50
2018-04-26T17:03:50
131,185,644
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package br.com.prog3.aula0910.nestedClass; public interface Mensagem { String retornarMensagem(); }
UTF-8
Java
109
java
Mensagem.java
Java
[]
null
[]
package br.com.prog3.aula0910.nestedClass; public interface Mensagem { String retornarMensagem(); }
109
0.743119
0.697248
6
16.166666
16.607395
42
false
false
0
0
0
0
0
0
0.5
false
false
4
8b8a6cbec3061aad229389b84e3a26d918b49ea2
32,547,262,172,996
12c8bbf7ff0e32b167ecc38a770368cfc6a94c0b
/isoft-core/src/main/java/com/isoftframework/common/page/pageInfo/HibernatePageInfo.java
33e9cd3e4b7ff99fd93f6e98dbd9346ee1bde80f
[]
no_license
wangzhengquan/isoft
https://github.com/wangzhengquan/isoft
9b7805f3537a193f4158f63f33e9fa6c57dbfc13
6852257ad13e7f82f88a5643b9b91ae9bc192dc6
refs/heads/master
2020-05-21T22:22:52.241000
2018-07-11T04:25:49
2018-07-11T04:25:49
21,271,849
1
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.isoftframework.common.page.pageInfo; /* * Created on 2005-6-20 */ import java.util.List; import com.isoftframework.service.IOrmService; public class HibernatePageInfo extends AbstractPageInfo { public static final String ORDER_BY_REGEX="(?i)order\\s+by(?-i)"; public static final String ORDER_BY="ORDER BY"; public static final String FROM_REGEX="(?i)from(?-i)"; public static final String FROM="FROM"; IOrmService service=null; public HibernatePageInfo(IOrmService service){ super(); this.service=service; } public HibernatePageInfo(IOrmService service,int curPage,int pageSize ) { super(pageSize); this.service=service; } public String generateCountSql(final String querySql){ return ( "select count(*) as count "+processQuerySqlForCount(querySql)); //this.countSql ="select count(T) from("+querySql+")T"; } private String processQuerySqlForCount(final String querySql){ String sql=querySql.replaceAll(FROM_REGEX, FROM); sql = querySql.substring(sql.indexOf(FROM)); //sql=RegexUtil.regexReplace(sql, ORDER_BY_REGEX, ORDER_BY); sql=sql.replaceAll(ORDER_BY_REGEX, ORDER_BY); int orderIdx=sql.lastIndexOf(ORDER_BY); if(orderIdx>-1){ sql=sql.substring(0,orderIdx); } return sql; } @Override public long computeTotalSize(String countSql) throws Exception { return (Long) service.findUnique(countSql ); } @Override public List queryWithLimit(String querySql, long start, int limit,Class clas) throws Exception { return service.findWithLimit(querySql,start,limit); } }
UTF-8
Java
1,573
java
HibernatePageInfo.java
Java
[]
null
[]
package com.isoftframework.common.page.pageInfo; /* * Created on 2005-6-20 */ import java.util.List; import com.isoftframework.service.IOrmService; public class HibernatePageInfo extends AbstractPageInfo { public static final String ORDER_BY_REGEX="(?i)order\\s+by(?-i)"; public static final String ORDER_BY="ORDER BY"; public static final String FROM_REGEX="(?i)from(?-i)"; public static final String FROM="FROM"; IOrmService service=null; public HibernatePageInfo(IOrmService service){ super(); this.service=service; } public HibernatePageInfo(IOrmService service,int curPage,int pageSize ) { super(pageSize); this.service=service; } public String generateCountSql(final String querySql){ return ( "select count(*) as count "+processQuerySqlForCount(querySql)); //this.countSql ="select count(T) from("+querySql+")T"; } private String processQuerySqlForCount(final String querySql){ String sql=querySql.replaceAll(FROM_REGEX, FROM); sql = querySql.substring(sql.indexOf(FROM)); //sql=RegexUtil.regexReplace(sql, ORDER_BY_REGEX, ORDER_BY); sql=sql.replaceAll(ORDER_BY_REGEX, ORDER_BY); int orderIdx=sql.lastIndexOf(ORDER_BY); if(orderIdx>-1){ sql=sql.substring(0,orderIdx); } return sql; } @Override public long computeTotalSize(String countSql) throws Exception { return (Long) service.findUnique(countSql ); } @Override public List queryWithLimit(String querySql, long start, int limit,Class clas) throws Exception { return service.findWithLimit(querySql,start,limit); } }
1,573
0.732359
0.726637
64
23.59375
25.931231
97
false
false
0
0
0
0
0
0
1.65625
false
false
4
0e65bc013044360a5eacbe25851191798bee9cb5
68,719,514,797
52c8226b26fdf0e12f4c72ae031db109929bfff3
/前后端分离实现登录/server/src/main/java/com/wg/po/SysUser.java
07a2774c6368e378785056b1f0987d7caeb308cf
[]
no_license
bdqx007/springboot_vue_demo
https://github.com/bdqx007/springboot_vue_demo
f82e84cde54ce5d8d159b297b7bfdb185951294f
5a9e1a531b9b4fa3125a8276a47341616625117d
refs/heads/master
2020-09-22T15:13:03.108000
2019-12-11T07:13:51
2019-12-11T07:13:51
225,254,968
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.wg.po; import lombok.Data; import java.io.Serializable; import java.util.Date; @Data public class SysUser implements Serializable { private Long id; private String nickName; private String userName; private String password; private Integer userType; private Date creatTime; private Integer logicState; }
UTF-8
Java
357
java
SysUser.java
Java
[ { "context": "\n\n private String nickName;\n\n private String userName;\n\n private String password;\n\n private Integ", "end": 226, "score": 0.9894200563430786, "start": 218, "tag": "USERNAME", "value": "userName" } ]
null
[]
package com.wg.po; import lombok.Data; import java.io.Serializable; import java.util.Date; @Data public class SysUser implements Serializable { private Long id; private String nickName; private String userName; private String password; private Integer userType; private Date creatTime; private Integer logicState; }
357
0.722689
0.722689
28
11.785714
14.000911
46
false
false
0
0
0
0
0
0
0.392857
false
false
4
e78ef2bb19fc48257272f156684932a68004dc1c
22,574,348,112,080
ad64cbf06ad17da1d0379fdbacac887936d2c4e2
/src/main/java/com/billybyte/ui/messagerboxes/MessageBoxLooper.java
b928a7d7b3592ef89f3962f515bfd084668099f9
[ "MIT" ]
permissive
bgithub1/common-libs
https://github.com/bgithub1/common-libs
1b54a7849033a7f6ce9f57b3e35f3e2fd787a692
30bd6ddad880cd3da7d946ccb921d83352a2be8c
refs/heads/master
2020-12-28T19:23:39.310000
2016-01-13T02:10:44
2016-01-13T02:10:44
19,353,256
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.billybyte.ui.messagerboxes; import java.util.concurrent.TimeUnit; import javax.swing.JFrame; import com.billybyte.commonstaticmethods.Utils; /** * Loop to feed a }@code QueryInterface<String,String>} stuff to process * @author bperlman1 * */ public class MessageBoxLooper{ public interface MessageBoxLooperCallBack{ public String processResponse(String msgBoxResponse); } private final JFrame jframe = new JFrame(); private final MessageBoxLooperCallBack callBack; private final String title; private final String initialMessageToDisplay; private final boolean useConsole; /** * * @param callBack MessageBoxLooperCallBack which process message box response * @param timeoutValue - timeout for the query * @param timeoutType - timeoutType * @param title - title to be displayed in MessageBox * @param initialMessageToDisplay - initial contents of MessageBox entry area */ public MessageBoxLooper( MessageBoxLooperCallBack callBack, int timeoutValue,TimeUnit timeoutType, String title, String initialMessageToDisplay){ this.callBack = callBack; this.title = title; this.initialMessageToDisplay = initialMessageToDisplay; this.useConsole=false; } /** * * @param query - any query that you want to repeating execute * @param timeoutValue - timeout for the query * @param timeoutType - timeoutType * @param title - title to be displayed in MessageBox * @param initialMessageToDisplay - initial contents of MessageBox entry area */ public MessageBoxLooper( MessageBoxLooperCallBack callBack, String title, String initialMessageToDisplay, boolean useConsole){ this.callBack = callBack; this.title = title; this.initialMessageToDisplay = initialMessageToDisplay; this.useConsole = useConsole; } public void loop(){ String messageToDisplay = initialMessageToDisplay; String response= ""; while(true){ if(this.useConsole){ response = MessageBox.ConsoleMessage(title+" : " + messageToDisplay + " ->"); }else{ response = MessageBox.MessageBoxNoChoices(jframe, messageToDisplay, title, response); } if(response.compareTo(" ")<=0){ break; } messageToDisplay = callBack.processResponse(response); } Utils.prtObMess(this.getClass()," EXECUTED ALL REQUESTS. EXITING NOW"); } }
UTF-8
Java
2,334
java
MessageBoxLooper.java
Java
[ { "context": "erface<String,String>} stuff to process\n * @author bperlman1\n *\n */\npublic class MessageBoxLooper{\n\tpublic int", "end": 254, "score": 0.9996036887168884, "start": 245, "tag": "USERNAME", "value": "bperlman1" } ]
null
[]
package com.billybyte.ui.messagerboxes; import java.util.concurrent.TimeUnit; import javax.swing.JFrame; import com.billybyte.commonstaticmethods.Utils; /** * Loop to feed a }@code QueryInterface<String,String>} stuff to process * @author bperlman1 * */ public class MessageBoxLooper{ public interface MessageBoxLooperCallBack{ public String processResponse(String msgBoxResponse); } private final JFrame jframe = new JFrame(); private final MessageBoxLooperCallBack callBack; private final String title; private final String initialMessageToDisplay; private final boolean useConsole; /** * * @param callBack MessageBoxLooperCallBack which process message box response * @param timeoutValue - timeout for the query * @param timeoutType - timeoutType * @param title - title to be displayed in MessageBox * @param initialMessageToDisplay - initial contents of MessageBox entry area */ public MessageBoxLooper( MessageBoxLooperCallBack callBack, int timeoutValue,TimeUnit timeoutType, String title, String initialMessageToDisplay){ this.callBack = callBack; this.title = title; this.initialMessageToDisplay = initialMessageToDisplay; this.useConsole=false; } /** * * @param query - any query that you want to repeating execute * @param timeoutValue - timeout for the query * @param timeoutType - timeoutType * @param title - title to be displayed in MessageBox * @param initialMessageToDisplay - initial contents of MessageBox entry area */ public MessageBoxLooper( MessageBoxLooperCallBack callBack, String title, String initialMessageToDisplay, boolean useConsole){ this.callBack = callBack; this.title = title; this.initialMessageToDisplay = initialMessageToDisplay; this.useConsole = useConsole; } public void loop(){ String messageToDisplay = initialMessageToDisplay; String response= ""; while(true){ if(this.useConsole){ response = MessageBox.ConsoleMessage(title+" : " + messageToDisplay + " ->"); }else{ response = MessageBox.MessageBoxNoChoices(jframe, messageToDisplay, title, response); } if(response.compareTo(" ")<=0){ break; } messageToDisplay = callBack.processResponse(response); } Utils.prtObMess(this.getClass()," EXECUTED ALL REQUESTS. EXITING NOW"); } }
2,334
0.742502
0.741645
84
26.785715
23.33456
81
false
false
0
0
0
0
0
0
1.940476
false
false
4
f6cc440a895115867d789f61f4506212d3d3bf39
25,134,148,625,725
f92c6375933f64f9e0c245c00ea9fb93da7804e0
/webgame/src/main/java/com/gumptech/webgame/controller/GameController.java
4b45ab402799b6665957ff4554bf3920dc52f990
[]
no_license
MikeMouse/gt_s_gumpsdk
https://github.com/MikeMouse/gt_s_gumpsdk
25b93853757204bf48700afac3abfd1f5b77dc94
708417dbb4ab3bd23d4da7bae03a9222363eac3b
refs/heads/master
2016-08-12T16:49:41.802000
2016-03-04T07:37:36
2016-03-04T07:37:36
53,644,924
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.gumptech.webgame.controller; import com.gumptech.sdk.model.pay.App; import com.gumptech.sdk.util.HttpClientUtil; import net.sf.json.JSONArray; import net.sf.json.JSONObject; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.util.HashMap; import java.util.Map; /** * Created by Serious on 15/2/4. */ @Controller @RequestMapping("/game") public class GameController extends BaseController{ //角色信息 @RequestMapping("/queryRole") @ResponseBody public Object queryRole(HttpServletRequest request, HttpServletResponse response,@RequestParam long appId,@RequestParam long userId,@RequestParam String serverId)throws Exception{ JSONObject jb = new JSONObject(); App app = appService.getApp(appId); if (null == app) { return jb; } Map<String,String> map = new HashMap<String, String>(); map.put("userId",userId+""); map.put("serverId",serverId); String res = HttpClientUtil.post(app.getQueryRoleUrl(), map).getRight(); jb.put("result", JSONObject.fromObject(res)) ; return jb; } //区服信息 @RequestMapping("/queryServer") @ResponseBody public Object queryServer(HttpServletRequest request, HttpServletResponse response,@RequestParam long appId)throws Exception{ JSONObject jb = new JSONObject(); App app = appService.getApp(appId); if (null == app) { return jb.toString(); } String res = HttpClientUtil.get(app.getQuerySeversUrl()).getRight(); jb.put("result", JSONArray.fromObject(res)) ; return jb; } }
UTF-8
Java
1,917
java
GameController.java
Java
[ { "context": ".HashMap;\nimport java.util.Map;\n\n/**\n * Created by Serious on 15/2/4.\n */\n@Controller\n@RequestMapping(\"/game", "end": 590, "score": 0.9988217353820801, "start": 583, "tag": "USERNAME", "value": "Serious" } ]
null
[]
package com.gumptech.webgame.controller; import com.gumptech.sdk.model.pay.App; import com.gumptech.sdk.util.HttpClientUtil; import net.sf.json.JSONArray; import net.sf.json.JSONObject; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.util.HashMap; import java.util.Map; /** * Created by Serious on 15/2/4. */ @Controller @RequestMapping("/game") public class GameController extends BaseController{ //角色信息 @RequestMapping("/queryRole") @ResponseBody public Object queryRole(HttpServletRequest request, HttpServletResponse response,@RequestParam long appId,@RequestParam long userId,@RequestParam String serverId)throws Exception{ JSONObject jb = new JSONObject(); App app = appService.getApp(appId); if (null == app) { return jb; } Map<String,String> map = new HashMap<String, String>(); map.put("userId",userId+""); map.put("serverId",serverId); String res = HttpClientUtil.post(app.getQueryRoleUrl(), map).getRight(); jb.put("result", JSONObject.fromObject(res)) ; return jb; } //区服信息 @RequestMapping("/queryServer") @ResponseBody public Object queryServer(HttpServletRequest request, HttpServletResponse response,@RequestParam long appId)throws Exception{ JSONObject jb = new JSONObject(); App app = appService.getApp(appId); if (null == app) { return jb.toString(); } String res = HttpClientUtil.get(app.getQuerySeversUrl()).getRight(); jb.put("result", JSONArray.fromObject(res)) ; return jb; } }
1,917
0.704892
0.702788
54
34.203705
31.966059
183
false
false
0
0
0
0
0
0
0.759259
false
false
4
6d063394398acda57f5f0f5ec8a17d55f5cb81e7
18,940,805,781,270
c9f2bbdffe0bc9f9303d68414aea6fe948c3939c
/app/src/main/java/com/example/riya/demoapp2/MainActivity.java
56575101a3c3fae04e5792fac0c1448b4dc6fdda
[]
no_license
riyanagpal24/ImageView
https://github.com/riyanagpal24/ImageView
f7318588ea945d115b603116d9f8a1acb2e63749
58622e16b6718866c23f1cc2fa30e949a9c8093f
refs/heads/master
2020-03-07T05:19:51.833000
2018-03-30T06:57:57
2018-03-30T06:57:57
127,292,699
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.riya.demoapp2; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.ImageView; public class MainActivity extends AppCompatActivity { ImageView image; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); image = (ImageView) findViewById(R.id.imageView); } public void fade(View view) { image.animate().rotation(360).scaleX(0.5f).scaleY(0.5f).setDuration(3000); //image.animate().alpha(0f).setDuration(2000); //image.setImageResource(R.drawable.img2); } }
UTF-8
Java
709
java
MainActivity.java
Java
[ { "context": "package com.example.riya.demoapp2;\n\nimport android.support.v7.app.AppCompa", "end": 24, "score": 0.9425860643386841, "start": 20, "tag": "USERNAME", "value": "riya" } ]
null
[]
package com.example.riya.demoapp2; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.ImageView; public class MainActivity extends AppCompatActivity { ImageView image; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); image = (ImageView) findViewById(R.id.imageView); } public void fade(View view) { image.animate().rotation(360).scaleX(0.5f).scaleY(0.5f).setDuration(3000); //image.animate().alpha(0f).setDuration(2000); //image.setImageResource(R.drawable.img2); } }
709
0.70945
0.682652
26
26.26923
23.933495
82
false
false
0
0
0
0
0
0
0.461538
false
false
4
d688a6d416ae5056c7623c2655e51dc536d19694
11,081,015,669,987
7dd813442860db04f571b6a5442deaa9e03b3a80
/hzaction-master/src/main/java/com/action/actbase/entity/BasCustomerContactsEntity.java
be4d5afbc6f9fd0f643b0836a58649fafc362d17
[]
no_license
rubymatlab/hzaction
https://github.com/rubymatlab/hzaction
5761d89741d3a7d2f7922a5e3a79da2626760de9
1786e0378c00e9898dbd4adc344129ba39bde579
refs/heads/master
2022-12-25T23:47:20.872000
2020-04-02T14:08:02
2020-04-02T14:08:02
199,416,376
2
1
null
false
2022-12-16T04:25:05
2019-07-29T08:57:42
2020-04-02T14:08:17
2022-12-16T04:25:05
49,172
1
1
18
JavaScript
false
false
package com.action.actbase.entity; import java.math.BigDecimal; import java.util.Date; import java.lang.String; import java.lang.Double; import java.lang.Integer; import java.math.BigDecimal; import javax.xml.soap.Text; import java.sql.Blob; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; import org.hibernate.annotations.GenericGenerator; import javax.persistence.SequenceGenerator; import org.jeecgframework.poi.excel.annotation.Excel; /** * @Title: Entity * @Description: 客户资料明细 * @author onlineGenerator * @date 2019-07-18 23:41:34 * @version V1.0 * */ @Entity @Table(name = "bas_customer_contacts", schema = "") @SuppressWarnings("serial") public class BasCustomerContactsEntity implements java.io.Serializable { /**主键*/ private java.lang.String id; /**姓名*/ @Excel(name="姓名",width=15) private java.lang.String bccName; /**部门*/ @Excel(name="部门",width=15) private java.lang.String bccDept; /**职务*/ @Excel(name="职务",width=15) private java.lang.String bccPost; /**电话*/ @Excel(name="电话",width=15) private java.lang.String bccTel; /**备注*/ @Excel(name="备注",width=15) private java.lang.String bcRemark; /**客户资料外键*/ // @Excel(name="客户资料外键",width=15) private java.lang.String fromId; /**创建人名称*/ private java.lang.String createName; /**创建人登录名称*/ private java.lang.String createBy; /**创建日期*/ private java.util.Date createDate; /**更新人名称*/ private java.lang.String updateName; /**更新人登录名称*/ private java.lang.String updateBy; /**更新日期*/ private java.util.Date updateDate; /**所属部门*/ private java.lang.String sysOrgCode; /**所属公司*/ private java.lang.String sysCompanyCode; /**流程状态*/ private java.lang.String bpmStatus; /** *方法: 取得java.lang.String *@return: java.lang.String 主键 */ @Id @GeneratedValue(generator = "paymentableGenerator") @GenericGenerator(name = "paymentableGenerator", strategy = "uuid") @Column(name ="ID",nullable=false,length=36) public java.lang.String getId(){ return this.id; } /** *方法: 设置java.lang.String *@param: java.lang.String 主键 */ public void setId(java.lang.String id){ this.id = id; } /** *方法: 取得java.lang.String *@return: java.lang.String 姓名 */ @Column(name ="BCC_NAME",nullable=true,length=32) public java.lang.String getBccName(){ return this.bccName; } /** *方法: 设置java.lang.String *@param: java.lang.String 姓名 */ public void setBccName(java.lang.String bccName){ this.bccName = bccName; } /** *方法: 取得java.lang.String *@return: java.lang.String 部门 */ @Column(name ="BCC_DEPT",nullable=true,length=32) public java.lang.String getBccDept(){ return this.bccDept; } /** *方法: 设置java.lang.String *@param: java.lang.String 部门 */ public void setBccDept(java.lang.String bccDept){ this.bccDept = bccDept; } /** *方法: 取得java.lang.String *@return: java.lang.String 职务 */ @Column(name ="BCC_POST",nullable=true,length=32) public java.lang.String getBccPost(){ return this.bccPost; } /** *方法: 设置java.lang.String *@param: java.lang.String 职务 */ public void setBccPost(java.lang.String bccPost){ this.bccPost = bccPost; } /** *方法: 取得java.lang.String *@return: java.lang.String 电话 */ @Column(name ="BCC_TEL",nullable=true,length=32) public java.lang.String getBccTel(){ return this.bccTel; } /** *方法: 设置java.lang.String *@param: java.lang.String 电话 */ public void setBccTel(java.lang.String bccTel){ this.bccTel = bccTel; } /** *方法: 取得java.lang.String *@return: java.lang.String 备注 */ @Column(name ="BC_REMARK",nullable=true,length=32) public java.lang.String getBcRemark(){ return this.bcRemark; } /** *方法: 设置java.lang.String *@param: java.lang.String 备注 */ public void setBcRemark(java.lang.String bcRemark){ this.bcRemark = bcRemark; } /** *方法: 取得java.lang.String *@return: java.lang.String 客户资料外键 */ @Column(name ="FROM_ID",nullable=true,length=36) public java.lang.String getFromId(){ return this.fromId; } /** *方法: 设置java.lang.String *@param: java.lang.String 客户资料外键 */ public void setFromId(java.lang.String fromId){ this.fromId = fromId; } /** *方法: 取得java.lang.String *@return: java.lang.String 创建人名称 */ @Column(name ="CREATE_NAME",nullable=true,length=50) public java.lang.String getCreateName(){ return this.createName; } /** *方法: 设置java.lang.String *@param: java.lang.String 创建人名称 */ public void setCreateName(java.lang.String createName){ this.createName = createName; } /** *方法: 取得java.lang.String *@return: java.lang.String 创建人登录名称 */ @Column(name ="CREATE_BY",nullable=true,length=50) public java.lang.String getCreateBy(){ return this.createBy; } /** *方法: 设置java.lang.String *@param: java.lang.String 创建人登录名称 */ public void setCreateBy(java.lang.String createBy){ this.createBy = createBy; } /** *方法: 取得java.util.Date *@return: java.util.Date 创建日期 */ @Column(name ="CREATE_DATE",nullable=true,length=20) public java.util.Date getCreateDate(){ return this.createDate; } /** *方法: 设置java.util.Date *@param: java.util.Date 创建日期 */ public void setCreateDate(java.util.Date createDate){ this.createDate = createDate; } /** *方法: 取得java.lang.String *@return: java.lang.String 更新人名称 */ @Column(name ="UPDATE_NAME",nullable=true,length=50) public java.lang.String getUpdateName(){ return this.updateName; } /** *方法: 设置java.lang.String *@param: java.lang.String 更新人名称 */ public void setUpdateName(java.lang.String updateName){ this.updateName = updateName; } /** *方法: 取得java.lang.String *@return: java.lang.String 更新人登录名称 */ @Column(name ="UPDATE_BY",nullable=true,length=50) public java.lang.String getUpdateBy(){ return this.updateBy; } /** *方法: 设置java.lang.String *@param: java.lang.String 更新人登录名称 */ public void setUpdateBy(java.lang.String updateBy){ this.updateBy = updateBy; } /** *方法: 取得java.util.Date *@return: java.util.Date 更新日期 */ @Column(name ="UPDATE_DATE",nullable=true,length=20) public java.util.Date getUpdateDate(){ return this.updateDate; } /** *方法: 设置java.util.Date *@param: java.util.Date 更新日期 */ public void setUpdateDate(java.util.Date updateDate){ this.updateDate = updateDate; } /** *方法: 取得java.lang.String *@return: java.lang.String 所属部门 */ @Column(name ="SYS_ORG_CODE",nullable=true,length=50) public java.lang.String getSysOrgCode(){ return this.sysOrgCode; } /** *方法: 设置java.lang.String *@param: java.lang.String 所属部门 */ public void setSysOrgCode(java.lang.String sysOrgCode){ this.sysOrgCode = sysOrgCode; } /** *方法: 取得java.lang.String *@return: java.lang.String 所属公司 */ @Column(name ="SYS_COMPANY_CODE",nullable=true,length=50) public java.lang.String getSysCompanyCode(){ return this.sysCompanyCode; } /** *方法: 设置java.lang.String *@param: java.lang.String 所属公司 */ public void setSysCompanyCode(java.lang.String sysCompanyCode){ this.sysCompanyCode = sysCompanyCode; } /** *方法: 取得java.lang.String *@return: java.lang.String 流程状态 */ @Column(name ="BPM_STATUS",nullable=true,length=32) public java.lang.String getBpmStatus(){ return this.bpmStatus; } /** *方法: 设置java.lang.String *@param: java.lang.String 流程状态 */ public void setBpmStatus(java.lang.String bpmStatus){ this.bpmStatus = bpmStatus; } }
UTF-8
Java
8,207
java
BasCustomerContactsEntity.java
Java
[ { "context": " @Title: Entity\n * @Description: 客户资料明细\n * @author onlineGenerator\n * @date 2019-07-18 23:41:34\n * @version V1.0 \n", "end": 676, "score": 0.9990413188934326, "start": 661, "tag": "USERNAME", "value": "onlineGenerator" } ]
null
[]
package com.action.actbase.entity; import java.math.BigDecimal; import java.util.Date; import java.lang.String; import java.lang.Double; import java.lang.Integer; import java.math.BigDecimal; import javax.xml.soap.Text; import java.sql.Blob; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; import org.hibernate.annotations.GenericGenerator; import javax.persistence.SequenceGenerator; import org.jeecgframework.poi.excel.annotation.Excel; /** * @Title: Entity * @Description: 客户资料明细 * @author onlineGenerator * @date 2019-07-18 23:41:34 * @version V1.0 * */ @Entity @Table(name = "bas_customer_contacts", schema = "") @SuppressWarnings("serial") public class BasCustomerContactsEntity implements java.io.Serializable { /**主键*/ private java.lang.String id; /**姓名*/ @Excel(name="姓名",width=15) private java.lang.String bccName; /**部门*/ @Excel(name="部门",width=15) private java.lang.String bccDept; /**职务*/ @Excel(name="职务",width=15) private java.lang.String bccPost; /**电话*/ @Excel(name="电话",width=15) private java.lang.String bccTel; /**备注*/ @Excel(name="备注",width=15) private java.lang.String bcRemark; /**客户资料外键*/ // @Excel(name="客户资料外键",width=15) private java.lang.String fromId; /**创建人名称*/ private java.lang.String createName; /**创建人登录名称*/ private java.lang.String createBy; /**创建日期*/ private java.util.Date createDate; /**更新人名称*/ private java.lang.String updateName; /**更新人登录名称*/ private java.lang.String updateBy; /**更新日期*/ private java.util.Date updateDate; /**所属部门*/ private java.lang.String sysOrgCode; /**所属公司*/ private java.lang.String sysCompanyCode; /**流程状态*/ private java.lang.String bpmStatus; /** *方法: 取得java.lang.String *@return: java.lang.String 主键 */ @Id @GeneratedValue(generator = "paymentableGenerator") @GenericGenerator(name = "paymentableGenerator", strategy = "uuid") @Column(name ="ID",nullable=false,length=36) public java.lang.String getId(){ return this.id; } /** *方法: 设置java.lang.String *@param: java.lang.String 主键 */ public void setId(java.lang.String id){ this.id = id; } /** *方法: 取得java.lang.String *@return: java.lang.String 姓名 */ @Column(name ="BCC_NAME",nullable=true,length=32) public java.lang.String getBccName(){ return this.bccName; } /** *方法: 设置java.lang.String *@param: java.lang.String 姓名 */ public void setBccName(java.lang.String bccName){ this.bccName = bccName; } /** *方法: 取得java.lang.String *@return: java.lang.String 部门 */ @Column(name ="BCC_DEPT",nullable=true,length=32) public java.lang.String getBccDept(){ return this.bccDept; } /** *方法: 设置java.lang.String *@param: java.lang.String 部门 */ public void setBccDept(java.lang.String bccDept){ this.bccDept = bccDept; } /** *方法: 取得java.lang.String *@return: java.lang.String 职务 */ @Column(name ="BCC_POST",nullable=true,length=32) public java.lang.String getBccPost(){ return this.bccPost; } /** *方法: 设置java.lang.String *@param: java.lang.String 职务 */ public void setBccPost(java.lang.String bccPost){ this.bccPost = bccPost; } /** *方法: 取得java.lang.String *@return: java.lang.String 电话 */ @Column(name ="BCC_TEL",nullable=true,length=32) public java.lang.String getBccTel(){ return this.bccTel; } /** *方法: 设置java.lang.String *@param: java.lang.String 电话 */ public void setBccTel(java.lang.String bccTel){ this.bccTel = bccTel; } /** *方法: 取得java.lang.String *@return: java.lang.String 备注 */ @Column(name ="BC_REMARK",nullable=true,length=32) public java.lang.String getBcRemark(){ return this.bcRemark; } /** *方法: 设置java.lang.String *@param: java.lang.String 备注 */ public void setBcRemark(java.lang.String bcRemark){ this.bcRemark = bcRemark; } /** *方法: 取得java.lang.String *@return: java.lang.String 客户资料外键 */ @Column(name ="FROM_ID",nullable=true,length=36) public java.lang.String getFromId(){ return this.fromId; } /** *方法: 设置java.lang.String *@param: java.lang.String 客户资料外键 */ public void setFromId(java.lang.String fromId){ this.fromId = fromId; } /** *方法: 取得java.lang.String *@return: java.lang.String 创建人名称 */ @Column(name ="CREATE_NAME",nullable=true,length=50) public java.lang.String getCreateName(){ return this.createName; } /** *方法: 设置java.lang.String *@param: java.lang.String 创建人名称 */ public void setCreateName(java.lang.String createName){ this.createName = createName; } /** *方法: 取得java.lang.String *@return: java.lang.String 创建人登录名称 */ @Column(name ="CREATE_BY",nullable=true,length=50) public java.lang.String getCreateBy(){ return this.createBy; } /** *方法: 设置java.lang.String *@param: java.lang.String 创建人登录名称 */ public void setCreateBy(java.lang.String createBy){ this.createBy = createBy; } /** *方法: 取得java.util.Date *@return: java.util.Date 创建日期 */ @Column(name ="CREATE_DATE",nullable=true,length=20) public java.util.Date getCreateDate(){ return this.createDate; } /** *方法: 设置java.util.Date *@param: java.util.Date 创建日期 */ public void setCreateDate(java.util.Date createDate){ this.createDate = createDate; } /** *方法: 取得java.lang.String *@return: java.lang.String 更新人名称 */ @Column(name ="UPDATE_NAME",nullable=true,length=50) public java.lang.String getUpdateName(){ return this.updateName; } /** *方法: 设置java.lang.String *@param: java.lang.String 更新人名称 */ public void setUpdateName(java.lang.String updateName){ this.updateName = updateName; } /** *方法: 取得java.lang.String *@return: java.lang.String 更新人登录名称 */ @Column(name ="UPDATE_BY",nullable=true,length=50) public java.lang.String getUpdateBy(){ return this.updateBy; } /** *方法: 设置java.lang.String *@param: java.lang.String 更新人登录名称 */ public void setUpdateBy(java.lang.String updateBy){ this.updateBy = updateBy; } /** *方法: 取得java.util.Date *@return: java.util.Date 更新日期 */ @Column(name ="UPDATE_DATE",nullable=true,length=20) public java.util.Date getUpdateDate(){ return this.updateDate; } /** *方法: 设置java.util.Date *@param: java.util.Date 更新日期 */ public void setUpdateDate(java.util.Date updateDate){ this.updateDate = updateDate; } /** *方法: 取得java.lang.String *@return: java.lang.String 所属部门 */ @Column(name ="SYS_ORG_CODE",nullable=true,length=50) public java.lang.String getSysOrgCode(){ return this.sysOrgCode; } /** *方法: 设置java.lang.String *@param: java.lang.String 所属部门 */ public void setSysOrgCode(java.lang.String sysOrgCode){ this.sysOrgCode = sysOrgCode; } /** *方法: 取得java.lang.String *@return: java.lang.String 所属公司 */ @Column(name ="SYS_COMPANY_CODE",nullable=true,length=50) public java.lang.String getSysCompanyCode(){ return this.sysCompanyCode; } /** *方法: 设置java.lang.String *@param: java.lang.String 所属公司 */ public void setSysCompanyCode(java.lang.String sysCompanyCode){ this.sysCompanyCode = sysCompanyCode; } /** *方法: 取得java.lang.String *@return: java.lang.String 流程状态 */ @Column(name ="BPM_STATUS",nullable=true,length=32) public java.lang.String getBpmStatus(){ return this.bpmStatus; } /** *方法: 设置java.lang.String *@param: java.lang.String 流程状态 */ public void setBpmStatus(java.lang.String bpmStatus){ this.bpmStatus = bpmStatus; } }
8,207
0.686264
0.678301
362
19.814917
17.507267
72
false
false
0
0
0
0
0
0
1.248619
false
false
4
86fcd9bcf562b9c7c3ce072707fbffbcf067f4d6
6,975,026,896,081
b18641254e6b0f1b413a7d5cf855565085bd2d0b
/maven-swing-component/src/main/java/Main.java
9a3acc1992e8e0373edfb08311b41118a5abd35f
[ "MIT" ]
permissive
alexscheitlin/caesar-intellij-plugin
https://github.com/alexscheitlin/caesar-intellij-plugin
5f2d7ad527cadcd765ae3864f6f18ff0e4dedb35
ec85624cc21a36bdb8d8b7f910377b223986b98a
refs/heads/master
2020-03-24T14:15:46.111000
2018-09-06T17:43:18
2018-09-06T17:43:18
142,763,727
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import ch.scheitlin.alex.maven.*; import javax.swing.*; import java.awt.*; import java.util.ArrayList; import java.util.List; public class Main { static boolean darkTheme = true; public static void main(String[] args) { MavenBuild mavenBuild = getDummyData(); // create new maven swing component MavenPanel mavenPanel = new MavenPanel(mavenBuild, darkTheme); mavenPanel.setFont(new Font("Courier", Font.BOLD, 20)); mavenPanel.setBackground(Color.darkGray); // create frame and add error components JFrame frame = new JFrame(); frame.setLayout(new GridBagLayout()); GridBagConstraints c = new GridBagConstraints(); c.fill = GridBagConstraints.BOTH; c.gridx = 0; c.gridy = 0; c.weightx = 1.0; c.weighty = 1.0; frame.add(mavenPanel, c); frame.setSize(new Dimension(800, 800)); if (darkTheme) { Color dark = Color.darkGray; frame.setBackground(dark); } // set look and feel of frame try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (Exception ex) { } // show frame frame.setVisible(true); } private static MavenBuild getDummyData() { MavenModuleBuildStatus[] moduleStatus = { MavenModuleBuildStatus.SUCCESS, MavenModuleBuildStatus.SUCCESS, MavenModuleBuildStatus.SUCCESS, MavenModuleBuildStatus.SUCCESS, MavenModuleBuildStatus.FAILURE, MavenModuleBuildStatus.SKIPPED, MavenModuleBuildStatus.SKIPPED, }; int[] goalsPerModule = { 6, 3, 3, 7, 12, 0, 0, }; return getDummyMavenBuild(MavenBuildStatus.FAILURE, moduleStatus, goalsPerModule); } private static MavenBuild getDummyMavenBuild(MavenBuildStatus buildStatus, MavenModuleBuildStatus[] moduleStatus, int[] goalsPerModule) { MavenBuild mavenBuild = new MavenBuild(buildStatus, null, null, null); List<MavenModule> mavenModules = new ArrayList<>(); for (int i = 0; i < moduleStatus.length; i++) { mavenModules.add(getDummyMavenModule(i + 1, moduleStatus[i], goalsPerModule[i])); } mavenBuild.setModules(mavenModules); return mavenBuild; } private static MavenModule getDummyMavenModule(int moduleNumber, MavenModuleBuildStatus moduleStatus, int numberOfGoals) { MavenModule mavenModule = new MavenModule("Module " + moduleNumber); mavenModule.setStatus(moduleStatus); for (int i = 0; i < numberOfGoals; i++) { mavenModule.addGoal(getDummyMavenGoal(i + 1, 5 + i * 2)); } return mavenModule; } private static MavenGoal getDummyMavenGoal(int goalNumber, int numberOfLogLines) { MavenGoal mavenGoal = new MavenGoal(); mavenGoal.setName("Goal " + goalNumber); for (int i = 0; i < numberOfLogLines; i++) { mavenGoal.addLine(i + 1 + ": Goal " + goalNumber); } return mavenGoal; } }
UTF-8
Java
3,414
java
Main.java
Java
[]
null
[]
import ch.scheitlin.alex.maven.*; import javax.swing.*; import java.awt.*; import java.util.ArrayList; import java.util.List; public class Main { static boolean darkTheme = true; public static void main(String[] args) { MavenBuild mavenBuild = getDummyData(); // create new maven swing component MavenPanel mavenPanel = new MavenPanel(mavenBuild, darkTheme); mavenPanel.setFont(new Font("Courier", Font.BOLD, 20)); mavenPanel.setBackground(Color.darkGray); // create frame and add error components JFrame frame = new JFrame(); frame.setLayout(new GridBagLayout()); GridBagConstraints c = new GridBagConstraints(); c.fill = GridBagConstraints.BOTH; c.gridx = 0; c.gridy = 0; c.weightx = 1.0; c.weighty = 1.0; frame.add(mavenPanel, c); frame.setSize(new Dimension(800, 800)); if (darkTheme) { Color dark = Color.darkGray; frame.setBackground(dark); } // set look and feel of frame try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (Exception ex) { } // show frame frame.setVisible(true); } private static MavenBuild getDummyData() { MavenModuleBuildStatus[] moduleStatus = { MavenModuleBuildStatus.SUCCESS, MavenModuleBuildStatus.SUCCESS, MavenModuleBuildStatus.SUCCESS, MavenModuleBuildStatus.SUCCESS, MavenModuleBuildStatus.FAILURE, MavenModuleBuildStatus.SKIPPED, MavenModuleBuildStatus.SKIPPED, }; int[] goalsPerModule = { 6, 3, 3, 7, 12, 0, 0, }; return getDummyMavenBuild(MavenBuildStatus.FAILURE, moduleStatus, goalsPerModule); } private static MavenBuild getDummyMavenBuild(MavenBuildStatus buildStatus, MavenModuleBuildStatus[] moduleStatus, int[] goalsPerModule) { MavenBuild mavenBuild = new MavenBuild(buildStatus, null, null, null); List<MavenModule> mavenModules = new ArrayList<>(); for (int i = 0; i < moduleStatus.length; i++) { mavenModules.add(getDummyMavenModule(i + 1, moduleStatus[i], goalsPerModule[i])); } mavenBuild.setModules(mavenModules); return mavenBuild; } private static MavenModule getDummyMavenModule(int moduleNumber, MavenModuleBuildStatus moduleStatus, int numberOfGoals) { MavenModule mavenModule = new MavenModule("Module " + moduleNumber); mavenModule.setStatus(moduleStatus); for (int i = 0; i < numberOfGoals; i++) { mavenModule.addGoal(getDummyMavenGoal(i + 1, 5 + i * 2)); } return mavenModule; } private static MavenGoal getDummyMavenGoal(int goalNumber, int numberOfLogLines) { MavenGoal mavenGoal = new MavenGoal(); mavenGoal.setName("Goal " + goalNumber); for (int i = 0; i < numberOfLogLines; i++) { mavenGoal.addLine(i + 1 + ": Goal " + goalNumber); } return mavenGoal; } }
3,414
0.608084
0.599297
103
32.14563
29.096561
141
false
false
0
0
0
0
0
0
0.76699
false
false
4
2182b603bedce3718f80f79ea033be335120c6d0
20,882,131,026,683
515baef5dc06bc7313210ad0cb102004dc4eb177
/magent/src/main/java/bg/tusofia/cs/drm/wms/magent/rest/JobQueriesController.java
8ce1f2e200304b4e8219721fe4395e1018ed02ea
[ "Apache-2.0" ]
permissive
iivalchev/drm-wms
https://github.com/iivalchev/drm-wms
afda655cbeadf6d476673a1c63a0b4d844849c96
21c843ff18494ffdb7b1058f88e80ab2ed057d6b
refs/heads/master
2021-01-13T12:58:28.687000
2014-09-11T20:31:22
2014-09-11T20:31:22
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package bg.tusofia.cs.drm.wms.magent.rest; import bg.tusofia.cs.drm.wms.magent.domain.events.JobResourceEvent; import bg.tusofia.cs.drm.wms.magent.domain.events.RequestJobResourceEvent; import bg.tusofia.cs.drm.wms.magent.domain.events.RequestUserJobResourcesEvent; import bg.tusofia.cs.drm.wms.magent.domain.events.UserJobResourcesEvent; import bg.tusofia.cs.drm.wms.magent.service.JobService; import bg.tusofia.cs.drm.wms.resources.JobResource; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import java.util.Collection; /** * Created by Ivan on 6/17/2014. */ @Controller public class JobQueriesController extends AbstractJobController { @RequestMapping(method = RequestMethod.GET, value = "/{id}") public ResponseEntity<JobResource> viewJob(@PathVariable String id) { JobResourceEvent jobResourceEvent = jobService.requestJobResource(new RequestJobResourceEvent(Long.valueOf(id))); ResponseEntity<JobResource> response; if (!jobResourceEvent.isFound()) { response = new ResponseEntity<JobResource>(HttpStatus.NOT_FOUND); } else { response = new ResponseEntity<JobResource>(jobResourceEvent.getJobResource(), HttpStatus.OK); } return response; } @RequestMapping(method = RequestMethod.GET, value = "/user/{userId}") public ResponseEntity<Collection<JobResource>> viewUserJobs(@PathVariable String userId) { UserJobResourcesEvent userJobResourcesEvent = jobService.requestUserJobResources(new RequestUserJobResourcesEvent(userId)); ResponseEntity<Collection<JobResource>> response; if (!userJobResourcesEvent.isFound()) { response = new ResponseEntity<Collection<JobResource>>(HttpStatus.NOT_FOUND); } else { response = new ResponseEntity<Collection<JobResource>>(userJobResourcesEvent.getJobResources(), HttpStatus.OK); } return response; } }
UTF-8
Java
2,264
java
JobQueriesController.java
Java
[ { "context": ";\n\nimport java.util.Collection;\n\n/**\n * Created by Ivan on 6/17/2014.\n */\n@Controller\npublic class JobQue", "end": 892, "score": 0.999254584312439, "start": 888, "tag": "NAME", "value": "Ivan" } ]
null
[]
package bg.tusofia.cs.drm.wms.magent.rest; import bg.tusofia.cs.drm.wms.magent.domain.events.JobResourceEvent; import bg.tusofia.cs.drm.wms.magent.domain.events.RequestJobResourceEvent; import bg.tusofia.cs.drm.wms.magent.domain.events.RequestUserJobResourcesEvent; import bg.tusofia.cs.drm.wms.magent.domain.events.UserJobResourcesEvent; import bg.tusofia.cs.drm.wms.magent.service.JobService; import bg.tusofia.cs.drm.wms.resources.JobResource; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import java.util.Collection; /** * Created by Ivan on 6/17/2014. */ @Controller public class JobQueriesController extends AbstractJobController { @RequestMapping(method = RequestMethod.GET, value = "/{id}") public ResponseEntity<JobResource> viewJob(@PathVariable String id) { JobResourceEvent jobResourceEvent = jobService.requestJobResource(new RequestJobResourceEvent(Long.valueOf(id))); ResponseEntity<JobResource> response; if (!jobResourceEvent.isFound()) { response = new ResponseEntity<JobResource>(HttpStatus.NOT_FOUND); } else { response = new ResponseEntity<JobResource>(jobResourceEvent.getJobResource(), HttpStatus.OK); } return response; } @RequestMapping(method = RequestMethod.GET, value = "/user/{userId}") public ResponseEntity<Collection<JobResource>> viewUserJobs(@PathVariable String userId) { UserJobResourcesEvent userJobResourcesEvent = jobService.requestUserJobResources(new RequestUserJobResourcesEvent(userId)); ResponseEntity<Collection<JobResource>> response; if (!userJobResourcesEvent.isFound()) { response = new ResponseEntity<Collection<JobResource>>(HttpStatus.NOT_FOUND); } else { response = new ResponseEntity<Collection<JobResource>>(userJobResourcesEvent.getJobResources(), HttpStatus.OK); } return response; } }
2,264
0.763251
0.760159
48
46.166668
35.541836
131
false
false
0
0
0
0
0
0
0.604167
false
false
4
5078e8adf2ad227cbf99703f065ee475d4db673a
12,541,304,535,134
ad590a906e76b1b62e6e54db82290df966af4ed5
/Online_BookStore/src/com/suze/web/RegistServlet.java
ab0f8963278f749e852c1d162c9265be4030ccc0
[]
no_license
GreyPencil/Online_bookstore
https://github.com/GreyPencil/Online_bookstore
6bf86961e172b5ed211914d362f6f61fec77301c
8476166040f4cbb2554c9ed48faa52112ecc1627
refs/heads/master
2023-02-21T23:28:19.769000
2021-01-27T03:36:26
2021-01-27T03:36:26
325,915,313
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.suze.web; import com.suze.pojo.User; import com.suze.service.UserService; import com.suze.service.impl.UserServiceImpl; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; /** * @author suzekang * @Description * @create 2021-01-06 10:59 PM */ public class RegistServlet extends HttpServlet { private UserService userService = new UserServiceImpl(); @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String username = req.getParameter("username"); String password = req.getParameter("password"); String email = req.getParameter("email"); String code = req.getParameter("code"); // System.out.println(username); if ("bnbnp".equalsIgnoreCase(code)) { if (userService.existsUsername(username)) { System.out.println("用户名【" + username + "】已存在"); req.setAttribute("msg","Username already exists"); req.setAttribute("username", username); req.setAttribute("email", email); req.getRequestDispatcher("/pages/user/regist.jsp").forward(req, resp); } else { userService.registUser(new User(null, username, password, email)); req.getRequestDispatcher("/pages/user/regist_success.jsp").forward(req, resp); } } else { //把回显信息,保存在request域中 req.setAttribute("msg","Verification code error"); req.setAttribute("username", username); req.setAttribute("email", email); System.out.println(("验证码【" + code + "】错误")); req.getRequestDispatcher("/pages/user/regist.jsp").forward(req, resp); } } }
UTF-8
Java
1,978
java
RegistServlet.java
Java
[ { "context": "ponse;\nimport java.io.IOException;\n\n/**\n * @author suzekang\n * @Description\n * @create 2021-01-06 10:59 PM\n *", "end": 357, "score": 0.9996967315673828, "start": 349, "tag": "USERNAME", "value": "suzekang" }, { "context": "ion {\n String username = req.getParameter(\"username\");\n String password = req.getParameter(\"pa", "end": 702, "score": 0.5380299687385559, "start": 694, "tag": "USERNAME", "value": "username" }, { "context": "ts\");\n req.setAttribute(\"username\", username);\n req.setAttribute(\"email\", email", "end": 1191, "score": 0.8198765516281128, "start": 1183, "tag": "USERNAME", "value": "username" }, { "context": " error\");\n req.setAttribute(\"username\", username);\n req.setAttribute(\"email\", email);\n\n", "end": 1711, "score": 0.8454324007034302, "start": 1703, "tag": "USERNAME", "value": "username" } ]
null
[]
package com.suze.web; import com.suze.pojo.User; import com.suze.service.UserService; import com.suze.service.impl.UserServiceImpl; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; /** * @author suzekang * @Description * @create 2021-01-06 10:59 PM */ public class RegistServlet extends HttpServlet { private UserService userService = new UserServiceImpl(); @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String username = req.getParameter("username"); String password = req.getParameter("password"); String email = req.getParameter("email"); String code = req.getParameter("code"); // System.out.println(username); if ("bnbnp".equalsIgnoreCase(code)) { if (userService.existsUsername(username)) { System.out.println("用户名【" + username + "】已存在"); req.setAttribute("msg","Username already exists"); req.setAttribute("username", username); req.setAttribute("email", email); req.getRequestDispatcher("/pages/user/regist.jsp").forward(req, resp); } else { userService.registUser(new User(null, username, password, email)); req.getRequestDispatcher("/pages/user/regist_success.jsp").forward(req, resp); } } else { //把回显信息,保存在request域中 req.setAttribute("msg","Verification code error"); req.setAttribute("username", username); req.setAttribute("email", email); System.out.println(("验证码【" + code + "】错误")); req.getRequestDispatcher("/pages/user/regist.jsp").forward(req, resp); } } }
1,978
0.639668
0.633437
67
27.746269
28.758564
114
false
false
0
0
0
0
0
0
0.61194
false
false
4
fb86113dc6cdd9d73a1533474f6cb4ffb469fa47
21,732,534,564,928
92c0c42a5c2651e05ae6520784836f2157f114ca
/src/main/java/com/training/dto/LoginForm.java
eb669b512fc13026de6b31711bc71503ad34eea1
[]
no_license
akash28121992/Training-Project
https://github.com/akash28121992/Training-Project
a29c3ba968bd02db01b4c5f39b1d47c5e35d298f
e2a8e67691de8612f4767cf1dcbe2f44e0e44ee4
refs/heads/main
2023-08-24T07:36:21.942000
2021-10-29T08:38:16
2021-10-29T08:38:16
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.training.dto; import javax.validation.constraints.Size; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import lombok.ToString; @AllArgsConstructor @NoArgsConstructor @Builder @Getter @Setter @ToString public class LoginForm { //@NotBlank @Size(min = 3, max = 100) private String username; //@NotBlank @Size(min = 6, max = 40) private String password; }
UTF-8
Java
463
java
LoginForm.java
Java
[]
null
[]
package com.training.dto; import javax.validation.constraints.Size; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import lombok.ToString; @AllArgsConstructor @NoArgsConstructor @Builder @Getter @Setter @ToString public class LoginForm { //@NotBlank @Size(min = 3, max = 100) private String username; //@NotBlank @Size(min = 6, max = 40) private String password; }
463
0.773218
0.758099
27
16.185184
11.52465
41
false
false
0
0
0
0
0
0
0.703704
false
false
4
14d4772b55ad33fac9b3f788ca95a0f485a42ece
12,455,405,162,867
902702cc7b564bf52c9897f7a7c5e6f33840da62
/app/src/main/java/com/heavendevelopment/mantvida20182/Activity/ProjetoVidaMain.java
d62845a39b0a6a552cea7e2aa58e25f96d0ef59f
[]
no_license
yuricavalcantedev/MantVida2017
https://github.com/yuricavalcantedev/MantVida2017
cd8c48aef3709e4edba865b004761f3e890e2484
1406d979f692d4cbdacab11a661f5c7178270670
refs/heads/master
2020-06-27T20:03:17.536000
2018-04-17T18:59:38
2018-04-17T18:59:38
74,520,776
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.heavendevelopment.mantvida20182.Activity; import android.Manifest; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.pm.PackageManager; import android.os.Environment; import android.support.design.widget.CoordinatorLayout; import android.support.design.widget.FloatingActionButton; import android.support.design.widget.Snackbar; import android.support.v4.app.ActivityCompat; import android.support.v4.content.ContextCompat; import android.support.v4.view.MenuItemCompat; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.SearchView; import android.support.v7.widget.Toolbar; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.ListView; import android.widget.RelativeLayout; import android.widget.TextView; import com.heavendevelopment.mantvida20182.Adapter.AdapterMeta; import com.heavendevelopment.mantvida20182.Dominio.Meta; import com.heavendevelopment.mantvida20182.R; import com.heavendevelopment.mantvida20182.Service.MetaService; import com.heavendevelopment.mantvida20182.Util; import com.itextpdf.text.Document; import com.itextpdf.text.DocumentException; import com.itextpdf.text.Element; import com.itextpdf.text.Font; import com.itextpdf.text.PageSize; import com.itextpdf.text.Paragraph; import com.itextpdf.text.pdf.PdfWriter; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.List; public class ProjetoVidaMain extends AppCompatActivity { private Context context; private ListView listViewProjetoVida; private List<Meta> listaMetas; private AdapterMeta adapterMeta; private Document document; private final int PERMISSION_CODE = 200; private AlertDialog alerta; Util util; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_projeto_vida_main); listViewProjetoVida = (ListView) findViewById(R.id.listview_projetoVida_main); context = this; util = new Util(context); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); toolbar.setTitle("Projeto de Vida"); setSupportActionBar(toolbar); getSupportActionBar().setDisplayHomeAsUpEnabled(true); //LISTENER DE VISUALIZAR UMA META CRIADA listViewProjetoVida.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { TextView tvId = (TextView) view.findViewById(R.id.tv_item_projetovida_idMeta); int idMeta = Integer.parseInt(tvId.getText().toString()); Bundle bundle = new Bundle(); bundle.putInt("idMeta",idMeta); Intent intent = new Intent(context, VisualizarMetaProjetoVida.class); intent.putExtras(bundle); startActivity(intent); } }); //LISTENER DE DELETAR UMA META listViewProjetoVida.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() { @Override public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) { String idString = ((TextView)view.findViewById(R.id.tv_item_projetovida_idMeta)).getText().toString(); final int idMeta = Integer.parseInt(idString); final MetaService metaService = new MetaService(context); final Meta metaExcluir = metaService.getMetaById(idMeta); AlertDialog.Builder builder = new AlertDialog.Builder(context) .setTitle("Excluir Meta") .setMessage("Você realmente deseja excluir a meta : " + metaExcluir.getTitulo()) .setNegativeButton("Não", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }) .setPositiveButton("Excluir", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); RelativeLayout relativeLayoutProjetoVidaMain = (RelativeLayout) findViewById(R.id.activity_projeto_vida_main); metaService.deletarMeta(idMeta); Snackbar.make(relativeLayoutProjetoVidaMain, "Meta excluída com sucesso", Snackbar.LENGTH_LONG).show(); fillListViewProjetoVida(); } }); AlertDialog alertDialog = builder.create(); alertDialog.show(); return true; } }); FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab_criar_meta); fab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startActivity(new Intent(context, CriarMetaProjetoVida.class)); } }); } @Override public void onResume(){ super.onResume(); fillListViewProjetoVida(); } private void fillListViewProjetoVida(){ MetaService metaService = new MetaService(context); listaMetas = metaService.getMetas(); TextView tv_nenhuma_meta = (TextView) findViewById(R.id.tv_nenhum_projeto_vida_main); if(listaMetas .size() == 0) tv_nenhuma_meta .setVisibility(View.VISIBLE); else tv_nenhuma_meta .setVisibility(View.INVISIBLE); adapterMeta = new AdapterMeta(context,listaMetas); listViewProjetoVida.setAdapter(adapterMeta); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.menu_search_projeto_vida, menu); MenuItem searchItem = menu.findItem(R.id.action_search); SearchView searchView = (SearchView) MenuItemCompat.getActionView(searchItem); searchView.setQueryHint("Título ou categoria..."); searchView.setOnQueryTextFocusChangeListener(new View.OnFocusChangeListener() { @Override public void onFocusChange(View v, boolean hasFocus) { } }); searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() { @Override public boolean onQueryTextSubmit(String query) { return false; } @Override public boolean onQueryTextChange(String searchQuery) { adapterMeta.filter(searchQuery.toString().trim()); listViewProjetoVida.invalidate(); return true; } }); MenuItemCompat.setOnActionExpandListener(searchItem, new MenuItemCompat.OnActionExpandListener() { @Override public boolean onMenuItemActionCollapse(MenuItem item) { // Do something when collapsed return true; // Return true to collapse action view } @Override public boolean onMenuItemActionExpand(MenuItem item) { // Do something when expanded return true; // Return true to expand action view } }); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if(id == android.R.id.home){ finish(); }else if (id == R.id.action_search) { return true; }else if (id == R.id.action_gerar_projeto_vida){ //chama a rotina de criar o PDF. callWriteOnSDCard(); } return super.onOptionsItemSelected(item); } @Override public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) { switch (requestCode) { case PERMISSION_CODE: for (int i = 0; i < permissions.length; i++) { if (permissions[i].equalsIgnoreCase(Manifest.permission.WRITE_EXTERNAL_STORAGE) && grantResults[i] == PackageManager.PERMISSION_GRANTED) { createDeleteFolder(); } } } super.onRequestPermissionsResult(requestCode, permissions, grantResults); } public void callWriteOnSDCard() { if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) { if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) { callDialog(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}); } else { ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, PERMISSION_CODE); } } else { createDeleteFolder(); } } // FILE public void createDeleteFolder() { String path = Environment.getExternalStorageDirectory().toString() + "/Mant Vida 2018"; File file = new File(Environment.getExternalStorageDirectory().toString() + "/Mant Vida 2018"); if (file.exists()) { new File(Environment.getExternalStorageDirectory().toString() + "/Mant Vida 2018", "Projeto de Vida.pdf").delete(); if (file.delete()) { util.toast("Aperte mais uma vez para gerar o Projeto de Vida em pdf"); } } else { if (file.mkdir()) { createFile(path); } else { } } } public void createFile(final String path) { try { String filename = "Projeto de Vida 2018.pdf"; String projetoVida; document = new Document(PageSize.A4); File dir = new File(path, filename); if (!dir.exists()) { dir.getParentFile().mkdirs(); } FileOutputStream fOut = new FileOutputStream(dir); fOut.flush(); //Fontes Font fontTitulo = new Font(Font.FontFamily.COURIER, 25, Font.BOLD); Font fontCategoria = new Font(Font.FontFamily.TIMES_ROMAN, 18); Font fontMetas = new Font(Font.FontFamily.HELVETICA, 14); Font fontSubTitulo = new Font(Font.FontFamily.TIMES_ROMAN, 18); Paragraph titulo = new Paragraph("Projeto de Vida 2017", fontTitulo); titulo.setAlignment(Element.ALIGN_CENTER); Paragraph subTitulo = new Paragraph("O ano da chuva de avivamento e bençãos de Deus", fontSubTitulo); subTitulo.setAlignment(Element.ALIGN_CENTER); PdfWriter.getInstance(document, fOut); document.open(); document.add(titulo); document.addTitle("Projeto de Vida 2018"); document.addSubject("Ramo Frutífero"); MetaService metaService = new MetaService(context); ArrayList<Meta> metasFamilia = metaService.getMetasByCategory(1); ArrayList<Meta> metasMinisterio = metaService.getMetasByCategory(2); ArrayList<Meta> metasFormacao = metaService.getMetasByCategory(3); ArrayList<Meta> metasRestituicao = metaService.getMetasByCategory(4); ArrayList<Meta> metasFinancas = metaService.getMetasByCategory(5); ArrayList<ArrayList<Meta>> listMetas = new ArrayList<>(); listMetas.add(metasFamilia); listMetas.add(metasMinisterio); listMetas.add(metasFormacao); listMetas.add(metasRestituicao); listMetas.add(metasFinancas); //titulo, dataInicio, dataTérmino //1 - Família, 2 - Ministério, 3 - Formação, 4 - Restituição, 5 - Finanças for (int i = 0; i < listMetas.size() - 1; i++) { projetoVida = ""; String nomeCategoria = escolheNomeCategoria(i + 1); Paragraph paragraphAreas = new Paragraph(nomeCategoria + "\n\n", fontCategoria); paragraphAreas.setAlignment(Element.CHAPTER); document.add(paragraphAreas); Paragraph paragraphMetas; for (int j = 0; j <= listMetas.get(i).size() - 1; j++) { Meta meta = listMetas.get(i).get(j); projetoVida += (meta.getTitulo() + " - de " + meta.getDataInicio() + " a " + meta.getDataConclusao() + "\n" ); } paragraphMetas = new Paragraph(projetoVida, fontMetas); paragraphMetas.setSpacingAfter(20); document.add(paragraphMetas); } CoordinatorLayout coordinatorLayout = (CoordinatorLayout) findViewById(R.id.coorLayoutProjetoVida); Snackbar.make(coordinatorLayout,"Projeto de vida.pdf criado com sucesso na pasta MantVida 2018",Snackbar.LENGTH_SHORT).show(); //Image logoIgreja = Image.getInstance(getClass().getResource("/com/example/alysson/mantvida2016/lg_icant72x72_gold.png")); //logoIgreja.setAlignment(Element.ALIGN_BOTTOM); //document.add(logoIgreja); } catch (DocumentException e) { e.printStackTrace(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { document.close(); } } // UTIL public void callDialog(final String[] permissions) { AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle("Deseja criar o pdf do seu Projeto de Vida 2018 ?"); builder.setPositiveButton("Sim", new DialogInterface.OnClickListener() { public void onClick(DialogInterface arg0, int arg1) { ActivityCompat.requestPermissions(ProjetoVidaMain.this, permissions, PERMISSION_CODE); util.toast("Pdf criado com sucesso!"); alerta.cancel(); } }); builder.setNegativeButton("Não", new DialogInterface.OnClickListener() { public void onClick(DialogInterface arg0, int arg1) { alerta.cancel(); } }); alerta = builder.create(); alerta.show(); } private String escolheNomeCategoria (int idCategoria){ String nomeCategoria; if(idCategoria == 1) nomeCategoria = "Família"; else if (idCategoria == 2) nomeCategoria = "Ministério"; else if (idCategoria == 3) nomeCategoria = "Formação"; else if (idCategoria == 4) nomeCategoria = "Restituição"; else nomeCategoria = "Finanças"; return nomeCategoria; } }
UTF-8
Java
15,750
java
ProjetoVidaMain.java
Java
[ { "context": ".getInstance(getClass().getResource(\"/com/example/alysson/mantvida2016/lg_icant72x72_gold.png\"));\n ", "end": 13960, "score": 0.9908555746078491, "start": 13953, "tag": "USERNAME", "value": "alysson" } ]
null
[]
package com.heavendevelopment.mantvida20182.Activity; import android.Manifest; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.pm.PackageManager; import android.os.Environment; import android.support.design.widget.CoordinatorLayout; import android.support.design.widget.FloatingActionButton; import android.support.design.widget.Snackbar; import android.support.v4.app.ActivityCompat; import android.support.v4.content.ContextCompat; import android.support.v4.view.MenuItemCompat; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.SearchView; import android.support.v7.widget.Toolbar; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.ListView; import android.widget.RelativeLayout; import android.widget.TextView; import com.heavendevelopment.mantvida20182.Adapter.AdapterMeta; import com.heavendevelopment.mantvida20182.Dominio.Meta; import com.heavendevelopment.mantvida20182.R; import com.heavendevelopment.mantvida20182.Service.MetaService; import com.heavendevelopment.mantvida20182.Util; import com.itextpdf.text.Document; import com.itextpdf.text.DocumentException; import com.itextpdf.text.Element; import com.itextpdf.text.Font; import com.itextpdf.text.PageSize; import com.itextpdf.text.Paragraph; import com.itextpdf.text.pdf.PdfWriter; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.List; public class ProjetoVidaMain extends AppCompatActivity { private Context context; private ListView listViewProjetoVida; private List<Meta> listaMetas; private AdapterMeta adapterMeta; private Document document; private final int PERMISSION_CODE = 200; private AlertDialog alerta; Util util; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_projeto_vida_main); listViewProjetoVida = (ListView) findViewById(R.id.listview_projetoVida_main); context = this; util = new Util(context); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); toolbar.setTitle("Projeto de Vida"); setSupportActionBar(toolbar); getSupportActionBar().setDisplayHomeAsUpEnabled(true); //LISTENER DE VISUALIZAR UMA META CRIADA listViewProjetoVida.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { TextView tvId = (TextView) view.findViewById(R.id.tv_item_projetovida_idMeta); int idMeta = Integer.parseInt(tvId.getText().toString()); Bundle bundle = new Bundle(); bundle.putInt("idMeta",idMeta); Intent intent = new Intent(context, VisualizarMetaProjetoVida.class); intent.putExtras(bundle); startActivity(intent); } }); //LISTENER DE DELETAR UMA META listViewProjetoVida.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() { @Override public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) { String idString = ((TextView)view.findViewById(R.id.tv_item_projetovida_idMeta)).getText().toString(); final int idMeta = Integer.parseInt(idString); final MetaService metaService = new MetaService(context); final Meta metaExcluir = metaService.getMetaById(idMeta); AlertDialog.Builder builder = new AlertDialog.Builder(context) .setTitle("Excluir Meta") .setMessage("Você realmente deseja excluir a meta : " + metaExcluir.getTitulo()) .setNegativeButton("Não", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }) .setPositiveButton("Excluir", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); RelativeLayout relativeLayoutProjetoVidaMain = (RelativeLayout) findViewById(R.id.activity_projeto_vida_main); metaService.deletarMeta(idMeta); Snackbar.make(relativeLayoutProjetoVidaMain, "Meta excluída com sucesso", Snackbar.LENGTH_LONG).show(); fillListViewProjetoVida(); } }); AlertDialog alertDialog = builder.create(); alertDialog.show(); return true; } }); FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab_criar_meta); fab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startActivity(new Intent(context, CriarMetaProjetoVida.class)); } }); } @Override public void onResume(){ super.onResume(); fillListViewProjetoVida(); } private void fillListViewProjetoVida(){ MetaService metaService = new MetaService(context); listaMetas = metaService.getMetas(); TextView tv_nenhuma_meta = (TextView) findViewById(R.id.tv_nenhum_projeto_vida_main); if(listaMetas .size() == 0) tv_nenhuma_meta .setVisibility(View.VISIBLE); else tv_nenhuma_meta .setVisibility(View.INVISIBLE); adapterMeta = new AdapterMeta(context,listaMetas); listViewProjetoVida.setAdapter(adapterMeta); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.menu_search_projeto_vida, menu); MenuItem searchItem = menu.findItem(R.id.action_search); SearchView searchView = (SearchView) MenuItemCompat.getActionView(searchItem); searchView.setQueryHint("Título ou categoria..."); searchView.setOnQueryTextFocusChangeListener(new View.OnFocusChangeListener() { @Override public void onFocusChange(View v, boolean hasFocus) { } }); searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() { @Override public boolean onQueryTextSubmit(String query) { return false; } @Override public boolean onQueryTextChange(String searchQuery) { adapterMeta.filter(searchQuery.toString().trim()); listViewProjetoVida.invalidate(); return true; } }); MenuItemCompat.setOnActionExpandListener(searchItem, new MenuItemCompat.OnActionExpandListener() { @Override public boolean onMenuItemActionCollapse(MenuItem item) { // Do something when collapsed return true; // Return true to collapse action view } @Override public boolean onMenuItemActionExpand(MenuItem item) { // Do something when expanded return true; // Return true to expand action view } }); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if(id == android.R.id.home){ finish(); }else if (id == R.id.action_search) { return true; }else if (id == R.id.action_gerar_projeto_vida){ //chama a rotina de criar o PDF. callWriteOnSDCard(); } return super.onOptionsItemSelected(item); } @Override public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) { switch (requestCode) { case PERMISSION_CODE: for (int i = 0; i < permissions.length; i++) { if (permissions[i].equalsIgnoreCase(Manifest.permission.WRITE_EXTERNAL_STORAGE) && grantResults[i] == PackageManager.PERMISSION_GRANTED) { createDeleteFolder(); } } } super.onRequestPermissionsResult(requestCode, permissions, grantResults); } public void callWriteOnSDCard() { if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) { if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) { callDialog(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}); } else { ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, PERMISSION_CODE); } } else { createDeleteFolder(); } } // FILE public void createDeleteFolder() { String path = Environment.getExternalStorageDirectory().toString() + "/Mant Vida 2018"; File file = new File(Environment.getExternalStorageDirectory().toString() + "/Mant Vida 2018"); if (file.exists()) { new File(Environment.getExternalStorageDirectory().toString() + "/Mant Vida 2018", "Projeto de Vida.pdf").delete(); if (file.delete()) { util.toast("Aperte mais uma vez para gerar o Projeto de Vida em pdf"); } } else { if (file.mkdir()) { createFile(path); } else { } } } public void createFile(final String path) { try { String filename = "Projeto de Vida 2018.pdf"; String projetoVida; document = new Document(PageSize.A4); File dir = new File(path, filename); if (!dir.exists()) { dir.getParentFile().mkdirs(); } FileOutputStream fOut = new FileOutputStream(dir); fOut.flush(); //Fontes Font fontTitulo = new Font(Font.FontFamily.COURIER, 25, Font.BOLD); Font fontCategoria = new Font(Font.FontFamily.TIMES_ROMAN, 18); Font fontMetas = new Font(Font.FontFamily.HELVETICA, 14); Font fontSubTitulo = new Font(Font.FontFamily.TIMES_ROMAN, 18); Paragraph titulo = new Paragraph("Projeto de Vida 2017", fontTitulo); titulo.setAlignment(Element.ALIGN_CENTER); Paragraph subTitulo = new Paragraph("O ano da chuva de avivamento e bençãos de Deus", fontSubTitulo); subTitulo.setAlignment(Element.ALIGN_CENTER); PdfWriter.getInstance(document, fOut); document.open(); document.add(titulo); document.addTitle("Projeto de Vida 2018"); document.addSubject("Ramo Frutífero"); MetaService metaService = new MetaService(context); ArrayList<Meta> metasFamilia = metaService.getMetasByCategory(1); ArrayList<Meta> metasMinisterio = metaService.getMetasByCategory(2); ArrayList<Meta> metasFormacao = metaService.getMetasByCategory(3); ArrayList<Meta> metasRestituicao = metaService.getMetasByCategory(4); ArrayList<Meta> metasFinancas = metaService.getMetasByCategory(5); ArrayList<ArrayList<Meta>> listMetas = new ArrayList<>(); listMetas.add(metasFamilia); listMetas.add(metasMinisterio); listMetas.add(metasFormacao); listMetas.add(metasRestituicao); listMetas.add(metasFinancas); //titulo, dataInicio, dataTérmino //1 - Família, 2 - Ministério, 3 - Formação, 4 - Restituição, 5 - Finanças for (int i = 0; i < listMetas.size() - 1; i++) { projetoVida = ""; String nomeCategoria = escolheNomeCategoria(i + 1); Paragraph paragraphAreas = new Paragraph(nomeCategoria + "\n\n", fontCategoria); paragraphAreas.setAlignment(Element.CHAPTER); document.add(paragraphAreas); Paragraph paragraphMetas; for (int j = 0; j <= listMetas.get(i).size() - 1; j++) { Meta meta = listMetas.get(i).get(j); projetoVida += (meta.getTitulo() + " - de " + meta.getDataInicio() + " a " + meta.getDataConclusao() + "\n" ); } paragraphMetas = new Paragraph(projetoVida, fontMetas); paragraphMetas.setSpacingAfter(20); document.add(paragraphMetas); } CoordinatorLayout coordinatorLayout = (CoordinatorLayout) findViewById(R.id.coorLayoutProjetoVida); Snackbar.make(coordinatorLayout,"Projeto de vida.pdf criado com sucesso na pasta MantVida 2018",Snackbar.LENGTH_SHORT).show(); //Image logoIgreja = Image.getInstance(getClass().getResource("/com/example/alysson/mantvida2016/lg_icant72x72_gold.png")); //logoIgreja.setAlignment(Element.ALIGN_BOTTOM); //document.add(logoIgreja); } catch (DocumentException e) { e.printStackTrace(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { document.close(); } } // UTIL public void callDialog(final String[] permissions) { AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle("Deseja criar o pdf do seu Projeto de Vida 2018 ?"); builder.setPositiveButton("Sim", new DialogInterface.OnClickListener() { public void onClick(DialogInterface arg0, int arg1) { ActivityCompat.requestPermissions(ProjetoVidaMain.this, permissions, PERMISSION_CODE); util.toast("Pdf criado com sucesso!"); alerta.cancel(); } }); builder.setNegativeButton("Não", new DialogInterface.OnClickListener() { public void onClick(DialogInterface arg0, int arg1) { alerta.cancel(); } }); alerta = builder.create(); alerta.show(); } private String escolheNomeCategoria (int idCategoria){ String nomeCategoria; if(idCategoria == 1) nomeCategoria = "Família"; else if (idCategoria == 2) nomeCategoria = "Ministério"; else if (idCategoria == 3) nomeCategoria = "Formação"; else if (idCategoria == 4) nomeCategoria = "Restituição"; else nomeCategoria = "Finanças"; return nomeCategoria; } }
15,750
0.616964
0.609589
433
35.321014
32.004848
142
false
false
0
0
0
0
0
0
0.584296
false
false
4
5697ca2d72918d043cec979346e734c8dcba30dc
12,455,405,164,092
b9f05936f7f29d38c627b811ce59ea1c0580ddde
/funi-platform-lshc-web/src/main/java/com/funi/platform/lshc/controller/CommonController.java
9cbae23766c4c7a2e939765df8d881467c6dccda
[]
no_license
luoyadong/funi-platform-lshc
https://github.com/luoyadong/funi-platform-lshc
1cb7a3cf86cc3f54ced0a0c1003a925709997256
74f47a74cb4eba965b4c376def0295c5f57c2e57
refs/heads/master
2021-06-13T21:08:55.228000
2019-06-09T08:19:17
2019-06-09T08:19:17
190,980,694
0
0
null
false
2021-04-26T19:13:48
2019-06-09T08:13:18
2019-06-09T08:23:33
2021-04-26T19:13:47
1,216
0
0
1
Java
false
false
package com.funi.platform.lshc.controller; import com.funi.framework.mvc.eic.controller.BaseController; import com.funi.platform.lshc.dto.ComboboxDto; import com.funi.platform.lshc.dto.ManageOrgDto; import com.funi.platform.lshc.service.CommonService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import java.util.ArrayList; import java.util.List; /** * 用于处理公共业务 * Created by sam on 2018/11/22.9:42 AM */ @Controller @RequestMapping("/common/") public class CommonController extends BaseController { @Autowired private CommonService commonService; /** * 根据字典类型获取该类型字典数据集合 * * @param type 在枚举类中定义 * @return */ @RequestMapping("getDictionaryList") @ResponseBody public List<ComboboxDto> getDictionaryList(String type, Boolean isForm) { return commonService.findDictionaryList(type, isForm); } @RequestMapping("getDictionaryListName") @ResponseBody public List<ComboboxDto> getDictionaryListName(String type) { return commonService.findDictionaryListName(type); } /** * 获取全域管理机构、或者根据userId获取管理机构 * * @param type 1:全域查询 0:根据当前userId查询,在枚举类中定义 * @return */ @RequestMapping("getManagerOrgList") @ResponseBody public List<ComboboxDto> getManagerOrgList(String type, Boolean isForm) { List<ComboboxDto> rtList = new ArrayList<ComboboxDto>(); List<ManageOrgDto> tmpList = commonService.findManagerOrgList(type, this.getUserInfo()); if(null != tmpList && tmpList.size() >0){ if(isForm == null || ! isForm) { ComboboxDto allDto = new ComboboxDto("全部", ""); rtList.add(allDto); } ComboboxDto tmpCom= null; for(ManageOrgDto obj:tmpList){ if(null != obj){ tmpCom = new ComboboxDto(); tmpCom.setName(obj.getOrgName()); tmpCom.setValue(obj.getOrgCode()); rtList.add(tmpCom); } } } return rtList; } }
UTF-8
Java
2,403
java
CommonController.java
Java
[ { "context": "ort java.util.List;\n\n/**\n * 用于处理公共业务\n * Created by sam on 2018/11/22.9:42 AM\n */\n@Controller\n@RequestMap", "end": 576, "score": 0.9868689775466919, "start": 573, "tag": "USERNAME", "value": "sam" } ]
null
[]
package com.funi.platform.lshc.controller; import com.funi.framework.mvc.eic.controller.BaseController; import com.funi.platform.lshc.dto.ComboboxDto; import com.funi.platform.lshc.dto.ManageOrgDto; import com.funi.platform.lshc.service.CommonService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import java.util.ArrayList; import java.util.List; /** * 用于处理公共业务 * Created by sam on 2018/11/22.9:42 AM */ @Controller @RequestMapping("/common/") public class CommonController extends BaseController { @Autowired private CommonService commonService; /** * 根据字典类型获取该类型字典数据集合 * * @param type 在枚举类中定义 * @return */ @RequestMapping("getDictionaryList") @ResponseBody public List<ComboboxDto> getDictionaryList(String type, Boolean isForm) { return commonService.findDictionaryList(type, isForm); } @RequestMapping("getDictionaryListName") @ResponseBody public List<ComboboxDto> getDictionaryListName(String type) { return commonService.findDictionaryListName(type); } /** * 获取全域管理机构、或者根据userId获取管理机构 * * @param type 1:全域查询 0:根据当前userId查询,在枚举类中定义 * @return */ @RequestMapping("getManagerOrgList") @ResponseBody public List<ComboboxDto> getManagerOrgList(String type, Boolean isForm) { List<ComboboxDto> rtList = new ArrayList<ComboboxDto>(); List<ManageOrgDto> tmpList = commonService.findManagerOrgList(type, this.getUserInfo()); if(null != tmpList && tmpList.size() >0){ if(isForm == null || ! isForm) { ComboboxDto allDto = new ComboboxDto("全部", ""); rtList.add(allDto); } ComboboxDto tmpCom= null; for(ManageOrgDto obj:tmpList){ if(null != obj){ tmpCom = new ComboboxDto(); tmpCom.setName(obj.getOrgName()); tmpCom.setValue(obj.getOrgCode()); rtList.add(tmpCom); } } } return rtList; } }
2,403
0.655157
0.64896
71
30.816902
23.540979
96
false
false
0
0
0
0
0
0
0.43662
false
false
4
ae2472c76becb1a3b349ed5af570766663b38720
876,173,378,570
77bd2187e11dabedd6e5ae938eb93156611ce3bb
/src/main/core/java/io/github/greyp9/arwo/core/view/StatusBarView.java
5a6edd7f0c580cde3f30b17a065d24215c670f5c
[ "Apache-2.0" ]
permissive
greyp9/arwo
https://github.com/greyp9/arwo
89e047abec568724e44751f7589bad9862e48877
164ac378889241268dd6823207dc0ab59b659d2e
refs/heads/master
2023-07-19T21:47:10.889000
2023-06-20T00:29:34
2023-06-20T00:29:34
43,374,847
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package io.github.greyp9.arwo.core.view; import io.github.greyp9.arwo.core.app.App; import io.github.greyp9.arwo.core.date.DateU; import io.github.greyp9.arwo.core.date.DateX; import io.github.greyp9.arwo.core.date.DurationU; import io.github.greyp9.arwo.core.html.Html; import io.github.greyp9.arwo.core.http.servlet.ServletHttpRequest; import io.github.greyp9.arwo.core.locus.Locus; import io.github.greyp9.arwo.core.value.NTV; import io.github.greyp9.arwo.core.vm.app.ManifestU; import io.github.greyp9.arwo.core.xml.ElementU; import org.w3c.dom.Element; import java.security.Principal; import java.util.Date; import java.util.Optional; public class StatusBarView { private final ServletHttpRequest httpRequest; private final Locus locus; public StatusBarView(final ServletHttpRequest httpRequest, final Locus locus) { this.httpRequest = httpRequest; this.locus = locus; } public final void addContentTo(final Element html) { final DateX dateX = locus.getDateX(); final Date date = httpRequest.getDate(); final String dateString = dateX.toString(date); final String user = Optional.ofNullable(httpRequest.getPrincipal()).map(Principal::getName).orElse(Html.HYPHEN); final String duration = DurationU.durationXSD(DateU.since(date)); final String status = String.format("[%s] [%s] [%s]", user, dateString, duration); final String version = ManifestU.getSpecificationVersion(getClass()); final String versionDetail = ManifestU.getImplementationVersion(getClass()); final Element divMenus = ElementU.addElement(html, Html.DIV, null, NTV.create(Html.CLASS, App.CSS.MENUS)); final Element divToolbar = ElementU.addElement(divMenus, Html.DIV, null, NTV.create(Html.CLASS, App.CSS.MENU)); final Element divR = ElementU.addElement(divToolbar, Html.DIV, null, NTV.create(Html.CLASS, App.CSS.RIGHT)); final Element divL = ElementU.addElement(divToolbar, Html.DIV, null); ElementU.addElement(divL, Html.SPAN, status, NTV.create(Html.CLASS, App.CSS.MENU)); ElementU.addElement(divR, Html.SPAN, version, NTV.create(Html.CLASS, App.CSS.MENU, Html.TITLE, versionDetail)); } }
UTF-8
Java
2,220
java
StatusBarView.java
Java
[ { "context": "package io.github.greyp9.arwo.core.view;\n\nimport io.github.greyp9.arwo.cor", "end": 24, "score": 0.8984792828559875, "start": 18, "tag": "USERNAME", "value": "greyp9" }, { "context": "o.github.greyp9.arwo.core.view;\n\nimport io.github.greyp9.arwo.core.app.App;\nimport io.github.greyp9.arwo.c", "end": 65, "score": 0.9665811061859131, "start": 59, "tag": "USERNAME", "value": "greyp9" }, { "context": "github.greyp9.arwo.core.app.App;\nimport io.github.greyp9.arwo.core.date.DateU;\nimport io.github.greyp9.arw", "end": 108, "score": 0.8941767811775208, "start": 102, "tag": "USERNAME", "value": "greyp9" }, { "context": "hub.greyp9.arwo.core.date.DateU;\nimport io.github.greyp9.arwo.core.date.DateX;\nimport io.github.greyp9.arw", "end": 154, "score": 0.8186704516410828, "start": 148, "tag": "USERNAME", "value": "greyp9" }, { "context": "hub.greyp9.arwo.core.date.DateX;\nimport io.github.greyp9.arwo.core.date.DurationU;\nimport io.github.greyp9", "end": 200, "score": 0.9161517024040222, "start": 194, "tag": "USERNAME", "value": "greyp9" }, { "context": "greyp9.arwo.core.date.DurationU;\nimport io.github.greyp9.arwo.core.html.Html;\nimport io.github.greyp9.arwo", "end": 250, "score": 0.8282813429832458, "start": 244, "tag": "USERNAME", "value": "greyp9" }, { "context": "thub.greyp9.arwo.core.html.Html;\nimport io.github.greyp9.arwo.core.http.servlet.ServletHttpRequest;\nimport", "end": 295, "score": 0.8564384579658508, "start": 289, "tag": "USERNAME", "value": "greyp9" }, { "context": "http.servlet.ServletHttpRequest;\nimport io.github.greyp9.arwo.core.locus.Locus;\nimport io.github.greyp9.ar", "end": 362, "score": 0.8676002025604248, "start": 356, "tag": "USERNAME", "value": "greyp9" }, { "context": "greyp9.arwo.core.locus.Locus;\nimport io.github.greyp9.arwo.core.value.NTV;\nimport io.github.greyp9.arwo", "end": 409, "score": 0.8567704558372498, "start": 406, "tag": "USERNAME", "value": "yp9" }, { "context": "b.greyp9.arwo.core.value.NTV;\nimport io.github.greyp9.arwo.core.vm.app.ManifestU;\nimport io.github.grey", "end": 454, "score": 0.8152875900268555, "start": 451, "tag": "USERNAME", "value": "yp9" }, { "context": "eyp9.arwo.core.vm.app.ManifestU;\nimport io.github.greyp9.arwo.core.xml.ElementU;\nimport org.w3c.dom.Elemen", "end": 506, "score": 0.8671574592590332, "start": 500, "tag": "USERNAME", "value": "greyp9" } ]
null
[]
package io.github.greyp9.arwo.core.view; import io.github.greyp9.arwo.core.app.App; import io.github.greyp9.arwo.core.date.DateU; import io.github.greyp9.arwo.core.date.DateX; import io.github.greyp9.arwo.core.date.DurationU; import io.github.greyp9.arwo.core.html.Html; import io.github.greyp9.arwo.core.http.servlet.ServletHttpRequest; import io.github.greyp9.arwo.core.locus.Locus; import io.github.greyp9.arwo.core.value.NTV; import io.github.greyp9.arwo.core.vm.app.ManifestU; import io.github.greyp9.arwo.core.xml.ElementU; import org.w3c.dom.Element; import java.security.Principal; import java.util.Date; import java.util.Optional; public class StatusBarView { private final ServletHttpRequest httpRequest; private final Locus locus; public StatusBarView(final ServletHttpRequest httpRequest, final Locus locus) { this.httpRequest = httpRequest; this.locus = locus; } public final void addContentTo(final Element html) { final DateX dateX = locus.getDateX(); final Date date = httpRequest.getDate(); final String dateString = dateX.toString(date); final String user = Optional.ofNullable(httpRequest.getPrincipal()).map(Principal::getName).orElse(Html.HYPHEN); final String duration = DurationU.durationXSD(DateU.since(date)); final String status = String.format("[%s] [%s] [%s]", user, dateString, duration); final String version = ManifestU.getSpecificationVersion(getClass()); final String versionDetail = ManifestU.getImplementationVersion(getClass()); final Element divMenus = ElementU.addElement(html, Html.DIV, null, NTV.create(Html.CLASS, App.CSS.MENUS)); final Element divToolbar = ElementU.addElement(divMenus, Html.DIV, null, NTV.create(Html.CLASS, App.CSS.MENU)); final Element divR = ElementU.addElement(divToolbar, Html.DIV, null, NTV.create(Html.CLASS, App.CSS.RIGHT)); final Element divL = ElementU.addElement(divToolbar, Html.DIV, null); ElementU.addElement(divL, Html.SPAN, status, NTV.create(Html.CLASS, App.CSS.MENU)); ElementU.addElement(divR, Html.SPAN, version, NTV.create(Html.CLASS, App.CSS.MENU, Html.TITLE, versionDetail)); } }
2,220
0.736036
0.730631
44
49.454544
34.957413
120
false
false
0
0
0
0
0
0
1.386364
false
false
4
a9dcf1b73633891211d37817552efe3b4d571505
7,876,970,069,585
ad8445e31b0d494cc8a149891728f348b09014bb
/MockStockRichClient/src/java/market/MarketGUI.java
7ccc7bd59f06dcdcb6310102cd4a1df3aa551e1b
[]
no_license
lamimolle/EDA15
https://github.com/lamimolle/EDA15
ae5049c42fdaf1454136a5ed90f2f1fdd39fb070
e3c275991ce45f29ef4bf5f7270f26069f02d85c
refs/heads/master
2016-09-05T10:20:19.789000
2015-03-18T14:30:58
2015-03-18T14:30:58
32,463,602
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package market; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.Timer; import middleware.common.StockProduct; /* * Market GUI that shows update events */ public class MarketGUI extends javax.swing.JFrame implements ActionListener { private StockListModel model; private Timer timer; public MarketGUI() { initComponents(); this.setTitle("MockStock Market"); this.model = new StockListModel(); this.jListEvent.setModel(model); this.timer = new Timer(1000, this); this.timer.setInitialDelay(0); this.timer.start(); System.out.println("Market started!!"); } // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jPanelBody = new javax.swing.JPanel(); jScrollPaneEvent = new javax.swing.JScrollPane(); jListEvent = new javax.swing.JList(); jButtonClear = new javax.swing.JButton(); analyticsButton = new javax.swing.JButton(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); jPanelBody.setBorder(javax.swing.BorderFactory.createTitledBorder("Events list")); jScrollPaneEvent.setBorder(javax.swing.BorderFactory.createEtchedBorder()); jListEvent.setBackground(java.awt.SystemColor.controlHighlight); jListEvent.setBorder(javax.swing.BorderFactory.createEmptyBorder(1, 1, 1, 1)); jListEvent.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION); jScrollPaneEvent.setViewportView(jListEvent); jButtonClear.setText("Clear events list"); jButtonClear.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButtonClearActionPerformed(evt); } }); analyticsButton.setText("Show analytics"); analyticsButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { analyticsButtonActionPerformed(evt); } }); org.jdesktop.layout.GroupLayout jPanelBodyLayout = new org.jdesktop.layout.GroupLayout(jPanelBody); jPanelBody.setLayout(jPanelBodyLayout); jPanelBodyLayout.setHorizontalGroup( jPanelBodyLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(jPanelBodyLayout.createSequentialGroup() .addContainerGap() .add(jPanelBodyLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(org.jdesktop.layout.GroupLayout.TRAILING, jScrollPaneEvent, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 530, Short.MAX_VALUE) .add(org.jdesktop.layout.GroupLayout.TRAILING, jPanelBodyLayout.createSequentialGroup() .add(0, 0, Short.MAX_VALUE) .add(analyticsButton, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 158, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED) .add(jButtonClear))) .addContainerGap()) ); jPanelBodyLayout.setVerticalGroup( jPanelBodyLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(jPanelBodyLayout.createSequentialGroup() .add(jScrollPaneEvent, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 522, Short.MAX_VALUE) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(jPanelBodyLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE) .add(jButtonClear) .add(analyticsButton)) .addContainerGap()) ); org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(jPanelBody, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); layout.setVerticalGroup( layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(layout.createSequentialGroup() .add(jPanelBody, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) .addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); pack(); }// </editor-fold>//GEN-END:initComponents @Override public void actionPerformed(ActionEvent e) { jListEvent.updateUI(); } public void addStockEvent(StockProduct stock) { model.addFront("New price of " + stock.getStockName() + " is " + stock.getStockPrice()); }; private void jButtonClearActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonClearActionPerformed model.clear(); }//GEN-LAST:event_jButtonClearActionPerformed private void analyticsButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_analyticsButtonActionPerformed new MarketAnalytics().setVisible(true); }//GEN-LAST:event_analyticsButtonActionPerformed // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton analyticsButton; private javax.swing.JButton jButtonClear; private javax.swing.JList jListEvent; private javax.swing.JPanel jPanelBody; private javax.swing.JScrollPane jScrollPaneEvent; // End of variables declaration//GEN-END:variables }
UTF-8
Java
6,033
java
MarketGUI.java
Java
[]
null
[]
package market; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.Timer; import middleware.common.StockProduct; /* * Market GUI that shows update events */ public class MarketGUI extends javax.swing.JFrame implements ActionListener { private StockListModel model; private Timer timer; public MarketGUI() { initComponents(); this.setTitle("MockStock Market"); this.model = new StockListModel(); this.jListEvent.setModel(model); this.timer = new Timer(1000, this); this.timer.setInitialDelay(0); this.timer.start(); System.out.println("Market started!!"); } // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jPanelBody = new javax.swing.JPanel(); jScrollPaneEvent = new javax.swing.JScrollPane(); jListEvent = new javax.swing.JList(); jButtonClear = new javax.swing.JButton(); analyticsButton = new javax.swing.JButton(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); jPanelBody.setBorder(javax.swing.BorderFactory.createTitledBorder("Events list")); jScrollPaneEvent.setBorder(javax.swing.BorderFactory.createEtchedBorder()); jListEvent.setBackground(java.awt.SystemColor.controlHighlight); jListEvent.setBorder(javax.swing.BorderFactory.createEmptyBorder(1, 1, 1, 1)); jListEvent.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION); jScrollPaneEvent.setViewportView(jListEvent); jButtonClear.setText("Clear events list"); jButtonClear.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButtonClearActionPerformed(evt); } }); analyticsButton.setText("Show analytics"); analyticsButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { analyticsButtonActionPerformed(evt); } }); org.jdesktop.layout.GroupLayout jPanelBodyLayout = new org.jdesktop.layout.GroupLayout(jPanelBody); jPanelBody.setLayout(jPanelBodyLayout); jPanelBodyLayout.setHorizontalGroup( jPanelBodyLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(jPanelBodyLayout.createSequentialGroup() .addContainerGap() .add(jPanelBodyLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(org.jdesktop.layout.GroupLayout.TRAILING, jScrollPaneEvent, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 530, Short.MAX_VALUE) .add(org.jdesktop.layout.GroupLayout.TRAILING, jPanelBodyLayout.createSequentialGroup() .add(0, 0, Short.MAX_VALUE) .add(analyticsButton, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 158, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED) .add(jButtonClear))) .addContainerGap()) ); jPanelBodyLayout.setVerticalGroup( jPanelBodyLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(jPanelBodyLayout.createSequentialGroup() .add(jScrollPaneEvent, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 522, Short.MAX_VALUE) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(jPanelBodyLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE) .add(jButtonClear) .add(analyticsButton)) .addContainerGap()) ); org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(jPanelBody, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); layout.setVerticalGroup( layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(layout.createSequentialGroup() .add(jPanelBody, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) .addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); pack(); }// </editor-fold>//GEN-END:initComponents @Override public void actionPerformed(ActionEvent e) { jListEvent.updateUI(); } public void addStockEvent(StockProduct stock) { model.addFront("New price of " + stock.getStockName() + " is " + stock.getStockPrice()); }; private void jButtonClearActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonClearActionPerformed model.clear(); }//GEN-LAST:event_jButtonClearActionPerformed private void analyticsButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_analyticsButtonActionPerformed new MarketAnalytics().setVisible(true); }//GEN-LAST:event_analyticsButtonActionPerformed // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton analyticsButton; private javax.swing.JButton jButtonClear; private javax.swing.JList jListEvent; private javax.swing.JPanel jPanelBody; private javax.swing.JScrollPane jScrollPaneEvent; // End of variables declaration//GEN-END:variables }
6,033
0.671805
0.66849
128
45.132813
37.290955
174
false
false
0
0
0
0
0
0
0.59375
false
false
4
976e59dc18ce6eff1700842bff3766e7c78b1741
17,437,567,228,914
b1163134428d4f3b0cdc6006ae01a8a9a63902bc
/app/src/main/java/com/basantandevloper/geo/muslimamaliyah/notification/NotificatioSoundBroadcast.java
e31db3f88468fc7c1dc47650b4cc4e5875acf8d7
[]
no_license
agusgenuine/Amaliah-Muslim
https://github.com/agusgenuine/Amaliah-Muslim
42562275b50eb27cba44c32ce5d6fd72a674aaf6
f27d8ddc6f8a99c945b8c9c8dd894f26d5406b73
refs/heads/master
2022-02-06T10:09:56.190000
2019-08-07T15:03:35
2019-08-07T15:03:35
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.basantandevloper.geo.muslimamaliyah.notification; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.media.MediaPlayer; import android.net.Uri; import android.os.Bundle; import android.util.Log; import android.widget.Toast; import com.basantandevloper.geo.muslimamaliyah.MediaPlayer.SongActivity; import java.io.IOException; public class NotificatioSoundBroadcast extends BroadcastReceiver { MediaPlayer mp ;// Here Integer posisi = 0; String url; @Override public void onReceive(Context context, Intent intent) { Bundle bd = intent.getExtras(); if (bd !=null) { posisi = (Integer) bd.get("posisi"); url = (String)bd.get("song"); mp = MediaPlayer.create(context,Uri.parse(url)); // mp = new MediaPlayer(); Log.d("BROADCASTSOUND"," " + mp.toString()); } if (intent.getAction().equals(NotificationSoundGenerator.NOTIFY_PLAY)){ // mp.start(); Toast.makeText(context, "NOTIFY_PLAY", Toast.LENGTH_LONG).show(); } else if (intent.getAction().equals(NotificationSoundGenerator.NOTIFY_PAUSE)){ // stopPlayer(); SongActivity song = new SongActivity(); Toast.makeText(context, "NOTIFY_PAUSE", Toast.LENGTH_LONG).show(); }else if (intent.getAction().equals(NotificationSoundGenerator.NOTIFY_NEXT)){ Integer nextPosisi = Integer.valueOf(posisi)+1; Toast.makeText(context, "NOTIFY_NEXT "+nextPosisi, Toast.LENGTH_LONG).show(); }else if (intent.getAction().equals(NotificationSoundGenerator.NOTIFY_DELETE)){ stopPlayer(); SongActivity song = new SongActivity(); Toast.makeText(context, "NOTIFY_DELETE", Toast.LENGTH_LONG).show(); }else if (intent.getAction().equals(NotificationSoundGenerator.NOTIFY_PREVIOUS)){ Integer prevPosisi = Integer.valueOf(posisi); if (Integer.valueOf(posisi)!=0){ prevPosisi = Integer.valueOf(posisi)-1; } Toast.makeText(context, "NOTIFY_PREVIOUS "+prevPosisi, Toast.LENGTH_LONG).show(); } } public void stopPlayer() { try { if (mp.isPlaying()) { mp.stop(); mp.release(); mp = null; } else { Log.e("null", "empty player"); } } catch (Exception e) { e.printStackTrace(); } } }
UTF-8
Java
2,560
java
NotificatioSoundBroadcast.java
Java
[]
null
[]
package com.basantandevloper.geo.muslimamaliyah.notification; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.media.MediaPlayer; import android.net.Uri; import android.os.Bundle; import android.util.Log; import android.widget.Toast; import com.basantandevloper.geo.muslimamaliyah.MediaPlayer.SongActivity; import java.io.IOException; public class NotificatioSoundBroadcast extends BroadcastReceiver { MediaPlayer mp ;// Here Integer posisi = 0; String url; @Override public void onReceive(Context context, Intent intent) { Bundle bd = intent.getExtras(); if (bd !=null) { posisi = (Integer) bd.get("posisi"); url = (String)bd.get("song"); mp = MediaPlayer.create(context,Uri.parse(url)); // mp = new MediaPlayer(); Log.d("BROADCASTSOUND"," " + mp.toString()); } if (intent.getAction().equals(NotificationSoundGenerator.NOTIFY_PLAY)){ // mp.start(); Toast.makeText(context, "NOTIFY_PLAY", Toast.LENGTH_LONG).show(); } else if (intent.getAction().equals(NotificationSoundGenerator.NOTIFY_PAUSE)){ // stopPlayer(); SongActivity song = new SongActivity(); Toast.makeText(context, "NOTIFY_PAUSE", Toast.LENGTH_LONG).show(); }else if (intent.getAction().equals(NotificationSoundGenerator.NOTIFY_NEXT)){ Integer nextPosisi = Integer.valueOf(posisi)+1; Toast.makeText(context, "NOTIFY_NEXT "+nextPosisi, Toast.LENGTH_LONG).show(); }else if (intent.getAction().equals(NotificationSoundGenerator.NOTIFY_DELETE)){ stopPlayer(); SongActivity song = new SongActivity(); Toast.makeText(context, "NOTIFY_DELETE", Toast.LENGTH_LONG).show(); }else if (intent.getAction().equals(NotificationSoundGenerator.NOTIFY_PREVIOUS)){ Integer prevPosisi = Integer.valueOf(posisi); if (Integer.valueOf(posisi)!=0){ prevPosisi = Integer.valueOf(posisi)-1; } Toast.makeText(context, "NOTIFY_PREVIOUS "+prevPosisi, Toast.LENGTH_LONG).show(); } } public void stopPlayer() { try { if (mp.isPlaying()) { mp.stop(); mp.release(); mp = null; } else { Log.e("null", "empty player"); } } catch (Exception e) { e.printStackTrace(); } } }
2,560
0.614062
0.6125
70
35.57143
27.163301
93
false
false
0
0
0
0
0
0
0.742857
false
false
4
4d37946f8b71c1d9f6630d37c863c25cdbeb5e18
26,242,250,222,497
30229d996b1aee6ca9e46292fbdb6bc7709e7751
/Programacion/Numeros_racionales/uso_numeros_racionales.java
b0b5e53a594fc745381b67ffb5dfd3f26c30cfc8
[ "MIT" ]
permissive
pabloriutort/Aula
https://github.com/pabloriutort/Aula
56861896e1fd5bbbaf32b155d5e03a69966a2458
c77dce7b0c4aa06d2461c7b242ce13a9655cb391
refs/heads/master
2016-09-06T19:17:00.287000
2015-07-24T10:43:07
2015-07-24T10:43:07
27,008,166
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package Numeros_racionales; /** * * @author Pablo */ public class uso_numeros_racionales { public static void main (String[]args){ try{ Numeros_racionales a,b,c; a=Numeros_racionales.lectura(); b=new Numeros_racionales(3,4); //Multiplicariamos a por 3/4. c=Numeros_racionales.producto(a,b); //Si queremos que lea otros numeros //escribimos lo mismo que hay en a. System.out.print ("El producto es: " +Numeros_racionales.toString(c)); }catch (Exception e){} } }
UTF-8
Java
696
java
uso_numeros_racionales.java
Java
[ { "context": "ckage Numeros_racionales;\r\n\r\n\r\n/**\r\n *\r\n * @author Pablo\r\n */\r\npublic class uso_numeros_racionales {\r\n ", "end": 164, "score": 0.9996420741081238, "start": 159, "tag": "NAME", "value": "Pablo" } ]
null
[]
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package Numeros_racionales; /** * * @author Pablo */ public class uso_numeros_racionales { public static void main (String[]args){ try{ Numeros_racionales a,b,c; a=Numeros_racionales.lectura(); b=new Numeros_racionales(3,4); //Multiplicariamos a por 3/4. c=Numeros_racionales.producto(a,b); //Si queremos que lea otros numeros //escribimos lo mismo que hay en a. System.out.print ("El producto es: " +Numeros_racionales.toString(c)); }catch (Exception e){} } }
696
0.58477
0.579023
25
25.92
27.563629
79
false
false
0
0
0
0
0
0
0.48
false
false
4
b8b0c3e496d4cf2a5b92b4f751a45b2ac77d539f
24,472,723,660,046
9618de694b59b445b883ac465a310e0b1fd54cb3
/src/test/java/com/qunar/TestGenerateServiceCode.java
809b6bd74bc17daf1fc8f40c1df0c1aad3d2a52f
[]
no_license
Qunzer/mybatis-generator
https://github.com/Qunzer/mybatis-generator
5124dfe339380d0f7735cdd29d2d5beb39b674bf
afcd18208c4bb1eb1ae3f0fa614785256e60c007
refs/heads/master
2021-01-01T05:03:02.819000
2016-04-12T04:05:48
2016-04-12T04:05:48
56,026,282
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.qunar; import com.qunar.mybatis.service.GenerateService; /** * Created by renqun.yuan on 2016/4/4. */ public class TestGenerateServiceCode { public static void main(String[] args) { String url = "jdbc:mysql://localhost:3306"; String userName = "root"; String password = "1234567890"; GenerateService generateService = new GenerateService(url, userName, password); String dbName = "mybatis"; String[] tables = {"hotel_book_info"}; String filePath = "D:/test"; generateService.generateCode(dbName, tables, filePath); } }
UTF-8
Java
607
java
TestGenerateServiceCode.java
Java
[ { "context": "ybatis.service.GenerateService;\n\n/**\n * Created by renqun.yuan on 2016/4/4.\n */\npublic class TestGenerateService", "end": 100, "score": 0.95805424451828, "start": 89, "tag": "USERNAME", "value": "renqun.yuan" }, { "context": "ing userName = \"root\";\n String password = \"1234567890\";\n GenerateService generateService = new G", "end": 325, "score": 0.9991853833198547, "start": 315, "tag": "PASSWORD", "value": "1234567890" } ]
null
[]
package com.qunar; import com.qunar.mybatis.service.GenerateService; /** * Created by renqun.yuan on 2016/4/4. */ public class TestGenerateServiceCode { public static void main(String[] args) { String url = "jdbc:mysql://localhost:3306"; String userName = "root"; String password = "<PASSWORD>"; GenerateService generateService = new GenerateService(url, userName, password); String dbName = "mybatis"; String[] tables = {"hotel_book_info"}; String filePath = "D:/test"; generateService.generateCode(dbName, tables, filePath); } }
607
0.657331
0.624382
19
30.947369
23.745302
87
false
false
0
0
0
0
0
0
0.736842
false
false
4
eac29d1de1e760241c469874bd9222ed70a4a3ad
33,114,197,883,112
c2359c3fa8af170550fd50fc120722c2faf71f22
/Phonebook.java
d83287ecb12b5a1e9bd068640654ec3ecd631902
[]
no_license
mahnaz123-ameer/Phone-Book--IntelliJ-IDEA
https://github.com/mahnaz123-ameer/Phone-Book--IntelliJ-IDEA
bc8f5c9fcda8942644217ec73681b75a7e0a974a
e7a710407b3661e31b732c64d100bdcbcefbcfa5
refs/heads/main
2023-05-31T06:39:06.227000
2021-06-09T10:35:03
2021-06-09T10:35:03
375,316,390
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.company; import java.util.ArrayList; import java.util.Scanner; public class Phonebook { private ArrayList<Contact> contacts; public static Phonebook instance; public static Phonebook getInstance(){ if(instance == null){ instance = new Phonebook(); } return instance; } private Phonebook() { } Scanner scanner = new Scanner(System.in); public void addContact(Contact c){ contacts.add(c); } public void showAllcontacts(){ for(Contact c : contacts){ c.toString(); } } public void findContact(String findname){ for(Contact a : contacts){ if(a.getName().equals(findname)){ return a; } } } public void DeleteContact( String findname){ Contact c = findContact(findname); contacts.remove(contacts); } public void SendMessage(String message){ System.out.println("Enter"); String name = scanner.next(); if(name.equals("")){ System.out.println("hmmm"); SendMessage(); } else } }
UTF-8
Java
1,237
java
Phonebook.java
Java
[]
null
[]
package com.company; import java.util.ArrayList; import java.util.Scanner; public class Phonebook { private ArrayList<Contact> contacts; public static Phonebook instance; public static Phonebook getInstance(){ if(instance == null){ instance = new Phonebook(); } return instance; } private Phonebook() { } Scanner scanner = new Scanner(System.in); public void addContact(Contact c){ contacts.add(c); } public void showAllcontacts(){ for(Contact c : contacts){ c.toString(); } } public void findContact(String findname){ for(Contact a : contacts){ if(a.getName().equals(findname)){ return a; } } } public void DeleteContact( String findname){ Contact c = findContact(findname); contacts.remove(contacts); } public void SendMessage(String message){ System.out.println("Enter"); String name = scanner.next(); if(name.equals("")){ System.out.println("hmmm"); SendMessage(); } else } }
1,237
0.530315
0.530315
56
20.053572
16.512354
48
false
false
0
0
0
0
0
0
0.303571
false
false
4
796abfcb5fd11b4a692881a719bd72c87c3980f2
23,845,658,444,636
550cf0763055e406eb2794a340610ba7b2b1641b
/src/game/underdevelopment/utilities/matrix/Matrix3By3.java
b7a81d81b19e39fae08944243a8196c5e86cb50c
[]
no_license
garyfredgiger/GameFramework
https://github.com/garyfredgiger/GameFramework
ed3a3a4df4b2d19b82209286ddcf02aeb54e8ea7
022c31c78119bdf384251afbbdfd88dc8578cf70
refs/heads/master
2016-09-06T18:03:01.994000
2014-03-11T03:25:02
2014-03-11T03:25:02
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package game.underdevelopment.utilities.matrix; /* * This is a container for the 3 x 3 matrix elements */ public class Matrix3By3 { public double element11, element12, element13; public double element21, element22, element23; public double element31, element32, element33; public Matrix3By3() { element11 = 0.0; element12 = 0.0; element13 = 0.0; element21 = 0.0; element22 = 0.0; element23 = 0.0; element31 = 0.0; element32 = 0.0; element33 = 0.0; } }
UTF-8
Java
504
java
Matrix3By3.java
Java
[]
null
[]
package game.underdevelopment.utilities.matrix; /* * This is a container for the 3 x 3 matrix elements */ public class Matrix3By3 { public double element11, element12, element13; public double element21, element22, element23; public double element31, element32, element33; public Matrix3By3() { element11 = 0.0; element12 = 0.0; element13 = 0.0; element21 = 0.0; element22 = 0.0; element23 = 0.0; element31 = 0.0; element32 = 0.0; element33 = 0.0; } }
504
0.662698
0.543651
24
20
16.867128
52
false
false
0
0
0
0
0
0
0.791667
false
false
4
ef2700b8016bc12b8ddb5e93193ae6410441766e
26,903,675,199,378
13928047994fdb25169f2253b678b59bc72dc3db
/ribbon/src/main/java/com/netflix/ribbon/RequestTemplate.java
8352abb636ee3592f045b7d236c2b6a21a0ca157
[ "Apache-2.0" ]
permissive
jlinxwiler/ribbon
https://github.com/jlinxwiler/ribbon
399ef3008d6613f62f07ef99177ec125e68e15be
483db72ca15b9bda6ffce5891cdcd5c148da03cf
refs/heads/master
2021-01-18T06:41:28.180000
2014-08-11T18:00:54
2014-08-11T18:00:54
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * Copyright 2014 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.ribbon; import com.netflix.hystrix.HystrixObservableCommand; import com.netflix.ribbon.hystrix.FallbackHandler; /** * @author awang * * @param <T> response entity type * @param <R> response meta data, e.g. HttpClientResponse */ public abstract class RequestTemplate<T, R> { public abstract RequestBuilder<T> requestBuilder(); public abstract String name(); public abstract RequestTemplate<T, R> copy(String name); public abstract RequestTemplate<T, R> withFallbackProvider(FallbackHandler<T> fallbackProvider); public abstract RequestTemplate<T, R> withResponseValidator(ResponseValidator<R> transformer); /** * Calling this method will enable both Hystrix request cache and supplied external cache providers * on the supplied cache key. Caller can explicitly disable Hystrix request cache by calling * {@link #withHystrixProperties(com.netflix.hystrix.HystrixObservableCommand.Setter)} * * @param cacheKeyTemplate * @return */ public abstract RequestTemplate<T, R> withRequestCacheKey(String cacheKeyTemplate); public abstract RequestTemplate<T, R> withCacheProvider(String cacheKeyTemplate, CacheProvider<T> cacheProvider); public abstract RequestTemplate<T, R> withHystrixProperties(HystrixObservableCommand.Setter setter); public static abstract class RequestBuilder<T> { public abstract RequestBuilder<T> withRequestProperty(String key, Object value); public abstract RibbonRequest<T> build(); } }
UTF-8
Java
2,188
java
RequestTemplate.java
Java
[ { "context": "ix.ribbon.hystrix.FallbackHandler;\n\n/**\n * @author awang\n *\n * @param <T> response entity type\n * @param <", "end": 751, "score": 0.9991171360015869, "start": 746, "tag": "USERNAME", "value": "awang" } ]
null
[]
/* * Copyright 2014 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.ribbon; import com.netflix.hystrix.HystrixObservableCommand; import com.netflix.ribbon.hystrix.FallbackHandler; /** * @author awang * * @param <T> response entity type * @param <R> response meta data, e.g. HttpClientResponse */ public abstract class RequestTemplate<T, R> { public abstract RequestBuilder<T> requestBuilder(); public abstract String name(); public abstract RequestTemplate<T, R> copy(String name); public abstract RequestTemplate<T, R> withFallbackProvider(FallbackHandler<T> fallbackProvider); public abstract RequestTemplate<T, R> withResponseValidator(ResponseValidator<R> transformer); /** * Calling this method will enable both Hystrix request cache and supplied external cache providers * on the supplied cache key. Caller can explicitly disable Hystrix request cache by calling * {@link #withHystrixProperties(com.netflix.hystrix.HystrixObservableCommand.Setter)} * * @param cacheKeyTemplate * @return */ public abstract RequestTemplate<T, R> withRequestCacheKey(String cacheKeyTemplate); public abstract RequestTemplate<T, R> withCacheProvider(String cacheKeyTemplate, CacheProvider<T> cacheProvider); public abstract RequestTemplate<T, R> withHystrixProperties(HystrixObservableCommand.Setter setter); public static abstract class RequestBuilder<T> { public abstract RequestBuilder<T> withRequestProperty(String key, Object value); public abstract RibbonRequest<T> build(); } }
2,188
0.72989
0.726234
58
36.724136
35.238983
117
false
false
0
0
0
0
0
0
0.5
false
false
4
3cdb1114924d94b9cd29dfc6a8690c4461bd54eb
19,043,885,034,265
9c0de7ced6d9957088103814afefa1f459c676af
/src/main/java/Lab06/Test.java
dfe75ca422d38ae27192e37612a3de325bbbf784
[]
no_license
afahrer/DataStructuresI
https://github.com/afahrer/DataStructuresI
6ef8edc689c120771074e1055e20b4af08e68197
e039ad99957f410e157874170ea4e387c62848b7
refs/heads/master
2022-03-12T00:02:23.237000
2019-07-25T19:19:42
2019-07-25T19:19:42
195,275,536
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * 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 Lab06; /** * * @author afahrer */ public class Test { /** * @param args the command line arguments */ public static void main(String[] args) { LinkedList list = new LinkedList(); list.addFirst("Hello"); list.addFirst("world"); list.addFirst("Java"); list.deleteFirst(); list.deleteLast(); list.addLast("Last"); list.printList(); } }
UTF-8
Java
624
java
Test.java
Java
[ { "context": " the editor.\n */\npackage Lab06;\n\n/**\n *\n * @author afahrer\n */\npublic class Test {\n\n /**\n * @param ar", "end": 226, "score": 0.9968704581260681, "start": 219, "tag": "USERNAME", "value": "afahrer" } ]
null
[]
/* * 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 Lab06; /** * * @author afahrer */ public class Test { /** * @param args the command line arguments */ public static void main(String[] args) { LinkedList list = new LinkedList(); list.addFirst("Hello"); list.addFirst("world"); list.addFirst("Java"); list.deleteFirst(); list.deleteLast(); list.addLast("Last"); list.printList(); } }
624
0.597756
0.594551
28
21.285715
19.831175
79
false
false
0
0
0
0
0
0
0.428571
false
false
4
1b6a37221299b4069cef82220bcf5baeeeeb9890
30,099,130,882,018
6883764034ca4765bb827f32d473c13c188a49ea
/git/src/com/rihui/service/imp/PersonImpl.java
6e3328cfacfab8de4f504704b0f779f3a646959e
[]
no_license
flying-sky/mygit
https://github.com/flying-sky/mygit
714bdfd1a75b0fbfd00d396e8f5706807ece0054
421ba6bbbd1468c49414e76c166988eef576ac94
refs/heads/master
2020-06-01T00:31:37.117000
2014-02-23T11:46:41
2014-02-23T11:46:41
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.rihui.service.imp; public class PersonImpl { }
UTF-8
Java
66
java
PersonImpl.java
Java
[]
null
[]
package com.rihui.service.imp; public class PersonImpl { }
66
0.69697
0.69697
5
11.2
13.40746
30
false
false
0
0
0
0
0
0
0.2
false
false
4
b9b792c5f46ea90cac639e5f2c253e7aa441d140
22,780,506,596,912
db948cbe76196ded1d242eeec84490a2eb0a61c2
/src/hashing/open_addressing/LinearProbingOpenAddressHashTable.java
1aa174f0a8f64b35c9e22b038ac2f5ff82c0e420
[]
no_license
g666/DataStructures
https://github.com/g666/DataStructures
34c3568cd57384182d2bc46227b440473b3275a4
a9af52a9b2107a314b74129d8b34edf66bef1056
refs/heads/master
2021-01-10T11:08:56.283000
2015-10-01T07:38:21
2015-10-01T07:38:21
43,483,297
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/** * */ package hashing.open_addressing; /** * @author Giuseppe Fusco (giuseppe.fusco.666@gmail.com) * */ public abstract class LinearProbingOpenAddressHashTable<K, V> extends OpenAddressHashTable<K, V> { public LinearProbingOpenAddressHashTable(int size) { super(size); } @Override public final int hashFunction(K key, int j) throws Exception { return (hashFunction(key)+j)%getSize(); } }
UTF-8
Java
410
java
LinearProbingOpenAddressHashTable.java
Java
[ { "context": "/\npackage hashing.open_addressing;\n\n/**\n * @author Giuseppe Fusco (giuseppe.fusco.666@gmail.com)\n *\n */\npublic abst", "end": 75, "score": 0.9998807907104492, "start": 61, "tag": "NAME", "value": "Giuseppe Fusco" }, { "context": ".open_addressing;\n\n/**\n * @author Giuseppe Fusco (giuseppe.fusco.666@gmail.com)\n *\n */\npublic abstract class LinearProbingOpenAd", "end": 105, "score": 0.9999339580535889, "start": 77, "tag": "EMAIL", "value": "giuseppe.fusco.666@gmail.com" } ]
null
[]
/** * */ package hashing.open_addressing; /** * @author <NAME> (<EMAIL>) * */ public abstract class LinearProbingOpenAddressHashTable<K, V> extends OpenAddressHashTable<K, V> { public LinearProbingOpenAddressHashTable(int size) { super(size); } @Override public final int hashFunction(K key, int j) throws Exception { return (hashFunction(key)+j)%getSize(); } }
381
0.719512
0.712195
21
18.523809
27.054829
98
false
false
0
0
0
0
0
0
0.714286
false
false
4
24a15550c74423bcc1b74e78d24f53d0eabc3566
12,859,132,098,810
4b14e7c5d02a34ff5c5681afcdbc5187fadfe947
/simpleservice/src/main/java/com/bg/cloud/controller/CustomerResource.java
008ef27a4325098d9c1cdf32b73be0548fc9b7b7
[]
no_license
jeobog/codestar-root
https://github.com/jeobog/codestar-root
e769346b98aee415d8b04b247391a5cefa719eaa
b8819f0b6bf97a2a2d2cb868ebc171deeb798108
refs/heads/master
2021-09-02T15:13:53.141000
2018-01-03T11:32:02
2018-01-03T11:32:02
115,689,379
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.bg.cloud.controller; import com.bg.cloud.controller.dto.CustomerDTO; import com.bg.cloud.controller.dto.PersonDTO; import org.modelmapper.ModelMapper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.MediaType; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import javax.validation.Valid; import javax.validation.constraints.NotNull; /** * Created by bosun on 1/3/18. */ @RestController @RequestMapping(value = "/api/v1/customers", produces = MediaType.APPLICATION_JSON_VALUE, consumes = MediaType.APPLICATION_JSON_VALUE) public class CustomerResource { @Autowired private ModelMapper modelMapper; @RequestMapping(method = RequestMethod.POST) public CustomerDTO createCustomer(@NotNull @Valid @RequestBody PersonDTO personDTO) { CustomerDTO customerDTO = modelMapper.map(personDTO, CustomerDTO.class); return customerDTO; } }
UTF-8
Java
1,129
java
CustomerResource.java
Java
[ { "context": "validation.constraints.NotNull;\n\n/**\n * Created by bosun on 1/3/18.\n */\n@RestController\n@RequestMapping(va", "end": 619, "score": 0.9994012713432312, "start": 614, "tag": "USERNAME", "value": "bosun" } ]
null
[]
package com.bg.cloud.controller; import com.bg.cloud.controller.dto.CustomerDTO; import com.bg.cloud.controller.dto.PersonDTO; import org.modelmapper.ModelMapper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.MediaType; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import javax.validation.Valid; import javax.validation.constraints.NotNull; /** * Created by bosun on 1/3/18. */ @RestController @RequestMapping(value = "/api/v1/customers", produces = MediaType.APPLICATION_JSON_VALUE, consumes = MediaType.APPLICATION_JSON_VALUE) public class CustomerResource { @Autowired private ModelMapper modelMapper; @RequestMapping(method = RequestMethod.POST) public CustomerDTO createCustomer(@NotNull @Valid @RequestBody PersonDTO personDTO) { CustomerDTO customerDTO = modelMapper.map(personDTO, CustomerDTO.class); return customerDTO; } }
1,129
0.798937
0.794508
32
34.28125
31.196188
134
false
false
0
0
0
0
0
0
0.5625
false
false
4
eb811f6c75bbd5a9b90029bae5cb869dff3e330f
2,911,987,869,427
0dbfa3c5a4bb5db82f63c47f4ab88a2bcf2c87ad
/app/src/main/java/net/suntrans/haipopeiwang/bean/DeviceChannelBean.java
24fc4849cb0ff281af9cfdff712556765ebfb652
[]
no_license
luping1994/HaipoPeiWang
https://github.com/luping1994/HaipoPeiWang
6ac80eca386884f3ab0d4e62012d3dd43758080b
612b58c3b2bcd276404153f8d9e23993a00d87e8
refs/heads/master
2020-03-29T09:05:16.814000
2018-09-21T09:23:08
2018-09-21T09:23:08
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package net.suntrans.haipopeiwang.bean; /** * Created by Looney on 2018/9/7. * Des: */ public class DeviceChannelBean { /** * title : 卧室顶灯 * id : 1842 * type : 2 * status : 0 * num : 4 * max_i : 20 * device_type : 2 * area_id : 181 */ public String title; public int id; public int type; public int status; public int num; public int max_i; public int device_type; public int area_id; }
UTF-8
Java
482
java
DeviceChannelBean.java
Java
[ { "context": "net.suntrans.haipopeiwang.bean;\n\n/**\n * Created by Looney on 2018/9/7.\n * Des:\n */\npublic class DeviceChann", "end": 65, "score": 0.9594071507453918, "start": 59, "tag": "USERNAME", "value": "Looney" } ]
null
[]
package net.suntrans.haipopeiwang.bean; /** * Created by Looney on 2018/9/7. * Des: */ public class DeviceChannelBean { /** * title : 卧室顶灯 * id : 1842 * type : 2 * status : 0 * num : 4 * max_i : 20 * device_type : 2 * area_id : 181 */ public String title; public int id; public int type; public int status; public int num; public int max_i; public int device_type; public int area_id; }
482
0.548523
0.508439
28
15.928572
10.419517
39
false
false
0
0
0
0
0
0
0.321429
false
false
4
e6ad5c0070cbd06bb76e1297611109fb130284e3
32,203,664,807,710
4ead7a22e929d9f2b58d52377df1b2d99079808c
/Java - 2° semestre/Lista05/Exer2.java
0c764bcf47de5dd422120e119ffcdec76fa51677
[ "MIT" ]
permissive
monteiroricardo/Documentos_FATEC
https://github.com/monteiroricardo/Documentos_FATEC
fa26998e1af09bab8d250526b344e70f8d62e038
9018f90cc19a3a4cb2815fbba4824bb7cc4304e6
refs/heads/main
2022-12-30T06:12:56.827000
2020-10-13T23:24:16
2020-10-13T23:24:16
305,404,675
1
0
MIT
true
2020-10-19T14:06:22
2020-10-19T14:06:21
2020-10-19T14:00:51
2020-10-19T14:00:06
48,786
0
0
0
null
false
false
/* Matheus Henrique de Oliveira Querido */ import java.util.Scanner; public class Exer2{ public static void main(String[] args){ Scanner leia = new Scanner(System.in); System.out.print("Digite seu número: "); int op = leia.nextInt(); if (op >= 0){System.out.println("Número positivo");} else {System.out.println("Número negativo");} } }
UTF-8
Java
422
java
Exer2.java
Java
[ { "context": "/* Matheus Henrique de Oliveira Querido */\n\n\nimport java.util.Scanner;\npublic class Exer2", "end": 39, "score": 0.9998805522918701, "start": 3, "tag": "NAME", "value": "Matheus Henrique de Oliveira Querido" } ]
null
[]
/* <NAME> */ import java.util.Scanner; public class Exer2{ public static void main(String[] args){ Scanner leia = new Scanner(System.in); System.out.print("Digite seu número: "); int op = leia.nextInt(); if (op >= 0){System.out.println("Número positivo");} else {System.out.println("Número negativo");} } }
392
0.577566
0.572792
13
31.23077
22.52914
64
false
false
0
0
0
0
0
0
0.461538
false
false
4
833ff7f17ff15e8970e942f0c979026c9833b92b
9,998,683,886,263
7aaf8fb5b70bb7101061add812e7de97baa5981a
/src/main/java/com/aurora/domain/base/CommentType.java
7125c397ce442516119a77fe8f46ca8c91a093ef
[]
no_license
SGU-AuroraStudio/AIDustbinServer
https://github.com/SGU-AuroraStudio/AIDustbinServer
4cab6b3c474243758af23198dbc093d851ef4da3
928b55c160e3df89e2d6c616d9b11dd4ecaaaea4
refs/heads/main
2023-04-04T18:47:14.092000
2021-04-20T15:20:51
2021-04-20T15:20:51
349,028,912
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.aurora.domain.base; /** * @Author Yao * @Date 2021/4/2 18:44 * @Description */ public enum CommentType { comment("comment"), reply("reply"); String type; CommentType(String type) { this.type = type; } public String getType() { return type; } public void setType(String type) { this.type = type; } }
UTF-8
Java
379
java
CommentType.java
Java
[ { "context": "package com.aurora.domain.base;\n\n/**\n * @Author Yao\n * @Date 2021/4/2 18:44\n * @Description\n */\npubli", "end": 51, "score": 0.846971869468689, "start": 48, "tag": "NAME", "value": "Yao" } ]
null
[]
package com.aurora.domain.base; /** * @Author Yao * @Date 2021/4/2 18:44 * @Description */ public enum CommentType { comment("comment"), reply("reply"); String type; CommentType(String type) { this.type = type; } public String getType() { return type; } public void setType(String type) { this.type = type; } }
379
0.569921
0.543536
24
14.791667
11.832087
38
false
false
0
0
0
0
0
0
0.291667
false
false
4
63d6175b6c5fe358efab8bc027c47c018cd69236
5,162,550,733,880
14368c979c0bc71d0033871bb7e1d985cdc0a57e
/src/main/java/com/liang/hotelreservation/SendMsg/ReservationHotelParams.java
8ed73034b7e73abbb33ca102a5f278694f1f5c87
[]
no_license
Taeyss/hotelreservation
https://github.com/Taeyss/hotelreservation
653e014e9e3df99c1f84f14265f2d41c23353ef8
936a204e8fd8c0118a9b0e7618fe5d41f1b1594a
refs/heads/master
2021-04-08T01:33:27.969000
2020-05-15T10:24:49
2020-05-15T10:24:49
248,724,914
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.liang.hotelreservation.SendMsg; public class ReservationHotelParams extends BaseParams { private String startDate; private String endDate; private Integer hotelid; private Integer hotelskuid; public Integer getHotelid() { return hotelid; } public void setHotelid(Integer hotelid) { this.hotelid = hotelid; } public String getStartDate() { return startDate; } public void setStartDate(String startDate) { this.startDate = startDate;} public String getEndDate() { return endDate; } public void setEndDate(String endDate) { this.endDate = endDate;} public Integer getHotelskuid() { return hotelskuid; } public void setHotelskuid(Integer hotelskuid) { this.hotelskuid = hotelskuid; } }
UTF-8
Java
806
java
ReservationHotelParams.java
Java
[]
null
[]
package com.liang.hotelreservation.SendMsg; public class ReservationHotelParams extends BaseParams { private String startDate; private String endDate; private Integer hotelid; private Integer hotelskuid; public Integer getHotelid() { return hotelid; } public void setHotelid(Integer hotelid) { this.hotelid = hotelid; } public String getStartDate() { return startDate; } public void setStartDate(String startDate) { this.startDate = startDate;} public String getEndDate() { return endDate; } public void setEndDate(String endDate) { this.endDate = endDate;} public Integer getHotelskuid() { return hotelskuid; } public void setHotelskuid(Integer hotelskuid) { this.hotelskuid = hotelskuid; } }
806
0.686104
0.686104
33
23.424242
23.190947
79
false
false
0
0
0
0
0
0
0.393939
false
false
4
c6fc69441dc66fbdb50e7e7729bf095f2d3fc6a3
5,162,550,735,714
fbdeff2eb6157bbe214926d85a6755419d06fe5b
/src/com/slamke/afterservice/adapter/AdapterFactory.java
23f226a4a03d27902f81e8058e1bacc0a81734f4
[]
no_license
pu409/UnityPrimaAfterServiceClient
https://github.com/pu409/UnityPrimaAfterServiceClient
7ffb60b08e2df408c084c7538012fa77c656c02f
a03f60dad1ce15ad3bf963a03de6a5f75374b32f
refs/heads/master
2021-01-12T10:17:58.934000
2016-12-12T03:13:36
2016-12-12T03:37:52
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.slamke.afterservice.adapter; import java.util.ArrayList; import java.util.HashMap; import android.content.Context; import android.widget.SimpleAdapter; import com.slamke.afterservice.R; public class AdapterFactory { private AdapterFactory() { } /** * 构造菜单Adapter * * @param menuNameArray * 名称 * @param imageResourceArray * 图片 * @return SimpleAdapter */ public static SimpleAdapter getMenuAdapter(Context mContext,String[] menuNameArray, int[] imageResourceArray) { ArrayList<HashMap<String, Object>> data = new ArrayList<HashMap<String, Object>>(); for (int i = 0; i < menuNameArray.length; i++) { HashMap<String, Object> map = new HashMap<String, Object>(); map.put("itemImage", imageResourceArray[i]); map.put("itemText", menuNameArray[i]); data.add(map); } SimpleAdapter simperAdapter = new SimpleAdapter(mContext, data, R.layout.item_small, new String[] { "itemImage", "itemText" }, new int[] { R.id.item_image, R.id.item_text }); return simperAdapter; } /** * 构造菜单Adapter * * @param menuNameArray * 名称 * @param imageResourceArray * 图片 * @return SimpleAdapter */ public static SimpleAdapter getMethodListAdapter(Context mContext,String[] menuNameArray, int[] imageResourceArray) { ArrayList<HashMap<String, Object>> data = new ArrayList<HashMap<String, Object>>(); for (int i = 0; i < menuNameArray.length; i++) { HashMap<String, Object> map = new HashMap<String, Object>(); map.put("itemImage", imageResourceArray[i]); map.put("itemText", menuNameArray[i]); data.add(map); } SimpleAdapter simperAdapter = new SimpleAdapter(mContext, data, R.layout.item_mini, new String[] { "itemImage", "itemText" }, new int[] { R.id.item_image, R.id.item_text }); return simperAdapter; } }
UTF-8
Java
1,881
java
AdapterFactory.java
Java
[]
null
[]
package com.slamke.afterservice.adapter; import java.util.ArrayList; import java.util.HashMap; import android.content.Context; import android.widget.SimpleAdapter; import com.slamke.afterservice.R; public class AdapterFactory { private AdapterFactory() { } /** * 构造菜单Adapter * * @param menuNameArray * 名称 * @param imageResourceArray * 图片 * @return SimpleAdapter */ public static SimpleAdapter getMenuAdapter(Context mContext,String[] menuNameArray, int[] imageResourceArray) { ArrayList<HashMap<String, Object>> data = new ArrayList<HashMap<String, Object>>(); for (int i = 0; i < menuNameArray.length; i++) { HashMap<String, Object> map = new HashMap<String, Object>(); map.put("itemImage", imageResourceArray[i]); map.put("itemText", menuNameArray[i]); data.add(map); } SimpleAdapter simperAdapter = new SimpleAdapter(mContext, data, R.layout.item_small, new String[] { "itemImage", "itemText" }, new int[] { R.id.item_image, R.id.item_text }); return simperAdapter; } /** * 构造菜单Adapter * * @param menuNameArray * 名称 * @param imageResourceArray * 图片 * @return SimpleAdapter */ public static SimpleAdapter getMethodListAdapter(Context mContext,String[] menuNameArray, int[] imageResourceArray) { ArrayList<HashMap<String, Object>> data = new ArrayList<HashMap<String, Object>>(); for (int i = 0; i < menuNameArray.length; i++) { HashMap<String, Object> map = new HashMap<String, Object>(); map.put("itemImage", imageResourceArray[i]); map.put("itemText", menuNameArray[i]); data.add(map); } SimpleAdapter simperAdapter = new SimpleAdapter(mContext, data, R.layout.item_mini, new String[] { "itemImage", "itemText" }, new int[] { R.id.item_image, R.id.item_text }); return simperAdapter; } }
1,881
0.680909
0.679827
61
29.311476
24.718441
90
false
false
0
0
0
0
0
0
2.327869
false
false
4
e7beb14748c6170255fe564fcd9e00c3b3c29311
12,919,261,672,258
a6601a56b84dffee4d113b7cef2f9bd8f5f9a219
/minesweeper/EmptyCell.java
fb790551eee6a38e72ad91507dda8b6e4293fa48
[]
no_license
LMSkippy/cs3620-as3-minesweeper
https://github.com/LMSkippy/cs3620-as3-minesweeper
36fea0496d43cd03c5d8328d825085cc359229b7
ae126a541c8dcd6e0d226b70e6d59bcb75541859
refs/heads/master
2020-05-02T16:11:14.172000
2019-04-02T23:04:59
2019-04-02T23:04:59
178,062,146
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
public class EmptyCell extends Cell { public EmptyCell() { super(); clickBehaviour = new ClickEmptyBehaviour(); flagBehaviour = new DefaultFlagBehaviour(); } }
UTF-8
Java
196
java
EmptyCell.java
Java
[]
null
[]
public class EmptyCell extends Cell { public EmptyCell() { super(); clickBehaviour = new ClickEmptyBehaviour(); flagBehaviour = new DefaultFlagBehaviour(); } }
196
0.627551
0.627551
9
20.777779
19.245651
51
false
false
0
0
0
0
0
0
0.333333
false
false
4
70cb023113a99e8f3692ecd40d26256aeac7842e
20,615,843,065,657
0d8771f3613dfd3bdde305d96fd22f545196f17c
/src/main/java/cn/fenqing/datastructures/linkedlist/Theme4.java
6dcbbd111598f2cf207f1b784610230f66893797
[]
no_license
fenqing168/study-arithmetic
https://github.com/fenqing168/study-arithmetic
101e731d700402d9c7a499db118aa0f25972c57e
6914ab620d681365f1fb112ffedcd15ad7ad86bc
refs/heads/master
2023-03-21T07:22:42.367000
2021-03-17T02:18:52
2021-03-17T02:18:52
335,571,071
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package cn.fenqing.datastructures.linkedlist; import cn.fenqing.test.RunTime; import java.util.Stack; /** * @author fenqing */ public class Theme4 { public static void main(String[] args) { LinkedListNode<Integer> root = new LinkedListNode<>(1, null); LinkedListNode<Integer> temp = root; for (int i = 2; i < 10000; i++) { LinkedListNode<Integer> newNode = new LinkedListNode<>(i, null); temp.setNext(newNode); temp = newNode; } LinkedList.list(root); RunTime.nanoTest(() -> { System.out.println(); reversPrint(root); }, "栈打印"); RunTime.nanoTest(() -> { System.out.println(); reversPrintRecurve(root); }, "递归打印"); } /** * 反向打印 * @param root 根节点 */ public static void reversPrint(LinkedListNode<Integer> root){ Stack<LinkedListNode<Integer>> stack = new Stack<>(); while (root != null){ stack.push(root); root = root.getNext(); } while (!stack.isEmpty()){ stack.pop().getData(); // System.out.println(); } } /** * 反向打印 * @param root 根节点 */ public static void reversPrintRecurve(LinkedListNode<Integer> root){ if(root == null){ return; } Stack<LinkedListNode<Integer>> stack = new Stack<>(); reversPrintRecurve(root.getNext()); root.getData(); // System.out.println(); } }
UTF-8
Java
1,589
java
Theme4.java
Java
[ { "context": ".RunTime;\n\nimport java.util.Stack;\n\n/**\n * @author fenqing\n */\npublic class Theme4 {\n\n public static void", "end": 127, "score": 0.9958133697509766, "start": 120, "tag": "USERNAME", "value": "fenqing" } ]
null
[]
package cn.fenqing.datastructures.linkedlist; import cn.fenqing.test.RunTime; import java.util.Stack; /** * @author fenqing */ public class Theme4 { public static void main(String[] args) { LinkedListNode<Integer> root = new LinkedListNode<>(1, null); LinkedListNode<Integer> temp = root; for (int i = 2; i < 10000; i++) { LinkedListNode<Integer> newNode = new LinkedListNode<>(i, null); temp.setNext(newNode); temp = newNode; } LinkedList.list(root); RunTime.nanoTest(() -> { System.out.println(); reversPrint(root); }, "栈打印"); RunTime.nanoTest(() -> { System.out.println(); reversPrintRecurve(root); }, "递归打印"); } /** * 反向打印 * @param root 根节点 */ public static void reversPrint(LinkedListNode<Integer> root){ Stack<LinkedListNode<Integer>> stack = new Stack<>(); while (root != null){ stack.push(root); root = root.getNext(); } while (!stack.isEmpty()){ stack.pop().getData(); // System.out.println(); } } /** * 反向打印 * @param root 根节点 */ public static void reversPrintRecurve(LinkedListNode<Integer> root){ if(root == null){ return; } Stack<LinkedListNode<Integer>> stack = new Stack<>(); reversPrintRecurve(root.getNext()); root.getData(); // System.out.println(); } }
1,589
0.530705
0.525533
64
23.171875
19.874256
76
false
false
0
0
0
0
0
0
0.484375
false
false
2
347f1866d7f3a30149f414e779adda958c786fec
19,241,453,553,735
d3f18f9820832c8d44ca2fa45425275d27d58bb3
/huobi-api/src/main/java/com/kevin/gateway/huobiapi/spot/response/wallet/SpotWithdrawResponse.java
73716b432618a4b399dd158aa6b6a8656a8ead23
[]
no_license
ssh352/exchange-gateway
https://github.com/ssh352/exchange-gateway
e5c1289e87184e68b1b2bcf01ffa07c53269437f
ecccf6aa1a42b3fe576fccb01f5939dcf4cae25d
refs/heads/master
2023-05-06T01:24:25.062000
2021-06-03T02:44:35
2021-06-03T02:44:35
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.kevin.gateway.huobiapi.spot.response.wallet; import lombok.Data; /** * 提币 */ @Data public class SpotWithdrawResponse { private long data;//提币 ID }
UTF-8
Java
175
java
SpotWithdrawResponse.java
Java
[]
null
[]
package com.kevin.gateway.huobiapi.spot.response.wallet; import lombok.Data; /** * 提币 */ @Data public class SpotWithdrawResponse { private long data;//提币 ID }
175
0.718563
0.718563
11
14.181818
17.631678
56
false
false
0
0
0
0
0
0
0.272727
false
false
2
4c31468fa9121d450d4d0569fde45b012d85a586
19,241,453,554,143
7206bc7f846ded4191d5378a3ea4609164b740ff
/cmfz-admin/src/main/java/com/wing/cmfz/controller/MasterController.java
a08bf7c4c2475eb32d3d9104ab247be5a4ca00f7
[]
no_license
WDreamIn/ssm-cmfz
https://github.com/WDreamIn/ssm-cmfz
793f714204003725e932648996c124dfb43d7777
2c8b427c0a38a0e149406a05f1c2091436fe3668
refs/heads/master
2020-03-22T09:10:03.117000
2018-07-12T07:14:44
2018-07-12T07:14:44
139,820,129
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.wing.cmfz.controller; import cn.afterturn.easypoi.excel.ExcelExportUtil; import cn.afterturn.easypoi.excel.ExcelImportUtil; import cn.afterturn.easypoi.excel.entity.ExportParams; import cn.afterturn.easypoi.excel.entity.ImportParams; import com.wing.cmfz.entity.Master; import com.wing.cmfz.entity.Result; import com.wing.cmfz.service.MasterService; import org.apache.commons.io.FilenameUtils; import org.apache.poi.ss.usermodel.Workbook; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.multipart.MultipartFile; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.File; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.UUID; /** * @Auther: Wing_Hui * @Date: 2018/7/8 12:39 * @Description: */ @Controller @RequestMapping("/master") public class MasterController { @Autowired private MasterService masterService; @RequestMapping("/showAll") public @ResponseBody Map<String,Object> showAllMaster(Integer page, Integer rows) { return masterService.findAll(page,rows); } /** * 获取单条数据 * @param masterId * @return */ @RequestMapping("/queryOne") public @ResponseBody Master queryOne(Integer masterId){ return masterService.queryOne(masterId); } @RequestMapping("/findmasters") public @ResponseBody Map findmaster(String name) { return masterService.findMaster(name); } @RequestMapping("/findmaster") public @ResponseBody List<Master> findmasters(String name) { return masterService.findMasters(name); } @RequestMapping("/upload") public @ResponseBody Result upload(MultipartFile xls) { // 参数一:输入流 // 参数二:pojo // 参数三:导入参数对象 ImportParams importParams = new ImportParams(); List<Master> masters = null; try { masters = ExcelImportUtil.importExcel(xls.getInputStream(),Master.class,importParams); masterService.insertAll(masters); } catch (Exception e) { e.printStackTrace(); } return new Result("ture","操作完成"); } @RequestMapping("/export") public void exportExcel(HttpServletResponse response) throws IOException { List<Master> masters = masterService.queryAll(); // Excel 文件 Workbook workbook = ExcelExportUtil.exportExcel(new ExportParams("持明法洲","上师信息表"),Master.class,masters); ServletOutputStream out = response.getOutputStream(); // 文件下载 设置响应头 // 相应头 默认使用的编码格式 iso-8859-1 String fileName = new String("上师信息.xls".getBytes(),"iso-8859-1"); // 相应类型 response.setContentType("application/vnd.ms-excel"); // 导出文件下载的方式 response.setHeader("content-disposition","attachment;fileName="+fileName); workbook.write(out); out.close(); } @RequestMapping("/addMaster") public void addMaster (Master master, MultipartFile pic , HttpServletRequest request) throws IOException { // 获得文件夹的名称 String realPath = request.getSession().getServletContext().getRealPath("/"); // 获取父目录 String webapps = new File(realPath).getParent(); // 创建文件夹upload File file = new File(webapps + "/upload"); if (!file.exists()) { file.mkdirs(); } // 生成UUID的唯一文件名 String newName = UUID.randomUUID().toString().replace("-", "")+ FilenameUtils.getExtension(pic.getName()); // 截取文件本身的后缀名 String oldName = pic.getOriginalFilename(); String suffix = oldName.substring(oldName.lastIndexOf(".")); //上传到webapps/upload中 pic.transferTo(new File(webapps +"/upload/" + newName + suffix)); master.setMasterPhoto(newName + suffix); masterService.addMaster(master); } @RequestMapping("/upMaster") public void upMaster (Master master, MultipartFile pic , HttpServletRequest request) throws IOException { // 更新需要判断是否文件为空 if (!pic.isEmpty()) { // 获得文件夹的名称 String realPath = request.getSession().getServletContext().getRealPath("/"); // 获取父目录 String webapps = new File(realPath).getParent(); // 创建文件夹upload File file = new File(webapps + "/upload"); if (!file.exists()) { file.mkdirs(); } // 生成UUID的唯一文件名 String newName = UUID.randomUUID().toString().replace("-", "")+ FilenameUtils.getExtension(pic.getName()); // 截取文件本身的后缀名 String oldName = pic.getOriginalFilename(); String suffix = oldName.substring(oldName.lastIndexOf(".")); //上传到webapps/upload中 pic.transferTo(new File(webapps +"/upload/" + newName + suffix)); master.setMasterPhoto("/upload/" +newName + suffix); } masterService.upMaster(master); } }
UTF-8
Java
5,603
java
MasterController.java
Java
[ { "context": ".util.Map;\nimport java.util.UUID;\n\n/**\n * @Auther: Wing_Hui\n * @Date: 2018/7/8 12:39\n * @Description:\n */", "end": 1090, "score": 0.8162257671356201, "start": 1086, "tag": "NAME", "value": "Wing" }, { "context": ".Map;\nimport java.util.UUID;\n\n/**\n * @Auther: Wing_Hui\n * @Date: 2018/7/8 12:39\n * @Description:\n */\n", "end": 1090, "score": 0.6215165853500366, "start": 1090, "tag": "USERNAME", "value": "" }, { "context": "Map;\nimport java.util.UUID;\n\n/**\n * @Auther: Wing_Hui\n * @Date: 2018/7/8 12:39\n * @Description:\n */\n@Co", "end": 1094, "score": 0.8469916582107544, "start": 1091, "tag": "NAME", "value": "Hui" } ]
null
[]
package com.wing.cmfz.controller; import cn.afterturn.easypoi.excel.ExcelExportUtil; import cn.afterturn.easypoi.excel.ExcelImportUtil; import cn.afterturn.easypoi.excel.entity.ExportParams; import cn.afterturn.easypoi.excel.entity.ImportParams; import com.wing.cmfz.entity.Master; import com.wing.cmfz.entity.Result; import com.wing.cmfz.service.MasterService; import org.apache.commons.io.FilenameUtils; import org.apache.poi.ss.usermodel.Workbook; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.multipart.MultipartFile; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.File; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.UUID; /** * @Auther: Wing_Hui * @Date: 2018/7/8 12:39 * @Description: */ @Controller @RequestMapping("/master") public class MasterController { @Autowired private MasterService masterService; @RequestMapping("/showAll") public @ResponseBody Map<String,Object> showAllMaster(Integer page, Integer rows) { return masterService.findAll(page,rows); } /** * 获取单条数据 * @param masterId * @return */ @RequestMapping("/queryOne") public @ResponseBody Master queryOne(Integer masterId){ return masterService.queryOne(masterId); } @RequestMapping("/findmasters") public @ResponseBody Map findmaster(String name) { return masterService.findMaster(name); } @RequestMapping("/findmaster") public @ResponseBody List<Master> findmasters(String name) { return masterService.findMasters(name); } @RequestMapping("/upload") public @ResponseBody Result upload(MultipartFile xls) { // 参数一:输入流 // 参数二:pojo // 参数三:导入参数对象 ImportParams importParams = new ImportParams(); List<Master> masters = null; try { masters = ExcelImportUtil.importExcel(xls.getInputStream(),Master.class,importParams); masterService.insertAll(masters); } catch (Exception e) { e.printStackTrace(); } return new Result("ture","操作完成"); } @RequestMapping("/export") public void exportExcel(HttpServletResponse response) throws IOException { List<Master> masters = masterService.queryAll(); // Excel 文件 Workbook workbook = ExcelExportUtil.exportExcel(new ExportParams("持明法洲","上师信息表"),Master.class,masters); ServletOutputStream out = response.getOutputStream(); // 文件下载 设置响应头 // 相应头 默认使用的编码格式 iso-8859-1 String fileName = new String("上师信息.xls".getBytes(),"iso-8859-1"); // 相应类型 response.setContentType("application/vnd.ms-excel"); // 导出文件下载的方式 response.setHeader("content-disposition","attachment;fileName="+fileName); workbook.write(out); out.close(); } @RequestMapping("/addMaster") public void addMaster (Master master, MultipartFile pic , HttpServletRequest request) throws IOException { // 获得文件夹的名称 String realPath = request.getSession().getServletContext().getRealPath("/"); // 获取父目录 String webapps = new File(realPath).getParent(); // 创建文件夹upload File file = new File(webapps + "/upload"); if (!file.exists()) { file.mkdirs(); } // 生成UUID的唯一文件名 String newName = UUID.randomUUID().toString().replace("-", "")+ FilenameUtils.getExtension(pic.getName()); // 截取文件本身的后缀名 String oldName = pic.getOriginalFilename(); String suffix = oldName.substring(oldName.lastIndexOf(".")); //上传到webapps/upload中 pic.transferTo(new File(webapps +"/upload/" + newName + suffix)); master.setMasterPhoto(newName + suffix); masterService.addMaster(master); } @RequestMapping("/upMaster") public void upMaster (Master master, MultipartFile pic , HttpServletRequest request) throws IOException { // 更新需要判断是否文件为空 if (!pic.isEmpty()) { // 获得文件夹的名称 String realPath = request.getSession().getServletContext().getRealPath("/"); // 获取父目录 String webapps = new File(realPath).getParent(); // 创建文件夹upload File file = new File(webapps + "/upload"); if (!file.exists()) { file.mkdirs(); } // 生成UUID的唯一文件名 String newName = UUID.randomUUID().toString().replace("-", "")+ FilenameUtils.getExtension(pic.getName()); // 截取文件本身的后缀名 String oldName = pic.getOriginalFilename(); String suffix = oldName.substring(oldName.lastIndexOf(".")); //上传到webapps/upload中 pic.transferTo(new File(webapps +"/upload/" + newName + suffix)); master.setMasterPhoto("/upload/" +newName + suffix); } masterService.upMaster(master); } }
5,603
0.662103
0.6583
162
31.462963
28.480476
118
false
false
0
0
0
0
0
0
0.506173
false
false
2
01f193dc36373c3ddb07beb8d6e056f3ec1b3c68
30,648,886,681,844
5212578f1ba5673eb3c6167e594bfd9555882913
/app/src/main/java/com/example/prakharagarwal/automaticirrigation/PresetTime_Adapter.java
4a895aa607a53f4cbb7648a93ef9d39998fc535a
[]
no_license
prakharagarwal76/HomeGenie
https://github.com/prakharagarwal76/HomeGenie
adfe2ab5f26f0717d74fa3004eed6eeb8320ef66
6dbb57ed56aac0df6c0791bdfe21b3015f36c2af
refs/heads/master
2021-01-12T11:22:44.600000
2016-12-05T17:06:31
2016-12-05T17:06:31
72,908,724
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.prakharagarwal.automaticirrigation; import android.app.AlarmManager; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.text.Html; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.ImageView; import android.widget.Spinner; import android.widget.TextView; import android.widget.Toast; import java.sql.SQLException; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.List; /** * Created by prakharagarwal on 03/11/16. */ public class PresetTime_Adapter extends ArrayAdapter<String> { private Context context; //private List<Long> id; private List<String> name; private List<String> starttime; private List<String> stoptime; private List<String> status; DBAdapter dba ; int flag; public PresetTime_Adapter(Context context, List<String> name,List<String> starttime,List<String> stoptime,List<String> status) { super(context,0,name); this.context = context; //this.id= new ArrayList<Long>(); this.name = new ArrayList<String>(); this.starttime = new ArrayList<String>(); this.stoptime = new ArrayList<String>(); this.status = new ArrayList<String>(); //this.id=id; this.name = name; this.starttime=starttime; this.stoptime=stoptime; this.status=status; } @Override public View getView(final int position, View convertView, ViewGroup parent) { if (convertView == null) { convertView = LayoutInflater.from(getContext()).inflate(R.layout.item_listview_preset, parent, false); } dba= new DBAdapter(getContext()); try { dba.open(); } catch (SQLException e) { e.printStackTrace(); } TextView t1 = (TextView) convertView.findViewById(R.id.list_item_preset_text1); TextView t2 = (TextView) convertView.findViewById(R.id.list_item_preset_text2); TextView t3 = (TextView) convertView.findViewById(R.id.list_item_preset_text3); TextView t4 = (TextView) convertView.findViewById(R.id.list_item_preset_text4); final ImageView i4 = (ImageView) convertView.findViewById(R.id.list_item_preset_image); flag=0; t1.setText(name.get(position)); t2.setText(starttime.get(position)); t3.setText(stoptime.get(position)); t4.setVisibility(View.INVISIBLE); if(status.get(position).equals("1")){ flag=1; i4.setImageDrawable(getContext().getResources().getDrawable(R.drawable.ic_alarm_on_black_24dp)); } if(status.get(position).equals("3")){ i4.setVisibility(View.INVISIBLE); t4.setVisibility(View.VISIBLE); } if(status.get(position).equals("4")){ i4.setVisibility(View.INVISIBLE); t4.setText("CANCELLED"); t4.setVisibility(View.VISIBLE); } i4.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(flag==0){ i4.setImageDrawable(getContext().getResources().getDrawable(R.drawable.ic_alarm_on_black_24dp)); dba.updateStatus(1,name.get(position)); Calendar cal1=Calendar.getInstance(); Calendar cal3=Calendar.getInstance(); SimpleDateFormat sdf=new SimpleDateFormat("d/M/yyyy H:m"); try {Date date=sdf.parse(starttime.get(position)); Date stopDate=sdf.parse(stoptime.get(position)); cal1.setTime(date); cal3.setTime(stopDate); Log.e("date",starttime.get(position)+""); }catch (ParseException e){ } String code=getCode(starttime.get(position)); Log.e("onClick: ",""+code); String start= code+"1"; String stop=code+"0"; dba.updateReqcode(name.get(position),start,stop); int startcode=Integer.parseInt(start); int stopcode=Integer.parseInt(stop); Intent intent = new Intent(getContext(), PresetBroadcastReceiver.class); intent.putExtra("status",1); intent.putExtra("name",name.get(position)); intent.putExtra("position",position); PendingIntent pendingIntent = PendingIntent.getBroadcast( getContext(),startcode, intent, PendingIntent.FLAG_CANCEL_CURRENT); AlarmManager alarmManager = (AlarmManager)getContext().getSystemService(getContext().ALARM_SERVICE); alarmManager.set(AlarmManager.RTC_WAKEUP,cal1.getTimeInMillis(), pendingIntent); Intent stopIntent = new Intent(getContext(), PresetBroadcastReceiver.class); stopIntent.putExtra("status",0); stopIntent.putExtra("name",name.get(position)); stopIntent.putExtra("position",position); PendingIntent pendingIntentStop = PendingIntent.getBroadcast( getContext(),stopcode, stopIntent, PendingIntent.FLAG_CANCEL_CURRENT); AlarmManager alarmManagerStop = (AlarmManager)getContext().getSystemService(getContext().ALARM_SERVICE); alarmManagerStop.set(AlarmManager.RTC_WAKEUP,cal3.getTimeInMillis(), pendingIntentStop); flag=1; }else{ int startCode=Integer.parseInt(dba.getReqcodeonn(name.get(position))); int stopCode=Integer.parseInt(dba.getReqcodeoff(name.get(position))); i4.setImageDrawable(getContext().getResources().getDrawable(R.drawable.ic_alarm_off_black_24dp)); dba.updateStatus(0,name.get(position)); Intent intent = new Intent(getContext(), PresetBroadcastReceiver.class); PendingIntent pendingIntent = PendingIntent.getBroadcast( getContext(),startCode, intent, 0); AlarmManager alarmManager = (AlarmManager)getContext().getSystemService(getContext().ALARM_SERVICE); alarmManager.cancel(pendingIntent); PendingIntent pendingStopIntent = PendingIntent.getBroadcast( getContext(),stopCode, intent, 0); AlarmManager alarmManagerStop = (AlarmManager)getContext().getSystemService(getContext().ALARM_SERVICE); alarmManagerStop.cancel(pendingStopIntent); flag=0; } } }); return convertView; } public String getCode(String date) { String coded=""; String[] splitted = date.split("[/ :]"); for (int i=0;i<splitted.length;i++) { if(i==2) { splitted[i] =""; } coded=coded + splitted[i]; } return coded; } public void removeAll(int listItemPosition) { name.remove(listItemPosition); starttime.remove(listItemPosition); stoptime.remove(listItemPosition); status.remove(listItemPosition); } }
UTF-8
Java
7,679
java
PresetTime_Adapter.java
Java
[ { "context": "package com.example.prakharagarwal.automaticirrigation;\n\nimport android.app.AlarmMan", "end": 34, "score": 0.98590487241745, "start": 20, "tag": "USERNAME", "value": "prakharagarwal" }, { "context": "il.Date;\nimport java.util.List;\n\n/**\n * Created by prakharagarwal on 03/11/16.\n */\npublic class PresetTime_Adapter ", "end": 760, "score": 0.9988935589790344, "start": 746, "tag": "USERNAME", "value": "prakharagarwal" } ]
null
[]
package com.example.prakharagarwal.automaticirrigation; import android.app.AlarmManager; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.text.Html; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.ImageView; import android.widget.Spinner; import android.widget.TextView; import android.widget.Toast; import java.sql.SQLException; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.List; /** * Created by prakharagarwal on 03/11/16. */ public class PresetTime_Adapter extends ArrayAdapter<String> { private Context context; //private List<Long> id; private List<String> name; private List<String> starttime; private List<String> stoptime; private List<String> status; DBAdapter dba ; int flag; public PresetTime_Adapter(Context context, List<String> name,List<String> starttime,List<String> stoptime,List<String> status) { super(context,0,name); this.context = context; //this.id= new ArrayList<Long>(); this.name = new ArrayList<String>(); this.starttime = new ArrayList<String>(); this.stoptime = new ArrayList<String>(); this.status = new ArrayList<String>(); //this.id=id; this.name = name; this.starttime=starttime; this.stoptime=stoptime; this.status=status; } @Override public View getView(final int position, View convertView, ViewGroup parent) { if (convertView == null) { convertView = LayoutInflater.from(getContext()).inflate(R.layout.item_listview_preset, parent, false); } dba= new DBAdapter(getContext()); try { dba.open(); } catch (SQLException e) { e.printStackTrace(); } TextView t1 = (TextView) convertView.findViewById(R.id.list_item_preset_text1); TextView t2 = (TextView) convertView.findViewById(R.id.list_item_preset_text2); TextView t3 = (TextView) convertView.findViewById(R.id.list_item_preset_text3); TextView t4 = (TextView) convertView.findViewById(R.id.list_item_preset_text4); final ImageView i4 = (ImageView) convertView.findViewById(R.id.list_item_preset_image); flag=0; t1.setText(name.get(position)); t2.setText(starttime.get(position)); t3.setText(stoptime.get(position)); t4.setVisibility(View.INVISIBLE); if(status.get(position).equals("1")){ flag=1; i4.setImageDrawable(getContext().getResources().getDrawable(R.drawable.ic_alarm_on_black_24dp)); } if(status.get(position).equals("3")){ i4.setVisibility(View.INVISIBLE); t4.setVisibility(View.VISIBLE); } if(status.get(position).equals("4")){ i4.setVisibility(View.INVISIBLE); t4.setText("CANCELLED"); t4.setVisibility(View.VISIBLE); } i4.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(flag==0){ i4.setImageDrawable(getContext().getResources().getDrawable(R.drawable.ic_alarm_on_black_24dp)); dba.updateStatus(1,name.get(position)); Calendar cal1=Calendar.getInstance(); Calendar cal3=Calendar.getInstance(); SimpleDateFormat sdf=new SimpleDateFormat("d/M/yyyy H:m"); try {Date date=sdf.parse(starttime.get(position)); Date stopDate=sdf.parse(stoptime.get(position)); cal1.setTime(date); cal3.setTime(stopDate); Log.e("date",starttime.get(position)+""); }catch (ParseException e){ } String code=getCode(starttime.get(position)); Log.e("onClick: ",""+code); String start= code+"1"; String stop=code+"0"; dba.updateReqcode(name.get(position),start,stop); int startcode=Integer.parseInt(start); int stopcode=Integer.parseInt(stop); Intent intent = new Intent(getContext(), PresetBroadcastReceiver.class); intent.putExtra("status",1); intent.putExtra("name",name.get(position)); intent.putExtra("position",position); PendingIntent pendingIntent = PendingIntent.getBroadcast( getContext(),startcode, intent, PendingIntent.FLAG_CANCEL_CURRENT); AlarmManager alarmManager = (AlarmManager)getContext().getSystemService(getContext().ALARM_SERVICE); alarmManager.set(AlarmManager.RTC_WAKEUP,cal1.getTimeInMillis(), pendingIntent); Intent stopIntent = new Intent(getContext(), PresetBroadcastReceiver.class); stopIntent.putExtra("status",0); stopIntent.putExtra("name",name.get(position)); stopIntent.putExtra("position",position); PendingIntent pendingIntentStop = PendingIntent.getBroadcast( getContext(),stopcode, stopIntent, PendingIntent.FLAG_CANCEL_CURRENT); AlarmManager alarmManagerStop = (AlarmManager)getContext().getSystemService(getContext().ALARM_SERVICE); alarmManagerStop.set(AlarmManager.RTC_WAKEUP,cal3.getTimeInMillis(), pendingIntentStop); flag=1; }else{ int startCode=Integer.parseInt(dba.getReqcodeonn(name.get(position))); int stopCode=Integer.parseInt(dba.getReqcodeoff(name.get(position))); i4.setImageDrawable(getContext().getResources().getDrawable(R.drawable.ic_alarm_off_black_24dp)); dba.updateStatus(0,name.get(position)); Intent intent = new Intent(getContext(), PresetBroadcastReceiver.class); PendingIntent pendingIntent = PendingIntent.getBroadcast( getContext(),startCode, intent, 0); AlarmManager alarmManager = (AlarmManager)getContext().getSystemService(getContext().ALARM_SERVICE); alarmManager.cancel(pendingIntent); PendingIntent pendingStopIntent = PendingIntent.getBroadcast( getContext(),stopCode, intent, 0); AlarmManager alarmManagerStop = (AlarmManager)getContext().getSystemService(getContext().ALARM_SERVICE); alarmManagerStop.cancel(pendingStopIntent); flag=0; } } }); return convertView; } public String getCode(String date) { String coded=""; String[] splitted = date.split("[/ :]"); for (int i=0;i<splitted.length;i++) { if(i==2) { splitted[i] =""; } coded=coded + splitted[i]; } return coded; } public void removeAll(int listItemPosition) { name.remove(listItemPosition); starttime.remove(listItemPosition); stoptime.remove(listItemPosition); status.remove(listItemPosition); } }
7,679
0.603724
0.596041
203
36.832512
32.176109
130
false
false
0
0
0
0
0
0
0.79803
false
false
2
a1ef30c93c7494e3f3954512185f8b40a6b9627e
31,619,549,255,039
51c6f8606af59c7cf8f77795eb966acc09038f80
/app/src/main/java/com/lianzhong/skyeye/bean/result/FuHeResult.java
ee51bd1ac63456de8cee16995df15a51519117ea
[]
no_license
GravesMrma/SkyEye
https://github.com/GravesMrma/SkyEye
004fa3d753b39747c14a190ded621a91fa2f4a33
d19ee200a6a3d9347d27117f68bff6711a102851
refs/heads/master
2020-06-08T00:43:19.707000
2019-10-26T09:35:17
2019-10-26T09:35:17
193,126,161
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.lianzhong.skyeye.bean.result; /** * Created by ZhouJunJie on 2019/1/11. * * @function */ public class FuHeResult { private int id; private String c_stocode; private String c_buscode; private String c_creater; private String c_creatername; private String c_date; private String c_code; private int c_type; private int c_finish; private int c_passrate; private int c_status; private String c_standby1; public String getC_standby1() { return c_standby1; } public void setC_standby1(String c_standby1) { this.c_standby1 = c_standby1; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getC_stocode() { return c_stocode; } public void setC_stocode(String c_stocode) { this.c_stocode = c_stocode; } public String getC_buscode() { return c_buscode; } public void setC_buscode(String c_buscode) { this.c_buscode = c_buscode; } public String getC_creater() { return c_creater; } public void setC_creater(String c_creater) { this.c_creater = c_creater; } public String getC_creatername() { return c_creatername; } public void setC_creatername(String c_creatername) { this.c_creatername = c_creatername; } public String getC_date() { return c_date; } public void setC_date(String c_date) { this.c_date = c_date; } public String getC_code() { return c_code; } public void setC_code(String c_code) { this.c_code = c_code; } public int getC_type() { return c_type; } public void setC_type(int c_type) { this.c_type = c_type; } public int getC_finish() { return c_finish; } public void setC_finish(int c_finish) { this.c_finish = c_finish; } public int getC_passrate() { return c_passrate; } public void setC_passrate(int c_passrate) { this.c_passrate = c_passrate; } public int getC_status() { return c_status; } public void setC_status(int c_status) { this.c_status = c_status; } }
UTF-8
Java
2,426
java
FuHeResult.java
Java
[ { "context": "ianzhong.skyeye.bean.result;\r\n\r\n/**\r\n * Created by ZhouJunJie on 2019/1/11.\r\n *\r\n * @function\r\n */\r\n\r\npublic cl", "end": 74, "score": 0.9994616508483887, "start": 64, "tag": "NAME", "value": "ZhouJunJie" } ]
null
[]
package com.lianzhong.skyeye.bean.result; /** * Created by ZhouJunJie on 2019/1/11. * * @function */ public class FuHeResult { private int id; private String c_stocode; private String c_buscode; private String c_creater; private String c_creatername; private String c_date; private String c_code; private int c_type; private int c_finish; private int c_passrate; private int c_status; private String c_standby1; public String getC_standby1() { return c_standby1; } public void setC_standby1(String c_standby1) { this.c_standby1 = c_standby1; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getC_stocode() { return c_stocode; } public void setC_stocode(String c_stocode) { this.c_stocode = c_stocode; } public String getC_buscode() { return c_buscode; } public void setC_buscode(String c_buscode) { this.c_buscode = c_buscode; } public String getC_creater() { return c_creater; } public void setC_creater(String c_creater) { this.c_creater = c_creater; } public String getC_creatername() { return c_creatername; } public void setC_creatername(String c_creatername) { this.c_creatername = c_creatername; } public String getC_date() { return c_date; } public void setC_date(String c_date) { this.c_date = c_date; } public String getC_code() { return c_code; } public void setC_code(String c_code) { this.c_code = c_code; } public int getC_type() { return c_type; } public void setC_type(int c_type) { this.c_type = c_type; } public int getC_finish() { return c_finish; } public void setC_finish(int c_finish) { this.c_finish = c_finish; } public int getC_passrate() { return c_passrate; } public void setC_passrate(int c_passrate) { this.c_passrate = c_passrate; } public int getC_status() { return c_status; } public void setC_status(int c_status) { this.c_status = c_status; } }
2,426
0.546579
0.540808
129
16.806202
16.216116
56
false
false
0
0
0
0
0
0
0.286822
false
false
2
bba6de33808ee70719af3b7a6d625ffa5021d0d8
29,772,713,343,334
a0f1001a3e872a17d21ec76461cc6761286c5734
/day01/WanzhijingApplication/app/src/main/java/com/example/wanzhijingapplication/fragment/GunzhuFragment.java
d0c5d90d76462261ab924d454450100546c7ecf4
[]
no_license
JohnZhang1000/group6
https://github.com/JohnZhang1000/group6
e7d0a447a77cc9e0426e9ba602fef2293d6f105a
a26297b745585e60f03264effa8a81ccb063e5f0
refs/heads/main
2023-02-08T22:48:08.882000
2021-01-05T00:26:52
2021-01-05T00:26:52
322,816,503
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.wanzhijingapplication.fragment; import android.os.Bundle; import androidx.fragment.app.Fragment; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Toast; import com.example.wanzhijingapplication.R; import com.example.wanzhijingapplication.SqBean; import com.example.wanzhijingapplication.SqUtlis; import com.example.wanzhijingapplication.bean.Shipin; import com.example.wanzhijingapplication.bean.Tu; import com.example.wanzhijingapplication.bean.WenBen; import com.example.wanzhijingapplication.bean.WodeBean; import com.example.wanzhijingapplication.iview.IView; import com.example.wanzhijingapplication.mdapter.Guanadapter; import com.example.wanzhijingapplication.precick.Precick; import java.util.ArrayList; /** * A simple {@link Fragment} subclass. */ public class GunzhuFragment extends Fragment implements IView { private RecyclerView rv; private ArrayList<WodeBean.DataBeanX.DataBean> dataBeans; private Guanadapter guanadapter; public GunzhuFragment() { // Required empty public constructor } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment View view= inflater.inflate(R.layout.fragment_gunzhu, container, false); rv = view.findViewById(R.id.rv); initData(); initView(); return view; } private void initView() { Precick precick = new Precick(this); precick.por(); } private void initData() { rv.setLayoutManager(new LinearLayoutManager(getActivity())); dataBeans = new ArrayList<>(); guanadapter = new Guanadapter(getActivity(), dataBeans); rv.setAdapter(guanadapter); guanadapter.setIoncick(new Guanadapter.Ioncick() { @Override public void ioncick(int pos) { SqBean sqBean = new SqBean(); WodeBean.DataBeanX.DataBean dataBean = dataBeans.get(pos); String title = dataBean.getTitle(); String activityIcon = dataBean.getActivityIcon(); sqBean.setText(title); sqBean.setUrl(activityIcon); Long insert = SqUtlis.getSqUtlis().insert(sqBean); if(insert>0){ Toast.makeText(getActivity(), "添加成功", Toast.LENGTH_SHORT).show(); } } }); } @Override public void tupian(Tu tu) { } @Override public void shipin(Shipin shipin) { } @Override public void wenben(WenBen wenBen) { } @Override public void wode(WodeBean wenBen) { dataBeans.addAll(wenBen.getData().getData()); guanadapter.item(dataBeans); guanadapter.notifyDataSetChanged(); } @Override public void shi(String string) { Log.d("tag",string); } }
UTF-8
Java
3,144
java
GunzhuFragment.java
Java
[]
null
[]
package com.example.wanzhijingapplication.fragment; import android.os.Bundle; import androidx.fragment.app.Fragment; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Toast; import com.example.wanzhijingapplication.R; import com.example.wanzhijingapplication.SqBean; import com.example.wanzhijingapplication.SqUtlis; import com.example.wanzhijingapplication.bean.Shipin; import com.example.wanzhijingapplication.bean.Tu; import com.example.wanzhijingapplication.bean.WenBen; import com.example.wanzhijingapplication.bean.WodeBean; import com.example.wanzhijingapplication.iview.IView; import com.example.wanzhijingapplication.mdapter.Guanadapter; import com.example.wanzhijingapplication.precick.Precick; import java.util.ArrayList; /** * A simple {@link Fragment} subclass. */ public class GunzhuFragment extends Fragment implements IView { private RecyclerView rv; private ArrayList<WodeBean.DataBeanX.DataBean> dataBeans; private Guanadapter guanadapter; public GunzhuFragment() { // Required empty public constructor } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment View view= inflater.inflate(R.layout.fragment_gunzhu, container, false); rv = view.findViewById(R.id.rv); initData(); initView(); return view; } private void initView() { Precick precick = new Precick(this); precick.por(); } private void initData() { rv.setLayoutManager(new LinearLayoutManager(getActivity())); dataBeans = new ArrayList<>(); guanadapter = new Guanadapter(getActivity(), dataBeans); rv.setAdapter(guanadapter); guanadapter.setIoncick(new Guanadapter.Ioncick() { @Override public void ioncick(int pos) { SqBean sqBean = new SqBean(); WodeBean.DataBeanX.DataBean dataBean = dataBeans.get(pos); String title = dataBean.getTitle(); String activityIcon = dataBean.getActivityIcon(); sqBean.setText(title); sqBean.setUrl(activityIcon); Long insert = SqUtlis.getSqUtlis().insert(sqBean); if(insert>0){ Toast.makeText(getActivity(), "添加成功", Toast.LENGTH_SHORT).show(); } } }); } @Override public void tupian(Tu tu) { } @Override public void shipin(Shipin shipin) { } @Override public void wenben(WenBen wenBen) { } @Override public void wode(WodeBean wenBen) { dataBeans.addAll(wenBen.getData().getData()); guanadapter.item(dataBeans); guanadapter.notifyDataSetChanged(); } @Override public void shi(String string) { Log.d("tag",string); } }
3,144
0.670918
0.670599
110
27.50909
23.318251
85
false
false
0
0
0
0
0
0
0.509091
false
false
2
f6ed8ae1b62f114ac394eb82e1886ec4f14b3492
3,547,643,033,397
84499b1f250541567e7057bd63fec39f13b4bf71
/src/main/java/com/cognizant/DaoImpl/AddDetails.java
1bf8eb2cefe43b3aeee4fc23ad126b47f691a0b1
[]
no_license
vineeth1816/RestPractice
https://github.com/vineeth1816/RestPractice
71d80f6645c2e5bb6fe16181784aba3a552ea277
cc51e2c9849b763e4dae08a5105398f315ab4b32
refs/heads/master
2023-06-09T22:23:47.360000
2021-06-27T06:20:03
2021-06-27T06:20:03
380,169,868
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.cognizant.DaoImpl; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.stereotype.Component; import com.cognizant.Dao.AddDetailsDao; import com.cognizant.Model.Person; @Component public class AddDetails implements AddDetailsDao { @Autowired JdbcTemplate jdbcTemplate; @Override public Boolean add(Person p) { int i=jdbcTemplate.update("INSERT INTO details VALUES(?,?)", p.getId(),p.getName()); if(i>0) return true; return false; } }
UTF-8
Java
557
java
AddDetails.java
Java
[]
null
[]
package com.cognizant.DaoImpl; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.stereotype.Component; import com.cognizant.Dao.AddDetailsDao; import com.cognizant.Model.Person; @Component public class AddDetails implements AddDetailsDao { @Autowired JdbcTemplate jdbcTemplate; @Override public Boolean add(Person p) { int i=jdbcTemplate.update("INSERT INTO details VALUES(?,?)", p.getId(),p.getName()); if(i>0) return true; return false; } }
557
0.775584
0.773788
24
22.208334
23.126427
86
false
false
0
0
0
0
0
0
1.25
false
false
2
d4e5100ce70e973c8bda91af1314b314fee8d701
12,086,037,993,995
e2ba3f1c1f2e74a4fb0e6f9bb2fa8e8c49334f4f
/methods/SimpleMethod.java
5f10747afa1074dd00b5dda6680ef89e99b63397
[]
no_license
Lukadoss/AOS_Particle_detection
https://github.com/Lukadoss/AOS_Particle_detection
18ab826674b0c26bb686a4e4233acfec9edabdf0
94fc8be01aae796ae075747b3973b3d4cc3b9861
refs/heads/master
2020-08-21T17:42:35.446000
2019-11-06T18:40:15
2019-11-06T18:40:15
216,210,749
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package methods; import java.util.ArrayList; import java.util.Collections; public class SimpleMethod { private double result; private ArrayList<Double> particleRadius; public SimpleMethod(ArrayList<Double> particleRadius) { this.particleRadius = particleRadius; } public double getResult() { return result; } public void doMean() { double avgVolume; double wholeVol = 0; for (double r : particleRadius) wholeVol += r; avgVolume = wholeVol / particleRadius.size(); // System.out.println(avgVolume); countResult(avgVolume); } public void doMedian() { double median; Collections.sort(particleRadius); if ((particleRadius.size()/2.0)%1==0){ median = particleRadius.get(particleRadius.size()/2); }else{ median = (particleRadius.get(particleRadius.size()/2)+particleRadius.get(particleRadius.size()/2+1))/2.0; } // System.out.println(median); countResult(median); } public void doMidRange() { double mid; Collections.sort(particleRadius); mid = (particleRadius.get(0)+particleRadius.get(particleRadius.size()-1))/2; // System.out.println(mid); countResult(mid); } private void countResult(double divisor) { ArrayList<Double> multiplicity = new ArrayList<>(); for (double r : particleRadius) multiplicity.add(r / divisor); // System.out.println(multiplicity); for (int i = 0; i < particleRadius.size(); i++) { if (particleRadius.get(i) <= divisor) { result += 1; } else { result += multiplicity.get(i); } } // System.out.println(result); } }
UTF-8
Java
1,797
java
SimpleMethod.java
Java
[]
null
[]
package methods; import java.util.ArrayList; import java.util.Collections; public class SimpleMethod { private double result; private ArrayList<Double> particleRadius; public SimpleMethod(ArrayList<Double> particleRadius) { this.particleRadius = particleRadius; } public double getResult() { return result; } public void doMean() { double avgVolume; double wholeVol = 0; for (double r : particleRadius) wholeVol += r; avgVolume = wholeVol / particleRadius.size(); // System.out.println(avgVolume); countResult(avgVolume); } public void doMedian() { double median; Collections.sort(particleRadius); if ((particleRadius.size()/2.0)%1==0){ median = particleRadius.get(particleRadius.size()/2); }else{ median = (particleRadius.get(particleRadius.size()/2)+particleRadius.get(particleRadius.size()/2+1))/2.0; } // System.out.println(median); countResult(median); } public void doMidRange() { double mid; Collections.sort(particleRadius); mid = (particleRadius.get(0)+particleRadius.get(particleRadius.size()-1))/2; // System.out.println(mid); countResult(mid); } private void countResult(double divisor) { ArrayList<Double> multiplicity = new ArrayList<>(); for (double r : particleRadius) multiplicity.add(r / divisor); // System.out.println(multiplicity); for (int i = 0; i < particleRadius.size(); i++) { if (particleRadius.get(i) <= divisor) { result += 1; } else { result += multiplicity.get(i); } } // System.out.println(result); } }
1,797
0.594324
0.58542
63
27.523809
23.672941
117
false
false
0
0
0
0
0
0
0.507937
false
false
2
5d2d1133ef4e7d0b08854169c6f30892df4cfc25
19,636,590,543,409
07c08e514ac6de2cf2305d860e164071e867e422
/Engajamento02-DanielMedeiros_MayconCamargo/frequencia-secomp-master/frequencia-secomp-master/src/main/java/org/example/App.java
779e77a49cb35f1bc71c64709e236926aa1751f1
[]
no_license
danmeirosp/frequencia-secomp
https://github.com/danmeirosp/frequencia-secomp
dafb1353d5ff1345d7271463b6c98602789d1675
50d3cd99663e460d0e4fbffc18df4914dfe9fd09
refs/heads/master
2021-03-17T04:44:48.140000
2020-03-13T01:51:19
2020-03-13T01:51:19
246,961,404
0
0
null
true
2020-03-13T01:09:45
2020-03-13T01:09:44
2020-03-07T00:01:09
2020-03-07T00:01:07
7
0
0
0
null
false
false
package org.example; import org.example.models.Aluno; import org.example.persistence.AlunoPersistence; import java.util.ArrayList; import java.util.List; import java.util.Scanner; /** * Hello world! * */ public class App { //criando list direto na classe app private static List<String> alunos; public static void main( String[] args ){ int menu = -1; //criacao arraylist alunos = new ArrayList<String>(); do { AlunoPersistence alunoPersistence = new AlunoPersistence(); Scanner scanner = new Scanner(System.in); System.out.println("1 Cadastra aluno, \n2 Exibe a lista, \n0 Encerra o aplicativo"); menu = scanner.nextInt(); switch (menu) { case 1: Aluno aluno = new Aluno(); System.out.println("Nome do aluno: \n"); aluno.setNome(scanner.nextLine()); System.out.println("RA do aluno: \n"); aluno.setRa(scanner.nextLine()); /*Utilizou a classe AlunoPersistence para validar se a String de entrada já se encontrava na lista. Resolução: Pode-se utilizar o método para criar a String do aluno e realizar sua validação dentro do proprio case buscando o método na mesma classe ao invés de utilizar uma outra classe. (CODIGO BEM ESTRUTURADO COM APENAS UMA CLASSE)*/ adicionaAluno(); System.out.println("Aluno Criado"); //alunoPersistence.adicionaAluno(aluno); break; case 2: /*O mesmo raciocinio da criação do aluno segue para imprimir os dados, utilizando apenas a chamada de um método dentro do próprio case.*/ exibeLista(); //alunoPersistence.exibeLista(); break; case 0: break; default: System.out.println("Opção Inválida!"); menu = -1; break; } } while (menu != 0); System.out.println(); } /*Utilização de métodos separando das funcionalidades - O case 1 e 2 fazem a busca dos métodos diretamente nessa mesma classe ao invés de buscar em outra classe - Utilizamos as funções que foram criadas na classe AlunoPersistence.java trazendo para dentro da App.java (UTILIZAÇÃO DE MÉTODOS PARA TORNAR O CODIGO MAIS EFICIENTE)*/ //adicionaAluno public void adicionaAluno(Aluno aluno) { boolean exist = false; for(Aluno a:this.alunos){ if(aluno.getRa().equals(a.getRa())){ exist = true; System.out.println("O aluno ja existe na lista !!"); break; } } this.alunos.add(aluno); } //Exibe lista de aluno public void exibeLista(){ for(Aluno a:this.alunos){ System.out.println("Nome :"+ a.getNome() + "RA :"+ a.getRa()); } } }
UTF-8
Java
3,135
java
App.java
Java
[]
null
[]
package org.example; import org.example.models.Aluno; import org.example.persistence.AlunoPersistence; import java.util.ArrayList; import java.util.List; import java.util.Scanner; /** * Hello world! * */ public class App { //criando list direto na classe app private static List<String> alunos; public static void main( String[] args ){ int menu = -1; //criacao arraylist alunos = new ArrayList<String>(); do { AlunoPersistence alunoPersistence = new AlunoPersistence(); Scanner scanner = new Scanner(System.in); System.out.println("1 Cadastra aluno, \n2 Exibe a lista, \n0 Encerra o aplicativo"); menu = scanner.nextInt(); switch (menu) { case 1: Aluno aluno = new Aluno(); System.out.println("Nome do aluno: \n"); aluno.setNome(scanner.nextLine()); System.out.println("RA do aluno: \n"); aluno.setRa(scanner.nextLine()); /*Utilizou a classe AlunoPersistence para validar se a String de entrada já se encontrava na lista. Resolução: Pode-se utilizar o método para criar a String do aluno e realizar sua validação dentro do proprio case buscando o método na mesma classe ao invés de utilizar uma outra classe. (CODIGO BEM ESTRUTURADO COM APENAS UMA CLASSE)*/ adicionaAluno(); System.out.println("Aluno Criado"); //alunoPersistence.adicionaAluno(aluno); break; case 2: /*O mesmo raciocinio da criação do aluno segue para imprimir os dados, utilizando apenas a chamada de um método dentro do próprio case.*/ exibeLista(); //alunoPersistence.exibeLista(); break; case 0: break; default: System.out.println("Opção Inválida!"); menu = -1; break; } } while (menu != 0); System.out.println(); } /*Utilização de métodos separando das funcionalidades - O case 1 e 2 fazem a busca dos métodos diretamente nessa mesma classe ao invés de buscar em outra classe - Utilizamos as funções que foram criadas na classe AlunoPersistence.java trazendo para dentro da App.java (UTILIZAÇÃO DE MÉTODOS PARA TORNAR O CODIGO MAIS EFICIENTE)*/ //adicionaAluno public void adicionaAluno(Aluno aluno) { boolean exist = false; for(Aluno a:this.alunos){ if(aluno.getRa().equals(a.getRa())){ exist = true; System.out.println("O aluno ja existe na lista !!"); break; } } this.alunos.add(aluno); } //Exibe lista de aluno public void exibeLista(){ for(Aluno a:this.alunos){ System.out.println("Nome :"+ a.getNome() + "RA :"+ a.getRa()); } } }
3,135
0.557878
0.554341
82
36.92683
31.691647
157
false
false
0
0
0
0
0
0
0.487805
false
false
2
f1da8a53d5764a70693a9e05edf26609a0b80030
19,636,590,546,122
1df6f5acaf14804dbea7b3273c1e7fa25b6f13fa
/src/com/vigglet/oei/service/Service.java
38ed920c55a3896f4b649e78ee68354bf7cab301
[]
no_license
knutsbyviktor/oei
https://github.com/knutsbyviktor/oei
d4b4380224a1ebf82e2243c5e4ae4aa3e90109f3
ac83f7cc02e27aa709d9327d6a899ff5584a79e4
refs/heads/master
2021-01-10T08:28:39.816000
2015-12-31T15:46:15
2015-12-31T15:46:15
48,744,087
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.vigglet.oei.service; import com.vigglet.model.BaseModel; import com.vigglet.oei.servicerow.Servicerow; import com.vigglet.oei.servicerow.ServicerowUtil; import com.vigglet.oei.servicetime.Servicetime; import com.vigglet.oei.servicetime.ServicetimeUtil; import com.vigglet.oei.technician.Technician; import com.vigglet.oei.vehicle.Vehicle; import com.vigglet.util.DateUtil; import com.vigglet.oei.technician.TechnicianUtil; import com.vigglet.oei.vehicle.VehicleUtil; import java.util.ArrayList; import java.util.List; /** * * @author vikn */ public class Service extends BaseModel{ private int id; private int vehicle; private int technician; private long date; private String note; private int company; private String description; private List<Servicerow> rows; private List<Servicetime> times; @Override public int getId() { return id; } public void setId(int id) { this.id = id; } public int getVehicle() { return vehicle; } public void setVehicle(int vehicle) { this.vehicle = vehicle; } public int getTechnician() { return technician; } public void setTechnician(int technician) { this.technician = technician; } public long getDate() { return date; } public void setDate(long date) { this.date = date; } public String getNote() { return note; } public void setNote(String note) { this.note = note; } public int getCompany() { return company; } public void setCompany(int company) { this.company = company; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public double getCalculatedhours(){ return 2.5; } public double getActualhours(){ double result = 0; for(Servicetime time : ServicetimeUtil.getInstance().findByService(getId())){ result += time.getHours(); } return result; } public double getMaterialCost(){ double result = 0; for(Servicerow sr : ServicerowUtil.getInstance().findByService(getId())){ result += sr.getPrice() * sr.getQuantity(); } return result; } public double getCalculatedcost(){ Technician technician = TechnicianUtil.getInstance().findById(getTechnician()); int result = 0; if(technician != null){ result = technician.getDebitingcost(); } return result * getCalculatedhours(); } public double getActualcost(){ double result = 0; for(Servicetime time : ServicetimeUtil.getInstance().findByService(getId())){ Technician technician = TechnicianUtil.getInstance().findById(time.getTechnician()); if(technician != null){ result += technician.getDebitingcost() * time.getHours(); } } return result; } public String getTechnicianString(){ Technician technician = TechnicianUtil.getInstance().findById(getTechnician()); String result = ""; if(technician != null){ result = technician.getFirstname() + " " + technician.getLastname(); } return result; } public int getTechnicianCost(){ Technician technician = TechnicianUtil.getInstance().findById(getTechnician()); int result = 0; if(technician != null){ result = technician.getDebitingcost(); } return result; } public String getVehicleString(){ Vehicle vehicle = VehicleUtil.getInstance().findById(getVehicle()); String result = ""; if(vehicle != null){ result = vehicle.getNumber() + " - " + vehicle.getName(); } return result; } public List<Servicerow> getRows(){ if(rows == null){ rows = new ArrayList(ServicerowUtil.getInstance().orderByListorder(getId())); } return rows; } public List<Servicetime> getTimes(){ if(times == null){ times = (List<Servicetime>) ServicetimeUtil.getInstance().findByService(getId()); } return times; } public String getDateString() { return DateUtil.formatDate(getDate()); } public String getCompanyString(){ return "NOT IMPLEMENTED YET"; } @Override public String toString() { return "Service{" + "id=" + id + ", vehicle=" + vehicle + ", technician=" + technician + ", date=" + date + ", note=" + note + ", company=" + company + '}'; } @Override public String toJson() { return "{" + " \"id\":" + id + "," + " \"vehicle\":" + getVehicle()+ "," + " \"vehicleString\":\"" + getVehicleString() + "\"," + " \"technician\":" + getTechnician() + "," + " \"technicianString\":\"" + getTechnicianString() + "\"," + " \"date\":" + getDate() +"," + " \"dateString\":\"" + getDateString() +"\"," + " \"note\":\"" + getNote() + "\"," + " \"company\":" + getCompany() + "," + " \"companyString\":\"" + getCompanyString() + "\"" + "}"; } // private void asdasdasd(){ // try { // Class<?> c = Class.forName(args[0]); // Object t = c.newInstance(); // // Method[] allMethods = c.getDeclaredMethods(); // for (Method m : allMethods) { // String mname = m.getName(); // if (!mname.startsWith("test") // || (m.getGenericReturnType() != boolean.class)) { // continue; // } // Type[] pType = m.getGenericParameterTypes(); // if ((pType.length != 1) // || Locale.class.isAssignableFrom(pType[0].getClass())) { // continue; // } // // out.format("invoking %s()%n", mname); // try { // m.setAccessible(true); // Object o = m.invoke(t, new Locale(args[1], args[2], args[3])); // out.format("%s() returned %b%n", mname, (Boolean) o); // // // Handle any exceptions thrown by method to be invoked. // } catch (InvocationTargetException x) { // Throwable cause = x.getCause(); // err.format("invocation of %s failed: %s%n", // mname, cause.getMessage()); // } // } // // // production code should handle these exceptions more gracefully // } catch (ClassNotFoundException x) { // x.printStackTrace(); // } catch (InstantiationException x) { // x.printStackTrace(); // } catch (IllegalAccessException x) { // x.printStackTrace(); // } // } @Override public boolean matchesSearchableFields(String... searchStrings) { for(String str : searchStrings){ str = str.toLowerCase().trim(); return getDateString().contains(str) || getNote().toLowerCase().contains(str) || getTechnicianString().toLowerCase().contains(str) || getVehicleString().toLowerCase().contains(str); } return false; } }
UTF-8
Java
7,395
java
Service.java
Java
[ { "context": "rayList;\nimport java.util.List;\n\n/**\n *\n * @author vikn\n */\npublic class Service extends BaseModel{\n \n", "end": 740, "score": 0.9992987513542175, "start": 736, "tag": "USERNAME", "value": "vikn" } ]
null
[]
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.vigglet.oei.service; import com.vigglet.model.BaseModel; import com.vigglet.oei.servicerow.Servicerow; import com.vigglet.oei.servicerow.ServicerowUtil; import com.vigglet.oei.servicetime.Servicetime; import com.vigglet.oei.servicetime.ServicetimeUtil; import com.vigglet.oei.technician.Technician; import com.vigglet.oei.vehicle.Vehicle; import com.vigglet.util.DateUtil; import com.vigglet.oei.technician.TechnicianUtil; import com.vigglet.oei.vehicle.VehicleUtil; import java.util.ArrayList; import java.util.List; /** * * @author vikn */ public class Service extends BaseModel{ private int id; private int vehicle; private int technician; private long date; private String note; private int company; private String description; private List<Servicerow> rows; private List<Servicetime> times; @Override public int getId() { return id; } public void setId(int id) { this.id = id; } public int getVehicle() { return vehicle; } public void setVehicle(int vehicle) { this.vehicle = vehicle; } public int getTechnician() { return technician; } public void setTechnician(int technician) { this.technician = technician; } public long getDate() { return date; } public void setDate(long date) { this.date = date; } public String getNote() { return note; } public void setNote(String note) { this.note = note; } public int getCompany() { return company; } public void setCompany(int company) { this.company = company; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public double getCalculatedhours(){ return 2.5; } public double getActualhours(){ double result = 0; for(Servicetime time : ServicetimeUtil.getInstance().findByService(getId())){ result += time.getHours(); } return result; } public double getMaterialCost(){ double result = 0; for(Servicerow sr : ServicerowUtil.getInstance().findByService(getId())){ result += sr.getPrice() * sr.getQuantity(); } return result; } public double getCalculatedcost(){ Technician technician = TechnicianUtil.getInstance().findById(getTechnician()); int result = 0; if(technician != null){ result = technician.getDebitingcost(); } return result * getCalculatedhours(); } public double getActualcost(){ double result = 0; for(Servicetime time : ServicetimeUtil.getInstance().findByService(getId())){ Technician technician = TechnicianUtil.getInstance().findById(time.getTechnician()); if(technician != null){ result += technician.getDebitingcost() * time.getHours(); } } return result; } public String getTechnicianString(){ Technician technician = TechnicianUtil.getInstance().findById(getTechnician()); String result = ""; if(technician != null){ result = technician.getFirstname() + " " + technician.getLastname(); } return result; } public int getTechnicianCost(){ Technician technician = TechnicianUtil.getInstance().findById(getTechnician()); int result = 0; if(technician != null){ result = technician.getDebitingcost(); } return result; } public String getVehicleString(){ Vehicle vehicle = VehicleUtil.getInstance().findById(getVehicle()); String result = ""; if(vehicle != null){ result = vehicle.getNumber() + " - " + vehicle.getName(); } return result; } public List<Servicerow> getRows(){ if(rows == null){ rows = new ArrayList(ServicerowUtil.getInstance().orderByListorder(getId())); } return rows; } public List<Servicetime> getTimes(){ if(times == null){ times = (List<Servicetime>) ServicetimeUtil.getInstance().findByService(getId()); } return times; } public String getDateString() { return DateUtil.formatDate(getDate()); } public String getCompanyString(){ return "NOT IMPLEMENTED YET"; } @Override public String toString() { return "Service{" + "id=" + id + ", vehicle=" + vehicle + ", technician=" + technician + ", date=" + date + ", note=" + note + ", company=" + company + '}'; } @Override public String toJson() { return "{" + " \"id\":" + id + "," + " \"vehicle\":" + getVehicle()+ "," + " \"vehicleString\":\"" + getVehicleString() + "\"," + " \"technician\":" + getTechnician() + "," + " \"technicianString\":\"" + getTechnicianString() + "\"," + " \"date\":" + getDate() +"," + " \"dateString\":\"" + getDateString() +"\"," + " \"note\":\"" + getNote() + "\"," + " \"company\":" + getCompany() + "," + " \"companyString\":\"" + getCompanyString() + "\"" + "}"; } // private void asdasdasd(){ // try { // Class<?> c = Class.forName(args[0]); // Object t = c.newInstance(); // // Method[] allMethods = c.getDeclaredMethods(); // for (Method m : allMethods) { // String mname = m.getName(); // if (!mname.startsWith("test") // || (m.getGenericReturnType() != boolean.class)) { // continue; // } // Type[] pType = m.getGenericParameterTypes(); // if ((pType.length != 1) // || Locale.class.isAssignableFrom(pType[0].getClass())) { // continue; // } // // out.format("invoking %s()%n", mname); // try { // m.setAccessible(true); // Object o = m.invoke(t, new Locale(args[1], args[2], args[3])); // out.format("%s() returned %b%n", mname, (Boolean) o); // // // Handle any exceptions thrown by method to be invoked. // } catch (InvocationTargetException x) { // Throwable cause = x.getCause(); // err.format("invocation of %s failed: %s%n", // mname, cause.getMessage()); // } // } // // // production code should handle these exceptions more gracefully // } catch (ClassNotFoundException x) { // x.printStackTrace(); // } catch (InstantiationException x) { // x.printStackTrace(); // } catch (IllegalAccessException x) { // x.printStackTrace(); // } // } @Override public boolean matchesSearchableFields(String... searchStrings) { for(String str : searchStrings){ str = str.toLowerCase().trim(); return getDateString().contains(str) || getNote().toLowerCase().contains(str) || getTechnicianString().toLowerCase().contains(str) || getVehicleString().toLowerCase().contains(str); } return false; } }
7,395
0.577552
0.575794
271
26.287823
25.841808
193
false
false
0
0
0
0
0
0
0.819188
false
false
2
c70102f1e8eed0a2c86385360a7253695d520ec0
30,219,389,915,635
7b5a744665462c985652bd05685b823a0c6d64f6
/zttx-tradefile/src/main/java/com/zttx/web/module/common/service/ImageService.java
df769bb35814eb3170b33f75a4b1b395ad19e384
[]
no_license
isoundy000/zttx-trading
https://github.com/isoundy000/zttx-trading
d8a7de3d846e1cc2eb0b193c31d45d36b04f7372
1eee959fcf1d460fe06dfcb7c79c218bcb6f5872
refs/heads/master
2021-01-14T01:07:42.580000
2016-01-10T04:12:40
2016-01-10T04:12:40
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.zttx.web.module.common.service; import com.zttx.web.bean.Watermark; import com.zttx.web.module.common.entity.UploadAttSize; import com.zttx.web.utils.ImageUtils; import com.zttx.web.utils.LoggerUtils; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.io.FileUtils; import org.apache.commons.io.FilenameUtils; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import java.io.File; import java.io.IOException; import java.util.List; /** * <p>File:ImageServiceImpl.java </p> * <p>Title: ImageServiceImpl </p> * <p>Description: ImageServiceImpl </p> * <p>Copyright: Copyright (c) 2014 08/10/2015 13:56</p> * <p>Company: 8637.com</p> * * @author playguy * @version 1.0 */ @Component public class ImageService { private static final Logger logger = LoggerFactory.getLogger(ImageService.class); @Autowired private UploadAttSizeService uploadAttSizeService; /** * 压缩图片 * @param file * @param cateKey * @throws IOException * @author 夏铭 */ public void resizeImage(File file, String cateKey) throws IOException { resizeImage(file, cateKey, null); } /** * 压缩图片, 可以加水印 * @param file * @param cateKey * @param watermark * @throws IOException * @author 夏铭 */ public void resizeImage(File file, String cateKey, Watermark watermark) throws IOException { String fileName = file.getAbsolutePath(); String extension = FilenameUtils.getExtension(fileName); FileUtils.copyFile(file, new File(fileName + "_orig." + extension)); if (StringUtils.isNotBlank(cateKey)) { List<UploadAttSize> uploadAttSizes = uploadAttSizeService.findByCateKey(cateKey); if (!CollectionUtils.isEmpty(uploadAttSizes)) for (UploadAttSize uploadAttSize : uploadAttSizes) { String pathname = fileName + "_" + uploadAttSize.getWidth() + "x" + uploadAttSize.getHeight() + "." + extension; File newFile = new File(pathname); File temp = ImageUtils.resizeImage(file, uploadAttSize.getWidth(), uploadAttSize.getHeight()); try { com.zttx.web.utils.FileUtils.moveFile(temp, newFile, true); } catch (Exception e) { LoggerUtils.logError(logger, e.getLocalizedMessage()); } } } } }
UTF-8
Java
2,691
java
ImageService.java
Java
[ { "context": "3:56</p>\n * <p>Company: 8637.com</p>\n *\n * @author playguy\n * @version 1.0\n */\n@Component\npublic class Image", "end": 865, "score": 0.9995532631874084, "start": 858, "tag": "USERNAME", "value": "playguy" }, { "context": "cateKey\n * @throws IOException\n * @author 夏铭\n */\n public void resizeImage(File file, St", "end": 1197, "score": 0.9237282872200012, "start": 1195, "tag": "NAME", "value": "夏铭" }, { "context": "termark\n * @throws IOException\n * @author 夏铭\n */\n public void resizeImage(File file, St", "end": 1475, "score": 0.9715160131454468, "start": 1473, "tag": "NAME", "value": "夏铭" } ]
null
[]
package com.zttx.web.module.common.service; import com.zttx.web.bean.Watermark; import com.zttx.web.module.common.entity.UploadAttSize; import com.zttx.web.utils.ImageUtils; import com.zttx.web.utils.LoggerUtils; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.io.FileUtils; import org.apache.commons.io.FilenameUtils; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import java.io.File; import java.io.IOException; import java.util.List; /** * <p>File:ImageServiceImpl.java </p> * <p>Title: ImageServiceImpl </p> * <p>Description: ImageServiceImpl </p> * <p>Copyright: Copyright (c) 2014 08/10/2015 13:56</p> * <p>Company: 8637.com</p> * * @author playguy * @version 1.0 */ @Component public class ImageService { private static final Logger logger = LoggerFactory.getLogger(ImageService.class); @Autowired private UploadAttSizeService uploadAttSizeService; /** * 压缩图片 * @param file * @param cateKey * @throws IOException * @author 夏铭 */ public void resizeImage(File file, String cateKey) throws IOException { resizeImage(file, cateKey, null); } /** * 压缩图片, 可以加水印 * @param file * @param cateKey * @param watermark * @throws IOException * @author 夏铭 */ public void resizeImage(File file, String cateKey, Watermark watermark) throws IOException { String fileName = file.getAbsolutePath(); String extension = FilenameUtils.getExtension(fileName); FileUtils.copyFile(file, new File(fileName + "_orig." + extension)); if (StringUtils.isNotBlank(cateKey)) { List<UploadAttSize> uploadAttSizes = uploadAttSizeService.findByCateKey(cateKey); if (!CollectionUtils.isEmpty(uploadAttSizes)) for (UploadAttSize uploadAttSize : uploadAttSizes) { String pathname = fileName + "_" + uploadAttSize.getWidth() + "x" + uploadAttSize.getHeight() + "." + extension; File newFile = new File(pathname); File temp = ImageUtils.resizeImage(file, uploadAttSize.getWidth(), uploadAttSize.getHeight()); try { com.zttx.web.utils.FileUtils.moveFile(temp, newFile, true); } catch (Exception e) { LoggerUtils.logError(logger, e.getLocalizedMessage()); } } } } }
2,691
0.648964
0.639548
82
31.378048
28.495031
128
false
false
0
0
0
0
0
0
0.487805
false
false
2
a8a9b437815a8fc4f0b9af3e80261ef142ea4986
7,645,041,848,378
5f645edf9813baa8618aef765466e1d929972941
/src/main/java/com/protagor/controller/DeveloperController.java
c4e6208f33d776f3d8d16a3a32e1d3488fefcee3
[]
no_license
Protagor/ConsoleCRUD
https://github.com/Protagor/ConsoleCRUD
35625b65e6233f36a53f735dddb53579c9c1c6a6
a680d1403c4baa7cd4392b756333dc3d0600ec29
refs/heads/master
2018-10-17T02:50:02.854000
2018-07-15T16:05:38
2018-07-15T16:05:38
140,708,288
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package main.java.com.protagor.controller; import main.java.com.protagor.exception.NoSuchElementInDBException; import main.java.com.protagor.model.Developer; import main.java.com.protagor.service.DeveloperService; import java.io.IOException; import java.util.*; public class DeveloperController { private DeveloperService developerService = new DeveloperService(); public DeveloperController() throws NoSuchElementInDBException { } public void deleteSelected(List<Long> developers) throws IOException, NoSuchElementInDBException { developerService.deleteSelected(developers); } public void deleteAll() throws IOException { developerService.deleteAll(); } public List<Developer> getAll() throws IOException, NoSuchElementInDBException { return developerService.getAll(); } public Developer getById(Long id) throws IOException, NoSuchElementInDBException { return developerService.getById(id); } public void save(Developer developer) throws IOException, NoSuchElementInDBException { developerService.save(developer); } }
UTF-8
Java
1,123
java
DeveloperController.java
Java
[]
null
[]
package main.java.com.protagor.controller; import main.java.com.protagor.exception.NoSuchElementInDBException; import main.java.com.protagor.model.Developer; import main.java.com.protagor.service.DeveloperService; import java.io.IOException; import java.util.*; public class DeveloperController { private DeveloperService developerService = new DeveloperService(); public DeveloperController() throws NoSuchElementInDBException { } public void deleteSelected(List<Long> developers) throws IOException, NoSuchElementInDBException { developerService.deleteSelected(developers); } public void deleteAll() throws IOException { developerService.deleteAll(); } public List<Developer> getAll() throws IOException, NoSuchElementInDBException { return developerService.getAll(); } public Developer getById(Long id) throws IOException, NoSuchElementInDBException { return developerService.getById(id); } public void save(Developer developer) throws IOException, NoSuchElementInDBException { developerService.save(developer); } }
1,123
0.759573
0.759573
38
28.552631
31.249166
102
false
false
0
0
0
0
0
0
0.421053
false
false
2
c10534ecb3c75d849f6c8c3b353399adee7776ee
16,776,142,301,796
80e1e6aec24b025d24ef735c51a84a7b7a3413e6
/src/com/main/pingduoduo2018chun/Question2.java
860437863602e6e47fdcedeb5454ab9a3bc37d7b
[]
no_license
Keeplingshi/JavaAlgorithms
https://github.com/Keeplingshi/JavaAlgorithms
1d363b21bc8f9f86a2ac21b5539cff315d19ee55
ee316d7460071597aa0520bcf34f6b59f2dab64c
refs/heads/master
2018-10-28T05:02:16.678000
2018-08-22T14:19:56
2018-08-22T14:19:56
111,682,221
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.main.pingduoduo2018chun; import java.util.Scanner; /** * 时针与分针 * @author Administrator * */ public class Question2 { public static void main(String[] args) { Scanner sc=new Scanner(System.in); String time=sc.nextLine(); String[] times=time.split(":"); int hour=Integer.parseInt(times[0]); int minute=Integer.parseInt(times[1]); if(hour>=12){ hour-=12; } double radiusHour=hour*30+minute*0.5; //时针的角度 double radiusMinute=minute*6; double result=0.0; if(radiusHour>radiusMinute){ result=radiusHour-radiusMinute; }else{ result=radiusMinute-radiusHour; } if(result>=180){ result=360-result; } if(result-(int)result>0){ System.out.println(String.format("%.1f", result)); }else{ System.out.println((int)result); } } }
UTF-8
Java
874
java
Question2.java
Java
[ { "context": "rt java.util.Scanner;\r\n\r\n/**\r\n * 时针与分针\r\n * @author Administrator\r\n *\r\n */\r\npublic class Question2 {\r\n\r\n\tpublic sta", "end": 108, "score": 0.990304172039032, "start": 95, "tag": "NAME", "value": "Administrator" } ]
null
[]
package com.main.pingduoduo2018chun; import java.util.Scanner; /** * 时针与分针 * @author Administrator * */ public class Question2 { public static void main(String[] args) { Scanner sc=new Scanner(System.in); String time=sc.nextLine(); String[] times=time.split(":"); int hour=Integer.parseInt(times[0]); int minute=Integer.parseInt(times[1]); if(hour>=12){ hour-=12; } double radiusHour=hour*30+minute*0.5; //时针的角度 double radiusMinute=minute*6; double result=0.0; if(radiusHour>radiusMinute){ result=radiusHour-radiusMinute; }else{ result=radiusMinute-radiusHour; } if(result>=180){ result=360-result; } if(result-(int)result>0){ System.out.println(String.format("%.1f", result)); }else{ System.out.println((int)result); } } }
874
0.624122
0.593677
46
16.565218
15.740632
53
false
false
0
0
0
0
0
0
1.891304
false
false
2
5f4a1c021760ff14cfe58c5f838ef8cfac7b04fb
18,923,625,946,027
001b47e8527922b4db3b89206b90b3ee86b1c1dd
/src/com/po/quiz/sweepline/Q1272.java
9f909fb5c316f70d8a30dfd1fa63edbdaedb35b6
[]
no_license
hanyangou/leetcode-java
https://github.com/hanyangou/leetcode-java
51a99b5ff0c92a04ba664886500c0f4fa7aec610
b52a25478e9199b5b0339fe039de7df6e47b2ac7
refs/heads/master
2021-05-18T06:10:29.950000
2020-08-17T23:17:26
2020-08-17T23:17:26
251,151,270
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.po.quiz.sweepline; import java.util.ArrayList; import java.util.List; public class Q1272 { public List<List<Integer>> removeInterval(int[][] intervals, int[] toBeRemoved) { List<List<Integer>> res = new ArrayList<>(); int removeStart = toBeRemoved[0]; int removeEnd = toBeRemoved[1]; for(int[] interval : intervals){ int start = interval[0]; int end = interval[1]; if(start >= removeEnd || end <= removeStart) { List<Integer> tmp = new ArrayList<>(); tmp.add(start); tmp.add(end); res.add(tmp); } else if (start < removeStart && end > removeEnd){ List<Integer> tmp1 = new ArrayList<>(); tmp1.add(start); tmp1.add(removeStart); res.add(tmp1); List<Integer> tmp2 = new ArrayList<>(); tmp2.add(removeEnd); tmp2.add(end); res.add(tmp2); } else if (start < removeStart && end <= removeEnd){ List<Integer> tmp1 = new ArrayList<>(); tmp1.add(start); tmp1.add(removeStart); res.add(tmp1); } else if (start >= removeStart && end >= removeEnd){ List<Integer> tmp1 = new ArrayList<>(); tmp1.add(removeEnd); tmp1.add(end); res.add(tmp1); } } return res; } }
UTF-8
Java
1,520
java
Q1272.java
Java
[]
null
[]
package com.po.quiz.sweepline; import java.util.ArrayList; import java.util.List; public class Q1272 { public List<List<Integer>> removeInterval(int[][] intervals, int[] toBeRemoved) { List<List<Integer>> res = new ArrayList<>(); int removeStart = toBeRemoved[0]; int removeEnd = toBeRemoved[1]; for(int[] interval : intervals){ int start = interval[0]; int end = interval[1]; if(start >= removeEnd || end <= removeStart) { List<Integer> tmp = new ArrayList<>(); tmp.add(start); tmp.add(end); res.add(tmp); } else if (start < removeStart && end > removeEnd){ List<Integer> tmp1 = new ArrayList<>(); tmp1.add(start); tmp1.add(removeStart); res.add(tmp1); List<Integer> tmp2 = new ArrayList<>(); tmp2.add(removeEnd); tmp2.add(end); res.add(tmp2); } else if (start < removeStart && end <= removeEnd){ List<Integer> tmp1 = new ArrayList<>(); tmp1.add(start); tmp1.add(removeStart); res.add(tmp1); } else if (start >= removeStart && end >= removeEnd){ List<Integer> tmp1 = new ArrayList<>(); tmp1.add(removeEnd); tmp1.add(end); res.add(tmp1); } } return res; } }
1,520
0.482895
0.467105
42
35.190475
18.620569
85
false
false
0
0
0
0
0
0
0.761905
false
false
2
d556d4b8c22e4e19d1e39dedd94a5ca190f4509f
24,111,946,444,680
9eba3c79fd334cf8c8def2de5e17b13d5ab90c94
/app/src/main/java/com/example/fragment/Activity/UpdatePasswordActivity.java
af70e649e3ef69225f8f8bf2361b0bb3e7ba03f0
[]
no_license
pavanItla/Fragment
https://github.com/pavanItla/Fragment
2b628101ff70fd0b7d4f6304a76f212e003bfd62
7c1c7c5e8fa2e7ffcf40613116b622da05f598d1
refs/heads/master
2020-06-05T19:12:26.148000
2019-06-22T12:05:37
2019-06-22T12:05:37
192,521,167
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.fragment.Activity; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Patterns; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import com.example.fragment.Model.DefaultResponse; import com.example.fragment.Model.UpdatePasswordResponse; import com.example.fragment.R; import com.example.fragment.api.RetrofitClient; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; public class UpdatePasswordActivity extends AppCompatActivity { private EditText editTexEmail; private EditText editTextNumber; private EditText editTextPassword; private Button UserValid; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_update_password); editTexEmail = findViewById(R.id.editTextEmail); editTextNumber = findViewById(R.id.editTextNumber); editTextPassword = findViewById(R.id.editTextPassword); UserValid = findViewById(R.id.Valid); UserValid.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { UserValid(); } }); } private void UserValid() { String email = editTexEmail.getText().toString().trim(); String number = editTextNumber.getText().toString().trim(); String password = editTextPassword.getText().toString().trim(); if (email.isEmpty()) { editTexEmail.setError("Email is required"); editTexEmail.requestFocus(); } else if (!Patterns.EMAIL_ADDRESS.matcher(email).matches()) { editTexEmail.setError("Enter a valid email"); editTexEmail.requestFocus(); } else if (number.isEmpty()) { editTextNumber.setError("Password required"); editTextNumber.requestFocus(); } else if (number.length() < 6) { editTextNumber.setError("Password should be atleast 6 character long"); editTextNumber.requestFocus(); } else if (password.isEmpty()) { editTextPassword.setError("Password required"); editTextPassword.requestFocus(); } else if (password.length() < 6) { editTextPassword.setError("Password should be atleast 6 character long"); editTextPassword.requestFocus(); } else { Call<UpdatePasswordResponse> Call = RetrofitClient .getInstance() .getApi() .updateUser(email,number,password); Call.enqueue(new Callback<UpdatePasswordResponse>() { @Override public void onResponse(Call<UpdatePasswordResponse> call, Response<UpdatePasswordResponse> response) { UpdatePasswordResponse defaultResponse = response.body(); if ((defaultResponse != null ? defaultResponse.getStatus() : 0) == 1) { String im = defaultResponse.getMessage(); Toast.makeText(UpdatePasswordActivity.this, "" + im, Toast.LENGTH_LONG).show(); Intent intent = new Intent(UpdatePasswordActivity.this, LoginActivity.class); startActivity(intent); } else if ((defaultResponse != null ? defaultResponse.getStatus() : 0) == 3) { String im = defaultResponse.getMessage(); Toast.makeText(UpdatePasswordActivity.this, "" + im, Toast.LENGTH_LONG).show(); } } @Override public void onFailure(Call<UpdatePasswordResponse> call, Throwable t) { } }); } } }
UTF-8
Java
3,924
java
UpdatePasswordActivity.java
Java
[]
null
[]
package com.example.fragment.Activity; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Patterns; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import com.example.fragment.Model.DefaultResponse; import com.example.fragment.Model.UpdatePasswordResponse; import com.example.fragment.R; import com.example.fragment.api.RetrofitClient; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; public class UpdatePasswordActivity extends AppCompatActivity { private EditText editTexEmail; private EditText editTextNumber; private EditText editTextPassword; private Button UserValid; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_update_password); editTexEmail = findViewById(R.id.editTextEmail); editTextNumber = findViewById(R.id.editTextNumber); editTextPassword = findViewById(R.id.editTextPassword); UserValid = findViewById(R.id.Valid); UserValid.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { UserValid(); } }); } private void UserValid() { String email = editTexEmail.getText().toString().trim(); String number = editTextNumber.getText().toString().trim(); String password = editTextPassword.getText().toString().trim(); if (email.isEmpty()) { editTexEmail.setError("Email is required"); editTexEmail.requestFocus(); } else if (!Patterns.EMAIL_ADDRESS.matcher(email).matches()) { editTexEmail.setError("Enter a valid email"); editTexEmail.requestFocus(); } else if (number.isEmpty()) { editTextNumber.setError("Password required"); editTextNumber.requestFocus(); } else if (number.length() < 6) { editTextNumber.setError("Password should be atleast 6 character long"); editTextNumber.requestFocus(); } else if (password.isEmpty()) { editTextPassword.setError("Password required"); editTextPassword.requestFocus(); } else if (password.length() < 6) { editTextPassword.setError("Password should be atleast 6 character long"); editTextPassword.requestFocus(); } else { Call<UpdatePasswordResponse> Call = RetrofitClient .getInstance() .getApi() .updateUser(email,number,password); Call.enqueue(new Callback<UpdatePasswordResponse>() { @Override public void onResponse(Call<UpdatePasswordResponse> call, Response<UpdatePasswordResponse> response) { UpdatePasswordResponse defaultResponse = response.body(); if ((defaultResponse != null ? defaultResponse.getStatus() : 0) == 1) { String im = defaultResponse.getMessage(); Toast.makeText(UpdatePasswordActivity.this, "" + im, Toast.LENGTH_LONG).show(); Intent intent = new Intent(UpdatePasswordActivity.this, LoginActivity.class); startActivity(intent); } else if ((defaultResponse != null ? defaultResponse.getStatus() : 0) == 3) { String im = defaultResponse.getMessage(); Toast.makeText(UpdatePasswordActivity.this, "" + im, Toast.LENGTH_LONG).show(); } } @Override public void onFailure(Call<UpdatePasswordResponse> call, Throwable t) { } }); } } }
3,924
0.624618
0.62156
111
34.351353
29.167318
118
false
false
0
0
0
0
0
0
0.54955
false
false
2
c370e569df33c769a3d2d48bbe77358bb0c03a8c
7,164,005,483,754
f8d6d008dfc85ef15a524c7ad696433bf1f8a6d1
/src/main/java/kr/or/ddit/lecture/dao/ILectureWeekDAO.java
7a6627f6996d953f6b5439c07fbd1cd794a26501
[]
no_license
cleverhood/final_project
https://github.com/cleverhood/final_project
68d07b40ff73d2b8a991f7b74dcd45b413eb0c1e
ca8713eed60c0b8fa40fc5d3f6db63a1a63b45d3
refs/heads/master
2020-08-01T06:52:21.178000
2019-09-25T17:41:27
2019-09-25T17:41:27
210,905,135
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package kr.or.ddit.lecture.dao; import org.springframework.stereotype.Repository; import kr.or.ddit.vo.LectureweekVO; @Repository public interface ILectureWeekDAO { public int insertLectureWeek(LectureweekVO lectureweekVO); }
UTF-8
Java
230
java
ILectureWeekDAO.java
Java
[]
null
[]
package kr.or.ddit.lecture.dao; import org.springframework.stereotype.Repository; import kr.or.ddit.vo.LectureweekVO; @Repository public interface ILectureWeekDAO { public int insertLectureWeek(LectureweekVO lectureweekVO); }
230
0.826087
0.826087
10
22
21.227341
59
false
false
0
0
0
0
0
0
0.5
false
false
2
f0f3cdd8c1946b6b2ab55763deccdd50b160226f
6,897,717,505,780
97757eb405489e569c3fcf5ed1e155396e42708b
/SeleniumClasses/src/VariablesAndDataTypes/VariablesAndDataTypes.java
940ad49847fc4d3fc7f24af21bf44a39c16084df
[]
no_license
Anjali3791/SeleniumAutomation
https://github.com/Anjali3791/SeleniumAutomation
69ad045261483304a425ab3474662e435402361a
4255a68455217f761a4adc8ef100deae6e241954
refs/heads/master
2020-04-26T08:51:43.455000
2019-04-07T11:57:23
2019-04-07T11:57:23
173,436,683
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package VariablesAndDataTypes; public class VariablesAndDataTypes { }
UTF-8
Java
72
java
VariablesAndDataTypes.java
Java
[]
null
[]
package VariablesAndDataTypes; public class VariablesAndDataTypes { }
72
0.833333
0.833333
5
13.4
16.119553
36
false
false
0
0
0
0
0
0
0.2
false
false
2
b8892da9656e5aa8bc419c9f7d75224c3bfd070d
6,897,717,504,760
750b79ad7c7a86f9e5ac36994cddde816395a886
/src/main/java/com/yourname/Service/StudentService.java
5845820d2d7ad55269287bc594a9f616eb8227ff
[]
no_license
Michael-Toth/SpringBoot007
https://github.com/Michael-Toth/SpringBoot007
d400394452c9326c400a9c52da4d3af1e27149b5
d9c5d5af0de45b4d6934f50235c24b5216e22931
refs/heads/master
2021-01-12T03:11:10.644000
2017-01-06T04:34:15
2017-01-06T04:34:15
78,171,093
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.yourname.Service; import com.yourname.Dao.StudentDao1; import com.yourname.Entity.Student; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.Collection; /** * Created by jomama on 1/4/2017. */ @Service public class StudentService { @Autowired private StudentDao1 studentDao1; public Collection<Student> getAllStudents(){ return this.studentDao1.getAllStudents(); } }
UTF-8
Java
515
java
StudentService.java
Java
[ { "context": "import java.util.Collection;\r\n\r\n/**\r\n * Created by jomama on 1/4/2017.\r\n */\r\n\r\n\r\n@Service\r\npublic class Stu", "end": 279, "score": 0.9996868968009949, "start": 273, "tag": "USERNAME", "value": "jomama" } ]
null
[]
package com.yourname.Service; import com.yourname.Dao.StudentDao1; import com.yourname.Entity.Student; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.Collection; /** * Created by jomama on 1/4/2017. */ @Service public class StudentService { @Autowired private StudentDao1 studentDao1; public Collection<Student> getAllStudents(){ return this.studentDao1.getAllStudents(); } }
515
0.720388
0.700971
25
18.6
19.68959
62
false
false
0
0
0
0
0
0
0.32
false
false
2
0d35b426a11965f25f64ea1094ed82c5d009fb57
19,344,532,753,831
5e44c83e94aecf3fa5bec6c23b66b7234bb8f289
/src/com/collisiongames/polygon/buffers/VertexArray.java
1705aa6fc05e07728c89780f6a09fef8a14fbea8
[ "Apache-2.0" ]
permissive
Collision-Games/Polygon-Engine
https://github.com/Collision-Games/Polygon-Engine
746f1efd8176e5f7cf56ff52fa03bacefcd35672
b85863a5a91f2ff5c4a1060ae51d85894ab6cd0f
refs/heads/master
2021-03-19T14:26:24.492000
2017-10-24T18:08:58
2017-10-24T18:08:58
107,894,661
0
0
null
false
2017-10-24T18:08:59
2017-10-22T19:09:00
2017-10-22T19:42:36
2017-10-24T18:08:59
21,340
0
0
1
Java
false
null
package com.collisiongames.polygon.buffers; import org.lwjgl.opengl.*; import static org.lwjgl.opengl.GL11.*; import static org.lwjgl.opengl.GL15.*; import static org.lwjgl.opengl.GL20.*; import static org.lwjgl.opengl.GL30.*; import static org.lwjgl.opengl.GL33.*; /** * A class for storing a Vertex Array buffer. * Vertex Arrays as mostly used for storing vertex data * and element data on it for later rendering. * * @since v0.1 * @author Daan Meijer */ public class VertexArray extends Buffer { //TODO check if data can be put into one buffer protected BufferObject elementBuffer, vertexBuffer; /** * Constructor for a instance of {@link VertexArray} * * @param vertices the vertex data of a model * @param indices the element(index data) of a model */ public VertexArray(float[] vertices, int[] indices) { super(glGenVertexArrays(), GL_VERTEX_ARRAY); bind(); elementBuffer = new BufferObject(GL_ELEMENT_ARRAY_BUFFER, GL_STATIC_DRAW, indices); vertexBuffer = new BufferObject(GL_ARRAY_BUFFER, GL_STATIC_DRAW, vertices); } /** * Store an array of generic vertex attribute data * * @param index specifies the index of the buffer to modified, max range is 16 * @param size the numbers of components per generic vertex attribute, must be 1, 2, 3 or 4 * @param dataType the data type of each component in the array, can be GL_BYTE, GL_SHORT, GL_INT, GL_LONG etc. * @param stride the byte offset between consecutive generic vertex attributes, If stride is 0, the generic vertex attributs are understood * to be tightly packed in the array * @param offset specifies the byte offset of the first component of the first generic vertex attribute in the array in the data store * @param bufferObject specifies the buffer to retrieve the data from * @param normalized specifies if the fixed-point data should be normalized(true) when they are accessed */ public void assignAttribPointer(int index, int size, int dataType, int stride, int offset, BufferObject bufferObject, boolean normalized) { bind(); assert bufferObject != null : "Buffer may not be null"; bufferObject.bind(); glEnableVertexAttribArray(index); glVertexAttribPointer(index, size, dataType, normalized, stride, offset); } /** * Store an array of generic vertex attribute data * * @param index specifies the index of the buffer to modified, max range is 16 * @param size the numbers of components per generic vertex attribute, must be 1, 2, 3 or 4 * @param dataType the data type of each component in the array, can be GL_BYTE, GL_SHORT, GL_INT, GL_LONG etc. * @param stride the byte offset between consecutive generic vertex attributes, If stride is 0, the generic vertex attributs are understood * to be tightly packed in the array * @param offset specifies the byte offset of the first component of the first generic vertex attribute in the array in the data store * of the buffer currently bound to GL_ARRAY_BUFFER target * @param normalized specifies if the fixed-point data should be normalized(true) when they are accessed */ public void assignAttribPointer(int index, int size, int dataType, int stride, int offset, boolean normalized) { bind(); assert isBound(GL_ARRAY_BUFFER) : "No bound buffer"; glEnableVertexAttribArray(index); glVertexAttribPointer(index, size, dataType, normalized, stride, offset); } /** * Modify the rate at which generic vertex attributes advance during instanced rendering * * @param index specifies the index of the vertex attribute * @param divisor specifies the number of instances the will pass between updates of the generic attribute at slot index */ public void setAttribDivisor(int index, int divisor) { bind(); glVertexAttribDivisor(index, divisor); } @Override protected void onDelete() { glDeleteVertexArrays(bufferID); } @Override protected void onBind() { glBindVertexArray(bufferID); } @Override protected void onUnBind() { glBindVertexArray(0); } }
UTF-8
Java
4,388
java
VertexArray.java
Java
[ { "context": " for later rendering.\n *\n * @since v0.1\n * @author Daan Meijer\n */\npublic class VertexArray extends Buffer {\n\n ", "end": 461, "score": 0.9998846054077148, "start": 450, "tag": "NAME", "value": "Daan Meijer" } ]
null
[]
package com.collisiongames.polygon.buffers; import org.lwjgl.opengl.*; import static org.lwjgl.opengl.GL11.*; import static org.lwjgl.opengl.GL15.*; import static org.lwjgl.opengl.GL20.*; import static org.lwjgl.opengl.GL30.*; import static org.lwjgl.opengl.GL33.*; /** * A class for storing a Vertex Array buffer. * Vertex Arrays as mostly used for storing vertex data * and element data on it for later rendering. * * @since v0.1 * @author <NAME> */ public class VertexArray extends Buffer { //TODO check if data can be put into one buffer protected BufferObject elementBuffer, vertexBuffer; /** * Constructor for a instance of {@link VertexArray} * * @param vertices the vertex data of a model * @param indices the element(index data) of a model */ public VertexArray(float[] vertices, int[] indices) { super(glGenVertexArrays(), GL_VERTEX_ARRAY); bind(); elementBuffer = new BufferObject(GL_ELEMENT_ARRAY_BUFFER, GL_STATIC_DRAW, indices); vertexBuffer = new BufferObject(GL_ARRAY_BUFFER, GL_STATIC_DRAW, vertices); } /** * Store an array of generic vertex attribute data * * @param index specifies the index of the buffer to modified, max range is 16 * @param size the numbers of components per generic vertex attribute, must be 1, 2, 3 or 4 * @param dataType the data type of each component in the array, can be GL_BYTE, GL_SHORT, GL_INT, GL_LONG etc. * @param stride the byte offset between consecutive generic vertex attributes, If stride is 0, the generic vertex attributs are understood * to be tightly packed in the array * @param offset specifies the byte offset of the first component of the first generic vertex attribute in the array in the data store * @param bufferObject specifies the buffer to retrieve the data from * @param normalized specifies if the fixed-point data should be normalized(true) when they are accessed */ public void assignAttribPointer(int index, int size, int dataType, int stride, int offset, BufferObject bufferObject, boolean normalized) { bind(); assert bufferObject != null : "Buffer may not be null"; bufferObject.bind(); glEnableVertexAttribArray(index); glVertexAttribPointer(index, size, dataType, normalized, stride, offset); } /** * Store an array of generic vertex attribute data * * @param index specifies the index of the buffer to modified, max range is 16 * @param size the numbers of components per generic vertex attribute, must be 1, 2, 3 or 4 * @param dataType the data type of each component in the array, can be GL_BYTE, GL_SHORT, GL_INT, GL_LONG etc. * @param stride the byte offset between consecutive generic vertex attributes, If stride is 0, the generic vertex attributs are understood * to be tightly packed in the array * @param offset specifies the byte offset of the first component of the first generic vertex attribute in the array in the data store * of the buffer currently bound to GL_ARRAY_BUFFER target * @param normalized specifies if the fixed-point data should be normalized(true) when they are accessed */ public void assignAttribPointer(int index, int size, int dataType, int stride, int offset, boolean normalized) { bind(); assert isBound(GL_ARRAY_BUFFER) : "No bound buffer"; glEnableVertexAttribArray(index); glVertexAttribPointer(index, size, dataType, normalized, stride, offset); } /** * Modify the rate at which generic vertex attributes advance during instanced rendering * * @param index specifies the index of the vertex attribute * @param divisor specifies the number of instances the will pass between updates of the generic attribute at slot index */ public void setAttribDivisor(int index, int divisor) { bind(); glVertexAttribDivisor(index, divisor); } @Override protected void onDelete() { glDeleteVertexArrays(bufferID); } @Override protected void onBind() { glBindVertexArray(bufferID); } @Override protected void onUnBind() { glBindVertexArray(0); } }
4,383
0.681404
0.675251
103
41.60194
41.16515
149
false
false
0
0
0
0
0
0
0.737864
false
false
2