Property has value in View but appears as 0 in page - html

Currently I am trying to display a user's age but it appears as 0 in the page.
This is the View
<div class="col-xs-6 col-sm-4 overview-box">
<table class="table-responsive">
<tbody>
<tr>
<td class="overview-description-wrap">
<span class="overview-description">#translations["Player_Age"]</span>
</td>
<td class="overview-info hidden-xs" style="display:table-cell">
<span class="overview-info-lg">#Model.Age</span>
#if (Model.ShowDateOfBirth)
{
<span class="overview-info-sm">(#Model.BirthDate.ToString("dd.MM.yyyy"))</span>
}
</td>
<td class="overview-info hidden-lg hidden-sm hidden-md">
<span class="overview-info-lg">#Model.Age</span>
<br />
<span class="overview-info-sm">(#Model.BirthDate.ToString("dd.MM.yyyy"))</span>
</td>
</tr>
</tbody>
</table>
</div>
And this is the action that gets the values
public PlayerOverviewViewModel GetPlayerViewModel(int playerId, int sport, int country, int currentPlayerId = 0, int clubId = 0, string color = "")
{
PlayerOverviewViewModel result = new PlayerOverviewViewModel();
Nomenclatures.Sports currentsport = (Nomenclatures.Sports)sport;
Nomenclatures.Countries currentCountry = (Nomenclatures.Countries)country;
var state = LoadPlayerState(playerId, sport);
var finishedMatches = GetFinishedMatches(state, playerId, rankingId: 0).ToList();
var upcomingMatches = GetUpcomingMatches(state, playerId, currentPlayerId, 9).ToList();
var testMatches = ParseUpcomingChallenges(state, upcomingMatches);
var eventInvitations = new List<EventInvitationViewModel>();
var tournamentInvitations = GetTournamentInvitations(currentPlayerId);
var parsedInvitations = ParseTournamentInvitations(state, tournamentInvitations);
eventInvitations.AddRange(parsedInvitations);
var clubLeagueInvitations = GetClubLeagueInvitations(currentPlayerId);
parsedInvitations = ParseClubLeagueInvitations(state, clubLeagueInvitations);
eventInvitations.AddRange(parsedInvitations);
var playerRankings = state.PlayerRankings;
var rankingNames = _data.OrganisationRankings.GetRankingNames(playerRankings.Select(x => x.OrganisationRankingId.Value));
var player = state.CurrentPlayer;
int organizationId = state.CurrentPlayer.HomeClubId ?? 0;
var topRanking = GetPlayerRanking(state);
var playerCareerTopRanking = GetPlayerHighestStanding(state);
var playerCareerTopRankingDate = GetTopPlayerRankingDate(state);
var doubleCareerTopRanking = GetTopDoubleRanking(state, sport, country);
var doubleCareerTopRankingDate = GetTopDoubleRankingDate(state, sport, country);
var homeclub = player.Organisation ?? new Organisation();
var profileImg = _data.Images.PlayerImage(playerId);
var playerCareerWins = GetPlayerCareerWins(playerId, sport, state.Challenges);
var playerCurrentYearWins = GetPlayerCurrentYearWins(playerId, sport, state.Challenges);
var playerCareerLooses = GetPlayerCareerLooses(playerId, sport, state.Challenges);
var playerCurrentYearLosses = GetPlayerCurrentYearLooses(playerId, sport, state.Challenges);
var doublePlayerCurrentYearWins = GetDoublePlayerCurrentYearWins(playerId, sport);
var doublePlayerCareerLooses = GetDoublePlayerCareerLooses(state, sport);
var doubleCareerWins = GetDoubleCareerWins(state, sport);
var doublePlayerCurrentYearLooses = GetDoublePlayerCurrentYearLooses(state, sport);
var careerEventParticipations = GetAllEventsParticipations(playerId, sport, state.Challenges);
var currentYearEventParticipations = GetCurrentYearEventsParticipations(playerId, sport, state.Challenges);
var doubleCareerEventParticipations = GetDoubleCareerEventParticipations(state, sport);
var doubleCurrentYearEventParticipations = GetDoubleCurrentYearEventParticipations(state, sport);
var best3Wins = GetBest3Wins(state, playerId);
var singlePlayerHighestRankingCurrentYear = GetSinglePlayerHighestRankingForCurrentYear(state);
var doublePartnerInvitation = GetDoublePartnerInvitation(playerId);
//var playerUnavalability = this.GetPlayerSchedule(playerId);
string racquetName = player.GetRacket();
string shoesName = player.GetShoes();
result.Id = player.p_id;
result.Name = player.Name;
result.FirstName = player.FirstName;
result.MiddleName = player.MiddleName;
result.LastName = player.LastName;
result.Email = player.UserProfile.Email;
result.Address = player.PersonalInfo.pi_address;
result.BirthDate = player.PersonalInfo.pi_birth;
result.Age = DateHelper.GetAge(result.BirthDate);
result.Gender = player.PersonalInfo.pi_gender == 1 ? "Male" : "Female";
result.UserName = player.UserProfile.UserName;
result.Country = player.PersonalInfo.Country.Name;
result.CountryCode = player.PersonalInfo.Country.Short.ToLower();
result.RankingType = ((Nomenclatures.RankingTypes)topRanking.r_rankingtype).Description();
result.RankingClass = ((Nomenclatures.EventClasses)(topRanking.r_class ?? 1)).Description();
result.Points = topRanking.vPoints;
result.Level = topRanking.r_level ?? 1;
result.Standing = topRanking.vStanding;
result.HomeClub = string.IsNullOrEmpty(homeclub.Name) ? "No home club" : homeclub.Name;
result.ImageUrl = _manager.GetImageUrl(profileImg.img_id, Nomenclatures.ImageType.UserProfilePic);
result.ImageId = profileImg.img_id;
result.Racquet = racquetName;
result.Shoes = shoesName;
result.DominantHand = ((Nomenclatures.DominantHand)player.PersonalInfo.DominantHand).ToString();
result.BackHand = ((Nomenclatures.Backhand)player.PersonalInfo.Backhand).ToString();
result.Facebook = player.PersonalInfo.FacebookProfile;
result.Twitter = player.PersonalInfo.TwitterProfile;
result.WebSite = player.PersonalInfo.WebSite;
result.EmailVisible = player.PersonalInfo.pi_email_v;
result.ShowDateOfBirth = player.PersonalInfo.pi_birth_v || player.p_id == currentPlayerId;
//result.ScheduleDays = playerUnavalability.ScheduleDays;
//result.PlayerUnavalabilityVM = playerUnavalability;
result.PlayerCountryFlag = player.PersonalInfo.Country.Short.ToLower();
result.CareerWins = playerCareerWins;
result.GlobalEventsParticipatedSingles = careerEventParticipations;
result.EventsParticipatedSingles = currentYearEventParticipations;
result.CareerWinLossSingles = playerCareerWins + "-" + playerCareerLooses;
result.WinLossSingles = playerCurrentYearWins + "-" + playerCurrentYearLosses;
result.CareerWinLossDouble = doubleCareerWins + "-" + doublePlayerCareerLooses;
result.WinLossDoubles = doublePlayerCurrentYearWins + "-" + doublePlayerCurrentYearLooses;
result.GlobalEventsParticipatedDoubles = doubleCareerEventParticipations;
result.EventsParticipatedDoubles = doubleCurrentYearEventParticipations;
result.Best3Wins.Items = new List<ICarouselItem>(best3Wins);
result.CareerHighSingles = playerCareerTopRanking == 0 ? "-" : playerCareerTopRanking.ToString();
result.CareerHighDoubles = doubleCareerTopRanking == 0 ? "-" : doubleCareerTopRanking.ToString();
result.CareerHighDateSingles = playerCareerTopRankingDate;
result.CareerHighDateDoubles = doubleCareerTopRankingDate;
result.SinglesHighestRankingCurrentYear = singlePlayerHighestRankingCurrentYear == 0 ? "-" : singlePlayerHighestRankingCurrentYear.ToString();
result.DoublesHighestRankingCurrentYear = ""; //TODO: implement this
result.DoublePlayers = new List<DoublePartnersViewModel>();//TODO: implement this
result.PlayerRankings = playerRankings;
result.RankingNames = rankingNames;
result.CurrentSport = currentsport;
result.RankingCountry = currentCountry;
result.SportNumber = sport;
result.CountryNumber = country;
result.ParticipantType = (int)player.ParticipantType;
result.Class = player.p_class ?? 1;
result.DoubleInvitations = doublePartnerInvitation;
result.LastDonationDate = player.LastDonationDate;
int months;
int.TryParse(ConfigurationManager.AppSettings["donationPeriod"], out months);
result.IsDonated = player.LastDonationDate != null && player.LastDonationDate.Value.AddMonths(months) >= DateTime.UtcNow.Date;
var form = finishedMatches.OrderByDescending(x => x.Date).Take(5).Select(x => x.IsWon ? "W" : "L");
result.Form = form;
result.MatchesSection = new MatchesSectionVM
{
PlayerId = playerId,
CurrentPlayerId = currentPlayerId,
FinishedMatches = finishedMatches,
UpcomingMatches = testMatches,
UpcommingMatchesWatermark = !testMatches.Any(),
EventInvitations = eventInvitations,
FinishedMatchesWatermark = !finishedMatches.Any(),
LeftButtonName = "Confirm",
WatermarkMessage = "You dont have any matches to confirm. Create a challenge or join an event",
ShowButtons = currentPlayerId == playerId,
};
return result;
}
And this is the action that displays everything
[Authorize]
public ActionResult Index(int clubId = 0, string color = "")
{
if (mPlayerID == 0)
{
WebSecurity.Logout();
return RedirectToAction("login", "account", new { clubId, color });
}
var playerViewModel = _service.GetPlayerViewModel(mPlayerID, (int)mSport, (int)mCountry, mPlayerID, clubId, color);
playerViewModel.HasPhoto = _data.Images.PlayerHasPhoto(mPlayerID);
var profileCompletion = GetProfileCompletionPercents(playerViewModel);
playerViewModel.Id = mPlayerID;
playerViewModel.CurrentPlayerId = mPlayerID;
playerViewModel.DonationModel = new PayPalDonationModel(_data, mPlayerID);
playerViewModel.Languages = _cacheService.GetActiveLanguages();
ViewBag.ProfileCompletion = profileCompletion.Item1;
ViewBag.CompletionNext = profileCompletion.Item2;
return View(playerViewModel);
}
The only things that don't appear are the birth date and the user's age. Any suggestions ? Debugger shows that the properties have values in the View.

Related

.net core connect to mysql server

I have a issue here for the connect mysql.
I have a vps that contain mysql server have a database name is 'tuyendungbg'. it's had table and data in there. But when i'm connect and query to select data, that have error for 'Table 'tuyendungbg.Careers' doesn't exist'.
here is my controller :
[HttpGet("/nganh-nghe/{slug?}")]
public IActionResult Index(string slug, [FromQuery(Name =
"p")] int currentPage, int
pageSize)
{
if (!string.IsNullOrEmpty(slug))
{
var career = _context.Careers.FirstOrDefault(x =>
x.Slug.Equals(slug));
if (career != null)
{
ViewBag.CareerName = career.CareerName;
//var qr = _context.Careers.ToList();
var qr = (from p in
_context.CompanyCareers.Where(x => x.CareerId ==
career.ID)
from b in _context.Companies.Where(x =>
x.Id == p.CompanyId)
from i in
_context.IndustrialAreas.Where(x => x.ID ==
b.IndustrialAreaId).DefaultIfEmpty()
select new CompanyModelView()
{
Id = b.Id,
CompanyName = b.CompanyName,
BasicSalary = b.BasicSalary,
Allowance = b.Allowance,
DateCreate = b.DateCreate,
JobTitle = b.JobTitle,
Src = b.Src,
_IndustrialArea = i,
Address = b.Address,
Slug = b.Slug,
WorkTypes = (from tc in
_context.CompanyWorkTypes.Where(x =>
x.CompanyId == b.Id)
from type in
_context.WorkTypes.Where(x => x.Id
==
tc.TypeId)
select type)
}
).OrderByDescending(x => x.DateCreate).ToList();
// var worktype = (from w in
_context.CompanyWorkTypes.Where(x =>
x.CompanyId
== qr.))
var totalCate = qr.Count();
if (pageSize <= 0) pageSize = 10;
int countPages =
(int)Math.Ceiling((double)totalCate / pageSize);
if (currentPage > countPages)
currentPage = countPages;
if (currentPage < 1)
currentPage = 1;
var pagingModel = new PagingModel()
{
countpages = countPages,
currentpage = currentPage,
generateUrl = (pageNumber) =>
Url.Action(nameof(Index), new
{
p = pageNumber,
pageSize = pageSize
})
};
ViewBag.pagingModel = pagingModel;
ViewBag.totalPost = totalCate;
ViewBag.cateIndex = (currentPage - 1) * pageSize;
var companies = qr.Skip((currentPage - 1) *
pageSize)
.Take(pageSize).ToList();
ViewBag.JobCount = companies.Count();
//Set slider menu
var leftSlider = new LeftSliderModel()
{
Areas = new SelectList(_context.Areas,
nameof(Area.ID),
nameof(Area.NameArea)),
Careers = new SelectList(_context.Careers,
nameof(Career.ID),
nameof(Career.CareerName)),
WorkTypes = _context.WorkTypes.ToList(),
Experiences = _context.Experiences.ToList()
};
ViewBag.LeftSlider = leftSlider;
return View(companies);
}
}
return NotFound();
}

"Lock wait timeout exceeded" when sending data from Google Sheets to MySQL

I wrote an Apps Script macro to send data from a Google spreadsheet to a MySQL table. In a first time, in delete some rows in the table and then I add rows in this table. I sometimes get a "Lock wait timeout exceeded; try restarting transaction" error. Sometimes it runs after 100 seconds, sometimes 4 minutes.
I don't understand what is wrong with this code.
//classeur.insertSheet("feuillebis")
//feuillebis=classeur.getSheets()[1]
//var feuillebis=classeur.getSheetByName('feuillebis')
var classeur = SpreadsheetApp.getActiveSpreadsheet() ;
var feuille = classeur.getActiveSheet();
var host = "107.167.186.180";
var databaseName = "eatology";
var userName = "root";
var password = "eatology";
var port = 3306;
var tableName = "weekly_order";
var url = 'jdbc:mysql://' + host + ':' + port + '/' + databaseName;
var nbrow = feuille.getMaxRows()
function Send_Weekly_Order_To_Data_Base() {
///here are all the connection parameters
var classeur = SpreadsheetApp.getActiveSpreadsheet();
var feuille = classeur.getActiveSheet();
var nbrow = feuille.getMaxRows();
var host = "107.167.186.180";
var databaseName = "eatology";
var userName = "root";
var password = "eatology";
var port = 3306;
var tableName = "weekly_order";
var url = 'jdbc:mysql://' + host + ':' + port + '/' + databaseName;
var conn = Jdbc.getConnection(url, userName, password);
conn.setAutoCommit(false);
///get the weekly_order as an array from the sql
var rowcount = 0;
var stmt2 = conn.createStatement();
var results = stmt2.executeQuery("SELECT * FROM eatology.weekly_order");
while (results.next()) {
if (results.getInt(1) > rowcount){
rowcount = results.getInt(1)
}
}
conn.commit();
results.close();
stmt2.close();
///delete the rows from the current week where we are running the macro
var timezone1 = classeur.getSpreadsheetTimeZone();
var date1 = Utilities.formatDate(feuille.getRange(2, 2).getValue(), timezone1, "yyyy-MM-dd");
var date2 = Utilities.formatDate(feuille.getRange(2, 3).getValue(), timezone1, "yyyy-MM-dd");
var date3 = Utilities.formatDate(feuille.getRange(2, 4).getValue(), timezone1, "yyyy-MM-dd");
var date4 = Utilities.formatDate(feuille.getRange(2, 5).getValue(), timezone1, "yyyy-MM-dd");
var date5 = Utilities.formatDate(feuille.getRange(2, 6).getValue(), timezone1, "yyyy-MM-dd");
var date6 = Utilities.formatDate(feuille.getRange(2, 7).getValue(), timezone1, "yyyy-MM-dd");
///clear the table weekly-order in the database
var stmt1 = conn.createStatement();
var result = stmt1.executeUpdate("DELETE FROM eatology.weekly_order where `Date` = " + "'" + date1 + "'" +" or `Date` = " + "'" + date2 + "'" +" or `Date` = " + "'" + date3 + "'" +" or `Date` = "+ "'" + date4 + "'" +" or `Date` = " + "'" + date5 + "'" +" or `Date` = "+ "'" + date6 + "'" );
//var result = stmt1.executeUpdate("DELETE FROM eatology.weekly_order where `Date` = " + "'" + date1 +"'");
conn.commit();
stmt1.close();
conn.close();
rowcount = rowcount + 1;
var conn = Jdbc.getConnection(url, userName, password);
conn.setAutoCommit(false);
var stmt = conn.prepareStatement('INSERT INTO eatology.weekly_order '
+ '(`Uid`, `Date`, `MP`, `Cname`, `Pname`, `Breakfast`, `Snack1`, `Lunch`, `Snack2`, `Dinner`) values (?,?,?,?,?,?,?,?,?,?)');
var program_name_line = 0;
var array = feuille.getRange(1, 1, nbrow, 7).getValues();
for (var j = 1; j < 7; j = j + 1) {
var inside = 0;
var i = 1;
while (array[i][0] != "Total" && i < 1000) {
i = i + 1
var color = feuille.getRange(i + 1, j + 1).getBackgrounds()
var fi1 = array[i][0].toString();
var fij = array[i][j].toString();
var empty = (fij == "");
var already = 0;
var test11111 = (color != "#5d31ce");
var cas1 = ((empty == false) && (fi1 != "Total") && (inside == 0));
var cas2 = (color == "#5d31ce" && inside == 1);
var cas3 = (empty == false);
if ((fi1 != "Total") && (inside == 0) && color != "#5d31ce") {
program_name_line = i;
inside = 1;
if (empty == false) {
var Uid = rowcount;
var Date1 = (Utilities.formatDate(array[1][j], timezone1, "yyyy-MM-dd"));
var MP = (array[program_name_line][0]);
var place = ((fij).indexOf("-"));
var length = (fij.length);
var Pname = ((fij).substring(place + 1, length));
var Cname = ((fij).substring(0, place));
var list = (meal(MP, Pname));
var Breakfast = list[0];
var Snack1 = list[1];
var Lunch = list[2];
var Snack2 = list[3];
var Dinner = list[4];
if (MP == "TM") {
var Breakfast = 1;
var Snack1 = 1;
var Lunch = 1;
var Snack2 = 1;
var Dinner = 1;
}
rowcount = rowcount + 1;
stmt.setInt(1, Uid);
stmt.setString(2, Date1);
stmt.setString(3, MP);
stmt.setString(4, Cname);
stmt.setString(5, Pname);
stmt.setInt(6, Breakfast);
stmt.setInt(7, Snack1);
stmt.setInt(8, Lunch);
stmt.setInt(9, Snack2);
stmt.setInt(10, Dinner);
stmt.addBatch();
}
}
else if (color == "#5d31ce" && inside == 1) {
inside = 0;
}
else if (empty == false && color != "#5d31ce") {
var Uid = rowcount ;
var Date1 = (Utilities.formatDate(array[1][j], timezone1, "yyyy-MM-dd"));
var MP = (array[program_name_line][0].toString());
var place = ((fij).indexOf("-"));
var length = (fij.length);
var Pname = ((fij).substring(place + 1, length));
var Cname = ((fij).substring(0, place));
var list = (meal(MP, Pname));
var Breakfast = (list[0]);
var Snack1 = (list[1]);
var Lunch = (list[2]);
var Snack2 = (list[3]);
var Dinner = (list[4]);
if (MP == "TM") {
var Breakfast = 1;
var Snack1 = 1;
var Lunch = 1;
var Snack2 = 1;
var Dinner = 1;
}
rowcount = rowcount+1;
stmt.setInt(1, Uid);
stmt.setString(2, Date1);
stmt.setString(3, MP);
stmt.setString(4, Cname);
stmt.setString(5, Pname);
stmt.setInt(6, Breakfast);
stmt.setInt(7, Snack1);
stmt.setInt(8, Lunch);
stmt.setInt(9, Snack2);
stmt.setInt(10, Dinner);
stmt.addBatch();
}
}
}
stmt.executeBatch();
conn.commit();
stmt.close();
conn.close();
}
function meal(MP, Pname){
var result= [0, 0, 0, 0, 0]
//in order to know if we have two snacks or only one because if the programm has more than 1200 cal, there are two snacks, otherwise, only one snack
var two_snacks = 1
if (MP.indexOf("1200") > -1) {
two_snacks = 0
}
//if the program type is '3'
if (Pname.indexOf("3") > -1) {
result[0] = 1;
result[1] = 1;
result[2] = 1;
result[4] = 1;
if (two_snacks == 1) {
result[3] = 1;
}
}
//if the program type is '2'
if (Pname.indexOf("2") > -1 && Pname.indexOf("S") == -1) {
result[0] = 1;
result[1] = 1;
result[2] = 1;
if (two_snacks == 1) {
result[3] = 1;
}
}
//if there is the B letter
if (Pname.indexOf("B") > -1) {
result[0] = 1;
}
//if there is the L letter
if (Pname.indexOf("L") > -1) {
result[2] = 1;
}
//if there is the D letter
if (Pname.indexOf("D") > -1) {
result[4] = 1;
}
//if there is the 2S letter
if (Pname.indexOf("2S") > -1) {
result[1] = 1;
result[3] = 1;
}
//if there is the 1S letter
if (Pname.indexOf("1S") > -1) {
result[1] = 1;
result[1] = 1;
}
return result
}

MYSQL Join and create Distinct json

I have the following select
if ($result = $mysqli->query("SELECT
a.quoteID, a.quoteTitle , a.notes, c.web_path
FROM quotes a
INNER JOIN users_files b on b.user_id = a.quoteID
INNER JOIN files c on c.id = b.file_id ORDER BY quoteID ASC"))
{
$tempArray = array();
while($row = $result->fetch_object()) {
$tempArray = $row;
array_push($myArray, $tempArray);
}
echo json_encode($myArray);
}
which gets me information I need.
[{"quoteID":"1","quoteTitle":"Title for 1","notes":"Deal no 1","web_path":"\/surplusAdmin3\/upload\/23.pdf"},{"quoteID":"1","quoteTitle":"Title for 1","notes":"Deal no 1","web_path":"\/surplusAdmin3\/upload\/22.jpeg"},{"quoteID":"1","quoteTitle":"Title for 1","notes":"Deal no 1","web_path":"\/surplusAdmin3\/upload\/21.jpeg"},{"quoteID":"1","quoteTitle":"Title for 1","notes":"Deal no 1","web_path":"\/surplusAdmin3\/upload\/20.jpeg"},{"quoteID":"2","quoteTitle":"Kaitlin","notes":"Smith","web_path":"\/surplusAdmin3\/upload\/24.jpg"},{"quoteID":"8","quoteTitle":"Bryar2","notes":"Long","web_path":"\/surplusAdmin3\/upload\/17.png"},{"quoteID":"11","quoteTitle":"Avram","notes":"Allison","web_path":"\/surplusAdmin3\/upload\/4.jpg"}]
I now need to get my result as:
[{"quoteID":"1","quoteTitle":"Title for 1","notes":"Deal no 1","web_path1":"\/surplusAdmin3\/upload\/23.pdf","web_path2":"\/surplusAdmin3\/upload\/22.jpeg","web_path3":"\/surplusAdmin3\/upload\/21.jpeg","web_path4":"\/surplusAdmin3\/upload\/20.jpeg"}]
I am not looking to re-do the MYSQL statement I just need to create a new array in the format I need.
I have the following code:
var currentQuoteID =0;
var dataChanged = [];
var arrayRow = -1 ;
var fileCount = 0;
dataReturned.forEach(function(e){
console.log(' current quote '+ currentQuoteID + ' = '+ e["quoteID"] + 'file count = '+ fileCount);
if ( currentQuoteID !== e["quoteID"]) {dataChanged.push(e); arrayRow = arrayRow + 1; fileCount = 1}
else
{
console.log('just add the filename array Row = ' +arrayRow );
// need to insert to the array arrayRow
// dataChanged.push('web_path'+fileCount,e["web_path"]);
toPush = 'web_path'+fileCount+'"'+':'+'"'+ e["web_path"];
var field = 'web_path'+fileCount;
var data = e["web_path"];
var tempArray = [field,data];
dataChanged.push(toPush);
dataChanged.field = data;
//dataChanged = dataChanged.concat(tempArray);
fileCount = fileCount +1;
}
currentQuoteID = e["quoteID"];
console.log('stuff '+ JSON.stringify(dataChanged));
});
The result I am getting is :
dataChanged = [{"quoteID":"1","quoteTitle":"Title for 1","notes":"Deal no 1","web_path":"/surplusAdmin3/upload/23.pdf","Type":"image"},"web_path1","/surplusAdmin3/upload/22.jpeg"]
What I need is
dataChanged = [{"quoteID":"1","quoteTitle":"Title for 1","notes":"Deal no 1","web_path":"/surplusAdmin3/upload/23.pdf","Type":"image","web_path1","/surplusAdmin3/upload/22.jpeg"}]
But I cannot workout what I need to do here.
Got it working as follows:
// loop through and add field 'Type' can all be done in one loop.
dataReturned.forEach(function(e){
if (typeof e === "object" ){
e["Type"] = "other";
// console.log('stuff '+e['Type'][i] )
}
});
//loop through and workout the file type
dataReturned.forEach(function(e){
if (typeof e === "object" ){
var ext = e['web_path'].substr(e['web_path'].lastIndexOf('.') + 1);
if ( (ext === 'jpeg' ) || ( ext === 'jpg' )|| ( ext === 'png' )|| ( ext === 'gif' ) || ( ext === 'pdf' ))
{ e["Type"] = "image"; }
//console.log(e['web_path']);
// console.log('stuff '+ JSON.stringify(e))
}
});
// create a new array formated as needed
var currentQuoteID =0;
var arrayRow = -1 ;
var fileCount = 0;
dataReturned.forEach(function(e){
e["quoteID"] + 'file count = '+ fileCount);
if ( currentQuoteID !== e["quoteID"]) {dataChanged.push(e); arrayRow = arrayRow + 1; fileCount = 1}
else
{
//console.log('just add the filename array Row = ' +arrayRow );
// need to insert to the array arrayRow
// dataChanged.push('web_path'+fileCount,e["web_path"]);
var field = 'web_path'+fileCount;
var data = webPath+e["web_path"];
var tempArray = [field,data];
dataChanged[arrayRow]['web_path'+fileCount] = data
fileCount = fileCount +1;
}
currentQuoteID = e["quoteID"];
console.log('stuff '+ JSON.stringify(dataChanged));
});

How to make swap(random) positions between 3 objects by AS3?

//array
var boxs: Array = new Array
boxs[0] = [b1.x = 307.95 , b1.y = 202]
boxs[1] = [b2.x = 233.95 , b2.y = 202]
boxs[2] = [b3.x = 159.95 , b3.y = 202]
//varable
var oldg:Number = 0
//random number
oldg = Number(Math.floor(Math.random()*boxs.length))
Naive approach:
public function Main()
{
const array:Array = [1,2,3,4,5,6,7];
trace(array);
// 1,2,3,4,5,6,7
swapTwoRandomElements(array);
trace(array);
// 1,2,3,6,5,4,7
}
private function swapTwoRandomElements(input:Array):void
{
const indices:Array = [];
for (var i:int = 0; i < input.length; i++)
{
indices.push(i);
}
const indexFirst:int = indices[int(Math.random() * indices.length)];
indices.splice(indexFirst, 1);
const indexSecond:int = indices[int(Math.random() * indices.length)];
indices.splice(indexSecond, 1);
const tmp:* = input[indexFirst];
input[indexFirst] = input[indexSecond];
input[indexSecond] = tmp;
}

Swift Firebase data format

when I did asked firebase the following.
print("\(WarSerArray[CompanyData.companyName]!.allValues)")
print("keys\(WarSerArray[CompanyData.companyName]!.allKeys)")
it printed out this information.
[{
PhonNumber = 7607588500;
address = "2378 Primrose Ave. Vista, CA. 92083";
currentStoreArray = Headquarters;
email = "james#opportunitysoftware.com";
faxNumber = "";
key = "-KLSM8y0BDfs6B1jtsA5";
name = "Service Center 1";
}]
keys[-KLSM8y0BDfs6B1jtsA5]
[{
PhonNumber = 7607588500;
address = "2378 Primrose Ave. Vista, CA. 92083";
currentStoreArray = Headquarters;
email = "james#opportunitysoftware.com";
faxNumber = "";
key = "-KLSM8zu6AFKa7V0beCh";
name = "Warehouse 1";
}]
keys[-KLSM8zu6AFKa7V0beCh]
how do I get name?
var CompanyData = CompanyDataStruct()
struct CompanyDataStruct {
var key = ""
var webpage:String! = ""
var OwnerName:String! = ""
var address:String! = ""
var managerPNumber:String = ""
var dueOnOrder = 0.0
var email:String! = ""
var fax:String! = ""
var itemsOrderHistory:String! = ""
var companyName:String! = ""
var money = 0.0
var notes:String! = ""
var tax = 0.0
var pNumber:String = ""
var ManagerContact = ""
var opw:String! = ""
var mpw:String! = ""
var OwedToCompany = 0.0
var OwedString:String! = ""
var taxID:String! = ""
var reSalesID:String! = ""
var BoxCount = 0
var secondTicketID:String! = ""
var secondTicketNumber = 0
var useSecondTicketID = false
var printerSettings = ""
var quoteDays = 0
var fulfillmentPrinter = false
var fulfillmentEmail = false
var printBill = false
var emailBill = false
var system = false
var printReceipt = false
var emailReceipt = false
var theFulFillEmail = ""
var logoName = ""
var delivery = false
var ac1 = ""
var ac2 = ""
var ac3 = ""
var storeID = ""
var warehouse = ""
var serviceCenter = ""
var currentStore = ""
var StoreCount = 0
var WareHouseCount = 0
var ServiceCenterCount = 0
var MoneySymbol = ""
var refundLevel = 0
var shareBarcode = true
var LoGoImage = DefaultImage
}
var WarehouseData2 = WareServiceStruct()
struct WareServiceStruct {
var name = String()
var address = String()
var currentStoreArray = String()
var phoneNumber = String()
var faxNumber = String()
var email = String()
var key = String()
}
let WareSerRef = FIRDatabase.database().reference().child("Owner").child("CompanyName").child("WareServ")
let WareSerRefName = FIRDatabase.database().reference().child("Owner").child("CompanyName").child("WareServ").child("name")
let WareSerRefAddress = FIRDatabase.database().reference().child("Owner").child("CompanyName").child("WareServ").child("address")
let WarSerRefCurrentStore = FIRDatabase.database().reference().child("Owner").child("CompanyName").child("WareServ").child("CurrentStore")
let WareSerRefPhone = FIRDatabase.database().reference().child("Owner").child("CompanyName").child("WareServ").child("PhoneNumber")
let WareSerRefFax = FIRDatabase.database().reference().child("Owner").child("CompanyName").child("WareServ").child("faxNumber")
let WareSerRefEmail = FIRDatabase.database().reference().child("Owner").child("CompanyName").child("WareServ").child("email")
let WareSerRefKey = FIRDatabase.database().reference().child("Owner").child("CompanyName").child("WareServ").child("key")
func WarehouseFirebaseSetter(sedner: WareServiceStruct) {
let key = WareSerRef.childByAutoId().key
WarehouseData2 = sedner
WarehouseData2.key = key
let WareToAdd = FBWarhouseData
let childUpdates = ["/Warehouse /\(CompanyData.companyName)/\(key)":WareToAdd]
WareSerRef.updateChildValues(childUpdates)
}
var FBWarhouseData = ["address" : WarehouseData2.address,"currentStoreArray" : WarehouseData2.currentStoreArray,"email" : WarehouseData2.email,"faxNumber" : WarehouseData2.faxNumber,"PhonNumber" : WarehouseData2.phoneNumber,"name" : WarehouseData2.name,"key" : WarehouseData2.key] as NSDictionary