Lets say I have this test:
class test extends TestCase
{
use RefreshDatabase;
/** #test */
public function test_ids_example()
{
$courses = factory(Post::class, 3)->create();
$this->assertEquals([1, 2, 3], $courses->pluck('id')->toArray());
}
/** #test */
public function test_ids_example_2()
{
$courses = factory(Post::class, 4)->create();
$this->assertEquals([1, 2, 3, 4], $courses->pluck('id')->toArray());
}
}
When I run the the test one by one, it passes..
but when I run the whole test file I get this error:
test::test_ids_example_2
Failed asserting that two arrays are equal.
--- Expected
+++ Actual
## ##
Array (
- 0 => 1
- 1 => 2
- 2 => 3
- 3 => 4
+ 0 => 4
+ 1 => 5
+ 2 => 6
+ 3 => 7
)
Because the tests doesn't reset the auto increment "id" even though I added "RefreshDatabase" trait. How to solve this? How can I rest the id for each test?
Related
My raku Inline::Python code module unexpectedly prints output even when the rs_str method is disabled.
use Inline::Python;
role Series {
has $args;
has $!py = Inline::Python.new;
has $.po; #each instance has own Python Series obj
method TWEAK {
my $py-str = qq{
class RakuSeries:
def __init__(self):
self.series = pd.Series($args)
#`[
def rs_str(self):
return(str(self.series))
#]
};
$!py.run($py-str);
$!po = $!py.call('__main__', 'RakuSeries');
}
method Str {
$!po.rs_str()
}
}
say ~Series.new( args => "[1, 3, 5, 6, 8]" );
>>>
0 1
1 3
2 5
3 6
4 8
Name: anon, dtype: int64
Is this a special tunnelling mode?
Poisson d'Avril
April Fool
першоквітневий дурень
Aprilscherz
I have two sets of array A and B, array A and B on submission is supposed to enter a database table.
A(result)
array:2 [
0 => 7
1 => 8
]
B
array:3 [
"student_test_id" => 8
"question_id" => 4
"test_id" => 3
]
EXPECTED RESULT
On submit, i want the values of Array A and B to enter this table like this
id| student_test_id | test_id | question_id |result
1 | 8 | 3 | 4 | 7
2 | 8 | 3 | 4 | 8
WHAT I HAVE TRIED
$result = $request->result;
$array_conv = array(
"student_test_id"=>$request->student_test_id,
"question_id"=>$request->question_id,
"test_id"=>$request->test_id,
);
foreach($request->result as $result){
$test_log = new StudentTestLog();
$test_log->student_test_id = $array_conv["student_test_id"];
$test_log->question_id = $array_conv["question_id"];
$test_log->test_id = $array_conv["test_id"];
$test_log->result = $result['id'];
$test_log->save();
if($test_log->save()){
return response()->json('Submited', 200);
}else{
return response()->json('Error Submitting', 400);
}
}
Please assist Thank you
When returning response from foreach except first all other iterations of loop are omitted as return ends method execution. You should move return statements outside the loop. Try something like this:
$array_conv = array(
"student_test_id"=>$request->student_test_id,
"question_id"=>$request->question_id,
"test_id"=>$request->test_id,
);
$data_to_persist = [];
foreach($request->result as $result){
array_push( $data_to_persist, [
'student_test_id' => $array_conv["student_test_id"],
'question_id' => $array_conv["question_id"],
'test_id' => $array_conv["test_id"],
'result' => $result['id']
]);
}
$saved = StudentTestLog::insert( $data_to_persist );
if($saved){
return response()->json('Submited', 200);
}else{
return response()->json('Error Submitting', 400);
}
PLEASE NEED HELP
This is what I'm doing:
var my_array_W:Array = new Array();
my_array_W.push({cor:Acorrect, tem:AnewTime, tab: "TB_A", nom:Aoseasnnombre});
my_array_W.push({cor:Bcorrect, tem:BnewTime, tab: "TB_B", nom:Boseasnnombre});
my_array_W.push({cor:Ccorrect, tem:CnewTime, tab: "TB_C", nom:Coseasnnombre});
my_array_W.push({cor:Dcorrect, tem:DnewTime, tab: "TB_D", nom:Doseasnnombre});
my_array_W.push({cor:Ecorrect, tem:EnewTime, tab: "TB_E", nom:Eoseasnnombre});
my_array_W.push({cor:Fcorrect, tem:FnewTime, tab: "TB_F", nom:Foseasnnombre});
This Output:
[tab] | [cor] | [tem]
TB_A 3 8.6877651541
TB_B 4 12.9287651344
TB_C 1 6199.334999999999923
TB_D 4 33.6526718521
TB_E 4 31.90468496844
TB_F 1 6.334999999923
So then I sort:
my_array_W.sortOn("tem", Array.NUMERIC);
my_array_W.sortOn("cor", Array.NUMERIC | Array.DESCENDING);
And Geting this T_T :
[tab] | [cor] | [tem]
TB_E 4 31.90468496844
TB_D 4 33.6526718521
TB_B 4 12.9287651344
TB_A 3 8.6877651541
TB_F 1 31.90468496844
TB_C 1 6199.334999999999923
I just wanna sort a Winner Table by Time(the less) and Correct(the high)
So the Winner is the One who make more correct answers in less time.
I really try so hard to get a sort like this:
[tab] | [cor] | [tem]
TB_B 4 12.9287651344
TB_E 4 31.90468496844
TB_D 4 33.6526718521
TB_A 3 8.6877651541
TB_F 1 6.334999999923
TB_C 1 6199.334999999999923
But couldn't achieve it
Your mistake is that you sort it 2 times. The second time does not additionally sort the sorted, it just sorts the whole Array anew. What you need is to use the Array.sort(...) method with a compareFunction argument:
my_array_W.sort(sortItems);
// Should return -1 if A < B, 0 if A == B, or 1 if A > B.
function sortItems(A:Object, B:Object):Number
{
// First, the main criteria.
if (A.cor > B.cor) return -1;
if (A.cor < B.cor) return 1;
// If A.cor == B.cor, then secondary criteria.
if (A.tem < B.tem) return -1;
if (A.tem > B.tem) return 1;
// Items seem to be equal.
return 0;
}
#Organis was so close.
But Finally I do the trick :D
With this line
my_array_W.sortOn(['cor', 'tem'],[ Array.NUMERIC | Array.DESCENDING, Array.NUMERIC ]);
I get the result I was looking for
Thanks
In your case you have to write a costume sorter function. to do that check my example:
Your first data:
var arr:Array = [];
arr.push({cor:4,tem:13});
arr.push({cor:3,tem:12});
arr.push({cor:2,tem:1});
arr.push({cor:3,tem:16});
arr.push({cor:1,tem:11});
The sorting function and sort result for sample one based on tem:
arr.sort(scrollSorter);
function temSorter(a,b):int
{
if(a.tem<b.tem)
return 1 ;//To pass a forward
else(a.tem>b.tem)
return -1;//To pass a backward
return 0;//a and b are same.
}
And the result is:
The result is this:
[
{
"cor": 3,
"tem": 16
},
{
"cor": 4,
"tem": 13
},
{
"cor": 3,
"tem": 12
},
{
"cor": 1,
"tem": 11
},
{
"cor": 2,
"tem": 1
}
]
Now the sample based on something close you need:
arr.sort(scrollSorter);
function userScoreCalculator(a):Number
{
return a.cor/a.tem;
}
function winnerSorter(a,b):int
{
var aScore:Number = userScoreCalculator(a);
var bScore:Number = userScoreCalculator(b);
if(aScore<bScore)
return 1 ;
else(aScore>bScore)
return -1
return 0
}
And the result is:
[
{
"cor": 2,
"tem": 1
},
{
"cor": 4,
"tem": 13
},
{
"cor": 3,
"tem": 12
},
{
"cor": 3,
"tem": 16
},
{
"cor": 1,
"tem": 11
}
]
Than means the person with score of 2 is winner because he made it in only 1 second. but other players are close to gather in tem parameter, so the next winner is the person with highest score. it comes from the userScoreCalculator() output. the higher output of that function is the winner.
Now take your time and change the userScoreCalculator() function to show the winner.
https://help.adobe.com/en_US/ActionScript/3.0_ProgrammingAS3/WS5b3ccc516d4fbf351e63e3d118a9b90204-7fa4.html
I'm stuck on creating an algorithm as follows. I know this shouldn't be too difficult, but I simply can't get my head around it, and can't find the right description of this kind of pattern.
Basically I need a multi-level counter, where when a combination exist in the database, the next value is tried by incrementing from the right.
1 1 1 - Start position. Does this exist in database? YES -> Extract this and go to next
1 1 2 - Does this exist in database? YES -> Extract this and go to next
1 1 3 - Does this exist in database? YES -> Extract this and go to next
1 1 4 - Does this exist in database? NO -> Reset level 1, move to level 2
1 2 1 - Does this exist in database? YES -> Extract this and go to next
1 2 2 - Does this exist in database? NO -> Reset level 2 and 1, move to level 3
2 1 1 - Does this exist in database? YES -> Extract this and go to next
2 1 2 - Does this exist in database? YES -> Extract this and go to next
2 1 3 - Does this exist in database? NO -> Reset level 1 and increment level 2
2 2 1 - Does this exist in database? YES -> Extract this and go to next
2 2 2 - Does this exist in database? YES -> Extract this and go to next
2 2 3 - Does this exist in database? YES -> Extract this and go to next
2 3 1 - Does this exist in database? NO -> Extract this and go to next
3 1 1 - Does this exist in database? NO -> Extract this and go to next
3 2 1 - Does this exist in database? NO -> End, as all increments tried
There could be more than three levels, though.
In practice, each value like 1, 2, etc is actually a $value1, $value2, etc. containing a runtime string being matched against an XML document. So it's not just a case of pulling out every combination already existing in the database.
Assuming, the length of the DB key is known upfront, here's one way how it can be implemented. I'm using TypeScript but similar code can be written in your favorite language.
First, I declare some type definitions for convenience.
export type Digits = number[];
export type DbRecord = number;
Then I initialize fakeDb object which works as a mock data source. The function I wrote will work against this object. This object's keys are representing the the database records' keys (of type string). The values are simple numbers (intentionally sequential); they represent the database records themselves.
export const fakeDb: { [ dbRecordKey: string ]: DbRecord } = {
'111': 1,
'112': 2,
'113': 3,
'211': 4,
'212': 5,
'221': 6,
'311': 7,
};
Next, you can see the fun part, which is the function that uses counterDigits array of "digits" to increment depending on whether the record presence or absence.
Please, do NOT think this is the production-ready code! A) there are unnecessary console.log() invocations which only exist for demo purposes. B) it's a good idea to not read a whole lot of DbRecords from the database into memory, but rather use yield/return or some kind of buffer or stream.
export function readDbRecordsViaCounter(): DbRecord[] {
const foundDbRecords: DbRecord[] = [];
const counterDigits: Digits = [1, 1, 1];
let currentDigitIndex = counterDigits.length - 1;
do {
console.log(`-------`);
if (recordExistsFor(counterDigits)) {
foundDbRecords.push(extract(counterDigits));
currentDigitIndex = counterDigits.length - 1;
counterDigits[currentDigitIndex] += 1;
} else {
currentDigitIndex--;
for (let priorDigitIndex = currentDigitIndex + 1; priorDigitIndex < counterDigits.length; priorDigitIndex++) {
counterDigits[priorDigitIndex] = 1;
}
if (currentDigitIndex < 0) {
console.log(`------- (no more records expected -- ran out of counter's range)`);
return foundDbRecords;
}
counterDigits[currentDigitIndex] += 1;
}
console.log(`next key to try: ${ getKey(counterDigits) }`);
} while (true);
}
The remainings are some "helper" functions for constructing a string key from a digits array, and accessing the fake database.
export function recordExistsFor(digits: Digits): boolean {
const keyToSearch = getKey(digits);
const result = Object.getOwnPropertyNames(fakeDb).some(key => key === keyToSearch);
console.log(`key=${ keyToSearch } => recordExists=${ result }`);
return result;
}
export function extract(digits: Digits): DbRecord {
const keyToSearch = getKey(digits);
const result = fakeDb[keyToSearch];
console.log(`key=${ keyToSearch } => extractedValue=${ result }`);
return result;
}
export function getKey(digits: Digits): string {
return digits.join('');
}
Now, if you run the function like this:
const dbRecords = readDbRecordsViaCounter();
console.log(`\n\nDb Record List: ${ dbRecords }`);
you should see the following output that tells you about the iteration steps; as well as reports the final result in the very end.
-------
key=111 => recordExists=true
key=111 => extractedValue=1
next key to try: 112
-------
key=112 => recordExists=true
key=112 => extractedValue=2
next key to try: 113
-------
key=113 => recordExists=true
key=113 => extractedValue=3
next key to try: 114
-------
key=114 => recordExists=false
next key to try: 121
-------
key=121 => recordExists=false
next key to try: 211
-------
key=211 => recordExists=true
key=211 => extractedValue=4
next key to try: 212
-------
key=212 => recordExists=true
key=212 => extractedValue=5
next key to try: 213
-------
key=213 => recordExists=false
next key to try: 221
-------
key=221 => recordExists=true
key=221 => extractedValue=6
next key to try: 222
-------
key=222 => recordExists=false
next key to try: 231
-------
key=231 => recordExists=false
next key to try: 311
-------
key=311 => recordExists=true
key=311 => extractedValue=7
next key to try: 312
-------
key=312 => recordExists=false
next key to try: 321
-------
key=321 => recordExists=false
next key to try: 411
-------
key=411 => recordExists=false
------- (no more records expected -- ran out of counter's range)
Db Record List: 1,2,3,4,5,6,7
It is strongly recommended to read the code. If you want me to describe the approach or any specific detail(s) -- let me know. Hope, it helps.
my table is like this and my collection is
$testmodel=Mage::getModel(test/p1)->getCollection();
my database table is below.
id cat_id rate p_id
1 1 4 1
2 1 2 1
3 1 3 2
4 2 5 3
5 2 3 1
and i want output like this in magento using collection
cat_id rate count_category
1 9 3
2 8 2
i found my PROBLEM correct code is below
$testmodel = Mage::getModel('test/p1')
->getCollection()
->addFieldToSelect('rate')
->addFieldToSelect('cat_id');
$testmodel ->getSelect()
->columns('SUM(rate) as total,COUNT(*) AS countCategory')
->group('cat_id');
if you use mysql4 as this model resource class then go to
Model/Mysql4/P1/Collection.php
here you need to add function
public function addGroupByCatId(){
$subSelect = clone $this->getSelect();
$CountsubSelect = clone $this->getSelect();
$subSelect->reset()
->from(array('rev' => 'youtable', 'SUM( rev.rate)')
->where('main_table.cat_id = rev.cat_id');
$CountsubSelect->reset()
->from(array('countrev' => 'youtable'),'COUNT(countrev.cat_id)')
->where('main_table.cat_id = countrev.cat_id');
$this->getSelect()
->join(
array('r' => 'youtable'),
'main_table.id = r.id',
array(
'review_sum' => new Zend_Db_Expr(sprintf('(%s)', $subSelect)),
'count_category' => new Zend_Db_Expr(sprintf('(%s)', $CountsubSelect)),
))
->group('main_table.cat_id');
return $this;
}
OR: Resouce as resource model then goto
if you use mysql4 as this model resource class then go to
Model/Resource/P1/Collection.php
here you need to add function
public function addGroupByCatId(){
$subSelect = clone $this->getSelect();
$CountsubSelect = clone $this->getSelect();
$subSelect->reset()
->from(array('rev' => 'youtable', 'SUM( rev.rate)')
->where('main_table.cat_id = rev.cat_id');
$CountsubSelect->reset()
->from(array('countrev' => 'youtable'),'COUNT(countrev.cat_id)')
->where('main_table.cat_id = countrev.cat_id');
$this->getSelect()
->join(
array('r' => 'youtable'),
'main_table.id = r.id',
array(
'review_sum' => new Zend_Db_Expr(sprintf('(%s)', $subSelect)),
'count_category' => new Zend_Db_Expr(sprintf('(%s)', $CountsubSelect)),
))
->group('main_table.cat_id');
return $this;
}
and final you get
$testmodel=Mage::getModel(test/p1)->getCollection();
$testmodel->addGroupByCatId();