ob_get_contents doesnt work when within foreach - foreach

Hi,
I have this code which works just fine
function show_aval($place) {
echo $place;
}
ob_start();
show_aval(london);
$show_aval = ob_get_contents();
ob_clean();
ob_start();
show_aval(york);
$show_aval2 = ob_get_contents();
ob_clean();
ob_start();
show_aval(liverpool);
$show_aval3 = ob_get_contents();
ob_clean();
but I want to simplify this code like this:
$avalrooms = [];
$cities = ["london", "york", "liverpool"];
foreach ($cities as $city) {
ob_start();
show_aval($city);
$avalrooms[$city] = ob_get_contents();
ob_clean;
}
however, this seems to nullify ob_get_contents because the function is being executed right away as show_aval($city); is stated.
Why is this happening?
Thank you.

Related

"CS0162: Warning as Error: Unreachable code detected" on Razor View

I have the following code within a script tag on my razor view:
self.regions = [];
#foreach(var region in Model.OperationRegions)
{
<text>
self.regions.push({
regionid: '#region.Region_Id',
regionname: '#region.Title',
selected: ko.observable(#(Model.RegionsList.Contains(region.Region_Id).ToString().ToLower()))
});
</text>
}
self.categories = [];
#foreach(var category in Model.Categories)
{
<text>
self.categories.push({
categoryid: '#category.Category_Id',
title: '#category.Title'
});
</text>
}
For clarity, the code outside of the foreach loops and within the text tags are Javascript and the purpose of the razor code is to populate my Javascript arrays with data from the server.
When I run this I am currently getting a server error saying "CS0162: Warning as Error: Unreachable code detected"
The error is thrown on the second "foreach" in the snippet.
Surprisingly I couldn't find another question referring to this error message on an MVC razor page so I'm posting this here.
My question is why is that line of code considered to be unreachable? I will update this question if I find anything else on my page to be relevant to the issue as I try to debug.
The error has disappeared now. I had renamed a property of my model and not recompiled before trying to load the page again. Recompiling made the error go away. I have no idea how the root cause translated to the error message shown but its fixed now in any case.
This is an extremely poor way to handle this. There's no need to build an array piece by piece like this. Just convert your list to JSON.
self.regions = #Html.Raw(Json.Encode(Model.OperationRegions.Select(region => new {
regionid = region.Region_Id,
regionname = region.Title,
selected = Model.RegionsList.Contains(region.Region_Id)
})));
The only thing this can't handle is making selected an observable. However, you can simply loop through the array and fix this:
for (var i = 0; i < self.regions.length; i++) {
self.regions[i].selected = ko.observable(self.regions[i].selected);
}
However, the better approach is to use another view model:
var OperationRegionViewModel = function (data) {
var self = {};
self.regionid = ko.observable(data.regionid);
self.regionname = ko.observable(data.regionname);
self.selected = ko.observable(data.selected);
return self;
};
Then, you can just do something like:
var regions = #Html.Raw(Json.Encode(Model.OperationRegions.Select(region => new {
regionid = region.Region_Id,
regionname = region.Title,
selected = Model.RegionsList.Contains(region.Region_Id)
})));
self.regions = $.map(regions, new OperationRegionViewModel);
Or, even better build your JSON all at once:
var json = #Html.Raw(Json.Encode(new {
regions = Model.OperationRegions.Select(r => new { ... }),
categories = Model.Categories.Select(c => new { ... }),
// etc
});
Then, inject this all into your view model:
var viewModel = (function (json) {
// other stuff
self.regions = $.map(json.regions, new OperationRegionViewModel);
self.categories = $.map(json.categories, new CategoryViewModel);
// etc
})(json);

Dart .onMouseOver

DivElement collectWoodHover = querySelector("#collectWood");
if (collectWoodHover.onMouseOver == true) {
querySelector("#collectWoodHover").style.display = "block";
} else {
querySelector("#collectWoodHover").style.display = "none";
}
Hello!
I was flicking through some of the stuff in the auto complete thing in Dart and found .onMouseOver.
I wonder if I am using it correctly because it doesn't seem to work. The div element is always hidden.
Thanks for your help in advance.
Try something like:
collectWoodHover.onMouseOver.listen( (event) {
print('onMouseOver!');
} );
onMouseOver is a stream. You can find more information how to use streams in Dart here.
onMouseOver is an event stream.
You use it like:
DivElement collectWoodHover = querySelector("#collectWood");
collectWoodHover.onMouseOver.listen((e) =>
e.target.style.display = "block";
}
collectWoodHover.onMouseOut.listen((e) =>
e.target.style.display = "none";
}
I have not actually tried this code. But you should get the idea.
I think you are not selecting the div correctly.
Try:
querySelector(collectWoodHover).style.display = "block";
Because it's a var as in sample, or:
querySelector("#onHover").style.display = "block";
if the div id is 'onHover' that should work

How to correctly use oembed to pull thumbs from youtube

I show a lot of thumbs on my homepage from youtube videos. I was using this function below to grab the thumb from a youtube url which works fast but it doesn't work for url's in the shortned form like youtu.be/JSHDLSKL.
function get_youtube_screen_link( $url = '', $type = 'default', $echo = true ) {
if( empty( $url ) )
return false;
if( !isset( $type ) )
$type = '';
$url = esc_url( $url );
preg_match("|[\\?&]v=([^&#]*)|",$url,$vid_id);
if( !isset( $vid_id[1] ) )
return false;
$img_server_num = 'i'. rand(1,4);
switch( $type ) {
case 'large':
$img_link = "http://{$img_server_num}.ytimg.com/vi/{$vid_id[1]}/0.jpg";
break;
case 'first':
// Thumbnail of the first frame
$img_link = "http://{$img_server_num}.ytimg.com/vi/{$vid_id[1]}/1.jpg";
break;
case 'small':
// Thumbnail of a later frame(i'm not sure how they determine this)
$img_link = "http://{$img_server_num}.ytimg.com/vi/{$vid_id[1]}/2.jpg";
break;
case 'default':
case '':
default:
$img_link = "http://{$img_server_num}.ytimg.com/vi/{$vid_id[1]}/default.jpg";
break;
}
if( $echo )
echo $img_link;
else
return $img_link;
}
So I tried to use Oembed to get the thumbs instead which works for all variations of the youtube url but it retrieves the 480px/360px thumb which causes a lot of cropping to get it down to the 120px/90px size I use to display them. The other issue was it caused my page speed to increase by 4 seconds which Im guessing is a problem with the way I'm implementing it. Here's how I call the thumb inside a loop.
<?php
require_once(ABSPATH.'wp-includes/class-oembed.php');
$oembed= new WP_oEmbed;
$name = get_post_meta($post->ID,'video_code',true);
$url = $name;
//As noted in the comments below, you can auto-detect the video provider with the following
$provider = $oembed->discover($name);
//$provider = 'http://www.youtube.com/oembed';
$video = $oembed->fetch($provider, $url, array('width' => 300, 'height' => 175));
$thumb = $video->thumbnail_url; if ($thumb) { ?>
<img src="<?php echo $thumb; ?>" width="120px" height="90px" />
<?php } ?>
So how should I be doing this to maximize efficiency?
I came across this page from youtube explaining their oembed support, They mentioned that they output to json format so I made a function that gets the json data and then enables you to use it.
Feel free to ask if you need more help.
<?php
$youtube_url = 'http://youtu.be/oHg5SJYRHA0'; // url to youtube video
function getJson($youtube_url){
$baseurl = 'http://www.youtube.com/oembed?url='; // youtube oembed base url
$url = $baseurl . $youtube_url . '&format=json'; // combines the url with format json
$json = json_decode(file_get_contents($url)); // gets url and decodes the json
return $json;
}
$json = getJson($youtube_url);
// from this point on you have all your data placed in variables.
$provider_url = $json->{'provider_url'};
$thumbnail_url = $json->{'thumbnail_url'};
$title = $json->{'title'};
$html = $json->{'html'};
$author_name = $json->{'author_name'};
$height = $json->{'height'};
$thumbnail_width = $json->{'thumbnail_width'};
$thumbnail_height = $json->{'thumbnail_height'};
$width = $json->{'width'};
$version = $json->{'version'};
$author_url = $json->{'author_url'};
$provider_name = $json->{'provider_name'};
$type = $json->{'type'};
echo '<img src="'.$thumbnail_url.'" />'; // echo'ing out the thumbnail image
Ok I came up with a solution from pieces of other questions. First we need to get the id from any type of url youtube has using this function.
function getVideoId($url)
{
$parsedUrl = parse_url($url);
if ($parsedUrl === false)
return false;
if (!empty($parsedUrl['query']))
{
$query = array();
parse_str($parsedUrl['query'], $query);
if (!empty($query['v']))
return $query['v'];
}
if (strtolower($parsedUrl['host']) == 'youtu.be')
return trim($parsedUrl['path'], '/');
return false;
}
Now we can get use YouTube Data API to get the thumbnail from the video id. Looks like this.
<?php
$vid_id = getVideoId($video_code);
$json = json_decode(file_get_contents("http://gdata.youtube.com/feeds/api/videos/$vid_id?v=2&alt=jsonc"));
echo '<img src="' . $json->data->thumbnail->sqDefault . '" width="176" height="126">';
?>
The problem is that is causing an extra 2 seconds load time so I simply use the $vid_id and place it inside http://i3.ytimg.com/vi/<?php echo $vid_id; ?>/default.jpg which gets rid of the 2 seconds added by accessing the youtube api.

ActionScript retrieval from PHP and returns null value

I am trying to retrieve data from database through php scripts and display in flash using actionscript 3.
For actionscript 3, I have 2 functions:
private var postArrayTxt:Array;
public function stampTwo() {
// constructor code
var stampNumber1:MovieClip = new stamp1();
var stampNumber2:MovieClip = new stamp2();
var stampNumber3:MovieClip = new stamp3();
postArrayTxt = new Array();
postArrayTxt[0] = stampNumber1;
postArrayTxt[1] = stampNumber2;
postArrayTxt[2] = stampNumber3;
trace("All stamps works");
retrieveDetailsFromDB();
}
The data retrieved from database will be displayed in the various movieclips where it will be calling retrieveDetailsFromDB().
public function retrieveDetailsFromDB():void {
var myLoader:URLLoader = new URLLoader();
myLoader.dataFormat = URLLoaderDataFormat.VARIABLES;
myLoader.load(new URLRequest("http://localhost/Converse/stampGalore/tryout.php"));
myLoader.addEventListener(Event.COMPLETE, onDataLoad);
// Error Handling
myLoader.addEventListener(IOErrorEvent.IO_ERROR, onIOError);
myLoader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, onSecurityError);
// Could be an error or just a message
myLoader.addEventListener(HTTPStatusEvent.HTTP_STATUS, onHTTPStatus);
function onDataLoad(evt:Event): void {
//var loader:Loader = new Loader();
//stamp221.addChild(loader);
//loader.load(new URLRequest(evt.target.data.facebookRemarks));
var delimiter:String = "|^_^|";
var stamp:String = evt.target.data.databaseRemarks;
trace(stamp);
var stampRemarkArr:Array = new Array();
stampRemarkArr = stamp.split(delimiter);
for (var i:Number=0; i<stampRemarkArr.length; i++) {
postArrayTxt[i].text = String(stampRemarkArr[i]);
trace("ended");
}
}
// error callbacks
function onIOError(evt:IOErrorEvent) {
trace("IOError: " + evt.text);
}
function onHTTPStatus(evt:HTTPStatusEvent) {
trace("HTTPStatus: " + evt.status);
}
function onSecurityError(evt:SecurityErrorEvent) {
trace("SecurityError: " + evt.text);
}
}
Last but not least, this is my php script.
<?php
header("Cache-Control: no-cache, must-revalidate");
header("Expires: Sat, 26 Jul 1997 05:00:00 GMT");
include_once "mysqli.connect.php";
$sql = "SELECT remarks FROM stamp";
$result = $mysqli->query($sql);
if ($mysqli->errno)
{
error_log($mysqli->error);
return;
}
$facebook = "";
$counter = 0;
while ($row = $result->fetch_array())
{
$database = $row["remarks"];
$delimiter = "|^_^|";
if ($counter == 0) {
$facebook .=$database;
} else {
//Use a delimiter "|^_^|" to seperate the records
$facebook .= $delimiter . $database;
}
$counter++;
}
$mysqli->close();
echo "databaseRemarks=" . $facebook;
?>
if I were to run the php script itself, the data could be retrieved from database. However, if I run in Flash, it returns a null value. Please help me as I have wasted a lot of time on this retrieve function. Thank you
This won't work:
var stamp:String = evt.target.data.databaseRemarks;
Flash doesn't know in which format is your data so you need to parse it first. So first read the data:
var rawData:String = evt.currentTarget.data;
Then parse it:
var parsedData:* = someFunctionToParseYourData(rawData);

Changing the color of a selected link that is embedded in a table

I'm trying to use class names to change the color of a link after it has been selected, so that It will remain the new color, but only until another link is selected, and then it will change back.
I'm using this code that was posted by Martin Kool in this question:
<html>
<head>
<script>
document.onclick = function(evt) {
var el = window.event? event.srcElement : evt.target;
if (el && el.className == "unselected") {
el.className = "selected";
var siblings = el.parentNode.childNodes;
for (var i = 0, l = siblings.length; i < l; i++) {
var sib = siblings[i];
if (sib != el && sib.className == "selected")
sib.className = "unselected";
}
}
}
</script>
<style>
.selected { background: #f00; }
</style>
</head>
<body>
One
Two
Three
</body>
It works fine until I try to out the links in a table. Why is this? Be easy, I'm a beginner.
There is no error, the links are changing to the "selected" class, but when another link is selected, the old links are keeping the "selected" class instead of changing to "unselected". Basically, as far as I can tell, it's functioning like a vlink attribute, which is not what I'm going for.
And yes, the links are all in different cells, how would you suggest I change the code so that it works correctly?
OK, actually, I spoke too soon.
document.onclick = function(evt)
{
var el = window.event? event.srcElement : evt.target;
if (el && el.className == 'unselected')
{
var links = document.getElementsByTagName('a');
for (var i = links.length - 1; i >= 0; i--)
{
if (links[i].className == 'selected')
links[i].className = 'unselected';
}
el.className = 'selected';
}
return false;
}
This code you gave me works great, visually, it does exactly what I want it to do. However, It makes my links stop working... They change color, but dont link to anything, and then when I remove the script, they work fine. What am I doing wrong/what do I have to change to make this work?
Also, I want to do the same thing somewhere else in my website, where the links are all in one <div> tag, separated by <p> tags. How can I make this work?
You're looping through the siblings. If the links are in separate <td>'s then they're no longer siblings.
You can loop through all the links like this:
document.onclick = function(evt)
{
var el = window.event? event.srcElement : evt.target;
if (el && el.className == 'unselected')
{
var links = document.getElementsByTagName('a');
for (var i = links.length - 1; i >= 0; i--)
{
if (links[i].className == 'selected')
links[i].className = 'unselected';
}
el.className = 'selected';
}
return false;
}
I've also added a return false; at the end of the function to stop you going to '#'
Is there an error or is there just nothing happening? A good first step if you are a javascript beginner is to use a tool like Firebug so you see detailed error messages, and you can add in console.log statements to see what's going on while you run your code.
By ‘in tables’ do you mean putting each link in its own cell? Because that would make this line:
var siblings = el.parentNode.childNodes;
fail to select other links outside of the cell. You'd have to find another way to signal which element is the link container.

Resources