images created with Symfony and Twig sometimes display wrong - image

I have some images created with Symfony, they are generated as:
src="data:image;base64,/9j/4AAQSkZJRg... etc"
data-holder-rendered="true"
With this code in my controller:
$sql = "select id,nombre,descripcion,encode(imagen, 'base64') as imagen from data.servicios_mapa order by destacado DESC, fecha_creacion DESC LIMIT 4" ;
$stmt = $conn->prepare( $sql );
$stmt->execute();
$mapas = $stmt->fetchAll();
$datos_mapa = array();
foreach($mapas as $m){
if($m['imagen'] != '' || $m['imagen'] != null){
$m['imagen'] = "data:image;base64,".$m['imagen'];
}else{
$m['imagen'] = "/imgs/no-image.jpg";
}
$datos_mapa[] = $m;
}
return $this->render('FrontendBundle:Default:index.html.twig', array("estructura"=>json_encode(array()),"datosmapas"=>$datos_mapa) );
Then in Twig:
<img src="{{ mapa.imagen }}" class="img-responsive fix-height">
But some of them are wrongly diplayed, like the left one:
http://fotos.subefotos.com/5909f04a9cfa9be2c4b286d1b87727eco.png
What could be the reasson? they are all generated with the same code.

Inside your loop, the else for the condition if($m['imagen'] != '' || $m['imagen'] != null) is never reached when $m['imagen'] == null or $m['imagen'] == ''
because null != '' gives true, and '' != null gives true
So you will have <img src="data:image;base64," class="img-responsive fix-height">
You should change it to : if($m['imagen'] != '' && $m['imagen'] != null)

Related

ProductsImport Laravel

I want to import both the price.xls and the price.xls file.
$productsArray = Excel::toArray(new ProductsImport(), 'fiyat.xls');
$products = $productsArray[0];
$dbProducts = [];
foreach ($products as $key => $value) {
if ($key > 1 && $value[5] != '' && $value[6] != '' && $value[7] != ''){
$sellPrice = strval($value[3]);
$merchantId = $value[5];
$productId = $value[6];
$priceId = $value[7];
I am writing like this, it doesn't work
$productsArray = Excel::toArray(new ProductsImport(), 'price.xls', 'price1.xls');

Optimize huge query to be eager loaded

I have a huge query that needs to be modified right now it doesn't eager load the withCount, whenever I call propertyimages_count it always return 0 instead of the correct count. But if I call $property->propertyimages()->count() it returns the correct number but it is not eager loading.
I'm not really sure why propertyimages_count, I am thinking maybe it is the alias.
$search = (isset($_GET['sSearch']) ? $_GET['sSearch'] : '');
$get = $this->method_vars($_GET);
$today = date('Y-m-d');
$where = Property::
withCount('propertyimages')
->with(['project', 'latestmaintenance', 'propertyimages'])
->join('projects', 'properties.project_id', '=', 'projects.id')
->where(function( $query ) use ($get) {
if($get['price_from'] >= 1 && $get['price_to'] <= 500000) {
$query->whereBetween('rental_price', [$get['price_from'], $get['price_to'] ]);
}
$query = $get['sqm_from'] >= 1 && $get['sqm_to'] <= 1000 ? $query->whereBetween('sqm', [$get['sqm_from'], $get['sqm_to'] ]) : $query;
if( $get['type'] != '' ) {
if( $get['type'] == 'house' ) {
$query->where('projects.type', 'Housing Project');
} else if( $get['type'] == 'condo' ) {
$query->where('projects.type', 'Condo Project');
} else if( $get['type'] == 'any' ) {
$query->whereIn('projects.type', ['Condo Project', 'Housing Project']);
}
}
$query = $get['view'] != '' ? $query->where('view', $get['view']) : $query;
$query = $get['project'] != '' ? $query->where('project_id', $get['project']) : $query;
$query = $get['bedrooms'] != '' ? $query->where('bedrooms', $get['bedrooms']) : $query;
$query = $get['bathrooms'] != '' ? $query->where('bathrooms', $get['bathrooms']) : $query;
$query = $get['property_status'] != '' ? $query->where('status', $get['property_status']) : $query;
if( $get['status'] != '' ) {
if( $get['status'] == 'rented' ) {
$query->whereRaw('CURDATE() >= check_in')->whereRaw('CURDATE() <= check_out');
} elseif( $get['status'] == 'vacant' ) {
$query->where(function($q) {
$q->whereRaw('CURDATE() NOT BETWEEN check_in AND check_out')->orWhereNull('check_in');
});
}
}
})
->orderBy('projects.name')
->orderBy('unit')
->whereRaw("(SELECT check_in
FROM property_rentals
WHERE property_rentals.property_id = properties.id
ORDER BY
CASE
WHEN check_out >= '{$today}' AND check_in <= '{$today}' THEN 0
WHEN check_in > '{$today}' THEN 1
ELSE 2
END
LIMIT 1) as check_in")
->whereRaw("(SELECT check_out
FROM property_rentals
WHERE property_rentals.property_id = properties.id
ORDER BY
CASE
WHEN check_out >= '{$today}' AND check_in <= '{$today}' THEN 0
WHEN check_in > '{$today}' THEN 1
ELSE 2
END
LIMIT 1) as check_out");
Maybe to add count images relation, something like this:
public function imagesCount()
{
return $this->hasMany('App\ProperyImage')
->selectRaw('property_id, count(*) as count)
->groupBy('property_id');
}
...and then add it to the with clause
Check this

DataTables Asp.Net MVC 4 Process

I have a project which using DataTables. Its working as ajax request. Its completing in 8-12 seconds. I need to optimize this code but i don't know how. String Process is worst part.
public JsonResult PageModel(Models.DataTable.ParamModel model, byte type)
{
DateTime startTime = DateTime.Now;
using (var db = Helper.Context())
{
var allEntries = db.MembershipVacations.Where(i => i.Type == type).ToList();
IEnumerable<DatabaseProcedure.Models.MembershipVacation> list = new List<DatabaseProcedure.Models.MembershipVacation>();
Func<DbModels.MembershipVacation, string> orderingFunction = (c =>
model.iSortCol_0 == 0 ? c.Membership.Username : "");
Func<DbModels.MembershipVacation, DateTime> dateOrderingFunction = (c =>
model.iSortCol_0 == 1 ? c.PostDate :
model.iSortCol_0 == 3 ? c.StartDate :
model.iSortCol_0 == 4 ? c.EndDate : DateTime.MaxValue);
/*Func<DbModels.MembershipVacation, string> orderingFunction = (c => model.iSortCol_0 == 1 ? c.ID.ToString() :
model.iSortCol_0 == 2 ? c.Membership.Username :
c.Description);*/
if (User.IsInRole("Admin"))
{
if (model.sSearch.IsNull())
{
if (model.sSortDir_0 == "asc")
{
list = allEntries
.OrderBy(orderingFunction);
if (model.iSortCol_0 == 1 || model.iSortCol_0 == 3 || model.iSortCol_0 == 4)
{
list = allEntries.OrderBy(dateOrderingFunction);
}
}
else
{
list = allEntries
.OrderByDescending(orderingFunction);
if (model.iSortCol_0 == 1 || model.iSortCol_0 == 3 || model.iSortCol_0 == 4)
{
list = allEntries.OrderByDescending(dateOrderingFunction);
}
}
list = list
.Skip(model.iDisplayStart)
.Take(model.iDisplayLength);
}
else
{
list = allEntries
.Where(i =>
i.Membership != null ? i.Membership.Username.Contains(model.sSearch, StringComparison.OrdinalIgnoreCase) : false
|| i.Membership != null && i.Membership.Department != null ? i.Membership.Department.Name.Contains(model.sSearch, StringComparison.OrdinalIgnoreCase) : false
|| i.StartDate.ToString().Contains(model.sSearch, StringComparison.OrdinalIgnoreCase)
|| i.EndDate.ToString().Contains(model.sSearch, StringComparison.OrdinalIgnoreCase));
if (model.sSortDir_0 == "asc")
{
list = list
.OrderBy(orderingFunction);
if (model.iSortCol_0 == 1 || model.iSortCol_0 == 3 || model.iSortCol_0 == 4)
{
list = list.OrderBy(dateOrderingFunction);
}
}
else
{
list = list
.OrderByDescending(orderingFunction);
if (model.iSortCol_0 == 1 || model.iSortCol_0 == 3 || model.iSortCol_0 == 4)
{
list = list.OrderByDescending(dateOrderingFunction);
}
}
}
}
else
{
var approveList = db.MembershipVacationApproves.ToList();
if (model.sSearch.IsNull())
{
list = approveList
.Where(i => i.MembershipID == UI.Helper.User.ID || i.MembershipVacation.MembershipID == UI.Helper.User.ID)
.Select(i => i.MembershipVacation)
.Distinct()
.Where(i => i.Type == type)
.Skip(model.iDisplayStart)
.Take(model.iDisplayLength);
}
else
{
list = approveList
.Where(i => i.MembershipID == UI.Helper.User.ID || i.MembershipVacation.MembershipID == UI.Helper.User.ID)
.Select(i => i.MembershipVacation)
.Distinct()
.Where(i =>
i.Type == type && (
i.Membership != null ? i.Membership.Username.Contains(model.sSearch, StringComparison.OrdinalIgnoreCase) : false
|| i.Membership.Department != null ? i.Membership.Department.Name.Contains(model.sSearch, StringComparison.OrdinalIgnoreCase) : false
|| i.StartDate.ToString().Contains(model.sSearch, StringComparison.OrdinalIgnoreCase)
|| i.EndDate.ToString().Contains(model.sSearch, StringComparison.OrdinalIgnoreCase)))
.Skip(model.iDisplayStart)
.Take(model.iDisplayLength);
}
}
List<string[]> result = new List<string[]>();
foreach (var item in list)
{
var waiting = item.MembershipVacationApproves.Count(i => i.State == UI.Vacation.ApproveState.Waiting) > 0;
var cancel = item.MembershipVacationApproves.Count(i => i.State == UI.Vacation.ApproveState.Cancel) > 0;
var approve = item.MembershipVacationApproves.Count(i => i.State == UI.Vacation.ApproveState.Approve) == item.MembershipVacationApproves.Count;
var edit = item.Membership.MembershipRelation != null ? item.Membership.MembershipRelation.OwnerID == UI.Helper.User.ID : false;
var canApprove = item.MembershipVacationApproves.Count(i => i.MembershipID == UI.Helper.User.ID) == 1;
StringBuilder name_link = new StringBuilder(),
durumu = new StringBuilder(),
islemler = new StringBuilder();
if (item.Membership.Staff != null)
{
name_link.Append("" + item.Membership.Username + "");
}
else
{
name_link.Append(item.Membership.Username);
}
if (!cancel)
{
if (approve)
{
if (DateTime.Now < item.StartDate)
{
durumu.Append("<small class='btn green-bg'>İstek onayladı.</small>");
}
else
{
if (DateTime.Now > item.EndDate)
{
durumu.Append("<small class='btn green'>Kişi izinden dönmüş.</small>");
}
else
{
durumu.Append("<small class='btn green'>Kişi izinde.</small>");
}
}
}
else
{
durumu.Append("<small class='btn orange'>İstek onaylanması için bekleniyor.</small>");
}
}
else
{
durumu.Append("<small class='btn red'>İstek iptal edilmiş</small>");
}
islemler.Append("<div class='btn-group'>");
islemler.Append("<a class='btn green' href='#' data-toggle='dropdown'><i class='icon-user'></i>İşlemler");
islemler.Append("<i class='icon-angle-down'></i></a>");
islemler.Append("<ul class='dropdown-menu'>");
islemler.Append("<li><a href='" + this.Url.Action("RequestDetail", "Vacation", new { id = item.ID }) + "' data-toggle='modal' data-target='#'><i class='icon-search'>");
islemler.Append("</i>İncele</a></li>");
/*if (User.IsInRole("İzin Onaylama") || edit)
{
islemler += "<li><a href='" + this.Url.Action("Request", "Vacation", new { id = item.ID }) + "'><i class='icon-search'>";
islemler += "</i>Düzenle</a></li>";
}*/
if (!(DateTime.Now > item.StartDate && approve) && canApprove)
{
islemler.Append("<li><i class='icon-ok'></i>Onayla</li>");
islemler.Append("<li><a href=" + this.Url.Action("DeclinePage", "Vacation", new { id = item.ID }) + " data-toggle='modal' data-target='#'><i class='icon-remove'></i>Onaylama</a></li>");
}
islemler.Append("</ul>");
islemler.Append("</div>");
result.Add(
new string[]
{
name_link.ToString(),
item.PostDate.ToString(),
item.Membership.Department != null ? item.Membership.Department.Name : string.Empty,
item.StartDate.ToString(),
item.EndDate.ToString(),
durumu.ToString(),
islemler.ToString()
});
}
var total = (DateTime.Now - startTime);
System.Diagnostics.Debug.WriteLine("total ms " + total.TotalMilliseconds);
return Json(new
{
sEcho = model.sEcho,
iTotalRecords = allEntries.Count(),
iTotalDisplayRecords = allEntries.Count(),
aaData = result
}, JsonRequestBehavior.AllowGet);
}
}
Worst part is last foreach process for make buttons and permissions
I would guess that you have an N+1 SQL query issue in your last foreach loop: you build list then trigger 5 SQL queries for each item in the list.
Advice to diagnose and fix:
Install MiniProfiler and enable database
profiling - then you'll be able to see which SQL queries are being
triggered by the request, and if you have any duplicate queries.
Make use of EntityFramework's Include method, to eager load related data when you're querying the items for list. This will save EF from having to issue separate duplicate queries within your foreach.

losing session in function with codeigniter

So I am using session to hold username and then check if its there. if yes, then use it to update related to current transaction. The following is my code:
public function update_edit()
{
/* echo " //// INSIDE UPDATE EDIT "; */
$this->form_validation->set_rules('fullname', 'الاسم الكامل', 'isset|required|min_length[6]|max_length[100]');
//echo 'Username: ';
//check that there are no form validation errors
if($this->form_validation->run() == FALSE)
{
echo " //// INSIDE FORM VALIDATION";
if(($this->session->userdata('username')!=""))
{
echo " //// INSIDE SESSION VALIDATION";
$data = array();
$session_user = $this->session->userdata('username');
if(isset($session_user) && $session_user != '' && $session_user != null)
{
$data = $this->profileModel->load_user_editable_data($session_user);
$this->load->view('layout/header');
$this->load->view('profile_edit', $data);
$this->load->view('layout/footer');
}else{
$this->error_page();
}
}else{
//$this->load->view('login');
$this->login();
}
}else{
echo "dasdaskhdkjashjdas";
$session_user = $this->session->userdata('username');
echo "Session User: " . $session_user;
if(isset($session_user) && $session_user != '' && $session_user != null)
{
echo "going to update;";
$complete = $this->profileModel->update_profile($session_user);
echo "<br>finished updating...";
if($complete == 1)
{
echo "Complete = " . $complete;
$this->load->view('layout/header');
$this->load->view('update_complete');
$this->load->view('layout/footer');
}elseif($complete == 2){
echo "Complete = " . $complete;
$this->error_page();
}
}
}
}
The problem here is that after echo dasdaskhdkjashjdas, nothing the session check doesn't work. I printed the value and it is empty. How can this be when in the function before it worked well and loaded the data? This function is supposed to check the loaded data changed or not, then submit that new data.
Please help :)
Change this:
if(isset($session_user) && $session_user != '' && $session_user != null)
to this:
if(!empty($session_user))

Codeigniter: Add a class to link if current_url() == href

Do you know of a way how to check if current_url() is equivalent to a link's href without using javascript? In doing so, if the href is the same then add class="active" to the link.
Edit: The first thing which comes to mind is making an array of all href values then using foreach to compare each one but maybe you have a better way than this?
Answer thanks to Nick Pyett:
if(!function_exists('anchor')){
function anchor($uri = '', $title = '', $attributes = '', $apply_active = FALSE){
if(!is_array($uri)){
$site_url = (!preg_match('!^\w+://! i', $uri)) ? site_url($uri) : $uri;
}
else {
$site_url = site_url($uri);
}
$title = (bool)$title ? $title : $site_url;
if($attributes != '') $attributes = _parse_attributes($attributes);
$active = $uri == uri_string() && $apply_active ? ' class="'.$apply_active.'"' : NULL;
return '<a href="'.$site_url.'"'.$attributes.$active.'>'.$title.'</a>';
}
}
You could extend the anchor function in the URL helper like this.
if ( ! function_exists('anchor'))
{
function anchor($uri = '', $title = '', $attributes = '', $apply_active = FALSE)
{
$title = (string) $title;
if ( ! is_array($uri))
{
$site_url = ( ! preg_match('!^\w+://! i', $uri)) ? site_url($uri) : $uri;
}
else
{
$site_url = site_url($uri);
}
if ($title == '')
{
$title = $site_url;
}
if ($attributes != '')
{
$attributes = _parse_attributes($attributes);
}
if ( $uri == uri_string() AND $apply_active )
{
$active = ' class="'.$apply_active.'"';
}
else $active = NULL;
return '<a href="'.$site_url.'"'.$attributes.$active.'>'.$title.'</a>';
}
}
I haven't tested this so check a look for bugs. Call the anchor function like this:
anchor('my_page', 'My Page', '', 'active');
See the docs for how to extend helpers: http://ellislab.com/codeigniter/user_guide/general/helpers.html
Edit: OK I've tested it and updated my answer so it should work well now.

Resources