script score function not working but addDecayFunction is working of FunctionScore query - search

I am using Elastica and going to use \Elastica\Query\FunctionScore(); function score --> script_score. Here addDecayFunction() woking fine but addScriptScoreFunction() not work and not through any exception.
DecyFunction is commented because it is working
Here is code
$scriptString = "doc['geo_location'].distanceInMiles('42.946697', '-76.113623')";
$script = new \Elastica\Script($scriptString);
$query = new \Elastica\Query\FunctionScore();
$query->addScriptScoreFunction($script);
// $locationOrigin = "32.804654, -117.242594";
// $locationScale = '2mi';
// $query->addDecayFunction(\Elastica\Query\FunctionScore::DECAY_GAUSS, 'geo_location', $locationOrigin, $locationScale);
$resultSet = $type->search($query);
$results = $resultSet->getResults();
$totalResults = $resultSet->getTotalHits();
if ( $totalResults > 0 ) {
echo "<b>Total Results Found are:</b> " . $totalResults . "<br>";
foreach ( $results as $result ) {
echo $result->getScore();
$data = $result->getData();
var_dump($data);
}
}

maybe you forget to enable scripts?
script.disable_dynamic: false

Related

Importing images along with other fields (username,subjectname) from excel in laravel

I am using phpspreadsheet. I want to import an excel sheet that have images too, it looks something like this,
I am able to retrieve fields separately and images separately, I want to get them together. Problem I am facing is that Images are being accessed with
$spreadsheet->getActiveSheet()->getDrawingCollection()
and for others field i have to access them like this
$spreadsheet->getRowIterator()
as both of them requires separate loops, should i be merging them into one or what is the right way so that i am able to retrieve both(images and fields) together.
Images retrieve code:
$spreadsheet = IOFactory::load($request->import_file);
$i = 0;
foreach ($spreadsheet->getActiveSheet()->getDrawingCollection() as $key => $drawing) {
if ($drawing instanceof MemoryDrawing) {
ob_start();
call_user_func(
$drawing->getRenderingFunction(),
$drawing->getImageResource()
);
$imageContents = ob_get_contents();
ob_end_clean();
switch ($drawing->getMimeType()) {
case MemoryDrawing::MIMETYPE_PNG :
$extension = 'png';
break;
case MemoryDrawing::MIMETYPE_GIF:
$extension = 'gif';
break;
case MemoryDrawing::MIMETYPE_JPEG :
$extension = 'jpg';
break;
}
} else {
$zipReader = fopen($drawing->getPath(), 'r');
$imageContents = '';
while (!feof($zipReader)) {
$imageContents .= fread($zipReader, 1024);
}
fclose($zipReader);
$extension = $drawing->getExtension();
}
$myFileName = time() .++$i. '.' . $extension;
$imagesCollection['answerImages_'.$key] =$myFileName;
file_put_contents('images/products/' . $myFileName, $imageContents);
$a = Answers::create([
'answerImages'=>$myFileName,
'questionId'=>($key <=4)?1:2,
]);
}
I want to store them into my table in database such that in questionImage column of database it has image name like this
and it is storing it currently but as I mentioned earlier i have to store them separtely
This is how i am storing other fields
$spreadsheet = IOFactory::load($the_file->getRealPath());
$sheet = $spreadsheet->getActiveSheet();
$row_limit = $sheet->getHighestDataRow();
$column_limit = $sheet->getHighestDataColumn();
$row_range = range( 1, $row_limit );
$column_range = range( 'F', $column_limit );
$startcount = 2;
$data = array();
foreach ( $row_range as $row ) {
$data[] = [
'courseName' =>$sheet->getCell( 'A' . $row )->getValue(),
'subjectName' => $sheet->getCell( 'B' . $row )->getValue(),
'question' => $sheet->getCell( 'C' . $row )->getValue(),
'questionImage' => $sheet->getCell( 'D' . $row )->getValue(),
];
$startcount++;
}
DB::table('questions')->insert($data);
How to get them together so that i can store them in one table
you should try maatwebsite/excel package. it will save your time.

Chunk and excel Laravel

guys.
I need help with this code. I need to download an excel with arround 550000 records. So i was wondering how can i use eloquent with chunk, skip and limit and get to make the excel or do something better than this. I started to making some code to save excel in a folder and then download in a zip, but i cant make works chunk and get.
I had problems with time execution and memory limit, but thats no more a problem.
This is my code.
$x=1;
for ($i=0; $i<=550000; $i=$i+15000) {
$personas="";
$personas = DB::table("cat_personas as c")->select("c.*","s.seccion","ca.casilla")
->leftJoin("cat_casillas as ca","c.cat_casilla_id","=","ca.id")
->join("cat_seccion as s","c.cat_seccion_id","=","s.id")
->where($filtros)
->whereRaw("c.id NOT IN ( SELECT cruzado FROM registro_persona )")
->whereRaw($whereCadena)
->orderby('c.consecutivo')
->orderby('c.apellido_paterno')
->orderby('c.apellido_materno')
->orderby('c.nombre')
->orderby('s.seccion')
->orderby('ca.casilla')
->skip($i)->limit(15000);
//$personas=$personas->get();
dd($personas->count());
if($personas->count()>0){
$spreadsheet = new Spreadsheet();
$r=1;
$sheet = $spreadsheet->getActiveSheet()
->setCellValue('A'.$r, '#')
->setCellValue('B'.$r, 'NOMBRE')
->setCellValue('C'.$r, 'APELLIDO PATERNO')
->setCellValue('D'.$r, 'APELLIDO MATERNO')
->setCellValue('E'.$r, 'SECCION')
->setCellValue('F'.$r, 'CASILLA')
->setCellValue('G'.$r, 'CONSECUTIVO');
$r++;
$personas->chunk(5000, function($personas) use (&$spreadsheet,&$r,&$sheet) {
$c=1;
//dd($personas->count());
foreach ($personas as $key) {
$sheet = $spreadsheet->getActiveSheet()
->setCellValue('A'.$r, $c)
->setCellValue('B'.$r, $key->nombre)
->setCellValue('C'.$r, $key->apellido_paterno)
->set`enter code here`CellValue('D'.$r, $key->apellido_materno)
->setCellValue('E'.$r, $key->seccion)
->setCellValue('F'.$r, $key->casilla)
->setCellValue('G'.$r, $key->consecutivo);
$r++;
$c++;
}
});
$writer = new Xlsx($spreadsheet);
//header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
//header('Content-Disposition: attachment; filename="personas.xlsx"');
$writer->save($path."/personas$x.xlsx");
$x++;
}
}
You can use chunk() this way.
$personas = DB::table("cat_personas as c")->select("c.*","s.seccion","ca.casilla")
->leftJoin("cat_casillas as ca","c.cat_casilla_id","=","ca.id")
->join("cat_seccion as s","c.cat_seccion_id","=","s.id")
->where($filtros)
->whereRaw("c.id NOT IN ( SELECT cruzado FROM registro_persona )")
->whereRaw($whereCadena)
->orderby('c.consecutivo')
->orderby('c.apellido_paterno')
->orderby('c.apellido_materno')
->orderby('c.nombre')
->orderby('s.seccion')
->orderby('ca.casilla');
$spreadsheet = new Spreadsheet();
$r = 1;
$sheet = $spreadsheet->getActiveSheet()
->setCellValue('A'.$r, '#')
->setCellValue('B'.$r, 'NOMBRE')
->setCellValue('C'.$r, 'APELLIDO PATERNO')
->setCellValue('D'.$r, 'APELLIDO MATERNO')
->setCellValue('E'.$r, 'SECCION')
->setCellValue('F'.$r, 'CASILLA')
->setCellValue('G'.$r, 'CONSECUTIVO');
$r++;
$c = 1;
$personas->chunk(500, function($personae) use ($spreadsheet, $r, $c) {
foreach ($personae as $persona) {
$spreadsheet->getActiveSheet()
->setCellValue('A'.$r, $c)
->setCellValue('B'.$r, $persona->nombre)
->setCellValue('C'.$r, $persona->apellido_paterno)
->setCellValue('D'.$r, $persona->apellido_materno)
->setCellValue('E'.$r, $persona->seccion)
->setCellValue('F'.$r, $persona->casilla)
->setCellValue('G'.$r, $persona->consecutivo);
$r++;
$c++;
}
});
$writer = new Xlsx($spreadsheet);
$writer->save($path . "/personas.xlsx");
There might be an issue with the total size of the spreadsheet, but if so, this should be a good start towards finding that solution.
PS - This is untested.

Netsuite itemFulfillment search where status = picked

I'm trying to export Netsuite ItemFulfillment Records into a local database so I can import into UPS Worldship to send them. I'm able to export recently modified records, but can't figure out how to filter on the shipStatus. Can anyone help lead me in the correct direction?
What I have that exports recently modified records, but does not filter correctly on shipStatus:
require_once '/PHPToolkit/NetSuiteService.php';
$start_time = microtime(true);
$service = new NetSuiteService();
$transactionSearchBasic = new TransactionSearchBasic();
// type = itemFulfillment
$searchMultiSelectEnumField = new SearchEnumMultiSelectField();
$searchMultiSelectEnumField->operator = 'anyOf';
$searchMultiSelectEnumField->searchValue[] = '_itemFulfillment';
$transactionSearchBasic->type = $searchMultiSelectEnumField;
// lastmodified > datelastrun
$SearchDateField = new SearchDateField();
$SearchDateField->operator = "after";
$SearchDateField->searchValue = "2019-12-01T00:00:00";
$transactionSearchBasic->lastModifiedDate = $SearchDateField;
// shipStatus = picked
$SearchStringField = new SearchStringField();
$SearchStringField->operator = 'is';
$SearchStringField->searchValue = '_picked';
$transactionSearchBasic->shipStatus = $SearchStringField;
$transactionSearch = new TransactionSearch();
$transactionSearch->basic = $transactionSearchBasic;
$request = new SearchRequest();
$request->searchRecord = $transactionSearch;
$searchResponse = $service->search($request);
if (!$searchResponse->searchResult->status->isSuccess) {
echo "SEARCH ERROR";
} else {
echo "SEARCH SUCCESS, records found: " . $searchResponse->searchResult->totalRecords . PHP_EOL;
}
$end_time = microtime(true);
$execution_time = ($end_time - $start_time);
echo " Execution time of script = ".$execution_time." sec";
Not sure why _picked is not working.
Can you try using internal id of these status values.
Internal Id Text
A Picked
B Packed
C Shipped
Instead of '_picked' try using 'A'.

PHP variables not showing up. GETid not working properly

I have all the login scripts and profiles set up. I have a data table where all the profile information is stored called plus_signup but I can't seem to get this GET[id] thing to work. Am I missing something? Here's what I have.
When I view the page with the code I have now, there are blank areas where PHP is supposed to fill in the variables.
session_start();
include "include/z_db.php";
if ($_GET['id']){
$id = $_GET['id'];
} else if (isset($_SESSION['id'])) {
$id = $_SESSION['id'];
}
else {
print "important data to render this page is missing";
exit();
$sql = mysql_query("SELECT * FROM plus_signup WHERE id='$userid'");
while($row = mysql_fetch_array($sql)){
$userid = $row["userid"];
$name = $row["name"];
$location = $row["location"];
$sex = $row["sex"];
$aboutme = $row["aboutme"];
}
$check_pic = "users/$id/image01.jpg";
$default_pic = "users/0/image01.jpg";
if (file_exists($check_pic)){
$user_pic = "<img src=\"$check_pic\" width=\"175px\"/>";
} else {
$user_pic = "<img src=\"$default_pic\"/>";
}}
I know it's a little late and that you may have already figured out the answer to this question, but I was having the same issue and just figured it out.
Your SQL query is calling on a variable that has not been defined.
session_start();
include "include/z_db.php";
if ($_GET['id']){
$id = $_GET['id'];
} else if (isset($_SESSION['id'])) {
$id = $_SESSION['id'];
}
else {
print "important data to render this page is missing";
exit();
$sql = mysql_query("SELECT * FROM plus_signup WHERE id='$userid'");
while($row = mysql_fetch_array($sql)){
$userid = $row["userid"];
$name = $row["name"];
$location = $row["location"];
$sex = $row["sex"];
$aboutme = $row["aboutme"];
}
$check_pic = "users/$id/image01.jpg";
$default_pic = "users/0/image01.jpg";
if (file_exists($check_pic)){
$user_pic = "<img src=\"$check_pic\" width=\"175px\"/>";
} else {
$user_pic = "<img src=\"$default_pic\"/>";
}}
You are getting the 'id' from the url and storing it as $id. When you call your query, you are having it search for where ID = $userid when you really should be having it search for ID = $id.
Make sure that your variables are the same throughout!
^Hope that helps some people avoid an hour or two of frustration when trying to figure out why their function isn't working!

How to link custom results in Drupal

My first time here an a newbee in Drupal and programming .
So I have a problem I need to some help with.
function query_results($searchstring, $datefrom) {
$tidresult = db_query("SELECT tid FROM {term_data} WHERE LOWER(name) = '%s'", strtolower($searchstring));
$resultarray = array();
while ($obj = db_fetch_object($tidresult)) {
$tid = $obj->tid;
$noderesults = db_query("SELECT n.nid, n.title FROM {node} n
INNER JOIN {term_node} tn ON tn.nid = n.nid
WHERE tn.tid='%s'", $tid);
while ($nodeobj = db_fetch_object($noderesults)) {
$resultarray[$nodeobj->nid] = $nodeobj->title;
}
}
$header = array(
array('data' => 'Nr.'),
array('data' => 'Name'),
);
$rows = array();
$i = 0;
foreach($resultarray as $nid => $title) {
$i++;
$rows[] = array('data' =>
array(
$i,
$title,
),
);
}
$output = theme('table', $header, $rows);
print theme("page", $output);
}
It's driving me crazy , i dint put all of the search code but it takes taxonomy tags from the database ( you type in textbox that has autocomplete, '$searchstring' ) and date ( you choose a time line like one day , yesterday ect. , '$datefrom').
For example reasons lets say it looks like this example when you click search.
I can't post my one pictures but I just gives me the titles ( like above but the are not listed) that I cannot click to lead me to the content.
But I wont it to look like result that is like content ( story ) so you have a clickable Title and some description , like this click to see example
where it says lorem ipsum and that text belowe.
If it is hard to make like in the picture can someone show me just how to make( like in the first picture) the results that are non clickable titles into clickable links that lead me to the content.
To get linked titles you need to use the l() function.
looking at the code you provided, I am not entirely sure how you are getting any results since you save the titles in $resultArray but use $rows when rendering the table.
Unless, $rows is specified somewhere else, $resultarray[$nodeobj->nid] = $nodeobj->title; should become $rows[$nodeobj->nid] = $nodeobj->title;
To make it match your table header, you need to add another 'cell' for the number column
$rows[$nodeobj->nid] = array(
$count++,
l($nodeobj->title, 'node/'.$nodeobj->nid)
);
To provide the excerpt too, you need to join the node_revisions table and get either the body or teaser column, then add it to your rows like this:
$rows[$nodeobj->nid] = array(
$count++,
'<h2>'. l($nodeobj->title, 'node/'.$nodeobj->nid) .'</h2>'. $nodeobj->teaser
);
assuming you get the teaser.
EDIT
the previous answer still holds. You can also simplify the code a bit by processing $rows straight in the $noderesults loop.
function query_results($searchstring, $datefrom) {
$tidresult = db_query("SELECT tid FROM {term_data} WHERE LOWER(name) = '%s'", strtolower($searchstring));
$rows = array();
$count = 0;
while ($obj = db_fetch_object($tidresult)) {
$tid = $obj->tid;
$noderesults = db_query("SELECT n.nid, n.title FROM {node} n "
."INNER JOIN {term_node} tn ON tn.nid = n.nid "
."WHERE tn.tid='%s'", $tid);
while ($nodeobj = db_fetch_object($noderesults)) {
$rows[] = array(
++$count,
l($nodeobj->title, 'node/'. $nodeobj->title)
);
}
}
$header = array(
array('data' => 'Nr.'),
array('data' => 'Name'),
);
$output = theme('table', $header, $rows);
print theme("page", $output);
}
-OR-
move it all in one query (note: I did not get a chance to test this, but I usually get it right the first time):
function query_results($searchstring, $datefrom) {
$rows = array();
$count = 0;
$results = db_query("SELECT n.nid, n.title
FROM {node} n
INNER JOIN {term_node} tn ON tn.nid = n.nid
WHERE tn.tid IN (SELECT tid FROM {term_data} WHERE LOWER(name) = '%s')", strtolower($searchstring));
while ($nodeobj = db_fetch_object($results)) {
$rows[] = array(
++$count,
l($nodeobj->title, 'node/'. $nodeobj->title)
);
}
$header = array(
array('data' => 'Nr.'),
array('data' => 'Name'),
);
$output = theme('table', $header, $rows);
print theme("page", $output);
}

Resources