Loop only adding one result - for-loop

Situation:
For each customer, make a purchase, subtract inventory from seller, add money to sellers account.
// for each customer
for ($c = 1; $c <= $maxCustomers; $c++) {
// decide what to buy
$willBuy = rand('1','7');
// buy indica
if ($willBuy == '1') {
// how many eights are they going to buy..
$willSpend = rand('1', '4');
if ($indicaPrice < $averageIndicaPrice) {
if ($indicaAvailable > $willSpend) {
// update products
$newIndica = $indicaAvailable - $willSpend;
update_user_meta($sellerID, 'Indica', $newIndica);
// pay for purchase
$newCash = $cash + $indicaPrice;
update_user_meta($sellerID, 'cashOnHand', $newCash);
echo "<tr>";
echo "<td>#".$c."</td>";
if ($willSpend > "1") { echo "<td>".$willSpend." 8th's of Indica Flowers</td>"; }
else { echo "<td>".$willSpend." 8th of Indica Flowers</td>"; }
echo "<td>$".$indicaPrice * $willSpend."</td>";
echo "</tr>";
}
else {
echo "<tr>";
echo "<td>#".$c."</td>";
echo "<td>Could not find anything they liked. No sale.</td>";
echo "<td>$0</td>";
echo "</tr>";
}
}
}
}
Problem #1: In the 'update products' section, it's only updating for 1 loop result. If there is more than one customer who buys 'indica' it only update the indica meta value for 1 result, not for each result (ie, if 2 people buy 3 indica each, it will only subtract 3 indica not 6).
Problem #2: The same thing happens in the 'pay for purchase' section. It only updates the cash for one purchase, not for each purchase.

You are never changing $indicaAvailable are you? Shouldn't you update it based on what was sold?

Related

Getting non overlapping between two dates with Carbon

UseCase: Admin assigns tasks to People. Before we assign them we can see their tasks in a gantt chart. According to the task assign date and deadline, conflict days (overlap days) are generated between tasks.
I wrote this function to get overlapping dates between two dates. But now I need to get non overlapping days between two dates, below is the function I wrote.
$tasks = Assign_review_tasks::where('assigned_to', $employee)
->where('is_active', \Constants::$REVIEW_ACTIVE)
->whereNotNull('permit_id')->get();
$obj['task'] = count($tasks);
// count($tasks));
if (count($tasks) > 0) {
if (count($tasks) > 1) {
$start_one = $tasks[count($tasks) - 1]->start_date;
$end_one = $tasks[count($tasks) - 1]->end_date;
$end_two = $tasks[count($tasks) - 2]->end_date;
$start_two = $tasks[count($tasks) - 2]->start_date;
if ($start_one <= $end_two && $end_one >= $start_two) { //If the dates overlap
$obj['day'] = Carbon::parse(min($end_one, $end_two))->diff(Carbon::parse(max($start_two, $start_one)))->days + 1; //return how many days overlap
} else {
$obj['day'] = 0;
}
// $arr[] = $obj;
} else {
$obj['day'] = 0;
}
} else {
$obj['day'] = 0;
}
$arr[] = $obj;
start_date and end_date are taken from database,
I tried modifying it to,
(Carbon::parse((min($end_one, $end_two))->add(Carbon::parse(max($start_two, $start_one))))->days)->diff(Carbon::parse(min($end_one, $end_two))->diff(Carbon::parse(max($start_two, $start_one)))->days + 1);
But it didn't work, in simple terms this is what I want,
Non conflicting days = (end1-start1 + end2-start2)- Current overlapping days
I'm having trouble translate this expression . Could you help me? Thanks in advance
before trying to reimplement complex stuff I recommend you take a look at enhanced-period for Carbon
composer require cmixin/enhanced-period
CarbonPeriod::diff macro method is what I think you're looking for:
use Carbon\CarbonPeriod;
use Cmixin\EnhancedPeriod;
CarbonPeriod::mixin(EnhancedPeriod::class);
$a = CarbonPeriod::create('2018-01-01', '2018-01-31');
$b = CarbonPeriod::create('2018-02-10', '2018-02-20');
$c = CarbonPeriod::create('2018-02-11', '2018-03-31');
$current = CarbonPeriod::create('2018-01-20', '2018-03-15');
foreach ($current->diff($a, $b, $c) as $period) {
foreach ($period as $day) {
echo $day . "\n";
}
}
This will output all the days that are in $current but not in any of the other periods. (E.g. non-conflicting days)

Amibroker AFL code Buy Sell status is not fetching with if condition

I have AFL which is working fine for crude oil. out of 10 trades, 8 trades are targets hitting. I have code for place orders auto trades. the auto trade code is working fine with other AFL codes but the problem is in below algorithm the BUY and SELL Boolean value is not giving to IF condition. But IIF(Buy .... conditions are working fine.
My main question is why BUY Sell True or false is not working in the last status in AFL. Kindly help me to resolve this.
_SECTION_BEGIN("T+4 day ");
Title = " ..:: duy ::.. - Filter of Stock " + " " + FullName() + " " + Date( ) ;
// 4-Day-Range Switch
prev=AMA2(C,1,0);
d=IIf(C>Ref(Max(Max(H,Ref(H,-20)),Max(Ref(H,-10),Ref(H,-15))),-1),Min(Min(L,Ref(L,-20)),Min(Ref(L,-10),Ref(L,-15))),
IIf(C<Ref(Min(Min(L,Ref(L,-20)),Min(Ref(L,-10),Ref(L,-15))),-1),Max(Max(H,Ref(H,-20)),Max(Ref(H,-10),Ref(H,-15))),PREV));
a=Cross(Close,d);
b=Cross(d,Close);
state=IIf(BarsSince(a)<BarsSince(b),1,0);
s=state>Ref(state,-1);
ss=state<Ref(state,-1);
sss=state==Ref(state,-1);
col=IIf(state == 1 ,51,IIf(state ==0,4,1));
Plot(C,"",Col,128);
Buy=s;
Sell=ss;
PlotShapes( shapeUpArrow * s ,6,0,L);
PlotShapes( shapeDownArrow *ss ,4,0,H);
dist = 0.8*ATR(10);
dist1 = 2*ATR(10);
for( i = 0; i < BarCount; i++ )
{
if( Buy )
{
PlotText( "\nBuy:" + L[ i ] + "\nT= " + (L*1.005) + "\nSL= " + (L*0.9975), i, L[ i ]-dist, colorGreen, colorWhite );
}
if( Sell )
{
PlotText( "Sell:" + H[ i ] + "\nT= " + (H*0.995) + "\nSL= " + (H*1.0025), i, H[ i ]+dist1, colorRed, colorWhite );
}
}
Buy = ExRem(Buy,Sell);
Sell = ExRem(Sell,Buy);
if ( LastValue(Buy)==1)
{
quantity=2;
orderId=placeOrderFuture("MCX", "FUTCOM", ChartSymbol, "BUY", "INTRADAY", "MARKET", quantity, 0, defaultTriggerPrice(), "19-APR-2018", defaultStrategyId(), defaultComments());
//orderId = placeOrderUsingParams(tradeType, AT_ORDER_TYPE, AT_QUANTITY, buyPrice, defaultTriggerPrice(), 1);
}
if ( LastValue(Sell) == 1 )
{
quantity=2;
orderId=placeOrderFuture("MCX", "FUTCOM", ChartSymbol, "SELL", "INTRADAY", "MARKET", quantity, 0, defaultTriggerPrice(), "19-APR-2018", defaultStrategyId(), defaultComments());
//orderId = placeOrderUsingParams("SELL", AT_ORDER_TYPE, AT_QUANTITY, sellPrice, defaultTriggerPrice(), 1);
}
LastValue documentation
With if statements, you need to specify a specific bar. And according to the documentation, LastValue may look into the future. I can't say for sure what's happening with your code, but the loops/if/switch can be tricky. This tutorial Looping in Amibroker might give you some insights into how they work.
You may try SelectedValue instead. If you haven't got any bars selected, it automatically defaults to the last bar. I use this for my realtime trading.
bi = SelectedValue(BarIndex());
if(Buy[bi])
{
...
}
On an unrelated note, your text plots aren't going to plot unfiltered signals, put your ExRem code under your initial Buy and Sell conditions.

How to limit maximum items of order by country in Magento?

How can I limit maximum items of order by country or by continent?
I know we can set the limit in the config just as this answer says.
But what about I just want to limit it by country or by continent?
For instance, I just want to allow max items of 120 per product that are shipped to France and then 60 items only for the shipping outside France.
My store is set in France.
tealuo, i have find a temporary solution for this works
Here step on details:
1.copy app>code>core>Mage>CatalogInventory>Model>Observer.php to app>code>local>Mage>CatalogInventory>Model>Observer.php
And goto function checkQuoteItemQty() add below
$county=null;
$country=$quoteItem->getQuote()->getShippingAddress()->getData('country_id');
after
if (!$quoteItem || !$quoteItem->getProductId() || !$quoteItem->getQuote()
|| $quoteItem->getQuote()->getIsSuperMode()) {
return $this;
}
Then in this function change
$result = $stockItem->checkQuoteItemQty($rowQty, $qtyForCheck, $qty);
to
$result = $stockItem->checkQuoteItemQty($rowQty, $qtyForCheck, $qty,$country);
And
from
$result = $stockItem->checkQuoteItemQty($optionQty, $qtyForCheck, $optionValue);
to
$result = $stockItem->checkQuoteItemQty($optionQty, $qtyForCheck, $optionValue,$country);
copy app>code>core>Mage>CatalogInventory>Model>Stock>Item.php
to app>code>local>Mage>CatalogInventory>Model>Stock>Item.php
edit checkQuoteItemQty function:
edit below code
if ($this->getMaxSaleQty() && $qty > $this->getMaxSaleQty()) {
$result->setHasError(true)
->setMessage(
Mage::helper('cataloginventory')->__('The maximum quantity allowed for purchase is %s. %s', $this->getMaxSaleQty() * 1,$county_id)
)
->setErrorCode('qty_max')
->setQuoteMessage(Mage::helper('cataloginventory')->__('Some of the products cannot be ordered in requested quantity.'))
->setQuoteMessageIndex('qty');
return $result;
}
To:
if(!is_null($county_id) && $county_id=='IN'){
if ($this->getMaxSaleQty() && $qty > 2) {
$result->setHasError(true)
->setMessage(
Mage::helper('cataloginventory')->__('The maximum quantity allowed for purchase is %s. %s', $this->getMaxSaleQty() * 1,$county_id)
)
->setErrorCode('qty_max')
->setQuoteMessage(Mage::helper('cataloginventory')->__('Some of the products cannot be ordered in requested quantity.'))
->setQuoteMessageIndex('qty');
return $result;
}
}
else{
if ($this->getMaxSaleQty() && $qty > $this->getMaxSaleQty()) {
$result->setHasError(true)
->setMessage(
Mage::helper('cataloginventory')->__('The maximum quantity allowed for purchase is %s. %s', $this->getMaxSaleQty() * 1,$county_id)
)
->setErrorCode('qty_max')
->setQuoteMessage(Mage::helper('cataloginventory')->__('Some of the products cannot be ordered in requested quantity.'))
->setQuoteMessageIndex('qty');
return $result;
}
}
See code
if(!is_null($county_id) && $county_id=='IN'){
means IN=India country code of India,Just change country IN to FR France country code
And see condition if ($this->getMaxSaleQty() && $qty > 2) change 2 to 60
And According to your reference
Magento: limit product max quantity to 1 per order. quantity 2 = 2 orders
make Maximum Allow Qty in Shopping cart to 120
Importnote: this->getProductId() is given product id.

Algorithm: optimally distribute N people among M tasks given P preferences

Example: 10 candidates each give 2 preferences (the first being more preferred than the second) for 3 available jobs, and their boss must then optimally allocate (and evenly distribute) them evenly based on their preferences. Obviously, unwanted jobs will require some random draw.
How would I write an algorithm that calculates this optimal allocation automatically?
I looked around and found bipartite graphs which might give me some clues, however I am having trouble wrapping my head around it!
For the "luck" aspect of the game, I already implemented a simple Fisher Yates Shuffle.
Preference weight:
If there are 2 preferences, when assigned to a worker, obtaining a first choice weighs +2, a second choice +1, an unwanted choice -1 (for example). The "optimality" goal is to maximize the aggregate preferences.
Your question is quite challenging, but i found a working (maybe not the most performant) solution. My Example is written in PHP, but you should be able to adapt it. I'll try to explain the "thoughts" behind the code.
Note: It seems like you added the "10 persons, 3 Jobs" constraint later - or i simple did overread it. However, my code should give you an example that you might be able to adapt to that constraint. My Code currently is assuming that there are n jobs for n persons. (The most easiest way of adapting it to the 10/3 criteria, would be to split up the 3 Jobs into 10 equal units of work, when assuming 10 workers!)
First, lets create some basic architecture stuff. We need person, job and obviously a matrix, representing the satisfaction of a person towards a job. The following snipped does exactly that:
<?php
class Person{
var $name;
var $prim;
var $sec;
function __construct($name, $prim, $sec){
$this->name = $name;
$this->prim = $prim;
$this->sec = $sec;
}
function likes($job){
if ($job->type == $this->prim) return 2;
if ($job->type == $this->sec) return 1;
else return -1;
}
}
class Job{
var $name;
var $type;
function __construct($name, $type){
$this->name = $name;
$this->type = $type;
}
}
$persons = array(
"Max" => new Person("Max", "programing", "testing"),
"Peter" => new Person("Peter", "testing", "docu"),
"Sam" => new Person("Sam", "designing", "testing")
);
$jobs = array(
"New Classes" => new Job("New Classes", "programing"),
"Theme change" => new Job("Theme change", "designing"),
"Test Controller" => new Job("Test Controller", "testing")
);
// debug: draw it:
echo "<h2>Happines with Jobs</h2> ";
echo "<table border=1>";
$p=0;
echo "<tr>";
foreach ($jobs AS $job){
$j=0;
foreach ($persons as $person){
if ($p++==0){
echo "<tr><td></td>";
foreach ($persons as $per) {
echo "<td>".$per->name."</td>";
}
echo "</tr>";
}
if ($j++==0){
echo "<td>".$job->name."</td>";
}
echo "<td>".$person->likes($job)."</td>";
}
echo "</tr>";
}
echo "</table>";
This will give you a table like this:
Second, we need to create ALL permutations of jobs and persons. (actually we don't need to, but doing so, will show you the reason, why we don't need to!)
To create all permutations, we are using just the name of a person or job. (we can resolve the name back to the actual object later)
//build up all permutations
$personNames = array();
foreach ($persons AS $person){
$personNames[] = $person->name;
}
$jobNames = array();
foreach ($jobs AS $job){
$jobNames[] = $job->name;
}
$personsPerms = array();
pc_permute($personNames,$personsPerms);
$jobsPerms = array();
pc_permute($jobNames,$jobsPerms);
function pc_permute($items, &$result, $perms = array( )) {
if (empty($items)) {
$result[] = join('/', $perms);
} else {
for ($i = count($items) - 1; $i >= 0; --$i) {
$newitems = $items;
$newperms = $perms;
list($foo) = array_splice($newitems, $i, 1);
array_unshift($newperms, $foo);
pc_permute($newitems,$result, $newperms);
}
}
}
Now, we have 2 Arrays: All job permutations and all person permutations.
For the Example given above, the arrays will look like this (3 Elements each, makes 3*2*1=6 Permutations per Array):
Array
(
[0] => Max/Peter/Sam
[1] => Peter/Max/Sam
[2] => Max/Sam/Peter
[3] => Sam/Max/Peter
[4] => Peter/Sam/Max
[5] => Sam/Peter/Max
)
Array
(
[0] => New Classes/Theme change/Test Controller
[1] => Theme change/New Classes/Test Controller
[2] => New Classes/Test Controller/Theme change
[3] => Test Controller/New Classes/Theme change
[4] => Theme change/Test Controller/New Classes
[5] => Test Controller/Theme change/New Classes
)
Now, We can create a nXn Table, containing ALL Values of the overall satisfaction for ALL possible job allocations:
// debug: draw it:
echo "<h2>Total Happines of Combination (full join)</h2> ";
echo "<table border=1>";
$p=0;
echo "<tr>";
$row = 0;
$calculated = array();
foreach ($jobsPerms AS $jobComb){
$j=0;
$jobs_t = explode("/", $jobComb);
foreach ($personsPerms as $personComb){
if ($p++==0){
echo "<tr><td></td>";
foreach ($personsPerms as $n) {
echo "<td>".$n."</td>";
}
echo "</tr>";
}
if ($j++==0){
echo "<td>".$jobComb."</td>";
}
$persons_t = explode("/", $personComb);
$h = 0;
echo "<td>";
for ($i=0; $i< count($persons_t); $i++){
$h += $persons[$persons_t[$i]]->likes($jobs[$jobs_t[$i]]);
}
echo $h;
echo "</td>";
}
$col=0;
$row++;
echo "</tr>";
}
echo "</table>";
Lets call this matrix "M"
This Matrix contains a "lot" of double combinations: (a/b) TO (1/2) is equal to (b/a) to (2/1) etc...
After all: We simple can ignore:
Either Each row > 1
OR Each column > 1
Ignoring all Columns > 1:
echo "<h2>Total Happines of Combination (ignoring columns)</h2> ";
echo "<table border=1>";
$p=0;
echo "<tr>";
$row = 0;
$calculated = array();
foreach ($jobsPerms AS $jobComb){
$j=0;
$jobs_t = explode("/", $jobComb);
$col = 0;
$personComb = $personsPerms[0];
if ($p++==0){
echo "<tr><td></td>";
echo "<td>".$personsPerms[0]."</td>";
echo "</tr>";
}
if ($j++==0){
echo "<td>".$jobComb."</td>";
}
$persons_t = explode("/", $personComb);
$h = 0;
echo "<td>";
for ($i=0; $i< count($persons_t); $i++){
$h += $persons[$persons_t[$i]]->likes($jobs[$jobs_t[$i]]);
}
echo $h;
echo "</td>";
$col=0;
$row++;
echo "</tr>";
}
echo "</table>";
Output:
And there you go! In this Example (one of) the most satisfying Solution would be:
Max -> New Classes (+2)
Peter -> Test Controller (+2)
Sam -> Theme Change (+2)
-> Happiness: 6.
There are other, equal distributions as well.
Example: 6 persons / 6 jobs:
$persons = array(
"Max" => new Person("Max", "programing", "testing"),
"Peter" => new Person("Peter", "testing", "docu"),
"Sam" => new Person("Sam", "designing", "testing"),
"Jeff" => new Person("Jeff", "docu", "programing"),
"Fred" => new Person("Fred", "programing", "designing"),
"Daniel" => new Person("Daniel", "designing", "docu")
);
$jobs = array(
"New Classes" => new Job("New Classes", "programing"),
"Theme change" => new Job("Theme change", "designing"),
"Test Controller" => new Job("Test Controller", "testing"),
"Create Manual" => new Job("Create Manual", "docu"),
"Program more!" => new Job("Program more!", "programing"),
"Style the frontend" => new Job("Style the frontend", "designing")
);
results in (Persons: Max / Peter / Sam / Jeff / Fred / Daniel)
Assuming by "evenly distribute" you mean you know how many people must be assigned to each project, this is the weighted matching problem (aka "maximum cardinality bipartite matching"). Just treat each open position (rather than each job) as a node - so, a job with 3 positions will have three nodes.
The wikipedia article gives several solutions.
Pseudocode
for(n to number of jobs left)
{
job n = a random candidate
if(random candidate first preference == job n)
remove random candidate from list and remove job from list
}
if(jobs left)
{
for(n to number of jobs left)
for(i to number of candidates)
if(candidate first preference == job n)
{
job n = candidate i
remove candidate i from list and remove job n from list
}
else if(candidate second preference == job n)
{
job n = candidate i
}
}

Magento grouped products label question

I have tier pricing setup for one of my products in Magento. Is there any way to change the "Buy 2 for $321.60 each" to "Buy 2-4 for $321.60 each" and "Buy 5+ for $205.52 each"? It won't always be these numbers (could be "Buy 3-4" or something).
The display logic for tier prices is located in app/design/frontend/watercare/default/template/catalog/product/view/tierprices.phtml
Replace the last else block with:
<?php
$_format = 'Buy %1$s for %2$s each';
if($index === count($_tierPrices) - 1)
{
$_format = 'Buy %1$s+ for %2$s each';
}
else
{
$_next = $_tierPrices[$index + 1];
$_qty = $_next['price_qty'] - 1;
if($_qty > 0) $_format = 'Buy %1$s-' . $_qty . ' for %2$s each';
}
echo $this->__($_format, $_price['price_qty'], $_price['formated_price']);
?>
This will make sure that the last tier price will always be {num}+ and the ones before it will be
2 - {num - 1}.
a quick fix to the code above (It wasn't working correctly for me in 1.7.0.2)
$_qty would stay the same for all the tiers a fix would be.
<?php
$_format = 'Buy %1$s for %2$s each';
if($index === count($_tierPrices) - 1)
{
$_format = 'Buy %1$s+ for %2$s each';
}
else
{
$i = $i + 1;
$_next = $_tierPrices[$index + $i];
$_qty = $_next['price_qty'] -1;
if($_qty > 0) $_format = 'Buy %1$s-' . $_qty . ' for %2$s each';
}
echo $this->__($_format, $_price['price_qty'], $_price['formated_price']);
?>

Resources