samedi 28 février 2015

How do I connect a sql server to my Javascript game?


I'm working on a project and I just need a holistic overview on how to go about it.


I'm going to use HTML/CSS canvas to make the game.


However, the game involves visualization of large amounts of data that is best served in a database. What I do not know how to do is: 1) Link my HTML/CSS game to a SQL database 2) Parse a text file to populate the database.


I don't have specific issues I just don't even know where to start? Some people have said AJAX? Others have said parse.com?





Google charts changing of a selected bar


I need to change the color of a selected bar after the chart has been loaded. The selected bar changes each time so I can't just specify in the style.



$(function() {
google.load('visualization', '1', { 'callback': drawChart, 'packages':['corechart'] });

function drawChart() {
var data = google.visualization.arrayToDataTable([
["Element", "Density", { role: "style" } ],
["Copper", 8.94, "#b87333"],
["Silver", 10.49, "silver"],
["Gold", 19.30, "gold"],
["Platinum", 21.45, "color: #e5e4e2"]
]);

var view = new google.visualization.DataView(data);
view.setColumns([0, 1,
{ calc: "stringify",
sourceColumn: 1,
type: "string",
role: "annotation" },
2]);

var options = {
title: "Density of Precious Metals, in g/cm^3",
width: 600,
height: 400,
bar: {groupWidth: "95%"},
legend: { position: "none" },
};
var chart = new google.visualization.ColumnChart(document.getElementById("columnchart_values"));
chart.draw(view, options);


}


})


I understand I can select a bar using:


var selectedItem = chart.getSelection()[0];


How would I change the color of "selectedItem" from here. Picture of chart if you are curious





javascript making a jquery countdown work with UTC times


I am using this jquery countdown:


http://ift.tt/1AVC432


I initialize it like this:



<div id="clock"></div>
<script type="text/javascript">
$('#clock').countdown('2015/03/27 00:00:00')
.on('update.countdown', function(event) {
var format = '%H:%M:%S';
if(event.offset.days > 0) {
format = '%-D day%!d ' + format;
}
$(this).html(event.strftime(format));
})
.on('finish.countdown', function(event) {
$(this).html('FINISHED!');
});
</script>


The target time I use is in UTC but it will only work if people enter the site in UTC. I need to make it work in all the timezones, I mean, wherever the user is from it always has to see the same time left...


How can this be done?





Object prototypes and Inheritance



// the original Animal class and sayName method
function Animal(name, numLegs) {
this.name = name;
this.numLegs = numLegs;
}
Animal.prototype.sayName = function() {
console.log("Hi my name is " + this.name);
};

// define a Penguin class
function Penguin() {
this.name = "penguin";
this.numLegs = 2;
}

// set its prototype to be a new instance of Animal
var penguin = new Animal("Penguin", 2);

penguin.sayName();


The compiler asks me to "Create a new Penguin instance called penguin"...


not sure what I'm doing wrong here





how to update the mouseposition on screen event on window resize?


What i need is to update the trackball controls to detect the mouse position event to a different screen size. I have an on click event which shows the position clicked point on screen with a yellow mark. If i refresh and try this event everything works fine, the event.x and event.y coordinates are correct referring at the window.innerWidth - window.innerHeight. When i resize the window the mark has an offset similar with the distortion of the resizing. If i resize the width only the mark has an offset at the axe(x). everything works using trackball controls. I am aware of the handleResize() function but it does not solved my problem.





How do i make music play when image is clicked?


I have a image that changes the background of the page already but i would also like it to play music when i click the image. Can anyone help? Here's My code


HTML:



<div id="background">
<div id="box">
<div class="button">
<img src="alien.png" type="button" id="my-button">
<br>
<p>Click The Alien!</p>
</div>
</div>


JavaScript:



<script>
var myData = {

1: {
imageUrl: "8.gif",

},

};

function changeImage() {
var randomNumber = Math.floor((Math.random() * 1) + 1);
document.getElementById("background").style.background = "url('" + myData[randomNumber].imageUrl + "')";
document.getElementById("text-box").innerHTML = myData[randomNumber].text;
}
document.getElementById("my-button").addEventListener("click", changeImage);




Using a jQuery Selector With a Variable


Is there any way to make something like the following code?



var input = ("$(\"#div .input[id='" + id + "']\")");
input.fadeIn();


Or maybe I could use something like the following?



var input = ("\"#div .input[id='" + id + "']\"");
$(input).fadeIn();


PS: Take my apologies as this question was cloned but the answers that I found were too ambiguous.





Google script get data from forum


How to get data from forum url. I need to copy post count. I think i managed somehow to make the script but i dont know how to connect it with google spreadsheet.


It should go account by account in column B till last and update the column A with count.


The script doesn't report me any errors with this code



function msg(message){
Browser.msgBox(message);
}

function onOpen() {
var ui = SpreadsheetApp.getUi();
ui.createMenu("Update")
.addItem('Update Table', 'updatePosts')
.addToUi();
}

function getPostCount(profileUrl){
var html = UrlFetchApp.fetch(profileUrl).getContentText();
var sliced = html.slice(0,html.search('Posts Per Day'));
sliced = sliced.slice(sliced.search('<dt>Total Posts</dt>'),sliced.length);
postCount = sliced.slice(sliced.search("<dd> ")+"<dd> ".length,sliced.search("</dd>"));

return postCount;
}

function updatePosts(){

if(arguments[0]===false){
showAlert = false;
} else {
showAlert=true;
}

var spreadSheet = SpreadsheetApp.getActiveSpreadsheet();
var accountSheet = spreadSheet.getSheetByName("account-stats");
var statsLastCol = statsSheet.getLastColumn();
var accountCount = accountSheet.getLastRow();
var newValue = 0;
var oldValue = 0;
var totalNewPosts = 0;
for (var i=2; i<=accountCount; i++){
newValue = parseInt(getPostCount(accountSheet.getRange(i, 9).getValue()));
oldValue = parseInt(accountSheet.getRange(i, 7).getValue());
totalNewPosts = totalNewPosts + newValue - oldValue;
accountSheet.getRange(i, 7).setValue(newValue);
statsSheet.getRange(i,statsLastCol).setValue(newValue-todaysValue);

}
if(showAlert==false){
return 0;
}
msg(totalNewPosts+" new post found!");
}


function valinar(needle, haystack){
haystack = haystack[0];
for (var i in haystack){

if(haystack[i]==needle){
return true;
}
}


return false;
}


Assuming this is the first time im doing something similar and working by the example from other site i really stuck.


I have one more question. In function getPostCount i send the function profileurl. Where i declare that ??





NodeJS unsafe-perm not working on package.json


I'm trying to run a npm install command with a preinstall script at my package.json. I know it's antipattern but I need to run some scripts as root.


It's working fine by adding a .npmrc file containing unsafe-perm = true to my root directory. But it's not working by add a config property in my package.json file:



{
"name": "foo",
"version": "1.4.4",
"config": {
"unsafe-perm":true
},
"scripts" : {
"preinstall" : "npm install -g bower"
}
}
// It is not working


According with NPM config docs it's ok adding this property in my package file. I want to understand why it's not working.





js function to work onLoad with onClick in cakephp


In cakephp the below code works fine when I load a page and select an option to enable/disable textfields.


The problem is that when I refresh the page when I click a cakephp button elsewhere, the textfields are enabled again that were previously set to disabled.


What I need to to check on loading the page what option is selected. How do I get the the Onclick function to work as well as setting the textfield state whenever the page loads. The onload function below doesnt work.



window.onload=function(){
if(val != 3) {
document.getElementById("startdatebox").disabled = true;
document.getElementById("enddatebox").disabled = true;
} else {
document.getElementById("startdatebox").disabled = false;
document.getElementById("enddatebox").disabled = false;
}

} ​

function myFunc(val) {
if(val != 3) {
document.getElementById("startdatebox").disabled = true;
document.getElementById("enddatebox").disabled = true;
} else {
document.getElementById("startdatebox").disabled = false;
document.getElementById("enddatebox").disabled = false;
}

// alert( document.getElementById("dateRange").value);

}

...
echo $this->Form->input('startDate',array('id'=>'startdatebox','label' => 'Start Date','class'=>'datepicker', 'type'=>'text','style'=>'width:100px;height:30px','value' => $datestart));

echo $this->Form->input('endDate',array('id'=>'enddatebox','label' => 'End Date','class'=>'datepicker', 'type'=>'text','style'=>'width:100px;height:30px','value' => $dateend));




$selectoption=array(1=>'Today',0=>'Fortnight',2=>'Monthly',3=>'Custom Range');
echo $this -> Form -> input('dateRange',
array('id'=>'dateRange2','label' => '<h6>Date Range</h6>','type' => 'radio',
'value' =>$dateSelect,'options' => $selectoption, 'onclick'=> 'myFunc(this.value)'));




Cant read properties of Object in meteor 's iron router's route


I want to pass object in data context in route. I am trying to read JavaScript object(which holds the business logic) . If i send the object as such , then i can read it's properties in template. But if i try to send a custom object by reading some of it's properties . Then I am getting error that it can not read properties of same object.



this.route('updateBook/' ,
{
path:'/updateBook',
loadingTemplate: 'loading',
data : function(){
var Book = Books.findOne({hasFinished:true});

var UpdateBookObject ={};
//UpdateBookObject.currentPage = Book.currentPage;
UpdateBookObject.name = Book.name;
UpdateBookObject.author = Book.author;
// UpdateBookObject.img = Book.img;
UpdateBookObject.numOfPages = Book.numOfPages;
UpdateBookObject.dateStarted = Book.dateStarted;
UpdateBookObject.dateToFinish = Book.dateToFinish;
UpdateBookObject.percentage = (UpdateBookObject.currentPage/UpdateBookObject.numOfPages).toFixed(2);
UpdateBookObject.pagesRemaining = UpdateBookObject.numOfPages - UpdateBookObject.currentPage;
var finishMoment = moment(UpdateBookObject.dateToFinish,"DD-MM-YYYY");
var startMoment = moment(UpdateBookObject.dateStarted,"DD-MM-YYYY");
UpdateBookObject.perDayToRead = finishMoment.diff(startMoment,'days');
return UpdateBookObject;
}


});




In Javascript, which operator is faster, the '*' multiply or '/' divide?


In javascript, is there a speed advantage between the multiplication operator and the division operator? As an example...



var foo = bar * 0.01;
var foo = bar / 100;


foo is the same for both, but which statement returns the value of foo the fastest? I know this may be an incredibly small difference, however, when loop processing large amounts of data it could make a bigger difference than realized, which would then make a difference in how I construct equations to facilitate the processing.





How do I initiate a WebRTC data channel?


I'm trying to create a WebRTC data channel between clients using web sockets.


I listed some ICE servers



var rtcsettings = {
iceServers: [
{url: "stun:stun.ekiga.net"},
{url: "stun:stun.voipbuster.com"},
{url: "stun:stun.1.google.com:19302"},
]
};


Then there is a connect function that creates a channel and offer and sends it over the web socket.



function(them) {
var pc = new RTCPeerConnection(rtcsettings);
self.channel = pc.createDataChannel("gamelink");
console.log(pc, self.channel);
self.peerconnection = pc;
pc.createOffer(function(offer) {
pc.setLocalDescription(new RTCSessionDescription(offer), function() {
self.socket.send(JSON.stringify({
"to": them,
"uuid": uuid,
"offer": offer,
}));
}, pc.close);
}, pc.close);
}


Then on the other end there is a callback that adds the offer to its connection and sends a response.


It also sets a callback for when a data channel is added, but this never fires. What am I missing?



function (message){
var offer = message.offer;
var pc = new RTCPeerConnection(rtcsettings);
pc.ondatachannel = function(ch) {
self.channel = ch;
console.log(self.channel);
}
console.log(pc);
pc.setRemoteDescription(new RTCSessionDescription(offer), function() {
pc.createAnswer(function(answer) {
pc.setLocalDescription(new RTCSessionDescription(answer), function() {
self.socket.send(JSON.stringify({
"to": message.uuid,
"uuid": uuid,
"answer": answer,
}));
}, pc.close);
}, pc.close);
}, pc.close);
self.peerconnection = pc;
}


Then finally there is another callback on the initiator that adds the response descriptor to its connection.



function(message) {
self.peerconnection.setRemoteDescription(
new RTCSessionDescription(message.answer),
function() { },
self.peerconnection.close);
}


All of the code except the socket stuff and the data channel stuff is taken almost verbatim from the MDN Basic Usage page.


I'm testing with Chrome on localhost, so firewalls should not be a problem.


After the exchange happens, both connections have a local and remote descriptor set. The data channel readyState is connecting. The PeerConnection's iceConnectionState is new and its signalingState is stable.


What's missing?





Adding multiple locations to google js map


I'm trying to add 3 locations to a Google map I have embedded in a website I am working on. Right now the map is working as intended with the single location pin. Is there a way to modify the js file to add the additional points?



// ========== START GOOGLE MAP ========== //
function initialize() {
var myLatLng = new google.maps.LatLng(30.227686, -81.386146);



var mapOptions = {
zoom: 14,
center: myLatLng,
disableDefaultUI: true,
scrollwheel: false,
navigationControl: false,
mapTypeControl: false,
scaleControl: false,
draggable: true,
mapTypeControlOptions: {
mapTypeIds: [google.maps.MapTypeId.ROADMAP, 'roadatlas']
}
};

var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);



var marker = new google.maps.Marker({
position: myLatLng,
map: map,
icon: 'img/location-icon.png',
title: '',
});

var contentString = '<div style="max-width: 300px" id="content">'+
'<div id="bodyContent">'+
'<h5 class="color-primary"><strong>Location 1</br> Ponte Vedra Office</strong></h5>' +
'<p style="font-size: 12px">103 B Solana Road </br>' +
'Ponte Vedra, FL 32082</br>' +
'Phone: 904-273-2717</p>'+
'</div>'+
'</div>';

var infowindow = new google.maps.InfoWindow({
content: contentString
});

google.maps.event.addListener(marker, 'click', function() {
infowindow.open(map,marker);
});

var styledMapOptions = {
name: 'US Road Atlas'
};

var usRoadMapType = new google.maps.StyledMapType(
roadAtlasStyles, styledMapOptions);

map.mapTypes.set('roadatlas', usRoadMapType);
map.setMapTypeId('roadatlas');
}

google.maps.event.addDomListener(window, "load", initialize);






// ========== END GOOGLE MAP ========== //


I am trying to include these 3 latitude/longitude sets on my map: (30.227686, -81.386146) (30.650060, -81.455185) (30.056330, -81.535824)


Thanks!





Create event handler is not called. Extending jQueryUI Dialog


declare



(function ($) {
$.widget('my.popup', $.ui.dialog, {
'create': function (event, ui) {
// this one is NOT called
console.debug('create');
},
'_create': function () {
// OK
console.debug('_create');

return this._super();
}
});
}(jQuery));


call



var div = jQuery('<div>').appendTo('body');
div.on('widgetcreate', function (event, ui) {
// this one is NOT called
console.debug('widgetcreate');
});
div.on('popupcreate', function (event, ui) {
// OK
console.debug('popupcreate');
});
div.popup();


I can understand why 'widgetcreate' does not work, but 'create' in options? jQuery.Widget has create (http://ift.tt/1FIOGLN) and I guess dialog should inherit it and fire it internally with proper new name.


What is the problem?





HOW to implement this method with a promise


How would I use a promise to wait for the asynchronous geocode method to return a result and then return either true or false?



function LocationValidator(value, element, paras) {
var geocoder = new google.maps.Geocoder();

geocoder.geocode({ 'address': value }, function (results, status) { // called asynchronously
if (status == google.maps.GeocoderStatus.OK) {
return true;
} else {
return false;
}
});
}




Could not able to get jsp table row values from one page and display the values in text box of another page


I need to get the values from my rows inside the table of a jsp page and display it in textbox of another jsp page i tried to do but i could manage to just call my another page but could not able to get the values from one page to another


My Jquery



$('tr').click(function () {
$('tr').removeClass('selected');
$(this).addClass('selected');
selectedRow = $(this);
});

$("tr").dblclick(function () {
var td = $(selectedRow).children('td');
for (var i = 0; i < td.length; ++i) {
/* alert(i + ': ' + td[i].innerText); */
}
var customer =td[0].innerText
alert('customer :' +customer);
window.location = "InternalConversion.jsp?customer="+customer;
});


JSP page



<table style="width: 100%;" class="embeddedFIXED" >
<thead>
<tr >
<th align="left">Branch</th>
<th align="left">City</th>
<th align="left">Country</th>
<th align="left">Branch Number</th>
<th align="left">Entity Type</th>

</tr>
</thead>
<tbody>
<%
BranchSearch b1= null;
int rownum = 1;
Iterator<BranchSearch> i = l1.iterator();
while (i.hasNext()) {
b1 = (BranchSearch)i.next();
String rowStyle = "TIRowAlt";
if (rownum % 2 == 0) {
rowStyle = "TIRow";
} else {
rowStyle = "TIRowAlt";
}
%>


<tr class="link1 <%=rowStyle%>" onclick="click()">

<td align="left" class="br" ><%=b1.getBranch()%></td>
<td align="left"><%=b1.getCity()%></td>
<td align="left"><%=b1.getCountry()%></td>
<td align="left"><%=b1.getBranchnumber()%></td>
<td align="left"><%=b1.getEntitytype()%> </td>

</tr>
<%
rownum++;
}
%>
</tbody>
</table>




How to insert a table within of a iframe?


I'd like to insert this piece of code without of an iframe:


I have the following HTML and JQUERY code and it works perfectly:



$('#info').append('<h3>' + 'Sectores de la comuna de Curicó' + '</h3>' +
'<table id="sectoresTableID" class="table table-hover table-condensed" style="width:99%">' +
'<head>' +
'<tr>' +
'<th>Número</th>' +
'<th>Sector</th>' +
'</tr>' +
'</head>' +
'<body>' +
'</body>' +
'</table>');


But now, I want to insert this table within of an Iframe, I have tried to insert a table tag within of append but It doesn't work.





Can Angular do two way data binding backwards between two input fields?


I can't make my two input fields update values when changing the opposite input.


What I want to do is make a basic $dollar to Gold oz calculator that takes in two input fields. Sample Preview: http://ift.tt/1DEmBoU


The first input is the dollar amount, the second an ounces amount. There is a third variable that contains the gold selling rate.


In my code I have been able to successfully changing the Dollar amount and make the oz amount update via angular two way data binding.


The problem is trying to make the opposite work; for example, changing the oz amount should also update the dollar amount.


Here is my html code:



<div class="row panel" ng-controller="ctrl">

<!-- Dollar input -->
<label class="small-6 columns">Dollar $:
<input type="number" ng-model="dollar">
</label>

<!-- Ounces input -->
<label class="small-6 columns">Ounces (oz):
<input type="number" value="{{ ozCalc() | number:4 }}">
</label>

</div>


Here is my angular code:



var app = angular.module('app', []);

app.controller('ctrl', ['$scope', function($scope) {
$scope.dollar = 0;
$scope.oz = 0;
$scope.rate = 1267;

//Dollar to Ounce Calculator
$scope.ozCalc = function() {
var oz = $scope.dollar / $scope.rate;
return oz;
};

//Ounce to Dollar Calculator
$scope.dollarCalc = function() {
var dollar = $scope.oz * $scope.rate;
return dollar;
};

}]);


Any help would be really appreciated. Thanks





React child component only fires 'onTouchMove' event once


** I'm pretty confident I can figure out a work around to the specific example given, I'm asking for help on SO to gain better knowledge of React specific idiosyncrasies of DOM creation and events. **


I setup a component that manages multiple components. These children have onMouseMove and onTouchMove events that call handler functions on the parent.


For context, the children components are timeline charts. When one child sees mouseover, it calls the parent handler function to figure out what time was moused over, then renders the same time on all of the children.


This works great in the browser with onMouseMove, the issue I'm having is when I try to add the same functionality to mobile touch browsers with onTouchMove. The initial onTouchMove event is called, but "this.setState({})" function called on the parent updates the children once, and no more touchmove events are called. Ideally a user could slide their finger along one charts timeline, and all the charts would continuously select the same hour of their timeline.


The timeline chart inside the children components are wrapped in a React.DOM.div, that is where the onTouchMove and onMouseMove calls are being generated, I can post that code too if needed.


If the only thing I change on the parent is it's state.index (there are no dom changes), and there are no dom changes in the children components above the wrapper element (only dom changes are inside the wrapper element), then shouldn't the wrappers onTouchMove events continue to fire? (side note, if I comment out "this.setState({})" from the parent handler and replace with a console.log call it will call continuously, so I know the code is working).


SO the question: why is the child component loosing it's current onTouchMove event? I'm new to react so could be missing something.


Thanks!



// simplified example:

var parentComponent = React.createFactory(
React.createClass({
getInitialState: function(){
return { index: this.props.index || -1 };
},
handle_container_mouse_move: function(evt){
var chart = evt.currentTarget;
var grid = chart.querySelector('.ct-grids');
var bbox = grid.getBBox();
var division = bbox.width / chart.querySelectorAll('.ct-series > line').length;
var x = evt.clientX - bbox.x - chart.offsetLeft - (division/2);
this.setState({ index: Math.round(x / division) });
},
handle_container_touch_move: function(evt){
var chart = evt.currentTarget;
var grid = chart.querySelector('.ct-grids');
var bbox = grid.getBBox();
var division = bbox.width / chart.querySelectorAll('.ct-series > line').length;
var x = evt.touches[0].clientX - bbox.x - chart.offsetLeft - (division/2);
this.setState({ index: Math.round(x / division) });
},
render: function(){

var children = [];

... other code ...

children.push(childComponent({
key: 'some_key',
index: this.state.index,
handle_child_mouse_move: this.handle_container_mouse_move,
handle_child_touch_move: this.handle_container_touch_move
}))

... other code ...

return React.DOM.div({}, children );

}}
}));


Thanks!


* edit *


It seams whenever a React component touches the dom it breaks touchmove:



// this will log lots of 'now's on console.log as the touch moves

$(document).on('touchmove', function(evt) {
console.log('now');
document.body.appendChild(document.createElement('div'));
});


// this will log only one 'now' on console.log

$(document).on('touchmove', function(evt) {
console.log('now');
React.render(CountyList({ time: 6 }), $state_list_container[0] );
});




javascript select item that has href in it


i'm im making a file manager where you can edit files in bulk but i cant get the select function to work.


im using this file browser http://ift.tt/1qJW7Pi


and i have given my UL an id and added this script to the page



$("#test li").click(function() {
alert(this.id); // get id of clicked li
});


but when i click on an item it opens the url of it in sted of selecting it





How to use onpopstate, with javascript, no jQuery?


I have a website that has 4 main pages, index, somepage, someotherPage, and LastOtherpage. They have different names, like index.php, food_and_health.php, enlightening_info.php, and about_us.php.


I have my ajax part(HTTPrequest) working fine, and the pushstate is working.


What I now want, is obviously, the popstate function working. I have read, and watched tutorials, but how would I do this with the this keyword?


I have a fiddle added, so you can see me code, its not working well in the fiddle, but works very good in chrome, firefox and late ie. I have something like this in mind for my onpopstate..



nav.history("this.object", "Title", "/this.url");
http://ift.tt/1N3Nat0


How would the onpopstate code look like? I know it is bad to ask for all the code, but this way I actually learn, as when I read the code, I understand it. I haven't fully got the grip of javascript eventhandling yet, as you can see I use onclick in my html documentes, and not eventhandling them. But this I know, I can do, it is just a lot of changing in my documents, and first priority for me, would be to have back/forward, refresh, and share functionality to work, so that I can actually share my website out in the web, without and lack of functionality! :)


Any help is much appreciated, thanks in advance :)





Populate store in ExtJS using hasMany associations


I am trying to populate all the records at once in a model and then assign each collective property to different container.


i.e. I have 1 grid and 1 combo on my page and trying both in one call. So I fetch the data successfully but it comes in forms of Nested JSON Data.



Ext.Model ('Person', {
fields: [
{ name: 'firstname' },
{ name: 'lastname' },
{ name: 'placesOfWork' }
],
associations: [
{ type: 'hasMany', model: 'PlaceOfWork', name: 'placesOfWork' }
});


this is my model class and whenever I try to assign it to grid so first thing I must need to iterate through each property and then create a new store at runtime to assign the data.


First I read the data by using store.reader.JsonData.placesOfWork which returns me a jsonArray and then create a store using the array elements.


Problem is not this as I got my data in grid and combo. But whenever I try to get my grid and store or comboValue then it always returns me null or store size "0"



var grid = Ext.getCmp("MyGRidID");
var store = grid.getStore();
alert(store.getCount());


It returns me 0 while data is available in my grid. similar thing happen when I try to get value from my combo which was dynamically bonded.



var combo = Ext.getCmp("MyCombo");
var value = combo.getValue();
var rawValue = combo.getRawValue();

alert(value);
alert(rawValue);


Both returns null and empty value.





Add an Editor for script to run, then Remove them - temporary Editor permission


I shared a spreadsheet with a sheet named "times". This sheet is range protected to other users, but them must view and have to sort it in several ways. I create some menus with menuEntries.push etc... wrote the scripts for sort this sheet in all the ways i need, but only people I set as administrator can sort using my menu. The others can't to do it cause they can't execute the script on range protected. I would like to grant permission to everybody only during the script exectuting, the code should sound something like this above ( that don't works )



function Editors() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var targetSheet = ss.getSheetByName("times");
var user = SpreadsheetApp.getActive().getEditors();
var permission = targetSheet.getSheetProtection();
permission.addUser(user);
SpreadsheetApp.flush();

var tableRange = "orario!b7:ap209";
var tableRange = "times";
var range = ss.getRange(tableRange);
range.sort( { column: 2, ascending: true } );

permission.removeUser(user)
targetSheet.setSheetProtection(permission)
}


...if someone can help me .... thanks in advance....





jquery - How to return default height toogle automaticly by clicking another place


Here, I have a working toogle code,so I have added some code that when click another place also return to default height(32px),but not working.



var toggled = false;
$('.dropdown-toggle').click(function() {
$('.changeHeight').css('height', toggled ? '32px' : '65px');
toggled = !toggled;
});

$(document).click( function(){ // if click another place will set default height
$('.changeHeight').css('height','32');
});




have element stop scrolling when element reaches footer


Reformatted question. I've tried a few different solutions ; .stop() and by offsetting the height of the element and trying some funky positioning. However, since the element fades in and out it achieves the desired effect. Is there a way to have the element that fades in stop scrolling when it reaches the footer?


JSfiddle: http://ift.tt/1Brbu3r



var pointOne = $("#form").offset().top;
$(window).on("scroll", function () {
$.fx.speeds.xslow = 750;
if ($(this).scrollTop() > pointOne) {
$("#middlecta").fadeIn('xslow').addClass('fixed');
} else {
$("#middlecta").fadeOut('xslow').removeClass('fixed').hide();
}
$("#middlecta-t").addClass("mob");
});




What can the JavaScript prototype system do beyond mimicking a classical class system?


The prototype system looks much more flexible than the traditional class system, but people seem to feel content with the so-called "best practices", which mimic the traditional class system:



function foo() {
// define instance properties here
}

foo.prototype.method = //define instance method here

new foo()


There must be other things that a prototypical system can do with all the flexibility.


Are there uses for a prototypical system outside of mimicking classes? What kinds of things can prototypes do which classes cannot, or are there none?





Control-Flow with NodeJS and Sequelize


I have the following function:



function retrieveNotifications(promotions) {
promotions.forEach( function(promotion) {

//find all notification groups that have to be notified
db
.Notification
.findAll()
.then(function (notifications) {
//some code that adds notifications to an object
});
});
};


How can I restructure it to wait till all notifications are added to the object. I can't use .then because it would be called multiple times because of the forEach





JavaScript Pseudoclasses Pattern


Hi i'm new to JavaScript and i'm studying Object Creation Patterns, in particular i'm focused on Pseudoclasses Pattern, so i wrote a few lines of code to check if i get the concept:



var Car = function (name, x, y) {
this.name = name;
this.x = x;
this.y = y;
};

Car.prototype.drive = function (byX, byY) {
this.x += byX;
this.y += byY;
};

var ferrari = new Car("Ferrari", 5, 5);
ferrari.drive(5, 5);

var ferrari_proto = Object.getPrototypeOf(ferrari);
var ferrari_proto_proto = Object.getPrototypeOf(ferrari_proto);
var ferrari_proto_proto_null = Object.getPrototypeOf(ferrari_proto_proto);

console.log(ferrari_proto); // Should be Function
console.log(ferrari_proto_proto); // Should be Object
console.log(ferrari_proto_proto_null); // Should be Null


What i got from running the code is:



{ drive: [Function] }
{ }
null


and logging the type of these objects i got:



object
object
object


Now, what i thought was that creating objects this way, the ferrari prototype would have been the Car function, so what i expected was:



function // Tha Car function
object // The Function prototype, that is Object
object // null, that is the end of the chain


Someone can explain me why i got these outputs and why i was wrong ?!





Insert a hyphen between even numbers inside an array


I am trying to insert a hyphen "‐" between the even numbers in an array so if i have 43268356925485942568 it shows 432–6–83569254–8594–256–8. The numbers are randomly generated. I tried several things but no luck.



<body>
<div id="arrayDisp">
</div>
<div id="numbers">

</div>
<script>
var numbers = new Array(20);
var numbers2 = new Array(20)

for (var i = 0; i< numbers.length; i++)
{
numbers[i] = parseInt(Math.random() * 10);
}

document.getElementById("arrayDisp").innerHTML = numbers.join(" ");

for(var i in numbers)
{
if(i%2 == 0)
{
numbers2.push('‐',i);
}
else
{
numbers2.push(i);
}
}
document.getElementById("numbers").innerHTML = numbers2.join("");

</script>
</body>




Isolate value of string by number of characters


How I can isolate value of string (00010111001101000001011100011001) on strings by number of characters(8) use jquery and javascript?


I want this: Result: [ "00010111", "00110100", "00010111", "00011001" ]





How to add add a page worker on intercepted page response


I'm building a firefox extension which intercepts a page load for a certain domain and returns it's own HTML instead. The issue I'm having is that once I've intercepted the page and returned the html, I can't seem to add a page-worker to allow the script to communicate back to the higher-privileged extension code. If there's a way to communicate back without a page-worker that'd be good too. Here's my code:



var { Class } = require('sdk/core/heritage');
var { Unknown } = require('sdk/platform/xpcom');
var { Cc, Ci, Cr, Cu } = require('chrome')
var observerService = Cc['@http://ift.tt/1efiEYk'].
getService(Ci.nsIObserverService);
var data = require("sdk/self").data;
var pageWorkers = require("sdk/page-worker");

Cu.import("resource://gre/modules/Services.jsm");

var TOPIC_MODIFY_REQUEST = 'http-on-modify-request';

var StartObserver = Class({
extends: Unknown,
interfaces: [ 'nsIObserver' ],
topic: '*',
register: function register() {
observerService.addObserver(this, this.topic, false);
},
unregister: function() {
observerService.removeObserver(this, this.topic);
},
observe: function observe(subject, topic, observeData) {
//console.log('star observer:', subject, topic, data);
if (TOPIC_MODIFY_REQUEST == topic) {
subject.QueryInterface(Ci.nsIHttpChannel);
let url = subject.URI.spec;
if(!url.indexOf("https://example.com")) {
subject.redirectTo(Services.io.newURI("data:text/html,"+data.load("intercept.html"), null, null));
//This is not adding the page-worker
pageWorkers.Page({
contentURL: "https://example.com",
contentScriptFile: [data.url("inject.js")],
contentScriptWhen: "start"
});
}
}
}
});

exports.Intercept = function(){
var startobserver = StartObserver();
startobserver.register();
};




highchart x axis not showing correct date labels


i am using highchart and loading a json dynamically. json provides me the date time series and its value


The chart is being created and the tooltip is showing the correct value only the x-axis labels are not shown correctly.



$(function () {
$('#container').highcharts({
xAxis: {
type: 'datetime',
dateTimeLabelFormats: {
day: '%e of %b'
}
},

series: [{
data: [
["2013-09-15 08:44:37",19.8],
["2013-09-15 08:47:37",18.4],
["2013-09-15 08:50:37",18.3],
["2013-09-15 08:53:37",18.1]
],
//pointStart: Date.UTC(2010, 0, 1),
pointInterval: 24 * 3600 * 1000 // one day
}]
});
});


live plunkr : http://ift.tt/1EArt0e


Kindly assist. Thanks





html - javascript not working in dynamic generated html form


A table row in a form which is dynamically generated with a "Add row " button.


One field in the row is Date which uses datepicker to select the date.


PROBLEM:


The datepicker doesn't show when the row is dynamically generated.


I am using bootstrap 3.


Here is the code that generate table row on button click.



function addRow(tableID) {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
if(rowCount < 40){ // limit the user from creating fields more than your limits
var row = table.insertRow(rowCount);
var colCount = table.rows[0].cells.length;
for(var i=0; i<colCount; i++) {
var newcell = row.insertCell(i);
newcell.innerHTML = table.rows[0].cells[i].innerHTML;
}
}else{
alert("Maximum Players per Entry is 40");

}


}





php function that sends message to XMPP server give no log and doesn't work


Im working on getting a webpage where users input a text in a form and click submit. From there it validates the input and sends it to a php function that uses JAXL 3.0 library to send the message to my XMPP server.


My problem is that when I call the JAXL function nothing just happens. it's like it can't finish the function as the next function never gets it's call. if I swap the order around the other functions gets called but it still doesn't finish the sendmessage() function.


I'm rusty/new in php and I can't get JAXL to provide a log or anything to debug where my issue is.


If anyone know how to debug this php/JAXL function properly it would be a large help.


I've searched the web around and looked at examples for JAXL but can't find my issue :/


EDIT: Tried some debugging with ECHO. I can't get a ECHO out if it's posted below my Create client. If I ECHO right above it works.


My Sendmessage function:



function sendping()
{
//get the form elements and store them in variables
$ping_text=$_POST["pingtext"];

// Config Details
$host = 'example.com';
$user = 'host';
$pass = 'password';

// Create Client
$client = new JAXL(array(
'log_path' => '/var/log/jaxl.log',
'jid' => $user.'@'.$host,
'pass' => $pass,
'log_level' => JAXL_INFO,
'auth_type' => 'PLAIN'
));

// Add Callbacks
$client->add_cb('on_auth_success', function() use ($host, $client, $ping_text) {
$client->send_chat_msg($host.'/announce/online', $ping_text);
$client->send_end_stream();

});
$client->add_cb('on_auth_failure', function($reason) use ($client)
{
$client->send_end_stream();
_info("got on_auth_failure cb with reason: $reason");
});
$client->add_cb('on_disconnect', function() use ($client)
{
_info("got on_disconnect cb");
});
// Startup Client
$client->start();


My hole .php page:



<?php
/*
Template Name: Stahp Ping
*/

require 'jaxl.php';

get_header(); ?>

<div id="hidden_div" style="display:none; margin-left:auto; margin-right:auto; margin-top:20px;
text-align:center;">
<p>Ping has been sent </p>
</div>

<div style="width:850px !important;
margin-left:auto;
margin-right:auto;
margin-top:20px;
text-align:center;" id="pingform">


<form action="<?php echo htmlspecialchars($_SERVER['REQUEST_URI']);?>" method="post" name="stahpbox">
<textarea name="pingtext" rows="8" cols="60"></textarea>
<input type="submit" value="Send Ping" />
</form>

</div>

<script type="text/javascript">
function showHide() {
var div = document.getElementById("hidden_div");
var pingdiv = document.getElementById("pingform");
if (div.style.display == 'none') {
div.style.display = '';
pingdiv.style.display='none';
}
else {
div.style.display = 'none';
pingdiv.style.display = '';
}
}
</script>

<?php
function sendping()
{
//get the form elements and store them in variables
$ping_text=$_POST["pingtext"];

// Config Details
$host = 'example.com';
$user = 'user';
$pass = 'password';

// Create Client
$client = new JAXL(array(
'log_path' => '/var/log/jaxl.log',
'jid' => $user.'@'.$host,
'pass' => $pass,
'log_level' => JAXL_INFO,
'auth_type' => 'PLAIN'
));

// Add Callbacks
$client->add_cb('on_auth_success', function() use ($host, $client, $ping_text) {
$client->send_chat_msg($host.'/announce/online', $ping_text);
$client->send_end_stream();

});
$client->add_cb('on_auth_failure', function($reason) use ($client)
{
$client->send_end_stream();
_info("got on_auth_failure cb with reason: $reason");
});
$client->add_cb('on_disconnect', function() use ($client)
{
_info("got on_disconnect cb");
});
// Startup Client
$client->start();
}

//Validation and redirection to send to jabber
// Initialize variables and set to empty strings
$pingtextERR="";
// Validate input and sanitize
if ($_SERVER['REQUEST_METHOD']== "POST") {
$valid = true; //Your indicator for your condition, actually it depends on what you need. I am just used to this method.

if (empty($_POST["pingtext"])) {
$pingtextERR = "Text is required";
$valid = false; //false
echo "<script type='text/javascript'>alert('$pingtextERR');</script>";
}
//if valid then redirect
if($valid){
echo "<script> showHide(); </script>";
sendping();
}
}

?>




Undefined error while trying to route to client folder using express


I'm trying to sendFile index.html from inside my client directory which is at the same level as my server directory, and getting the following error:



TypeError: undefined is not a function
at Object.handle (/myapp/server/routes/routes.js:31:7)


This is line 31 of my routes.js: res.sendFile(fileName, options, function (err) {


Full function



dashRouter.get('/', function(req, res) {

// res.send('dashboard!');

var fileName = 'index.html';

var options = {
root: __dirname + '../client/dashboard/',
dotfiles: 'deny',
headers: {
'x-timestamp': Date.now(),
'x-sent': true
}
};

res.sendFile(fileName, options, function (err) {
if (err) {
console.log(err);
res.status(err.status).end();
}
else {
console.log('Sent:', fileName);
}
});
});

return dashRouter;


My folder structure: enter image description here


Do you know why I'm getting that undefined error on the sendFile line?





Like function with Ajax / PHP / jQuery


1 week ago, i decided to start adding AJAX and more jquery to my Website. I think, the "combination" of PHP / Jquery / AJAX is the best thing ever.


Now i want to create a "like - system" in my community board. I did something similar already:



$(function(){
$('.action-button.like').click(function(){
//ajax part
var articleId = $('.article-Id').html();
$.ajax({
type: "GET",
async: true,
url: '/wiki/parts/likeArticle.php',
data: { 'articleId': articleId },
//change button
success: function (msg){
$('.action-button.like span').fadeOut(400);
},
error: function (err)
{ alert(err.responseText)}
});
});
});


as you can see, the button / element disappears after a click() on it. PHP data: the .php file "inserts the like" into the database ...


So - this works great ! Back to my question: After an user likes the post, i want to display a container with all users, which did this before.


I'm asking this, because i know how to do this / I have an Idea how i can realise my little project, but i dont know, if this is the propper way :)


My solution:


in $.ajax: I want to create a function on "success:" (and a new .php file, which loads all users / "likers") the function uses .load() and loads the file, so everything should be done right, shouldn't it ?


I hope you understand my problem, Greets :)





Longpolling (I think) is killing my local server


I am running a longpolling script to grab data from the database. It was working fine until moving my script to an MVC.


I have viewed the chrome developer tool and it's showing nothing in there, but the page just carries on loading, and when I go to refresh it won't load, I have to shit down my xampp server or close my browser... Here's my script:



<?php

class SystemController extends Controller
{

public function lastbid()
{

set_time_limit(0);


// main loop
while (true) {


//get the product info
$getbidresult = ProductModel::bidprice(Request::get('item'));

// if ajax request has send a timestamp, then $last_ajax_call = timestamp, else $last_ajax_call = null
$last_ajax_call = Request::get('timestamp');


// get timestamp of when file has been changed the last time
$lastbid = isset($getbidresult->timestamp) ? $getbidresult->timestamp : 0;

// if no timestamp delivered via ajax or data.txt has been changed SINCE last ajax timestamp
if ($last_ajax_call == null || $lastbid > $last_ajax_call) {

// put last bid info into an array
$result = array(
'bidamount' => isset($getbidresult->amount) ? System::escape($getbidresult->amount): 0,
'timestamp' => System::escape($lastbid)
);

// encode to JSON, render the result (for AJAX)
$json = json_encode($result);
echo $json;

// leave this loop step
break;

} else {
// wait for 1 sec (not very sexy as this blocks the PHP/Apache process, but that's how it goes)
sleep(10);
continue;
}
}

}
}


This is how I am grabbing the data with JS.



<script type="text/javascript">
function getContent(timestamp)
{
var queryString = {
'timestamp': timestamp
};
$.ajax(
{
type: 'GET',
url: '<?php echo Config::get('URL'); ?>system/lastbid?item=<?php echo System::escape($recentitem->id); ?>',
data: queryString,
success: function(data)
{
var obj = jQuery.parseJSON(data);
$('#bidprice-<?php echo System::escape($recentitem->id); ?>').html(obj.bidamount);
getContent(obj.timestamp);
}
});
}
$(function()
{
getContent();
});
$(document).ready(function() {
});
</script>


I've looked in apache logs with no avail unless I am looking in the wrong place. Does anything in the code look out of place, It doesn't to my knowledge but I may be overlooking something.


I have the script in a foreach, so I can initiate the div, for each product.





Angularjs - How to open custom modal on leaving the page?


I'm in a bit of a pickle. I have a form in the page. When user makes it dirty and tries to leave the page, a custom modal (mostly bootstrap modal) should pop up with a confirmation message as in "are you sure you want leave?"


I made a plunker which uses native browser's alert box (and also bootstrap pop modal). Alert box works - commented out. But modal is not working.


http://ift.tt/1EAqvky


Any help would be greatly appreciated.





How to run and debug an AngularJS application in Eclipse?


I'm trying to get started with Nodeclipse. I would like to run and debug an AngularJS application, e.g. the angular-phonecat example from Eclipse.


In particular, I would like to



  • use a Debug on Server launcher to start a server with my application and open a web browser (Firefox or Chromium).

  • set a breakpoint in a JavaScript file in Eclipse

  • click around in the web browser and have the Eclipse debugger stop at the breakpoint.


(The equivalent of this does work in NetBeans in a very intuitive way.)


From the Nodeclipse help, I don't see how to get started or whether this is possible at all.


I managed to run an debug a Node.js project with the Hello World template, but I don't see how to debug anything running in a web browser.


Does that require a Remote Javascript debug launcher? If so, how to use it?


Finally, I don't see how to actually run an AngularJS application in Nodeclipse. As far as I can tell, the AngularJS Eclipse plugin only implements editing features but does not deal with running and debugging. Do I need to turn the Angular project into a Node.js application? If so, how?





Chrome is sending top url of iframe


Suddenly Chrome is able to get the cross-domain url. Firefox is not able to do this.


I have got the following setup:



www.page.com/ads.htm



there is implemented a javascript code which is able to get the top url


this page is loaded by



page.com/frame.html (without www so that is hits the same origin policy)



where I have implemented a iframe which is showing to www page.com/ads.htm


at last page.com/frame.html is loaded in an iframe by



http://ift.tt/1LXEUJE



In the past the javascript code in ads.htm has been able to get only the page.com/frame.html. But suddenly Chrome is able to get the http://ift.tt/1LXEUJE. Firefox is not able to do this.


How can that happen and how can I avoid this?





Single Line/Non-Loop Javascript method to find item with specific text then invoke a click


I'm wanting to be able to click on an input that has no ID thats inside a LABEL that has no ID either.


Here is sample HTML...



<label>
<input type="radio" />
item1
</label>
<label>
<input type="radio" />
item2
</label>
<label>
<input type="radio" />
item3
</label>


now using ONLY Javascript. How could I go about just invoking a click on the item2 in this example?


I know that I could prolly do a FOR loop through all the document.getElementsByTag("label") then check the text of each one and then probably invoke a click after i've found th specific label...


BUT i was wondering if it was posssible to do this in a very simplified method instead like using document.querySelectorAll("label") or something to this effect? like is there noting that would allow me to do like a uh...



document.querySelectorAll("label[text='item2']").click()


Nothing like this or anything possible?


EDIT #1 - based off people stating its impossible for single selectors


If its not possible to do it using a querySelectorAll and you would have to use a For-Loop/While then how would you do this in a single line?


I know sometimes you can do stuff like...



javascript:(function() { document.getElementById('LABELID').value+='SETVALUE'; document.querySelectorAll("Button[type='submit']")[0].click();})()


Is it possible to do this search and click in a single line also?





Debounce a function with argument


I'm trying to debounce a save function that takes the object to be saved as a parameter. Something like:



var save = _.debounce(function(obj) {
...
}, delay);


For an auto-save that fires on keystroke, this stops the save from happening until the user stops typing, or at least that's the idea.


Where this falls apart is if I try to save two objects in quick succession. Because the debounce doesn't take the passed in object into account, only the second call to save will fire and only one object will be saved.


I could make obj an instance of a class that has its own save method that takes care of debouncing saves to just that object. Or keep a list of partial/curried functions somewhere, but I'm hoping there's a one stop solution out there. Something like:



var save = _.easySolution(function(obj) {
...
}, delay);




Stop error propagation in Bluebird promises


How can I stop a thrown error from propagating all the way down the chain? It shows in my catch() block but it doesn't stop and crashes the server with an uncaught exception.



var run function() {
return job.getAndStore().then(function(res) {
....
}).catch(function(e) {
console.log('Just stop please...');
});
}

run();


I have to do this which I know not quite right:



try {
run();
} catch(e) {
console.log('Now it stops')
}


The run() is part of some cron library that doesn't have any promise support so I am wrapping it in the function to call it.





Unable to Pass Values from One PHP Page to Another


There is similar code in the application that works in this same fashion, but my addition is not working. I can get the search page to pop-up in a new window, but when I select the group to pass to the form page and display the pop-up window will not close or populate the form field on the add form page. Any help would be appreciated.


ADD Form PHP Page Want to hide a readonly form field for a group name and display a button to search group listing from another page.


Form Field Page HTML Code



<div class="form-group">
<label class="col-sm-3 control-label" for="groupId">Group *</label>
<div class="col-sm-6" id="div_gr_name" style="<?php if ($gr_id < 1) {?> display:none <?php } else { ?> display:inline <?php } ?>">>
<input type='text' name='gr_name' class='span2 form-control' placeholder="Search Group Name" value="<?php if ($gr_id != -1) {echo $gr_name;} else {echo '';} ?>" id='gr_name' readonly='true' required/>
</div>
<div class="col-sm-2" style = "<?php if ($gr_id > 1) {?> display:none <?php } else { ?> display:inline <?php } ?>">
<button type="button" class="btn btn-primary" onclick='OpenPopup()'>Search</button>
</div>
<div>
<span id='paientNameMissing'></span>
</div>
</div>


Javascript OpenPopup from footer page



function OpenPopup() {
try {
window.open("searchgroup.php", "_blank", "width=850,height=500,scrollbars=yes,resizable=yes");
}

catch (ex) {
alert(ex);
}

finally {
event.cancelBubble = true;
event.returnValue = false;
return false;
}
}


Searchgroup Selection PHP Page


Group Selection Page PHP & HTML Code



//retrieve our table contents
while($row=mysql_fetch_array($rs)){
extract($row);
//creating new table row per record
echo "<tr>
<td>{$gr_name}</td>
<td>{$gr_leadername}</td>
<td>{$gr_leadcontact}</td>
<td>{$gr_leademail}</td>
<td>";?><a href='#' onclick="select_group('<?php echo $gr_id ?>', '<?php echo mysql_real_escape_string($gr_name); ?>') ">Select</a><?php echo "</td>
</tr>";
}
//end table
echo "</tbody>
</table>
</div>";
}


Select Group javascript function



function select_group( id, name ){
var selvalue = id;
var selvalue1 = name;
window.opener.document.getElementById('gr_id').value = selvalue;
window.opener.document.getElementById('gr_name').value = selvalue1;

if (id!=0) {
window.opener.document.getElementById('div_gr_name').style.display = "inline";
}

else {
window.opener.document.getElementById('div_gr_name').style.display = "none";
}

window.close();
}




Google maps not full size unless you refresh page


I am using jquery mobile to create a webpage and I followed the tutorial found here: http://ift.tt/1N3qLfo Basically in a nutshell the video is about adding multiple markers on a google maps and then making sure all the markers are shown on the map at the same time.


MY problem is that when i load the page whether on my phone or my computer the map is not the correct size BUT the height and width of what the map SHOULD be is visible


Now if i refresh the page the map becomes full size.


I am just guessing but maybe the page is loading without finishing loading the google maps api BUT i am just guessing


Here is the code I used to create the map



function init() {
var mapDiv = document.getElementById("map_canvas3");
var mapOptions = {
center: new google.maps.LatLng(48.8582, 2.2945),
zoom: 13,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(mapDiv, mapOptions);

var locations = [];
locations.push ( {name:"Eifel Tower", latlng: new

google.maps.LatLng(48.8582, 2.2945)} );
locations.push ( {name:"The Louvre", latlng: new

google.maps.LatLng(48.8611, 2.3364)} );

var bounds = new google.maps.LatLngBounds ();
for (var i=0;i<locations.length;i++ ) {
var marker = new google.maps.Marker({position: locations[i].latlng,

map:map, title:locations[i].name});
bounds.extend (locations[i].latlng);

}
map.fitBounds (bounds);

}
window.onload = init;


Here is the html



<div data-role="page" id="mapEiffelTower" >

<div data-role="header">
<a href="#homePage" class="ui-btn-left ui-btn ui-icon-back ui-

btn-icon-notext ui-shadow ui-corner-all" data-role="button"

role="button">Back</a>
<img src="assets/Logo-01.png" id="logoHeader" alt="logo"/>
<!--<a href="index.html" class="ui-btn ui-icon-bars ui-btn-icon-

notext "></a>-->


</div> <!--end of header-->

<div data-role="content" >
<div id="map_canvas3">
</div>

</div> <!-- end of content -->



</div> <!-- end of mapEiffelTower page -->


And here is what it looks like for me now


!http://ift.tt/1LXES4n


Is there a line of code that I can enter to fix this problem?





Python code translation to javascript code


im having a trouble with translating a code


python code:



def leiaUuritav():
for linn in m.keys():
if m[linn]["uurida"]==1:return linn
return False

m={alglinn:{"kaugus":0, "kust":"", "uurida":1}}
uuritav=leiaUuritav()
while uuritav:
m[uuritav]["uurida"]=0
for uus in linnad[uuritav].keys():
if uus not in m.keys():
m[uus]={"kaugus": m[uuritav]["kaugus"]+linnad[uuritav][uus],
"kust": uuritav, "uurida":1}
m[uuritav]["uurida"]=0
uuritav=leiaUuritav()


to Javascript, i tried to translate it but the output is wrong, i know that i made some mistakes but i dont know where.



var alglinn="Tallinn";
function uuritav(){
for (city in lines.length){
if(lines[city]["uurida"]==1){return city;}
else{return false;}
}
}
var lines={alglinn:{"kaugus":0,"kust":"","uurida":1}};
console.log(lines);
var uuritav=uuritav();
while(uuritav){
lines[uuritav]["uurida"]=0;
for(uus in cities[uuritav]){
if(uus != lines[uuritav]){
m[uus]={"kaugus": m[uuritav]["kaugus"]+cities[uuritav][uus],
"kust": uuritav, "uurida":1}
}else{m[uuritav]["uurida"]=0}
uuritav=leiaUuritav();
}
}console.log(m);


I think that i made a mistakes from there, but im not sure



for(uus in cities[uuritav]){
if(uus != lines[uuritav]){
m[uus]={"kaugus": m[uuritav]["kaugus"]+cities[uuritav][uus],
"kust": uuritav, "uurida":1}
}else{m[uuritav]["uurida"]=0}
uuritav=leiaUuritav();


im trying to translate python to javascript but i dont know all the meaning so if somebody could help me with that?





ColdFusion Convert To Number


Pulling screen resolution with easy JavaScript Document Write. Using ColdFusion 9.0.


I can get proper numbers etc. But they are not "numbers" must be coming as text. As I cannot use as a number variable...


The code gets me: Available browser width: 1366 Available browser height: 728


And error of: The value document.write(screen.availWidth); cannot be converted to a number.


Any ideas of how to simply convert these to numbers I can work with... Without putting into a form and resubmitting through a form???


Thx



<cfset screenwidth = "<script>document.write(screen.width);</script>" >
<cfset screenheight = "<script>document.write(screen.height);</script>" >
<cfset availWidth = "<script>document.write(screen.availWidth);</script>" >
<cfset availHeight = "<script>document.write(screen.availHeight);</script>">

<cfoutput>
<div style="padding:15px;">
Available browser width: #availWidth#<br />
Available browser height: #availHeight#<br />
</div>
</cfoutput>

<cfset nw = availWidth * 2>

<cfset nh = availheight * 2>

<cfoutput>#nw# and #nh#</cfoutput>




Convert basic like function to ajax request


I have this very basic like function in my app but its not how i want it to be because every time i click the button it reloads the page, so i want to translate this codes to ajax request. but i dont know javascript or jquery.


in my Views.blade.php



<a href="{{ URL::route('like', array('id' => $posts->id)) }}" class="like">Like</a><br>


and my routes



Route::get('like{id}', array(
'uses' => 'LoginUsersController@like',
'as' => 'like'
));


and my controller



public function like($id)
{
$post = Post::findOrFail($id);
$post->likes++;
$post->save();

return Redirect::back();
}


im hoping that someone can show me how this is done in ajax request.





Node express GET route fails every other request when wildcard match


I have a router setup to accept any GET request that doesn't match the word "API" in it. This is for my single page app so that any bookmarked urls my javascript can't use its routes for.


The problem is every other time I refresh the page with a test url it fails.


URL: http://localhost:3000/my-test-url


First time hitting url, my index page loads.


Second time refreshing the page, error.


Cannot GET /my-test-url


Third time hitting refresh it works, and fourth time fails, and so on.



app.engine('html', cons.underscore);
app.set('view engine', 'html');
app.set('views', path.resolve(__dirname, '../client'));

// serve static content for the app from the "client" directory in the application directory
//express.static(path.join(__dirname, '../client')))
app.get(/^(?!.*\bapi\b).*$/ig, function(req, res) {
res.render('index');
});

app.listen(app.get('port'), function() {
console.log('Server up: http://localhost:' + app.get('port'));
});


Is there something that keeps the request open after it works the first time? The network tab in the browser shows the same URL each time but alternating with 404 error. Any suggestions are appreciated.





vendredi 27 février 2015

Convert object to string in Javascript


I know to that primitive wrappers are discouraged in Javascript. Does it apply to strings too ? I want to convert an object to string in javascript. I have done it new String(object). Is it good ? or is it better to do object + "" ?





How I Add string lo list of model in javascript


I am trying to add strings in javascript to list of string in the model but nothing returning



public class a
{
public a()
{
myFamilyHiddenDropDown= new List<string>();
}
public List<string> myFamilyHiddenDropDown { get; set; }
}


View



@Html.HiddenFor(x => x.myFamilyHiddenDropDown)
<input id="next" type="submit" value="send" />

$('#myFamilyHiddenDropDown').push("1");
$('#myFamilyHiddenDropDown').push("2");


Controller



public ActionResult a(a item)
{
}




JQuery Mobile ListView Not Refreshing - After initialization?


I've been at this for hours now and it's probably a very stupid mistake on my part, but for some reason I can't get this listview to refresh. I'm using JQuery Mobile (1.4.5), and I'm building a mobile web app. I've tried to initialize my list in my index.html like so:



<div data-role="content" id="ulListView">
<form id="newSearch"><input type="search" placeholder="Enter a written work" name="search-mini" id="search" data-mini="true" /></form>
<ul id="list" data-role="listview" data-inset="true"></ul>
</div>


I use my list to grab JSON and then append results to the list. I'm doing that like so [Javascript]



... foreach JSON loop up here [Tested working]
var listItem = '<li>' + entry.title + '</li>';
console.log("listItem " + listItem);
$("#list").html(listItem);
console.log("Appended " + '<li>' + entry.title + '</li>' + " to list");
});


$("#list").listview('refresh');


So far, I feel as if I've tried everything, from listview().listview('refresh'), using the "create" method, placing code inside or outside of the loop, using the div id instead of the ul id, various JSFiddle examples, posts here on StackOverflow, etc.


Once again, I'm sure it's just something stupid I forgot to look at, but I can't seem to find the issue! I'm very grateful for any help you guys can give me.


Thanks again! :)





replacing angular deep watcher


I have this data object called fulldata, which is an array of objects.



fulldata = [
{'key': 'abc', values: {.....},....},
{'key': 'efg', values: {.....},....},
{'key': 'hij', values: {.....},....},
.....]


this data is used to display charts using D3, and the keys of the objects represent the legend of the chart. Each time user enters a chart, the object is added to fulldata. Now if the values property of the objects changes(due to various user actions), i will have to re render the chart accordingly but if only the key changes, I just need to update the legend.


I tried deep watching the entire fulldata and change only the legend if key is changed based on a conditional. It works fine but the application is very slow because the values property is a very huge data set.


I tried making a separate function getKeys() to get all the keys and watch that function but its throwing me an error saying "Error:10 $digest() iterations reached. Aborting!"


Is there anything else I can try to accomplish what i want with a better performance than deep watching? If anyone has an idea or has encountered similar issue, please help. Thanks.





listen to phonegap background event in angular controller


I have a phonegap app and want to know when the app goes to background using pause (http://ift.tt/1C3H3BC) event. document.addEventListener("pause",yourCallbackFunction, false); However, I am looking for a way to make yourCallbackFunction trigger the $scope.cancel when the current route is /orders in the current scope and ignore otherwise. How can I achieve this? Appreciate any help.


Note: Device ready had already been fired by the time I come to this page in the application, so not needed to handle the deviceReady.


Code in context here:


html:



<!doctype html>
<head>
</head>
<body ng-app="myapp">
<!-- Add your site or application content here -->
<div ng-view=""></div>

<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular-resource.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular-cookies.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular-sanitize.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular-route.min.js"></script>

<script src="app/app.js"></script>

</body>
</html>


javascript in app.js:



angular.module('myapp', [ 'ngRoute' ])
.config(['$routeProvider', '$locationProvider', function ($routeProvider, $locationProvider) {
$routeProvider
.when('/', { templateUrl: 'login/login.html', controller: 'LoginCtrl' })
.when('/orders', { templateUrl: 'app/orders/orders.html', controller: 'OrdersCtrl' });
.otherwise({ redirectTo: '/' });
}]);

app.controller('OrdersCtrl', [ '$scope','$filter','$timeout', function($scope,$filter,$timeout,) {

$scope.date = new Date();
$scope.refresh = function(){
getOrders(); //Implemented elsewhere
}
$scope.cancel = function(){
cancelRefresh(); //Implemented elsewhere
}

}]);




DataTables issue with date field


Date field behaves little strange and gives different behaviour in Firefox and Chrome


In Chrome this is what date field looks like when i try to create a new record even though i enter date through date widget i still get error message http://ift.tt/1vG8cbG


Same with update field.Everything is populated except date field http://ift.tt/1DhEcAz


In mozilla firefox Date widget is altogether not displayed http://ift.tt/1vG8dMO


But yes date is displayed when trying to update a record but without date widget http://ift.tt/1DhEcQN


Here is my js code



var editor = new $.fn.dataTable.Editor( {
"ajax": "php/table.JKBINSR.php",
"table": "#JKBINSR",
"fields": [
{
"label": "ACCOUNT NO",
"name": "accntno",
"type": "text"
},
{
"label": "ACCOUNT TITLE",
"name": "accnttitle",
"type": "text"
},
{
"label": "ALIAS ACCOUNT NO",
"name": "alias",
"type": "select",
"ipOpts": [
{
"label": "CC",
"value": "CC"
},
{
"label": "CD",
"value": "CD"
},
{
"label": "OTL",
"value": "OTL"
},
{
"label": "CAR",
"value": "CAR"
},
{
"label": "OTHR",
"value": "OTHR"
}
]
},
{
"label": "DATE OF INSURANCE",
"name": "doi",
"type": "date",
"dateFormat": "mm-dd-y",
"dateImage": "images\/calender.png"
},
{
"label": "DATE OF EXPIRY",
"name": "doe",
"type": "date",
"dateFormat": "mm-dd-y",
"dateImage": "images\/calender.png"
},
{
"label": "AMOUNT",
"name": "amount",
"type": "text"
},
{
"label": "POLICY NO",
"name": "POLNO",
"type": "text"
},
{
"label": "REMARKS",
"name": "remark",
"type": "text"
}
]
} );


and the server code



Editor::inst( $db, 'JKBINSR', 'id' )
->fields(
Field::inst( 'accntno' )
->validator( 'Validate::minMaxLen', array( 'empty'=>false, 'min'=>16, 'max'=>16 ) ),
Field::inst( 'accnttitle' )
->validator( 'Validate::notEmpty' ),
Field::inst( 'alias' )
->validator( 'Validate::notEmpty' ),
Field::inst( 'doi' )
->validator( 'Validate::dateFormat', array( 'empty'=>false, 'format'=>'m-d-y' ) )
->getFormatter( 'Format::date_sql_to_format', 'm-d-y' )
->setFormatter( 'Format::date_format_to_sql', 'm-d-y' ),
Field::inst( 'doe' )
->validator( 'Validate::dateFormat', array( 'empty'=>false, 'format'=>'m-d-y' ) )
->getFormatter( 'Format::date_sql_to_format', 'm-d-y' )
->setFormatter( 'Format::date_format_to_sql', 'm-d-y' ),
Field::inst( 'amount' )
->validator( 'Validate::notEmpty' ),
Field::inst( 'POLNO' ),
Field::inst( 'remark' )
)

->process( $_POST )
->json();




Javascript Mocha Tests - Testing function expressions inside function expressions


I haven't used Mocha before, so I am a real novice when it comes to testing. However, I wanted to know if it's possible to test a function expression inside of a function expression? I know there are other posts on how you cannot access function expressions inside function declarations and so on.


So, is it possible to access function expressions inside function expressions and test with Mocha? For example, I have the following code:



var masterFunction = function() {

var siGogglin = functionDeclaration(putSomethingHere);

function functionDeclaration(code) {
var yoyo = [];

//some stuff I don't want you to see

return yoyo;
};
};


Is it possible to test the function functionDeclaration from the variable siGogglin within masterFunction? If so, could you give me an example of how it could be done?


Thanks.





indexOf keeps returning -1 Javascript


For the life me of I can't figure out why indexOf cant find the number in the array. It keeps returning -1. My goal is to ban a noun and put it into a ban array list, the list must be unique. So each element in the array must be different. Since I keep getting -1, my while loop is never executing.


Can anyone please explain to me what I'm doing wrong!



if( useA < 101 && totalAs < 5){
article1Num = 4; // A
noun1Num = [Math.floor(Math.random() * 5)];
//^^^ random number to try use

//--------
// Code to check if number is ban
alert("Test Noun1Num is " + noun1Num);
alert(bannedNounsTest.indexOf(noun1Num));
//^^^^ITS ALWAYS -1 !!!!!!! EVEN if there is a match!
while (bannedNounsTest.indexOf(parseInt(noun1Num)) >= 0 ) {
// ^^^searching the value of the current noun in ban, -1 if none
alert("In Loop and noun1Num is " + noun1Num);
noun1Num = [Math.floor(Math.random() * 5)];
// ^^looking for new number not in index while
}

//----------

bannedNounsTest.push(noun1Num); // put in ban list
totalAs++;




Div that flexible by content, but stretched by body tag (height)


I have div container, stretched vertically to 'body':



position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
padding-top: 51px; /* bootstrap menu in the top */


Inside it I have 2 DIVs on the one level.



  • The 1st (RED) must be stretched to browser's window. But it minimal height shouldn't be smaller, than the second's height.

  • The 2nd (BLACK) have 2 fixed heights (changing by JS).


What I need: enter image description here


Red and Black DIVs are placed on ONE level and have position: absolute.


DIV1 stretches to browser window. And it doesn't stop even when browsers height become smaller than BLACK div's height.


So I can't set DIV1 min-height to fixed value (in that case my problem could be solved).


Can I solve this problem WITHOUT using JS, but only with CSS+HTML?


UPDATE: jsFiddle example enter image description here





d3.js link seperation in tree layout


what I'm trying to do is to have a gap in between the links of a d3.js tree layout in which the node name fits (See image).


http://ift.tt/1vGWpK8


My graph looks similar to this example: http://ift.tt/1iEMxZg What I tried to change is the d.y in the projection.



var diagonal = d3.svg.diagonal.radial()
.projection(function(d) { return [d.y, d.x / 180 * Math.PI]; });


Which results in a change of both parent and child links. I'm sure there is a simple solution to this, but I don't get it right now.


Thanks for any help.





.remove() doesn't achieve desired effect


http://ift.tt/1BJgjqw


I'm trying to write a lightbox script, which can open images when clicked. As you can see in the fiddle, that part works. But closing the image by clicking the lightbox in order to execute the function .remove() doesn't quite work out. Why is that?



$(".discuss-entry img").each(function() {
var image = $(this);
var src = image.attr("src");
var windowWidth = $(window).width();
var windowHeight = $(window).height();
var imageWidth = image.outerWidth();
var imageHeight = image.outerHeight();

var left = ((windowWidth-imageWidth)/2)
var top = ((windowHeight-imageHeight)/2)

if(image.closest("a")[0]===undefined) {
image.on("click",function(){
$("<div class='lightbox'><img src='"+src+"' style='top: "+top+"px; left: "+left+"px' /></div>").appendTo("body");
});
$(".lightbox").on("click", "img", function() {
$(this).remove();
});
}
});




Difference between angularjs-nvd3-directives vs angular-nvd3


I would need any suggestion help or whatever. I am doing BI tools with new technologies and I am really interesting on them, even participating in one of these project. However, I would like to know a priori pros and cons


Links


http://ift.tt/1FE6pns


http://ift.tt/1oT6095


Thx





Compressing Google Maps Tiles


I'm looking for a way to compress the tiles from a Google Map (which I've already done) and then somehow replace the old tiles with the compressed tiles. This is how a tile looks in the code, for example:<img src="http://ift.tt/1Ey1fvl" draggable="false" style="width: 256px; height: 256px; -webkit-user-select: none; border: 0px; padding: 0px; margin: 0px;">


The reason I want to do this is because Google PageSpeed Insights keeps complaining:



Should Fix: Optimize images Properly formatting and compressing images can save many bytes of data. Optimize the following images to reduce their size by 245.2KiB (17% reduction).



(And all of the images it wants me to optimize are from the map.) I haven't been able to find anything googling around, so I don't even know if it's possible to do what I'm asking. Any ideas?





Object.assign recursive


Is there a version (planned or already implemented) of Object.assign that does deep merges instead of shallow ones?


I'm currently using merge.recursive from the merge package, but I would like my code to be as vanilla as possible.


Official sources preferred.





How to make certain objects hidden when CSS Sticky footer bar floats over


I have a mildly transparent sticky footer that I've taken from CSS bootstrap and I was wondering how to make specific properties within various css selectors have values that make them opacity=0 or similar, (i.e., so that they are hidden) when the transparent sticky footer floats over.


Is there a tried and tested method for this...? Perhaps a javascript method...?


If someone could point me in the right direction or give me a started for 10 that would be much appreciated.





horizontalscrollview click event not working


I implement HorizontalScrollView using this sample code and this . I have fetch data from server but i cant find way to implement onclick listener , How can I make horizontalscrollview click event ?



ArrayList<star> actorsList;

actorsList = new ArrayList<Actors>();
new JSONAsyncTask().execute("http://ift.tt/1tzZHvh");

centerLockHorizontalScrollview = (CenterLockHorizontalScrollview) findViewById(R.id.scrollView);
adapter = new ActorAdapter(getApplicationContext(), R.layout.row, actorsList);
centerLockHorizontalScrollview.setAdapter(MainActivity.this, adapter);


getView method :



@Override
public View getView(int position, View convertView, ViewGroup parent) {

View v = convertView;
if (v == null) {
holder = new ViewHolder();
v = vi.inflate(Resource, null);

/// //// /////

v.setTag(holder);
} else {
holder = (ViewHolder) v.getTag();
}
//// //// /////
return v;
}


CenterLockHorizontalScrollview class



public class CenterLockHorizontalScrollview extends HorizontalScrollView {
Context context;
int prevIndex = 0;

public CenterLockHorizontalScrollview(Context context, AttributeSet attrs) {
super(context, attrs);
this.context = context;
this.setSmoothScrollingEnabled(true);

}

public void setAdapter(Context context,ActorAdapter mAdapter) {

try {
fillViewWithAdapter(mAdapter);
} catch (ZeroChildException e) {

e.printStackTrace();
}
}

private void fillViewWithAdapter(ActorAdapter mAdapter)
throws ZeroChildException {
if (getChildCount() == 0) {
throw new ZeroChildException(
"CenterLockHorizontalScrollView must have one child");
}
if (getChildCount() == 0 || mAdapter == null)
return;

ViewGroup parent = (ViewGroup) getChildAt(0);

parent.removeAllViews();

for (int i = 0; i < mAdapter.getCount(); i++) {
parent.addView(mAdapter.getView(i, null, parent));
}
}



public void setCenter(int index) {

ViewGroup parent = (ViewGroup) getChildAt(0);

View preView = parent.getChildAt(prevIndex);
preView.setBackgroundColor(Color.parseColor("#64CBD8"));
android.widget.LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
lp.setMargins(5, 5, 5, 5);
preView.setLayoutParams(lp);

View view = parent.getChildAt(index);
view.setBackgroundColor(Color.RED);

int screenWidth = ((Activity) context).getWindowManager()
.getDefaultDisplay().getWidth();

int scrollX = (view.getLeft() - (screenWidth / 2))
+ (view.getWidth() / 2);
this.smoothScrollTo(scrollX, 0);
prevIndex = index;
}

}