i am using titanium 3.3 and alloy 1.4.1. the user should be able to send an email to all selected people (those people are in an array called "contacts") from his phone's address book.
the user can select and deselect names/emails from his addressbook in a listview (yellow background in the linked screenshot).
screenshot:
http://s30.postimg.org/rsa82u9qp/listview_checkbox.png
the correct info (email) is pulled from the address book and added to the contacts array when one checks the checkbox. so selecting via the checkbox works, but when one deselects the checkbox the email/item is not removed from the array. see the last log entry line:
Ti.API.info(JSON.stringify(contacts) + " this is matches array at the
end");
the email which has been selected before and is now deselected is still in the contacts array.
i also found this, but it doesnt help unfortunately.
http://developer.appcelerator.com/question/163878/loop-through-listview-to-grab-items-with-certain-properties#comment-206400
the code:
$.listview.addEventListener('itemclick',function(e){
var item = e.section.getItemAt(e.itemIndex);
if (item.properties.accessoryType == Ti.UI.LIST_ACCESSORY_TYPE_NONE) {
item.properties.accessoryType = Ti.UI.LIST_ACCESSORY_TYPE_CHECKMARK;
Ti.API.info(item.textEmail.text + " this is item.textEmail.textinside adding if");
var added = item.textEmail.text;
if (!_.contains(contacts,added)) {contacts.push(added);
}
Ti.API.info(JSON.stringify(added) + " item 1 added");
Ti.API.info(contacts + " this is matches array inside adding if");
}
else {
item.properties.accessoryType = Ti.UI.LIST_ACCESSORY_TYPE_NONE;
var removed = item.textEmail.text;
contacts = _.without(contacts, removed);
//contacts.splice(removed);
Ti.API.info(JSON.stringify(removed) + " item 2 removed");
Ti.API.info(JSON.stringify(contacts) + " this is contacts in removing if case");
}
e.section.updateItemAt(e.itemIndex, item);
Ti.API.info(JSON.stringify(contacts) + " this is matches array at the end");
});
any ideas what im doing wrong here?
First you should have a flat Array (contacts):
var contacts = new Array();
...
Then add/remove textEmail.text properties and search them properly
if (item.properties.accessoryType == Ti.UI.LIST_ACCESSORY_TYPE_NONE)
{
item.properties.accessoryType = Ti.UI.LIST_ACCESSORY_TYPE_CHECKMARK;
var i;
for(i in item.textEmail.text) //item.textEmail.text is Object
{
if(contacts.indexOf(item.textEmail.text[i]) === -1)
{
contacts.push(item.textEmail.text[i]);
Ti.API.info(item.textEmail.text[i] + " item added");
}
}
Ti.API.info(contacts + " this is matches array inside adding if");
}
else
{
item.properties.accessoryType = Ti.UI.LIST_ACCESSORY_TYPE_NONE;
var i;
for(i in item.textEmail.text)
{
var p = contacts.indexOf(item.textEmail.text[i]);
if(p !== -1)
{
contacts.splice(p,1);
Ti.API.info(item.textEmail.text[i] + " item removed");
}
}
Ti.API.info(contacts + " this is contacts in removing if case");
}
// if item.textEmail.text is equal to Email Person Object:
{ "work" : ["...", "..."], "home" : ["...", "..."] }
var i, j;
for(i in item.textEmail.text)
{
for(j = 0; j < item.textEmail.text[i].length; j++)
{
// Start Add Code
if(contacts.indexOf(item.textEmail.text[i][j]) === -1)
{
contacts.push(item.textEmail.text[i]);
} // End Add Code
// Start Remove Code
var p = contacts.indexOf(item.textEmail.text[i]);
if(p !== -1)
{
contacts.splice(p,1);
} // End Remove Code
}
}
Related
This might be less difficult than I'm making it out to be, but I'm trying to make a Discord.JS bot command, that will take however many arguments I have. For example: !randomize 1,2,3,4,5,6,7,8,9,10
And the bot would respond with something like: "I have chosen: 4,2,7,3,9!" Any help?
Current attempt: Not exactly sure what I'm doing.
function shuffleArray(array) {
for (var i = array.length - 1; i > 0; i--) {
var j = Math.floor(Math.random() * (i + 1));
var temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}`
`bot.on('message', async msg => {
if(msg.content === "!add") {
//message.member.user.tag
var msgArray = msg.content.split(" ");
var args = msgArray.slice(1);
var user = args[1];
//if(!args[1]) return msg.channel.send("Please specify an argument!");
if(nameList.includes(user)) {
msg.reply("You're already on the list.")
} else {
nameList.push(args[1]);
msg.channel.send(`${args[1]} has been added to the list!\n Current List:` + nameList);
}
}
if(msg.content === "!bonus") {
if(nameList.length === 0) {
msg.reply("Either the list is empty, or I'm not in the mood!");
} else {
shuffleArray(nameList);
var chosenOne = nameList.pop();
nameList = [];
msg.reply(chosenOne + ' has been chosen! Good luck!');
}
}
if(msg.content === "!list") {
if(nameList.length === 0) {
msg.channel.send("Either the list is empty, or I'm not in the mood!");
} else {
msg.channel.send('The current list:' + nameList);
}
});```
Here's some simple steps to select 5 random elements from an array...
Construct an array of possible selections. In this example I've used names for the first 10 letters of the alphabet. In your code, it'll be the command arguments or predefined nameList.
Make a new array to hold the elements picked.
At some point before #3, you should check to make sure the pool the user has provided is large enough to make 5 selections (Array.length).
Use a for loop to execute the next code multiple times.
Generate a random number representing the index of a selected element (Math.random(), Math.floor()/double NOT bitwise operator).
Push the selection into the array.
Remove the chosen element from the original pool (Array.splice()).
Return the results.
const pool = ['Albert', 'Bob', 'Charlie', 'David', 'Edward', 'Francis', 'George', 'Horacio', 'Ivan', 'Jim'];
const selected = [];
for (let i = 0; i < 5; i++) {
const num = ~~(Math.random() * pool.length);
selected.push(pool[num]);
pool.splice(num, 1);
}
console.log(`I have chosen: ${selected.join(', ')}`);
Take this example and manipulate it within your code to suit your purpose.
I'm trying to assign row object to an array from a check box click event. For this i have created a global array like below.
SelectedGrid: any[] = [];
At the moment of clicking it seems it going into the array, but when i checked the second checkbox 1st item is gone missing from the array.
May I know why that happens?
following is the function i call in check box click event.
public clickConditionRow(row, col, rowSelected) {
if (rowSelected.isChecked) {
this.SelectedGrid.push(rowSelected);
console.dir(this.SelectedGrid);
console.log(this.SelectedGrid.length);
} else {
console.log("Unselected ");
var toDel = this.SelectedGrid.indexOf(rowSelected);
this.SelectedGrid.splice(toDel);
console.dir(this.SelectedGrid);
}
if (!this.rootScope.$$phase) {
this.rootScope.$apply();
}
// for print the values
for (var y = 0; y < this.SelectedGrid.length; y++) {
console.log("Element " + y + " = " + this.SelectedGrid[y]);
console.dir(this.SelectedGrid[y]);
}
}
I cannot reproduce your bug (maybe you are overriding the array somewhere else?) but I see 2 potential problems and want to point them out:
Using indexOf with and object might not work and return -1 (see the code below)
splice(toDel) should be splice(toDel, 1) or it will delete all items staring from index toDel to the end of the array.
const a = { id: 1 }
const b = { id: 2 }
const list = [ a, b ]
// This returns 1
console.log(list.indexOf(b))
// This returns -1
console.log(list.indexOf({ id: 2 }))
I have this code in my simple flash. I want to save name and score in my quiz. My code reference in this website http://www.mollyjameson.com/blog/local-flash-game-leaderboard-tutorial/
I want to make my code in just one actionscript. But I didn't success do it.
var m_FlashCookie = SharedObject.getLocal("LeaderboardExample");
var EntryName:String ="nama kamu";
var EntryScore:String ="nilai";
const NUM_SCORES_SAVED:int = 10;
inputBoxScore.text = EntryScore;
inputBoxName.text = EntryName
var latest_score_object:Object = {
name: EntryName,
score: EntryScore
};
var arr:Array;
arr = m_FlashCookie.data.storedArray
if ( arr == null)
{
arr = new Array();
}
arr.push( latest_score_object );
arr.sortOn("score", Array.NUMERIC | Array.DESCENDING);
if ( arr.length < NUM_SCORES_SAVED )
{
arr.pop();
}
btnSave.addEventListener(MouseEvent.CLICK, saveData);
function saveData(event:Event):void
{
m_FlashCookie.data.arr = arr;
m_FlashCookie.flush();
}
var myHTMLL:String = "";
var total_stored_scores:int = arr.length;
btnLoad.addEventListener(MouseEvent.CLICK, loadData);
function loadData(event:Event):void
{
for (var i:int = 0; i < total_stored_scores; ++i)
{
// loop through every entry, every entry has a "name" and "score" field as that's what we save.
var leaderboard_entry:Object = arr[i];
// is this the last score that was just entered last gamestate?
if ( leaderboard_entry == latest_score_object )
{
myHTMLL += (i+1) + ". <b><font color=\"#0002E5\">"+ leaderboard_entry.name + " " + leaderboard_entry.score +"</font></b><br>";
}
else
{
myHTMLL += (i+1) + ". "+ leaderboard_entry.name + " " + leaderboard_entry.score +"<br>";
}
}
myHTML.text = myHTMLL;
}
Can anybody help me?
You're saving the array as data.arr but reading the array as data.storedArray. You need to make them the same.
In other words, you've written this:
m_FlashCookie.data.arr = arr;
And when you load:
arr = m_FlashCookie.data.storedArray;
This clearly doesn't make sense: data.storedArray is never set, so it will never have a value, so you will always end up with a new empty array.
You need to use the same property on the shared object data. For example:
m_FlashCookie.data.storedArray = arr;
m_FlashCookie.flush();
Looking at your code, there's a number of other issues:
The latest score is immediately removed because arr.length < NUM_SAVED_SCORES is going to be true from the start, since arr starts out empty, and it then calls arr.pop() which will remove the latest entry that was just added. So the array is always empty.
It adds the score immediately with arr.push(latest_score_object) instead of waiting until the user clicks save, so the value of the input texts don't matter at all -- the saved values will always be "nama kamu" and "nilai".
The following fixes all the issues mentioned:
var leaderboard = SharedObject.getLocal("leaderboard");
const MAX_SAVED_SCORES:int = 10;
inputBoxName.text = "nama kamu";
inputBoxScore.text = "nilai";
var entries:Array = leaderboard.data.entries || [];
var latestEntry:Object;
displayScores();
btnLoad.addEventListener(MouseEvent.CLICK, loadClick);
btnSave.addEventListener(MouseEvent.CLICK, saveClick);
function loadClick(e:MouseEvent):void {
displayScores();
}
function saveClick(e:MouseEvent):void {
saveLatestScore();
displayScores();
}
function saveLatestScore():void {
// create the latest entry based on input texts
latestEntry = {
name: inputBoxName.text,
score: inputBoxScore.text
};
// add the entry and sort by score, highest to lowest
entries.push(latestEntry);
entries.sortOn("score", Array.NUMERIC | Array.DESCENDING);
// if reached the limit, remove lowest score
if (entries.length > MAX_SAVED_SCORES) {
entries.pop();
}
// store new sorted entries to shared object
leaderboard.data.entries = entries;
leaderboard.flush();
}
function displayScores():void {
var myHTMLL:String = "";
for (var i:int = 0; i < entries.length; ++i) {
// loop through every entry, every entry has a "name" and "score" field as that's what we save.
var entry:Object = entries[i];
// is this the last score that was just entered last gamestate?
if (entry == latestEntry)
myHTMLL += (i+1) + ". <b><font color=\"#0002E5\">"+ entry.name + " " + entry.score +"</font></b><br/>";
else
myHTMLL += (i+1) + ". "+ entry.name + " " + entry.score +"<br/>";
}
myHTML.htmlText = myHTMLL;
}
I have been using this java code to call a random html page from a list of 49 on a set timer (or upon page refresh). I would like to convert it so that a cookie - or something else - saves the pages that have already been shown so that upon refresh the user always receives a new page, until the list is finished, at which point the cookie is emptied/deleted.
I found this code for a cookie image array. Could I use it with this? A variant of this also appears here. Apologies, my coding is pretty poor. Any advice appreciated:
<script type="text/javascript">
var sites = [
"name1.html",
"name2.html",
"name3.html",
"name...etc.html",
"name49.html",
]
$(document).ready(function() {
newPage();
});
function newPage()
{
setTimeout(newPage, 60000);
var min = 0;
var max = 48;
var num = Math.floor(Math.random() * (max - min + 1)) + min;
$('#target').attr('src',sites[num]);
}
</script>
var numSites = 49;
var seen = new Array(numSites);
$(document).ready(function() {
var cookie = unescape(getCookie("seen"));
seen = cookie ? cookie.split(',') : seen;
setTimeout(gotoNext, 60000);
});
function gotoNext() {
var num = getRandom();
var count = 0;
while (seen[num] == 1) {
num++;
if (num >= numSites) {
num = 0;
count++;
if (count > 1) {
resetSeen();
num = getRandom();
}
}
}
seen[num] = 1;
setCookie("seen", escape(seen.join(',')), 365);
window.location = "name" + num + ".html";
}
function getCookie(cname) {
var name = cname + "=";
var ca = document.cookie.split(';');
for(var i=0; i<ca.length; i++) {
var c = ca[i].trim();
if (c.indexOf(name)==0) return c.substring(name.length, c.length);
}
return "";
}
function setCookie(cname, cvalue, exdays) {
var d = new Date();
d.setTime(d.getTime() + (exdays*24*60*60*1000));
var expires = "expires=" + d.toGMTString();
document.cookie = cname + "=" + cvalue + "; " + expires;
}
function resetSeen() {
for (var i=0; i<numSites; i++) {
seen[i] = "";
}
}
function getRandom() {
return Math.ceil(Math.random() * numSites);
}
It looks like you're using jQuery so I'll recommend using a jquery plugin for managing cookies much more neatly.
Copy & paste the contents of this URL to a new js file on your server and include it after the jquery file: https://raw.githubusercontent.com/carhartl/jquery-cookie/master/jquery.cookie.js
Or you could possibly use the get/set cookie functions from the other answer you mention.
The main thing to remember is that the cookie is stored as a string so you'll be join()ing and split()ing the array.
The other thing to note is that because we want a random item from the items we haven't visited yet it's more efficient to keep track of those rather than the ones we have visited.
What this means is we always choose a random item from what's left instead of looping over everything and checking each time if we've been there already as that would get very inefficient.
var sites = [ 'name1.html', 'name2.html', 'name3.html', ...etc... ],
unvisited = sites.slice(0); // .slice(0) clones the array
// if the cookie has a value then make it into the unvisited array
if ( $.cookie( 'unvisited' ) )
unvisited = $.cookie( 'unvisited' ).split( ',' );
$(document).ready(function() {
newPage();
});
function newPage() {
setTimeout( newPage, 60000 );
// check if the unvisited array needs resetting
if ( unvisited.length == 0 ) {
unvisited = sites.slice(0);
$.removeCookie( 'unvisited' );
}
// get a new index from the unvisited array
var num = Math.floor( Math.random() * unvisited.length );
// remove the item from the array and save the cookie
var site = unvisited.splice( num, 1 )[ 0 ];
// save the unvisited array minus the site we just spliced out
$.cookie( 'unvisited', unvisited.join( ',' ) );
$( '#target' ).attr( 'src', site );
}
How can we make checkboxes remain checked when the page is refreshed in a Sencha ExtJS 3.3.0 GridPanel?
I have a GridPanel which displays some information with checkboxes. When the page is refreshed, the checkbox should still be checked.
Any suggestions, ideas, or code samples?
Had the same problem and I fixed it in such way - manually save id's of records that I show in cookies. Solution is not beautiful, but works for me.
store.on({
'beforeload': function () {
var checkeditems = [];
for(var i=0;i<gridResources.selModel.selected.length;i++)
{ checkeditems.push(grid.selModel.selected.items[i].data.ID);
}
if(checkeditems.length>0)
setCookie("RDCHECKBOXES", checkeditems.join("|"));
},
'load': function () {
if (getCookie("RDCHECKBOXES")) {
var checkeditems = getCookie("RDCHECKBOXES").split("|");
for (var i = 0; i<gridResources.store.data.items.length && checkeditems.length>0; i++) {
for(var j=0;j<checkeditems.length;j++) {
if (gridResources.store.data.items[i].data.ID == checkeditems[j]) {
gridResources.selModel.select(gridResources.store.data.items[i], true);
checkeditems.splice(j, 1);
break;
}
}
}
}
}
});
Here are code for functions getCookie() and setCookie():
// Example:
// setCookie("foo", "bar", "Mon, 01-Jan-2001 00:00:00 GMT", "/");
function setCookie (name, value, expires, path, domain, secure) {
document.cookie = name + "=" + escape(value) +
((expires) ? "; expires=" + expires : "") +
((path) ? "; path=" + path : "") +
((domain) ? "; domain=" + domain : "") +
((secure) ? "; secure" : "");
}
// Example:
// myVar = getCookie("foo");
function getCookie(name) {
var cookie = " " + document.cookie;
var search = " " + name + "=";
var setStr = null;
var offset = 0;
var end = 0;
if (cookie.length > 0) {
offset = cookie.indexOf(search);
if (offset != -1) {
offset += search.length;
end = cookie.indexOf(";", offset)
if (end == -1) {
end = cookie.length;
}
setStr = unescape(cookie.substring(offset, end));
}
}
return(setStr);
}
Have you looked at all at the ExtJS documentation or the included samples? There's a sample grid using the CheckColumn extension that does exactly what you ask.
In the example linked, take note that the checkbox column is linked to a boolean record field
// in your record
{name: 'indoor', type: 'bool'}
and represented in the grid's column model by a CheckColumn:
// in the grid's column model
xtype: 'checkcolumn',
header: 'Indoor?',
dataIndex: 'indoor',
width: 55
This way, when boolean data comes into the store from the server in JSON or XML, the values are represented as checkboxes in the grid. As long as you write your changes to the server, your checkbox boolean values will be preserved.