How to implement "NSUserDefaults" functionality equivalent in Corona? - iphone

All I want is to save my user(player) highscores, and this information to persist between application(game) launches in Corona SDK (Lua). I do want it to work on iOS and Android nicely. My highscores data is actually two lua tables containing numbers.
What's the correct and easiest way to do it?

You may save the scores into a table, and then serialize it into json format text file.
local json=require("json")
local savefile="scores.json"
scores=
{
{
level=1,
status=0,
highscore=0,
},
{
level=2,
status=0,
highscore=0,
},
}
function getScore(filename, base)
-- set default base dir if none specified
if not base then
base = system.DocumentsDirectory
end
-- create a file path for corona i/o
local path = system.pathForFile(filename, base)
-- will hold contents of file
local contents
-- io.open opens a file at path. returns nil if no file found
local file = io.open(path, "r")
local scores
if file then
-- read all contents of file into a string
contents = file:read( "*a" )
if content ~= nil then
scores=json.decode(content)
end
io.close(file) -- close the file after using it
end
return scores
end
function saveScore(filename, base)
-- set default base dir if none specified
if not base then
base = system.DocumentsDirectory
end
-- create a file path for corona i/o
local path = system.pathForFile(filename, base)
-- io.open opens a file at path. returns nil if no file found
local file = io.open(path, "wb")
if file then
-- write all contents of file into a string
file:write(json.encode(scores))
io.close(file) -- close the file after using it
end
end
The global scores variable can be manipulated like a normal table, and when you want to load or save the scores table you can call the functions above.

Related

Accept a specific type of file Matlab

I have a GUI using a Browe Button to search a file :
function Browse(app, event)
FileName,FilePath ]= uigetfile();
ExPath = fullfile(FilePath, FileName);
app.FileTextArea.Value = ExPath;
end
And i save the file Path in a Text Area.
I have another button that start a matlab script with the file path as parameter and so i would like to accept only a certain type of file (.ctm which is my own type of file) if possible like this :
if file is .ctm
do something
else
print('a .ctm file is needed')
Thanks for helping
There are two things you can do:
Display only the files with a certain extension with uigetfile()
[fileName, dataDir] = uigetfile('*.ctm', 'Select a *.ctm file', yourDefaultPth);
Verify that selected file has a .ctm extension
[data.dir,data.fileName,data.ext] = fileparts(fullfile(dataDir, fileName)); % dataDir and fileName from pt. 1
if strcmp(data.ext, '.ctm')
% do something
else
print('a .ctm file is needed')
end
Keep in mind that neither of the two will verify that the content of the file is the one you're expecting and if someone will manually modify extension of the file, your program will most likely crash. It's good for a start but if you want to do a more reliable check, you should verify that the content of the file is correct, not its extension.

Get a New Directory Name from Mkdir

I'm running a code in Maltab the creates directories through mkdir. Problem is, I'm creating their name by some logic on run-time, so I don't know what the dir name would be. I know I can first create the name as
string dirName = nameLogic();
mkdir(dirName);
but I would like to know the dirName from the created directory itself. Naivly, that would be
[outputdirName] = mkdir(fuzzylogicdirName);
I should add that I'm not religiously attached to mkdir, and another yet more suitable method might be in place.
Thanks
I might get you wrong. In any case what mkdir does is just creating a folder, hence the folder name must be known (possibly determined at run-time) before the call.
A structure like
folderName = folderNameLogic([run_time_variables]);
% # folderName = 'something_run_time_variables(1)_and_run_time_variables(2)'
status = mkdir(folderName)
if status == 1
disp(['success in creating folder ' folderName]);
else
disp(['ERROR in creating folder ' folderName]);
end
is thus necessary.
Clearly nothing prevents you from wrapping the call a function of yours returning the folder name. E.g.
function [folderName] = mkdir_retname(folderName)
status = mkdir(folderName);
if status == 0
folderName = '0';
end
end

Check for Valid Image using getFilesAsync()

Using WinJS, while looping through a directory, how to retrieve only images in that particular directory and ignoring any other file extension, including the DoubleDots .. and the SingleDot . etc?
Something like:
var dir = Windows.Storage.KnownFolders.picturesLibrary;
dir.getFilesAsync().done(function (filesFound) {
for(var i=0; i < filesFound.length; i++){}
if(filesFound[i] IS_REALLY_AN_IMAGE_(jpeg,jpg,png,gif Only)){
//Retrieve it now!
}else{
//Escape it.
}
}})
Instead of trying to process pathnames, it will work much better to use a file query, which lets the file system do the search/filtering for you. A query also allows you to listen for the query's contentschanged event if you want to dynamically track the folder contents rather than explicitly enumerating again.
A query is created via StorageFolder.createFileQuery, createFolderQuery, or other variants. In your particular case, where you want to filter by file types, you can use createFileQueryWithOptions. This function takes a QueryOptions object which you can initialize with an array of file types. For example:
var picturesLibrary = Windows.Storage.KnownFolders.picturesLibrary;
var options = new Windows.Storage.Search.QueryOptions(
Windows.Storage.Search.CommonFileQuery.orderByName, [".jpg", ".jpeg", ".png", ".gif"]);
//Could also use orderByDate instead of orderByName
if (picturesLibrary.areQueryOptionsSupported(options)) {
var query = picturesLibrary.createFileQueryWithOptions(options);
showResults(query.getFilesAsync());
}
where showResults is some function that takes the promise from query.getFilesAsync and iterates as needed.
I go into this subject at length in Chapter 11 of my free ebook, Programming Windows Store Apps with HTML, CSS, and JavaScript, 2nd Edition, in the section "Folders and Folder Queries". Also refer to the Programmatic file search sample, as I do in the book.
When you want to display the image files, be sure to use thumbnails instead of loading the whole image (images are typically much larger than a display). That is, for each StorageFile, call its getThumbnailAsync or getScaledImageAsThumbnailAsync method. Pass the resulting thumbnail (blob) to URL.createObjectURL which returns a URL you can assign to an img.src attribute. Or you can use a WinJS.UI.ListView control, but that's another topic altogether (see Chapter 7 of my book).

Images upload form laravel

My image upload doesn't work:
Controller:
if (Input::hasFile('image')) {
$bikecreate->image = Input::file('image');
$destinationPath = public_path().'/upload/';
$filename = str_random(6) . '_' . $bikecreate->users_id ;
Input::file('image')->move($destinationPath, $filename);
}
Form:
{{ Form::file('image', array('files' => true)) }}
After accepting form everything looks ok, but after the end of upload, filepath in database show .tmp/file at my server.
Without seeing the rest of your code it's hard to see exactly what's going on but my guess is that your line $bikecreate->image = Input::file('image') is where you're setting the file's path for the database. You've actually set the UploadedFile instance as the image property on $bikecreate there, which, presumably, when serialised to something to put into the database gets __toString() called on it.
__toString() called on a File instance (which itself inherits __toString from SPLFileInfo returns the path to that file. So you'd think you're get the uploaded filename, but actually because an uploaded file is actually a temporary file in PHP, you get the temporary name.
Try changing that line to the following:
$bikecreate->image = Input::file('image')->getClientOriginalName();
This retrieves the actual original name of the uploaded file, not the temporary path given to it by PHP.
It goes without saying that this is only pertinent to UploadedFiles, normal files should just be able to be __toStringed to get the path to the file, although you'll notice that it would be the full path and not the basename. To get that, use getBaseName().

Mirth: How to get source file directory from file reader channel

I have a file reader channel picking up an xml document. By default, a file reader channel populates the 'originalFilename' in the channel map, which ony gives me the name of the file, not the full path. Is there any way to get the full path, withouth having to hard code something?
You can get any of the Source reader properties like this:
var sourceFolder = Packages.com.mirth.connect.server.controllers.ChannelController.getInstance().getDeployedChannelById(channelId).getSourceConnector().getProperties().getProperty('host');
I put it up in the Mirth forums with a list of the other properties you can access
http://www.mirthcorp.com/community/forums/showthread.php?t=2210
You could put the directory in a channel deploy script:
globalChannelMap.put("pickupDirectory", "/Mirth/inbox");
then use that map in both your source connector:
${pickupDirectory}
and in another channel script:
function getFileLastModified(fileName) {
var directory = globalChannelMap.get("pickupDirectory").toString();
var fullPath = directory + "/" + fileName;
var file = Packages.java.io.File(fullPath);
var formatter = new Packages.java.text.SimpleDateFormat("yyyyMMddhhmmss");
formatter.setTimeZone(Packages.java.util.TimeZone.getTimeZone("UTC"));
return formatter.format(file.lastModified());
};
Unfortunately, there is no variable or method for retrieving the file's full path. Of course, you probably already know the path, since you would have had to provide it in the Directory field. I experimented with using the preprocessor to store the path in a channel variable, but the Directory field is unable to reference variables. Thus, you're stuck having to hard code the full path everywhere you need it.