How to update main array in laravel - arrays

I Need help on updating Main Array with its data changed in a foreach loop.
Here is my code :
$query = DB::table('autostk')
->where('autostk.branchid', $branch_id)
->where('autostk.itemcode', $request->itemcode)
->whereDate('autostk.date', '<=', $request->tdate)
->where('autostk.branchid', $branch_id)
->leftjoin('journal', 'autostk.refno', '=', 'journal.vno')
->where('journal.code', '>=', 100)
->where('journal.branchid', $branch_id)
->leftjoin('accounts', 'journal.code', '=', 'accounts.code')
->where('accounts.branchid', $branch_id)
->select('journal.code', 'accounts.title', 'autostk.*')
->orderBY('date')->get()
->map(function ($item, $key) {
return (array)$item;
})
->all();
foreach ($query as $row) {
if (is_null($row['qtyin'])) {
$row['qtyin'] = 0;
}
if (is_null($row['qtyout'])) {
$row['qtyout'] = 0;
}
if (is_null($row['rate'])) {
$row['rate'] = 0;
}
if ($row['vtype'] = 'PI' && $row['qtyin'] > 0) {
$stkval = ($bal * $avgrate) + ($row['qtyin'] * $row['rate']);
if ($bal > 0) {
$bal = $bal + $row['qtyin'] - $row['qtyout'];
if ($bal > 0 && $stkval > 0) {
$avgrate = $stkval / $bal;
}
} else {
$bal = $bal + $row['qtyin'] - $row['qtyout'];
$avgrate = $row['rate'];
}
} else {
$bal = $bal + $row['qtyin'] - $row['qtyout'];
}
$row['balqty'] = $bal;
$row['avgrate'] = $avgrate;
}
My question is how to update $query with changes made to $row. I am new to php and laravel and have tried push(), put(), etc. Don't know which function is required in this case.

To keep changes you've applied to $row inside the foreach you just need to pass it by reference:
foreach ($query as &$row) { //notice the & before $row
Alternatively, you could could use just move the code inside your foreach to inside your map closure:
->map(function ($item, $key) use ($bal, $avgrate) {
$row = (array)$item;
if (is_null($row['qtyin'])) {
$row['qtyin'] = 0;
}
if (is_null($row['qtyout'])) {
$row['qtyout'] = 0;
}
if (is_null($row['rate'])) {
$row['rate'] = 0;
}
if ($row['vtype'] = 'PI' && $row['qtyin'] > 0) {
$stkval = ($bal * $avgrate) + ($row['qtyin'] * $row['rate']);
if ($bal > 0) {
$bal = $bal + $row['qtyin'] - $row['qtyout'];
if ($bal > 0 && $stkval > 0) {
$avgrate = $stkval / $bal;
}
} else {
$bal = $bal + $row['qtyin'] - $row['qtyout'];
$avgrate = $row['rate'];
}
} else {
$bal = $bal + $row['qtyin'] - $row['qtyout'];
}
$row['balqty'] = $bal;
$row['avgrate'] = $avgrate;
return $row;
})

Try following code:
$query = DB::table('autostk')
->where('autostk.branchid', $branch_id)
->where('autostk.itemcode', $request->itemcode)
->whereDate('autostk.date', '<=', $request->tdate)
->where('autostk.branchid', $branch_id)
->leftjoin('journal', 'autostk.refno', '=', 'journal.vno')
->where('journal.code', '>=', 100)
->where('journal.branchid', $branch_id)
->leftjoin('accounts', 'journal.code', '=', 'accounts.code')
->where('accounts.branchid', $branch_id)
->select('journal.code', 'accounts.title', 'autostk.*')
->orderBY('date')->get()
->map(function ($item, $key) {
return (array)$item;
})
->all();
$row_data = [];
foreach ($query as $row) {
if (is_null($row['qtyin'])) {
$row['qtyin'] = 0;
}
if (is_null($row['qtyout'])) {
$row['qtyout'] = 0;
}
if (is_null($row['rate'])) {
$row['rate'] = 0;
}
if ($row['vtype'] = 'PI' && $row['qtyin'] > 0) {
$stkval = ($bal * $avgrate) + ($row['qtyin'] * $row['rate']);
if ($bal > 0) {
$bal = $bal + $row['qtyin'] - $row['qtyout'];
if ($bal > 0 && $stkval > 0) {
$avgrate = $stkval / $bal;
}
} else {
$bal = $bal + $row['qtyin'] - $row['qtyout'];
$avgrate = $row['rate'];
}
} else {
$bal = $bal + $row['qtyin'] - $row['qtyout'];
}
$row['balqty'] = $bal;
$row['avgrate'] = $avgrate;
$row_data[] = $row;
}
Now use $row_data.

Option 1
//use toArray() in last to get the result as an array
$query = ...->all()->toArray();
foreach ($query as $key => $row) {
//inside here instead of using $row, use $query[$key]
//so for example $row['rate'] = 0; becomes:
$query[$key]['rate'] = 0;
}
Option 2
//use toArray() in last to get the result as an array
$query = ...->all()->toArray();
//use pass by reference with help of &
foreach ($query as $key => &$row) {
...
}
However, be very careful with a pass by reference approach otherwise you might run into issues if you reuse the same array.
Option 3
$query = ...->all();
foreach ($query as $key => $row) {
//access it as object
//instead of using $row['qtyin'] use:
$row->qtyin = 0;
}
Its dealer's choice :)

Related

sqlsrv_fetch_array() expects parameter 1 to be resource, object given

Good Day,
I was looking for the solution of this code. But unfortunately I couldn`t fix it hope someone can enlighten me on this matter.
function getCharactersBySerial($serial)
{
$charinfo = "";
$i = 0;
$CI =& get_instance();
$CI->mssql = $CI->load->database( 'world', TRUE );
$char_result = $CI->mssql->query("SELECT * FROM RF_World.dbo.tbl_base WHERE Serial= $serial and DCK='0'");
while ($character = sqlsrv_fetch_array($char_result))
{
$charinfo['Serial'] = $character['Serial'];
$charinfo['Name'] = $character['Name'];
$charinfo['AccountSerial'] = $character['AccountSerial'];
$i = 1;
return $charinfo;
}
if ($i == 0 ) {
return "None";
}
}
and this is the other one they have both same errors
function getCharactersGuildBySerial($serial)
{
$charinfo = "";
$i = 0;
$CI =& get_instance();
$CI->mssql = $CI->load->database( 'world', TRUE );
$char_result = $CI->mssql->query("SELECT B.Name, L.id FROM tbl_base as B INNER JOIN tbl_general as G ON G.Serial = B.Serial INNER JOIN tbl_Guild as L ON L.Serial = G.GuildSerial WHERE B.Serial= $serial and B.DCK='0'");
while ($character = sqlsrv_fetch_array($char_result))
{
$charinfo['GuildName'] = $character['id'];
$charinfo['Name'] = $character['Name'];
$i = 1;
return $charinfo;
}
if ($i == 0 ) {
$charinfo['Name'] = 'None';
return $charinfo;
}
}
I just fund out the error was because of my Condition and it only appears if the query doesn`t have a result. Please check below for the fix that I did:
function getCharactersBySerial($serial)
{
$charinfo = "";
$i = 0;
$CI =& get_instance();
$CI->mssql = $CI->load->database( 'world', TRUE );
$char_result = $CI->mssql->query("SELECT * FROM RF_World.dbo.tbl_base WHERE Serial= $serial and DCK='0'");
if($char_result->num_rows()<=0){
return 'None';
}else{
while ($character = sqlsrv_fetch_array($char_result))
{
$charinfo['Serial'] = $character['Serial'];
$charinfo['Name'] = $character['Name'];
$charinfo['AccountSerial'] = $character['AccountSerial'];
$i = 1;
return $charinfo;
}
}
}
and
function getCharactersGuildBySerial($serial)
{
$charinfo = "";
$i = 0;
$CI =& get_instance();
$CI->mssql = $CI->load->database( 'world', TRUE );
$char_result = $CI->mssql->query("SELECT B.Name, L.id FROM tbl_base as B INNER JOIN tbl_general as G ON G.Serial = B.Serial INNER JOIN tbl_Guild as L ON L.Serial = G.GuildSerial WHERE B.Serial= $serial and B.DCK='0'");
if($char_result->num_rows()<=0){
$charinfo['Name'] = 'None';
return $charinfo;
}else{
while ($character = sqlsrv_fetch_array($char_result))
{
$charinfo['GuildName'] = $character['id'];
$charinfo['Name'] = $character['Name'];
$i = 1;
return $charinfo;
}
}
}

Is there any way to replace text in ChromiumBrowser like Chrome already has?

I'm making a web editor application using CefSharp WinForms library, but I couldn't find a way to replace text from CefSharp API.
There is a find method in WebBrowserExtensions but no replace method.
Question 1:
Does anyone know where replacing text method is in CefSharp?
Or there is no way to replace text in CefSharp? If yes, I need to find a detour for it.
Question 2:
There are yellow blocks marked found words when I try Find method, but those blocks are not a part of selection range of window object in HTML. Are those blocks made by native not web browser?
Answer:
I made "find and replace" function by myself using javascript, so if someone tries to do something like me then you can use below codes:
var lastsearchedNodeIndex = -1;
var lastSearchedTextIndex = -1;
var lastRange = null;
function getTextLengthFromStartTo(targetNodeIndex) {
var childNodes = editor.childNodes;
var textLength = 0;
if (targetNodeIndex >= childNodes.length) {
return editor.textContent.length;
}
for (var i = 0; i < targetNodeIndex; i++) {
if (childNodes[i].textContent != null) {
textLength += childNodes[i].textContent.length;
}
}
return textLength;
}
function getCurrentCaretIndex() {
var currentCaretIndex = 0;
var doc = editor.ownerDocument || editor.document;
var win = doc.defaultView || doc.parentWindow;
var sel;
if (typeof win.getSelection != "undefined") {
sel = win.getSelection();
if (sel.rangeCount > 0) {
var range = win.getSelection().getRangeAt(0);
var preCaretRange = range.cloneRange();
preCaretRange.selectNodeContents(editor);
preCaretRange.setEnd(range.endContainer, range.endOffset);
currentCaretIndex = preCaretRange.toString().length;
}
} else if ( (sel = doc.selection) && sel.type != "Control") {
var textRange = sel.createRange();
var preCaretTextRange = doc.body.createTextRange();
preCaretTextRange.moveToElementText(editor);
preCaretTextRange.setEndPoint("EndToEnd", textRange);
currentCaretIndex = preCaretTextRange.text.length;
}
return currentCaretIndex;
}
function getCurrentNodeIndexAtCaret(caretIndex) {
if (caretIndex == 0) {
return 0;
}
var currentNodeIndex = -1;
for (var i = 0; i < editor.childNodes.length; i++) {
var frontTextLength = getTextLengthFromStartTo(i);
var backTextLength = getTextLengthFromStartTo(i + 1);
if (caretIndex > frontTextLength && caretIndex <= backTextLength) {
currentNodeIndex = i;
break;
}
}
return currentNodeIndex;
}
function getCurrentTextIndexInNodexAtCaret(nodeIndex, caretIndex) {
var textLength = getTextLengthFromStartTo(nodeIndex);
var textIndex = caretIndex - textLength;
return (textIndex < 0) ? 0 : textIndex;
}
function clearSelection() {
if (window.getSelection().rangeCount > 0) {
if (lastRange != null) {
window.getSelection().removeAllRanges();
lastRange.collapse(true);
window.getSelection().addRange(lastRange);
}
}
}
function getTextNodesIn(node) {
var textNodes = [];
if (node.nodeType == 3) {
textNodes.push(node);
} else {
var children = node.childNodes;
for (var i = 0, len = children.length; i < len; ++i) {
textNodes.push.apply(textNodes, getTextNodesIn(children[i]));
}
}
return textNodes;
}
function setSelectionRange(el, start, end) {
if (document.createRange && window.getSelection) {
var range = document.createRange();
range.selectNodeContents(el);
var textNodes = getTextNodesIn(el);
var foundStart = false;
var charCount = 0, endCharCount;
for (var i = 0, textNode; textNode = textNodes[i++]; ) {
endCharCount = charCount + textNode.length;
if (!foundStart && start >= charCount && (start < endCharCount || (start == endCharCount && i <= textNodes.length))) {
range.setStart(textNode, start - charCount);
foundStart = true;
}
if (foundStart && end <= endCharCount) {
range.setEnd(textNode, end - charCount);
break;
}
charCount = endCharCount;
}
var sel = window.getSelection();
sel.removeAllRanges();
sel.addRange(range);
lastRange = range;
sel.anchorNode.parentElement.scrollIntoView();
} else if (document.selection && document.body.createTextRange) {
var textRange = document.body.createTextRange();
textRange.moveToElementText(el);
textRange.collapse(true);
textRange.moveEnd("character", end);
textRange.moveStart("character", start);
textRange.select();
}
}
function findText(text, caseSensitive) {
var currentCaretIndex = getCurrentCaretIndex();
clearSelection();
var regex;
if (caseSensitive) {
regex = text;
} else {
regex = new RegExp(text, "gi");
}
var childNodes = editor.childNodes;
var startNodeIndex = getCurrentNodeIndexAtCaret(currentCaretIndex);
var endNodeIndex = childNodes.length;
var startTextIndex = 0;
if (window.getSelection().focusOffset == 1) {
startTextIndex = lastSearchedTextIndex + 1;
} else {
startTextIndex = getCurrentTextIndexInNodexAtCaret(startNodeIndex, currentCaretIndex);
}
var searchedTextIndex = -1;
var searchedNodeIndex = 0;
var searchTargetSentence = null;
var searchLoopCount = 0;
if (currentCaretIndex == editor.textContent.length) {
startNodeIndex = 0;
startTextIndex = 0;
}
do
{
for (var i = startNodeIndex; i < endNodeIndex; i++) {
if (typeof (childNodes[i].textContent) == undefined || childNodes[i].textContent == null) {
startTextIndex = 0;
continue;
}
if (startTextIndex == childNodes[i].textContent.length) {
startTextIndex = 0;
continue;
}
if (startTextIndex > 0) {
searchTargetSentence = childNodes[i].textContent.substring(startTextIndex, childNodes[i].textContent.length);
} else {
searchTargetSentence = childNodes[i].textContent;
}
searchedTextIndex = searchTargetSentence.search(regex);
if (searchedTextIndex > -1) {
searchedTextIndex += startTextIndex;
searchedNodeIndex = i;
break;
}
startTextIndex = 0;
}
if (searchedTextIndex == -1) {
endNodeIndex = startNodeIndex + 1;
startNodeIndex = 0;
searchLoopCount++;
}
} while (searchLoopCount < 2 && searchedTextIndex == -1);
lastsearchedNodeIndex = searchedNodeIndex;
lastSearchedTextIndex = searchedTextIndex;
if (searchedNodeIndex > -1 && searchedTextIndex > -1) {
var textStartIndex = getTextLengthFromStartTo(searchedNodeIndex) + searchedTextIndex;
setSelectionRange(editor, textStartIndex, textStartIndex + text.length);
return true;
} else {
return false;
}
}
function replaceText(textToFind, textToReplace, caseSensitive) {
if (findText(textToFind, caseSensitive) == true) {
var sel, range;
if (window.getSelection) {
sel = window.getSelection();
if (sel.rangeCount) {
range = sel.getRangeAt(0);
range.deleteContents();
range.insertNode(document.createTextNode(textToReplace));
}
} else if (document.selection && document.selection.createRange) {
range = document.selection.createRange();
range.text = textToReplace;
}
return true;
} else {
return false;
}
}
There are no replace text method in CefSharp.
I think you have two options
Implement in javascript/html in the browser (DIY or something
like Tiny)
Manipulating the html from C# using GetSourceAsync and LoadHtml (Documentation)
Second question - I think you may be able to at least read the hits using the FindHandler. Have not tested this myself.

How to do numeric iterators in angularjs?

I have to convert Java code to angularjs ..In java i used while loop for numeric iterator something like below and in angularjs i tried ng-repeat but its not worked as loop sometime increase by +1 or +2 etc.Can someone please guide ho to do numeric iteration in angularjs?
int curretPos = 0;
String namePattern ="SOmeValue";
while (curretPos < namePattern.length()) {
String featureName = "";
if (Constants.namePatternformat.charAt(0) == namePattern.charAt(curretPos)
&& Constants.namePatternformat.charAt(1) == namePattern.charAt(curretPos + 1)) { // name pattern
curretPos = curretPos + 2;
int nextPos = namePattern.indexOf(Constants.namePatternformat.charAt(2), curretPos);
if (nextPos != -1) {
featureName = namePattern.substring(curretPos, nextPos);
curretPos = nextPos;
if (features.containsKey(featureName)) {
name = name.concat(String.valueOf(features.get(featureName)));
} else {
throw SomeException;
}
} else {
throw SomeException;
}
} else if (Constants.namePatternParent.charAt(0) == namePattern.charAt(curretPos)
&& (Character.toLowerCase(Constants.namePatternParent.charAt(1)) == Character.toLowerCase(namePattern.charAt(curretPos + 1)))) { // parent name pattern
if((namePattern.length() - curretPos) >= Constants.namePatternParent.length()) {
if (!Constants.namePatternParent.equals(namePattern.substring(curretPos, (curretPos+Constants.namePatternParent.length())))) {
throw SomeException;
}
}else{
throw SomeException;
}
curretPos = curretPos + (Constants.namePatternParent.length() - 1);
if(null != parent){
name = name.concat(parent);
}
} else if (Constants.namePatternIncrement.charAt(0) == namePattern.charAt(curretPos)
&& (Character.toLowerCase(Constants.namePatternIncrement.charAt(1)) == Character.toLowerCase(namePattern.charAt(curretPos + 1)))) { // increment name pattern
if((namePattern.length() - curretPos) > Constants.namePatternIncrement.length()) {
if (!Constants.namePatternIncrement.substring(0, 5).equals(namePattern.substring(curretPos, curretPos+5))) {
throw SomeException;
}
}else{
throw SomeException;
}
curretPos = curretPos + (Constants.namePatternIncrement.length() - 2) + 1;
int nextPos =
namePattern.indexOf(Constants.namePatternIncrement
.charAt(Constants.namePatternIncrement.length() - 1), curretPos);
if (nextPos != -1) {
featureName = namePattern.substring(curretPos, nextPos);
curretPos = nextPos;
if (features.containsKey(featureName)) {
if (null != features.get(featureName)
&& features.get(featureName).matches("^-?\\d+$")) {
int currentInstance = Integer.valueOf(features.get(featureName)) + (instance-1);
name = name.concat(String.valueOf(currentInstance));
} else {
throw SomeException;
}
} else {
throw SomeException;
}
} else {
throw SomeException;
}
} else {
name = name.concat(String.valueOf(namePattern.charAt(curretPos)));
}
curretPos = curretPos + 1;
}

How to sort an arraylist by multiple fields in Typescript

How can I sort an arraylist in Typescript by multiple fields.
For example, I have this object:
enter image description here
My single sort method works fine:
private sortFunction(a: RSFolderObject, b: RSFolderObject) {
var a_label = a.label.toLowerCase();
var b_label = b.label.toLowerCase();
if (a_label < b_label) {
return -1;
} else if (a_label > b_label) {
return 1;
} else {
return 0;
}
}
For multiple sorting I used that:
private sortFunction(a: RSFolderObject, b: RSFolderObject) {
var a_label = a.label.toLowerCase();
var b_label = b.label.toLowerCase();
var a_description = a.description[0].toLowerCase().replace("\\", "");
var b_description = b.description[0].toLowerCase().replace("\\", "");
if (a_label < b_label || a_description < b_description) {
return -1;
} else if (a_label > b_label || a_description > b_description) {
return 1;
} else {
return 0;
}
}
But it does not work.
OK, I solved it like this:
private sortFunction(a: RSFolderObject, b: RSFolderObject) {
var a_label = a.label.toLowerCase();
var b_label = b.label.toLowerCase();
var a_description = a.description[0].toLowerCase().replace("\\", "");
var b_description = b.description[0].toLowerCase().replace("\\", "");
if (a_label < b_label) {
return -1;
}
else if (a_label > b_label) {
return 1;
}
else {
if (a_description < b_description) {
return -1;
}
else if (a_description > b_description) {
return 1;
}
else {
return 0;
}
}
}

Read questions and answers in an array and display

Comparing array elements and add 1 or 0 if the arrays are the same or not. But they are not adding up, where could i be doing it wrong? Because the arrays do not seem to be comparing.
<html>
<head>
<title>Chosen answers</title>
</head>
<body>
<pre>
<?php
//Posting of the chosen answers
$answers = $_POST['selected_answers'];
echo '<b><u>THE ANSWERS YOU HAVE CHOSEN ARE:</u></b><br /><br />';
print_r($answers);
//Opening of the answers file, reading and printing it
$openFile = fopen("answers.txt", "r") or exit ("unable to open the answers file");
$fileContents = fread($openFile, filesize("answers.txt"));
fclose($openFile);
$delimiter = " ";
$myArray = explode($delimiter, $fileContents);
$score = $score1 = $score2 = $score3 = $score4 = $score5 = $score6 = $score7 = $score8 = 0;
//Computation of marks scored for the answered questions
if ($answers[0] == $myArray[0])
{
$score = 1;
}
elseif ($answers[0] !=$myArray[0])
{
$score = 0;
}echo '<br />';
if ($answers[1] == $myArray[1])
{
$score1 = 1;
}
elseif ($answers[1] !=$myArray[1])
{
$score1 = 0;
}echo '<br />';
if ($answers[2] == $myArray[2])
{
$score2 = 1;
}
elseif ($answers[2] !=$myArray[2])
{
$score2 = 0;
}echo '<br />';
if ($answers[3] == $myArray[3])
{
$score3 = 1;
}
elseif ($answers[3] !=$myArray[3])
{
$score3 = 0;
}echo '<br />';
if ($answers[4] == $myArray[4])
{
$score4 = 1;
}
elseif ($answers[4] !=$myArray[4])
{
$score4 = 0;
}echo '<br />';
if ($answers[5] == $myArray[5])
{
$score5 = 1;
}
elseif ($answers[5] !=$myArray[5])
{
$score5 = 0;
}echo '<br />';
if ($answers[6] == $myArray[6])
{
$score6 = 1;
}
elseif ($answers[6] !=$myArray[6])
{
$score6 = 0;
}echo '<br />';
if ($answers[7] == $myArray[7])
{
$score7 = 1;
}
elseif ($answers[7] !=$myArray[7])
{
$score7 = 0;
}echo '<br />';
if ($answers[8] == $myArray[8])
{
$score8 = 1;
}
elseif ($answers[8] !=$myArray[8])
{
$score8 = 0;
}
$Total = $score + $score1 + $score2 + $score3 + $score4 + $score5 + $score6 + $score7 + $score8 ;
echo "<b><u>$Total</u></b>";
?>
</pre>
</body>
</html>
How can I be able to compare the two arrays and compute the total marks. the first array $answers is from a submitted form. and the second one is read from another text file called answers.txt
your code is too redundant you should optimize it. try it
<?php
$total=0;
if ($answers[1]=="Data coupling")
{
$total++;
}
else
{
print_r($answers[1]);
}
//third question
if ($answers[2]=="Unit testing")
{
$total++;
}
else
{
print_r($answers[2]);
}
//fourth question
if ($answers[3]=="Mutation testing")
{
$total++;
}
else
{
print_r($answers[3]);
}
//fifth question
if ($answers[4]=="white box testing")
{
$total++;
}
else
{
print_r($answers[4]);
}
//sixth question
if ($answers[5]=="Ad hoc")
{
$total++;
}
else
{
print_r($answers[5]);
}
//seventh question
if ($answers[6]=="information domain values")
{
$total++;
}
else
{
print_r($answers[6]);
}
//eigth question
if ($answers[7]=="Functional and behavioral")
{
$total++;
}
else
{
print_r($answers[7]);
}
//nineth question
if ($answers[8]=="Efficiency")
{
$total++;
}
else
{
print_r($answers[8]);
}
//code to generate the total score
echo $total;
?>

Resources