I've been struggling a couple days now attempting to write this code. Basically,we have to perform a binarySearch based on the SSN of Comparable "Student" objects in a Student array. After performing the binarySearch on the SSN, the student who is associated with that SSN's first and last name should print out. I am finding difficulty in writing the binarySearch.
Here's my code so far:
my Student class:
public class Student implements Comparable<Student>{
private String firstName, lastName, SSN, bankAccount;
public Student(String first, String last, String ssn, String bkacct) {
this.firstName = first;
this.lastName = last;
this.SSN = ssn;
this.bankAccount = bkacct;
}
//toString method
public String toString() {
return "Employee: [FirstName = " + firstName + ", LastName = " + lastName + ", SSN = " + SSN + ", BankAccount = "
+ bankAccount + "]";
}
public boolean equals(Object other) {
return (lastName.equals(((Student)other).getLastName()) &&
firstName.equals(((Student)other).getFirstName())&&
SSN.equals(((Student)other).getSSN()) &&
bankAccount.equals(((Student)other).getBankAccount()));
}
//Sorting the array based on SSN
public int compareTo(Student target) {
int result;
if (lastName.equals(target.getLastName()))
result = SSN.compareTo((String) target.getSSN());
else
result = SSN.compareTo((String) target.getSSN());
return result;
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
public Object getSSN() {
return SSN;
}
public String getBankAccount() {
return bankAccount;
}
and my class where i perform my binarySearch
public class ObjectBubbleSortTest {
//setting up binarySearch to find Array
public static <Student extends Comparable<Student>> int binarySearch(Student[] student, Student target) {
int low = 0;
int high = student.length - 1;
int middle = (low+high + 1)/2;
int location = -1;
while((low <= high) && (location == -1)) {
if (student[middle].compareTo(target) == 0 ) {
location = middle;
}
else if (student[middle].compareTo(target) < 0) { //middle element too high
high = middle - 1;
}
else {
low = middle + 1;
}
middle = (low + high + 1)/2;
}
return location;
}
public static void main(String[] args) {
//EMPLOYEES OF BURGER KING
Student[] student = new Student[5];
//order: First Name, Last Name, SSN, Bank_Account_Number
student[0] = new Student("Adam", "Sarrone", "1234567", "9022345");
student[1] = new Student("Ryan", "Petrowvoksi", "4345123", "0120345");
student[2] = new Student("Jenn", "Henderson", "8124512", "564214");
student[3] = new Student("Ricky", "Jean", "3512345", "612345");
student[4] = new Student("Dare", "Ogun", "421451", "198213");
System.out.println("Original array order: \n");
for (Student element : student)
System.out.print(element + "\n");
ObjectBubbleSorter.bubbleSort(student);
System.out.println();
System.out.println("\nSorted array order: \n");
for (Student element : student)
System.out.print(element + "\n");
System.out.println();
//need helping figuring out why the binary search is not printing out
int studentName = binarySearch(student, "421451");
System.out.print(studentName);
}
}
I am also getting an error on "int studentName = binarySearch" stating The method binarySearch(Student[], Student) in the type ObjectBubbleSortTest is not applicable for the arguments (Student[], String). I understand what it means but struggling to make my binarySearch adaptable to fix that error.
Any help would be greatly appreciated. Thank you.
It would be clear if you read the error message once again carefully.
"int studentName = binarySearch" stating The method binarySearch(Student[], Student) in the type ObjectBubbleSortTest is not applicable for the arguments (Student[], String).
So basically the method signature you have is int binarySearch(Student[] student, Student target), but when you call it in main() it's binarySearch(student, "421451");
You may want to instead call the method like binarySearch(student, student[4]);
Related
My mat-paginator in app.component.html:
<mat-paginator [pageSizeOptions]="[5, 15, 30]" [pageSize]="5" [length]="totalElements"
(page)="nextPage($event)">
</mat-paginator>
app component:
totalElements = 5;
// tslint:disable-next-line:typedef
nextPage(event: PageEvent) {
const request = {};
// #ts-ignore
request.page = event.pageIndex.toString();
// #ts-ignore
this.totalElements = request.size = event.pageSize.toString();
// #ts-ignore
this.getDevelopers(request);
}
getDevelopers:
public getDevelopers(request: {page: string, size: string}): void {
this.loading = true;
this.developerService.getAllUsers(request)
.subscribe(data => {
// #ts-ignore
this.users = data.content;
// #ts-ignore
this.totalElements = data.totalElements;
this.loading = false;
}
}
My controller:
#GetMapping
#ResponseBody
#ApiOperation(value = "Get list of all developers")
public Page<GetByIdDeveloperResponse> getAllDevelopers(
#RequestParam(name = "page", defaultValue = "0") int page,
#RequestParam(name = "size", defaultValue = "4") int size,
#RequestParam(name = "sort_by", defaultValue = "id") String sortBy
) {
Page<GetByIdDeveloperResponse> developers = developerMapper.getDeveloperResponseListFromDeveloperList(developerService.getAllDevelopers(page, size, sortBy));
return new PageImpl<GetByIdDeveloperResponse>(developers.getContent(), PageRequest.of(page, size), developers.getTotalElements());
}
I can change size of page, but i can't open other page.
< > are not aviable for me
In postman everything in is ok, but here it doesn't work.
How looks my service method:
public List<Developer> getAllDevelopers(int page, int size, String sortValue) {
logger.info("Get all developers was called, page: " + page + " size: " + size + " sort by: " + sortValue);
Pageable paging = PageRequest.of(page, size, Sort.by(sortValue));
Page<Developer> pagedResult = developerRepository.findAll(paging);
return pagedResult.getContent();
}
How repository looks:
#Repository
public interface DeveloperRepository extends PagingAndSortingRepository<Developer, String> {
Developer findById(String id);
}
How json looks:
When i am trying to GET .../developers?size=10
I got 10 total elements, i think problem is related to "totalPages": 1,
Because even if i get all elements, there will be only 1 page
Debug:
You lose your paged result data (page number, page size, etc.) in your service method when you do return pagedResult.getContent().
Consider the following:
Service method:
public Page<Developer> getAllDevelopers(int page, int size, String sortValue) {
logger.info("Get all developers was called, page: " + page + " size: " + size + " sort by: " + sortValue);
Pageable paging = PageRequest.of(page, size, Sort.by(sortValue));
return developerRepository.findAll(paging);
}
Controller method:
#GetMapping
#ApiOperation(value = "Get list of all developers")
public Page<GetByIdDeveloperResponse> getAllDevelopers(
#RequestParam(name = "page", defaultValue = "0") int page,
#RequestParam(name = "size", defaultValue = "4") int size,
#RequestParam(name = "sort_by", defaultValue = "id") String sortBy
) {
return this.developerService.getAllDevelopers(page, size, sortBy)
.map(this.developerMapper::mapToGetByIdDeveloperResponse)
}
Im trying to send an array that contains some objects via connection made in SignalR, the connection is not a problem, everything works fine. When the data arrives to the view it is no longer the array i need to use.
This is the class:
public class Empresa
{
public string nombre { get; set; }
public int vidID { get; set; }
public string img64 { get; set; }
public string color { get; set; }
}
At the end the object will be something like this:
The object is send to the view and this is the output:
I have already tried with JsonConvert.SerializeObjectas i found on other threads, yet it doesnt seems to work. I tried to convert the data send with this jQuery.parseJSON(data) (Left) and with this JSON.parse(data)(Right); it throws an error on both cases as seen in the picture below.
I'm not sure if it is that way because the object sended is made this way:
private readonly ConcurrentDictionary<int, Empresa> _ar1 = new ConcurrentDictionary<int, Empresa>();
var data = new List<Empresa>
{
new Empresa{nombre ="Globex Corp",color="red",vidId=1, img="data:image/jpeg;base64,blabla" },
new Empresa{nombre ="AM",color="blue",vidId=2, img="data:image/jpeg;base64,blabla" }
}
for(int i = 0; i<=6; i++)
{
_ar1.TryAdd(data[i].vidID, data[i]);
}
This is inside other function but it is the next one that involves the data send.
public IEnumerable<Empresa> GetArreglo()
{
return _ar1;
}
So far im not sure what could be wrong or if i need to aproach a different solution.
If any more info is needed ill post it. And even it is obvious im a newby still learning on this.
EDIT:
This is all the code involved:
// This is the JS
<script>
var ubi = '#ViewBag.ubicacion';
console.log("UbicaciĆ³n: " + ubi);
var conex = $.connection.channel;
var $marco = $('#marco');
var $imagen = $('#imagen');
var $empresa = $('#empresa');
function empezar() {
var min;
var max;
var pos;
var arreglo = new Array;
function init() {
conex.server.createGroup(ubi);
console.log("Entro al canal");
arreglo = conex.server.getArreglo(ubi);
//pos = arreglo.split('|');
//a.split is not a function
console.log(arreglo);
//console.log(pos);
setInterval(update, 6000);
}
function update() {
}
$.connection.hub.start().done(init);
}
window.onload = function() { empezar(); }
</script>
//It gets the conection to the HUB:
[HubName("channel")]
public class CanalHub : Hub
{
private readonly Canal _canal;
public CanalHub() : this(Canal.Instance) { }
public CanalHub(Canal canal)
{
_canal = canal;
}
public string[] GetArreglo(string ubi)
{
string[] array = _canal.GetArreglo(ubi);
return array;
//it is now a string[] because i wanted to
//try creating the obj with .split('|')
}
// And finally this is the last part involved:
public class Canal
{
private static Random random = new Random();
private volatile List<Canales> listaCan = new List<Canales>();
private readonly static Lazy<Canal> _instance = new Lazy<Canal>(() => new Canal(GlobalHost.ConnectionManager.GetHubContext<CanalHub>().Clients));
private readonly ConcurrentDictionary<int, Empresa> _datos = new ConcurrentDictionary<int, Empresa>();
private readonly ConcurrentDictionary<int, Empresa> _ar1 = new ConcurrentDictionary<int, Empresa>();
private Canal(IHubConnectionContext<dynamic> clients)
{
Clients = clients;
//Create the sample objects for the class
var datos = new List<Empresa>
{
new Empresa{nombre="Globex Corp", color="#A87F3D", vidID=1, img="balbal" },
new Empresa{nombre="AM", color="#535E89", vidID=2, img="balba" },
new Empresa{nombre="Frutijugos", color="#92191A", vidID=3, img="askldj" }
};
for (int i = 0; i <=6 ; i++)
{
_ar1.TryAdd(datos[i].vidID, datos[i]);
}
for (int i = 7; i <= 13; i++)
{
_ar2.TryAdd(datos[i].vidID, datos[i]);
}
for (int i = 14; i <= 20; i++)
{
_ar3.TryAdd(datos[i].vidID, datos[i]);
}
//sort them on 3 different arrays
}
private IHubConnectionContext<dynamic> Clients { get; set; }
public static Canal Instance
{
get { return _instance.Value; }
}
public string[] GetArreglo(string ubi)
{
string[] array = new string[7];
int i = 0;
if (ubi == "Campanario")
{
foreach (var item in _ar1)
{
array[i] += item.Value.nombre + "|";
array[i] += item.Value.color + "|";
array[i] += item.Value.img + "|";
array[i] += item.Value.vidID + "|";
i++;
}
return array;
}
//sort the array values and add them to the array
else return null;
}
It appears that your javascript promise is not set up correctly. The object in the view is the promise object and not the object returned. You are going to need to set up the promise correctly. deferred promise
I am adding some data in List of Tuple type like this in Razor view
List<Tuple<int, int, string>> Downloadlist = new List<Tuple<int, int, string>>();
And adding items to this list
Downloadlist.Add(new Tuple<int, int, string>(11, 7, "somedata"));
Now I would like to access the array of data in javascript
<script>
var listofdownloadpages = '#ViewData["DownloadPages"]';
if (listofdownloadpages != null) {
alert(listofdownloadpages.length);
for (var i = 0; i < listofdownloadpages.length; i++) {
alert(listofdownloadpages[i].wishid + ' ' + listofdownloadpages[i].remain);
}
}
else {
alert("not found anything");
}
But this not giving me the items in correct way please help.
This will work
Controller
public ActionResult Test()
{
List<Tuple<int, int, string>> Downloadlist = new List<Tuple<int, int, string>>();
Downloadlist.Add(new Tuple<int, int, string>(11, 7, "somedata"));
ViewData["DownloadPages"] = Downloadlist;
return View();
}
View & JS
<script>
var listofdownloadpages = #Html.Raw(Json.Encode(#ViewBag.DownloadPages));
if (listofdownloadpages != null) {
alert(listofdownloadpages.length);
for (var i = 0; i < listofdownloadpages.length; i++) {
alert(listofdownloadpages[i].Item1 + ' ' + listofdownloadpages[i].Item2);
}
}
else {
alert("not found anything");
}
</script>
Here My Classes
public class EmployeeProjectMaster
{
public int EmployeeProjectMasterId { get; set; }
//Class Variables
//Here i wants to get list of EmployeeProjectTransaction
//this is the way i tried
public EmployeeProjectMasterModelClient()
{
this.EmployeeProjectTransactionModel = new HashSet<EmployeeProjectTransactionModelClient>();
}
public virtual IEnumerable<EmployeeProjectTransactionModelClient> EmployeeProjectTransactionModel { get; set; }
}
public class EmployeeProjectTransaction
{
public int EmployeeProjecTransactiontId { get; set; }
public int EmployeeProjectMasterId { get; set; }
public int EmployeeId { get; set; }
public string EmployeeName {get;set;}
//Class Variables
}
public class Employee
{
public int EmployeeId { get; set; }
public string Employeefullname {get;set;}
}
Then here my linq query
//Get All Employee Project Details To Grid
public ActionResult GetAllEmployeeProjectDetails()
{
//DataTable Parameter
var draw = Request.Form.GetValues("draw").FirstOrDefault();
//Paging parameter
var start = Request.Form.GetValues("start").FirstOrDefault();
var length = Request.Form.GetValues("length").FirstOrDefault();
//Paging parameter
var sortColumn = Request.Form.GetValues("columns[" + Request.Form.GetValues("order[0][column]").FirstOrDefault() + "][name]").FirstOrDefault();
var sortColumnDir = Request.Form.GetValues("order[0][dir]").FirstOrDefault();
//filter parameter
var searchValue = Request.Form.GetValues("search[value]").FirstOrDefault();
List<EmployeeProjectMasterModelClient> allEmployeeProject = new List<EmployeeProjectMasterModelClient>();
int pageSize = length != null ? Convert.ToInt32(length) : 0;
int skip = start != null ? Convert.ToInt32(start) : 0;
int recordsTotal = 0;
//Database Query
using (InnoESolutionsDbEntities oInnoESolutionsDbEntities = new InnoESolutionsDbEntities())
{
var v = (from Epmm in oInnoESolutionsDbEntities.EmployeeProjectMasterModels
join Eptm in oInnoESolutionsDbEntities.EmployeeProjectTransactionModels
on Epmm.EmployeeProjectMasterId equals Eptm.EmployeeProjectMasterId
select new {Epmm, Eptm});
if (!string.IsNullOrEmpty(searchValue))
{
v = v.Where(b =>
b.Epmm.ProjectModel.ProjectName.Contains(searchValue)
);
}
if (!(string.IsNullOrEmpty(sortColumn) && string.IsNullOrEmpty(sortColumnDir)))
{
//for make sort simpler we will add system.linq.dynamic reference
//v = v.OrderBy(sortColumn + " " + sortColumnDir);
v = v.OrderBy(a => a.Epmm.EmployeeProjectMasterId + " " + a.Eptm.EmployeeProjectMasterId);
}
recordsTotal = v.Count();
allEmployeeProject = v.Skip(skip).Take(pageSize).Where(y => y.Epmm.IsActive && !y.Epmm.IsDelete && y.Eptm.IsActive && !y.Eptm.IsDelete).Select(x => new EmployeeProjectMasterModelClient
{
EmployeeProjectMasterId = x.Epmm.EmployeeProjectMasterId,
ProjectId = x.Epmm.ProjectId,
ProjectName = x.Epmm.ProjectModel.ProjectName,
WorkDateS = SqlFunctions.DateName("day", x.Epmm.WorkDate) + "/ " + SqlFunctions.DateName("month", x.Epmm.WorkDate) + "/ " + SqlFunctions.DateName("year", x.Epmm.WorkDate),
SalaryForEachEmployee = x.Epmm.SalaryForEachEmployee,
EmployeeProjectTransactionModel = *************************************How to Load Trnsaction Details As A list Here
}).ToList();
}
return Json(new { draw = draw, recordsFiltered = recordsTotal, recordsTotal = recordsTotal, data = allEmployeeProject });
}
Above c# function and Linq query for load angular data table. it's needs to select List Inside a List. i Wrote linq query for join. I don't know whether If it is correct or not.when you answer my question please consider that query. Have tried lot of time but i have failed. in query when i try to get record into allEmployeeProject . how to load transaction Details As a list inside allEmployeeProject list asterisk symbol indicates what i need to do. i wants list of employee for particular master record.
Here output what i want
MasterId | TransactionId |Employee Id | Employee Name
---------+---------------+------------+---------------
1 | 1 | 4 | name 1
| 2 | 2 | name 3
I think what you need is GroupBy method.
allEmployeeProject = v.Skip(skip).Take(pageSize).Where(y => y.Epmm.IsActive && !y.Epmm.IsDelete && y.Eptm.IsActive && !y.Eptm.IsDelete).Select(x => new EmployeeProjectMasterModelClient
{
EmployeeProjectMasterId = x.Epmm.EmployeeProjectMasterId,
ProjectId = x.Epmm.ProjectId,
ProjectName = x.Epmm.ProjectModel.ProjectName,
WorkDateS = SqlFunctions.DateName("day", x.Epmm.WorkDate) + "/ " + SqlFunctions.DateName("month", x.Epmm.WorkDate) + "/ " + SqlFunctions.DateName("year", x.Epmm.WorkDate),
SalaryForEachEmployee = x.Epmm.SalaryForEachEmployee
});
var allEmployeeProjectsByMaster = allEmployeeProject.GroupBy(x => x.EmployeeProjectMasterId).ToList();
Now you can have transaction list grouped by EmployeeProjectMaster with allEmployeeProjectsByMaster variable, just map it to relevant data model using Select.
I've been trying to get some custom client site date validation working and so far I cannot seem to get it to work properly.
I have a custom date editor defined like this:
#model DateTime?
#{
if (Model.HasValue)
{
int day = Model.Value.Day;
int month = Model.Value.Month;
int year = Model.Value.Year;
}
List<SelectListItem> days = new List<SelectListItem>();
for (int i = 1; i <= 31; i++)
{
days.Add(new SelectListItem { Text = i.ToString(), Value = i.ToString(), Selected = Model.HasValue && Model.Value.Day == i});
}
List<SelectListItem> months = new List<SelectListItem>();
for (int i = 1; i <= 12; i++)
{
months.Add(new SelectListItem { Text = i.ToString(), Value = i.ToString(), Selected = Model.HasValue && Model.Value.Month == i});
}
List<SelectListItem> years = new List<SelectListItem>();
var minYear = DateTime.Now.Year - 100;
var maxYear = DateTime.Now.Year - 18;
for (int i = maxYear; i >= minYear; i--)
{
years.Add(new SelectListItem { Text = i.ToString(), Value = i.ToString(), Selected = Model.HasValue && Model.Value.Year == i });
}
}
#Html.DropDownList("days", days, "Day", new { #class="form__select" } )
#Html.DropDownList("months", months, "Month", new { #class="form__select" } )
#Html.DropDownList("years", years, "Year", new { #class="form__select" } )
And I have a custom validation attribute defined like this:
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = false)]
public class DoBValidatorAttribute : ValidationAttribute, IClientValidatable
{
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
List<ModelClientValidationRule> clientRules = new List<ModelClientValidationRule>();
ModelClientValidationRule validDateRule = new ModelClientValidationRule
{
ErrorMessage = "Please enter a valid date.",
ValidationType = "validdate"
};
validDateRule.ValidationParameters.Add("dayelement", metadata.PropertyName + ".days");
validDateRule.ValidationParameters.Add("monthelement", metadata.PropertyName + ".months");
validDateRule.ValidationParameters.Add("yearelement", metadata.PropertyName + ".years");
clientRules.Add(validDateRule);
return clientRules;
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
DateTime dateResult;
int day = Convert.ToInt32(validationContext.Items["days"]);
int month = Convert.ToInt32(validationContext.Items["months"]);
int year = Convert.ToInt32(validationContext.Items["years"]);
// Put date parts together and check is valid...
if (DateTime.TryParse(year + "/" + month + "/" + day, out dateResult))
{
return ValidationResult.Success;
}
// Not valid
return new ValidationResult(string.Format(ErrorMessageString, validationContext.DisplayName));
}
}
In order to (try) and wire all this together I also have this in my JavaScript:
jQuery.validator.unobtrusive.adapters.add(
'validdate', // notice this is coming from how you named your validation rule
['dayelement'],
['monthelement'],
['yearelement'],
function (options) {
options.rules['datepartcheck'] = options.params;
options.messages['datepartcheck'] = options.message;
}
);
jQuery.validator.addMethod('datepartcheck', function (value, element, params) {
var year = params[2];
var month = params[1];
var day = params[0];
var birthDate = year + '/' + month-1 + '/' + day;
var isValid = true;
try {
// datepicker is a part of jqueryUI.
// include it and you can take advantage of .parseDate:
$.datepicker.parseDate('yy/mm/dd', birthDate);
}
catch (error) {
isValid = false;
}
return isValid;
}, '');
I've put a breakpoint on all these methods but the GetClientValidationRules method is never called which I think means that the rules are never going to be applied to the HTML for one thing.
What am I doing wrong here? I just cannot figure it out. If I could I would ditch all of it and use a plain datepicker but the client is insistent on this format.
UPDATE
Just to be clear in the generated HTML the controls generated are three <select> inputs.
I'm wondering if it might be better to split this into three separate int properties on my model and use a range validator instead.