vendredi 31 juillet 2015

Reading multiple files into a single file in MATLAB

I'm attempting to pull data in from 25 different files and combine them into one single file. Each of the files is in a different directory and I've been able to create the loop that goes through the directories to pull the specific file in. However, within that file there are 6 doubles I want to read in and I want each of these doubles numbered accordingly (1, 2, 3,...25). What is the best way to do this without brute force copy and pasting the code 25 times, if there is such a way? Everything I've seen is that this is considered dynamically creating variables and not a good practice. The unfortunate thing is I then need to do that 21 more times.

Example code typed in:

for nsub=1:numel(subdirectories)
    %loading file into workspace
%for N=1:length(subdirectories) % 25 subdirectories
for i=1:25

where I want day{1} to be the first day, day{2} to be the second and so forth. Day in this case is a 21x6 double. Ideally, I'd like to save this as a big .mat file that I can call the individual pieces of the arrays to perform statistical analysis (mean, std dev, MLR, SLR, etc) on them. Thanks.

Will This copy file method work in android studio?

Using android studio

will the following code work to copy your call logs to your sd card root?

         public void buttonOnClick(View v) {
// do something when the button is clicked
        Button button=(Button) v;
         File from = new File(Environment.getInternalStorage().getAbsolutePath()+"/data/data/");
         File to = new File(Environment.getExternalStorage().getAbsolutePath()+"/backup/contacts2.db");

images and filepaths in a .jar

im making a bomberman game and im close to getting it done. The game works ok when i run it in netbeans. I can run the game in any PC that has netbeans in it. But when i build the project into a .jar so i can make it run without netbeans, none of my files and images are being correctly loaded and they give null pointer exception. the way i'm managing the image (and file) paths in my program is the following:

IMG = new File( getClass().getClassLoader().getResource("pic/img.gif").getPath() ) );

the getClass().getClassLoader().getResource("pic/img.gif").getPath() gives me the current path of the image despite of the computer im working on, but this only works when i run the game with netbeans and not when i run it form the .jar after building the project. Let me give you an example:

in the main menu of my game i have an option that shows the instructions of the game. it opens a window with a text box, and then it opens a file which contain the instructions, writing its content in the text box. When i run the game from netbeans it works perfectly, but when i run the .jar it fails to open the file. here are the strings that returns the getResource function:

if i run from netbeans: /C:/Users/x/Documents/NetBeansProjects/Bomberman4.0/build/classes/windows/Instructions.txt

but if i run the .jar it returns: file:/C:/Users/x/Documents/NetBeansProjects/Bomberman4.0/dist/Bomberman4.0.jar!/windows/Instructions.txt

the first one works, it show the instructions, but the second one doesn't. I tried to delete the "file:" part of the second path, but it still doesn't work. so here comes the question:

Why isn't the game loading files from the .jar? What do i have to do to make a game with files and images run from a single .jar so i can run it in any computer?

And as a side question: when i build a executable Jar File, it contains all the images and files that the program needs, so i only need that .jar file to run the program? or do i also need the whole project folder (in which all the images and files are contained) to run the game? thank you in advance.

Android - Not being able to retrieve file from external Share Button

I'm trying to retrieve the file that the user wants to share via, for example, the Photo Gallery App. So, when they tap on the share button, and select my application, I'm retrieving the File's Uri through the method Uri fileUri = (Uri) getIntent().getExtras().get(Intent.EXTRA_STREAM);. This works fine.

Then, I try to get the File whose Uri is the one I have. I do that this way:

File file = new File(fileUri.getPath());

But, afterwards, when I try to open it and read it, I get the ENOENT (No such file or directory). Furthermore, when I execute the file.exists() method, it returns false. So I don't know where the problem is.

Here is the code:

Uri fileUri = (Uri) getIntent().getExtras().get(Intent.EXTRA_STREAM);
File file = new File(fileUri.getPath());

FileInputStream imageInFile = new FileInputStream(file);

What am I doing wrong?

Java: Dissecting a string

I have content inside of a file and I am trying to dissect certain portions of said content.

Inside of file: FNAME:John:LNAME:Doe:AGE:40:DOB:July 31, 1975

This is all on one line

Now, I am wanting to only get as output:

  • John Doe 40 July 31, 1975

The current output is:

  • John:LNAME:DOE:AGE:40:DOB:July 31, 1975

I've tried using:

System.out.println(line.substring(line.indexOf(":") + 1, line.lastIndexOf(":")));

but that only cuts out "FNAME:" and nothing else.

I hope this is explained in enough detail and I apologize if it is not. Thank you for your help.


Scanner cfg_reader = new Scanner(cfg_file);

        while (cfg_reader.hasNext()) {
            String line =;
            System.out.println(line.substring(line.indexOf(":") + 1, line.lastIndexOf(":")));

Keep in mind, this is my current code and what I've provided you above my code selection is different from what this is.

Apache-Spark passing files to the master node

I've already written code in python to implement binary classification, and I want to parallelize this classification process based on different data files in my local computer using Apache-Spark. I have already done the following steps:

  1. I've written the whole project containing 4 python files: "" (used for running my classification application), "" (used for binary classification), "" (used for load the learning parameters for classification) and "" (used for pre-processing data). The project also uses the dependency files: "tokenizer.perl" (used in preprocessing part) and "nonbreaking_prefixes/nonbreaking_prefix.en" (also used in preprocessing part).

  2. The main part of my script file "" is defined as follow, ### Initialize the Spark conf = SparkConf().setAppName("ruofan").setMaster("local") sc = SparkContext(conf = conf, pyFiles=[All python files in my project as well as "nonbreaking_prefix.en" and "tokenizer.perl"])

    ### Read data directory from S3 storage, and create RDD datafile = sc.wholeTextFiles("s3n://bucket/data_dir")

    ### Sent the application on each of the slave node datafile.foreach(lambda (path, content): classifier(path, content))

However, When I run my script "", it seems like cannot find the file "nonbreaking_prefix.en". The following is the error I got:

ERROR: No abbreviations files found in /tmp/spark-f035270e-e267-4d71-9bf1-8c42ca2097ee/userFiles-88093e1a-6096-4592-8a71-be5548a4f8ae/nonbreaking_prefixes

But I actually passed the file "nonbreaking_prefix.en" to the master node, and I have no ideas on the error. I would really appreciate if anyone helps me fix the problem.

How to handle File download dialog/popup in IE browser USING SELENIUM and C#

I have page which downloads a file which shows a dialog on the bottom with OPEN SAVE CANCEL options, how can I click those options ? I am using IE browser, I saw some solutions using third party AutoIt, Robot class, but I am looking with Selenium and C# only. Attached is the image of what I am talking.. Any idea how can we do this ?enter image description here

Appending to an array vs writing to file

I'm writing a program which takes in a byte array of potentially millions of bytes, reads each one from a BinaryArrayInputStream, and if the byte is not "printable" (ascii 32-126), that byte is encoded in a certain way and written to a BinaryArrayOutputStream instance; if the byte is "printable" it is directly written to that same BinaryArrayOutputStream instance. So from a broader view I am taking in a byte array, and getting back a similar byte array except certain characters have been encoded.

My question is: would it be faster to write my data out to a file or to continuously be writing to this OutputStream?

Terminal - run 'file' (file type) for the whole directory

I'm a beginner in the terminal and bash language, so please be gentle and answer thoroughly. :)

I'm using Cygwin terminal.

I'm using the file command, which returns the file type, like:

$ file myfile1
myfile1: HTML document, ASCII text

Now, I have a directory called test, and I want to check the type of all files in it.

My endeavors:

I checked in the man page for file (man file), and I could see in the examples that you could type the names of all files after the command and it gives the types of all, like:

$ file myfile{1,2,3}
myfile1: HTML document, ASCII text
myfile2: gzip compressed data
myfile3: HTML document, ASCII text

But my files' names are random, so there's no specific pattern to follow. I tried using the for loop, which I think is going to be the answer, but this didn't work:

$ for f in ls; do file $f; done
ls: cannot open `ls' (No such file or directory)

$ for f in ./; do file $f; done
./: directory

Any ideas?

Shell - Save file with extension?

The following is the code I have (and compiles), however, it saves the file without any extension. How can I save the file as a ".plist" ?

do shell script "echo '{ Filter = { Bundles = ( \"'" & proj & "'\" ); }; }' >> ~/Desktop/gametocheat/" & proj & " "

"proj" is a string. - If this looks a bit weird is because im doing it on Applescript, but is pretty much the same code as shell.


How to read a Binary Document from Couchbase - JavaSDK API

I am trying to insert and retrieve small files in couchbase, insertion is successful but when I try to fetch the content and write it to a file am getting below error.

    BinaryDocument responsefromDB = bucket.get("KESAVAN", BinaryDocument.class);
    try {
        FileOutputStream ostream = new FileOutputStream("C:\\Satz\\Test - Copy\\Output.txt");
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
    } catch (IOException e) {
        // TODO Auto-generated catch block

Error : Exception in thread "main" java.lang.UnsupportedOperationException: direct buffer at at at at com.util.task.CouchbaseClient.main(

Show the only image in the folder

Simple question that I'm not sure how to ask google:

If I have a folder for each user on my website, and each folder has only 1 jpg picture in it ( along with other different, currently unimportant files ),

Is there an easy way to display that img without actually specifying the name of the jpg file? eg.

<img src=";

Or would I have to use php scandir on the directory each time to get the specific name?

Sorry if duplicate, I wasn't able to find an answer elsewhere and wasn't sure how to actually search this. Thanks.

Writing To A File With Multiple Streams C#

I am trying to download a large file (<1GB) from one server to another using HTTP. To do this I am making HTTP range requests in parallel. This lets me download the file in parallel.

When saving to disk I am taking each response stream, opening the same file as a file stream, seeking to the range I want and then writing.

However I find that all but one of my response streams times out. It looks like the disk I/O cannot keep up with the network I/O. However, if I do the same thing but have each thread write to a separate file it works fine.

For reference, here is my code writing to the same file:

int numberOfStreams = 4;
List<Tuple<int, int>> ranges = new List<Tuple<int, int>>();
string fileName = @"C:\MyCoolFile.txt";
//List populated here
Parallel.For(0, numberOfStreams, (index, state) =>
        HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create("Some URL");
        using(Stream responseStream = webRequest.GetResponse().GetResponseStream())
            using (FileStream fileStream = File.Open(fileName, FileMode.OpenOrCreate, FileAccess.Write, FileShare.Write))
                fileStream.Seek(ranges[index].Item1, SeekOrigin.Begin);
                byte[] buffer = new byte[64 * 1024];
                int bytesRead;
                while ((bytesRead = responseStream.Read(buffer, 0, buffer.Length)) > 0)
                    if (state.IsStopped)
                    fileStream.Write(buffer, 0, bytesRead);
    catch (Exception e)
        exception = e;

And here is the code writing to multiple files:

int numberOfStreams = 4;
List<Tuple<int, int>> ranges = new List<Tuple<int, int>>();
string fileName = @"C:\MyCoolFile.txt";
//List populated here
Parallel.For(0, numberOfStreams, (index, state) =>
        HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create("Some URL");
        using(Stream responseStream = webRequest.GetResponse().GetResponseStream())
            using (FileStream fileStream = File.Open(fileName + "." + index + ".tmp", FileMode.OpenOrCreate, FileAccess.Write, FileShare.Write))
                fileStream.Seek(ranges[index].Item1, SeekOrigin.Begin);
                byte[] buffer = new byte[64 * 1024];
                int bytesRead;
                while ((bytesRead = responseStream.Read(buffer, 0, buffer.Length)) > 0)
                    if (state.IsStopped)
                    fileStream.Write(buffer, 0, bytesRead);
    catch (Exception e)
        exception = e;

My question is this, is there some additional checks/actions that C#/Windows takes when writing to a single file from multiple threads that would cause the file I/O to be slower than when writing to multiple files? All disk operations should be bound by the disk speed right? Can anyone explain this behavior?

Thanks in advance!

javascript - locally generating and downloading a huge file

I have the following JavaScript code which downloads a file, which I can't help but think I got from here: Create a file in memory for user to download, not through server

However, this function crashes in Chrome because I'm trying to download too much data (it might be a couple of MB, but it seems to work OK for downloads under 1 MB. I haven't done many metrics on it).

I really like this function because it lets me create a string from an existing huge JavaScript variable and immediately download it.

So my two questions then are:

A) Whats causing the crash? Is it the size of the string text or is there something in this function? I read that 60MB strings were possible in JavaScript and I don't think I'm quite reaching that.

B) If it is this function, is there another simple way to download some huge-ish file that allows me to generate the content locally via JavaScript?

function download(filename, text) {
  var element = document.createElement('a');
  element.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(text));
  element.setAttribute('download', filename); = 'none';

Having trouble with adding wav file to exe

I need to import a .wav file, but not from a directory. It has to be in the exe file. I added an existing item by projecets-> add existing item After that I saw the name of the file at the references tab under the solution explorer. So the question is , is this the right way to import a file inside of the exe file, and if it is , how can I add that file into the code tab.

 System.Media.SoundPlayer player2 = new System.Media.SoundPlayer(beep2.wav);


I tried this one and get "beep 2 does not exist" problem

Any help?

MessageBox.Show("Thanks :) ");

Continue executing a program, after end of ssh

I have a script that runs an executable with 1000 different parameters (one per execution). This can take many hours. I run this in the lab computer. Now, I do this via ssh, from my home computer. Can I do an ssh, start executing the script, logout, but somehow allow the script to continue executing?

I mean the lab pc will still be open and I do not care about the stdout of the program. The interesting results will be written into a file, which I can check when I login again.

I tried to do so, but the script will stop executing as soon as I logout.

Reading data from CSV file using JavaScript and using it

I need to analyze data using JS, and display it on an HTML page. The data source is a CSV file, so I used the following code for extracting the data:

        var data;


        function handleFileSelect(evt) {
            var file =[0];

            Papa.parse(file, {
                header: true,
                dynamicTyping: true,
                complete: function(results) {
                data = results;

When I press F12 in Chrome - with breakpoint on the row following "data=results", I can see that "data" is an array with 50 objects - each contains a whole row from the CSV in a Key-Value format, where the "Key" is the header from the file and the "value" is the content.

The problem is that I can't access the data. For example, I tried writing:

var x = document.getElementById("one"); x.innerHTML=data[1].Date;

but there's an error on the second line... So - Does anyone can help me with how can I get access to the "data" variable? in which part of the code I need to insert the lines that tries to get the data?

Spotting unique difference between two files in Solaris8

Would someone be kind enough to help me to do the following,

I have two files in a location on a Solaris8 box. I want to compare the two files and spot the unique difference between them(lines) and pipe them to another file.

I tried the following method listed in one of the topics, but it didn't work out in Solaris8,

diff -a --suppress-common-lines -y file1.txt file2.txt >> file3.txt

Reading uploaded text file contents in html

I want to show contents of uploaded file in html, I can just upload a text file. My example.html:

<html xmlns="" >
Please specify a file, or a set of files:<br>
<input type="file" name="datafile" size="40">

<textarea id="2" name="y" style="width:400px;height:150px;"></textarea>

How can I show contents of any uploaded text file in textarea shown below? ScreenShot

add_options_page() & __FILE__ issue

When I use add_options_page( $page_title, $menu_title, $capability, $menu_slug, $function); Here when I add __FILE__ for $menu_slug as add_options_page( $page_title, $menu_title, $capability, __FILE__, $function); then I get only folder name and file name in the menu slug, like this http://localhost/wp-site-name/wp-admin/options-general.php?page=folder-name/file-name.php where __FILE__ represents the full path. How it happens?

FileInput content loaded from server

I use bootstrap file input plugin ( link : ) to upload thumbs.

i create a page to add a new product info with a thumb and send it to database. Now i want to update a product and change its thumb.

So my question is :

Is there any way to set thumb ( server side ) into file input ? it helps me to decide if i want to update thumb or not when i click to update button.

NB :I use php for .

Thank you.

How to fetch information randomly from files in C++?

I am creating a quiz game in C++. So, the main requirement is that questions should be fetched randomly from file each time program runs. So, How can I do this in C++? Consider following two simple programs.


#include <iostream>
#include <fstream>
#include <string>
using std::cout;
using std::ofstream;
using std::string;
int main()
    ofstream fout("test.txt");
        cout<<"Error in opening file";
    string s[3];
    s[0]="C++ provides object oriented string handling";
    s[1]="C++ provides object oriented exception handling";
    s[2]="C++ provides highest flexibility to the programmer";
    for(int i=0;i<3;i++)


#include <iostream>
#include <fstream>
#include <string>
using std::cout;
using std::string;
using std::ifstream;
int main()
    ifstream fin("test.txt");
        cout<<"Error in opening file";
    string s[3];
    for(int i=0;i<3;i++)
    for(int i=0;i<3;i++)

What should I do so that when I compile Read.cpp & run Read.exe file the 3 strings should be fetched randomly from file & gets displayed?

Your help is highly appreciated.

Rename multiple files using a name list

I've got a folder with many (around 500) files, named like

Then I've got a .txt (called "names.txt") file formatted like
roz001 O korytnačke a opici
roz002 Vlk a líška

Basically, it goes like "(filename without extension)(space)(string with desired filename without extension)".

How can I rename these files using this list? I need to rename file "roz001.mp3" to "O korytnačke a opici.mp3" and so on. I don't really care how will this be accomplished - I have access to a terminal (I'm on a Mac) and I can also use Python, but I'm willing to use any means that can be used to do this.

Thank you in advance for all and any help.

Java: Read Line From File Based on Start of Line

I know how to read from file using Java. What I want to do is read a specific line which starts with specific text.

What I plan on doing is storing certain program settings in a txt file so I can retrieve them quickly when I exit/restart program.

For example, the file may look something like this:

First Name: John
Last Name: Smith
Password: 123456789 

The : would be the deliminator and in the program I want to be able to retrieve specific values based on the "key" (such as "First Name", "Last Name" and so on).

I know I could store it to DB but I want to write it quickly to test my program without going through hassle of writing it to DB.


How to set alignment properly to file?

I am adding a little bit of alignment to file . I add name, say having size 20, to file and it messes up all my alignment! Do you know how to set width to file without using escape characters, like setw()?

The following code is just a part of student-related functions-

void save()
    FILE* fp;
    fp = fopen("Student.txt", "w");
fprintf(fp,"Roll No\tName\t\t\t\tPaper 1\tPaper 2\tPaper 3\tTotal  \tGrade\n");
    for(int i = 0; i < time; ++i)
        fprintf(fp, "%d\t%s\t   \t%d\t%d\t%d\t%d\t%c\n", info[i].rollNo, info[i].name,info[i].p1, info[i].p2, info[i].p3, info[i].total, info[i].grade);
    cout << "Successfully written to file!" << endl;

Thank you!!1

C#: Convert flat file to xml using xsd

I need help to covert flat file to XML format using defined XSD in C#.

can anyone please guide me achiev this?

using vsprintf and file operations

#define printm(X) handleVarArgs X
void writeFile(std::string & s)
    FILE *fp;
    fputs( s.c_str(), fp );

void handleVarArgs( char* format, ...)
    std::string s;
    va_list args;
    va_start (args, format);
    vsprintf (const_cast<char *>(s.c_str()),format, args);
    va_end (args);

const char *  func() { 
    std::string errorLog("Kiev"); 
    return errorLog.c_str();

int main()

    printm(("My  Name is %s and surname is %s and age is %d",func(),"john",25));
    return 0;

I am getting segmentation fault if i call writeFile() function. But no segmentation fault when i remove writeFile() What is the relationship between Files and Var Args?

txt file with splitted lines in batch

I am working on a batch script which extract some datas of some lines.

I curently read my file using:

for /l %%x in (1, 1, !number_of_equipements!) do (
    set x=%%i

But sometimes in my file, I have splitted lines like this one:

Cisco Web Usage Controls - Web Categorization Prefix Filters: 1438235190 (Thu 
Jul 30 06:00:38 2015)

And I need to grab the date to do some calculations and unfortunately my x variable will contain the first line and the second line in separated iterations.

What is the best to do ? I have thought about re-writting the entire file with a certain condition, or do exceptions depending on the line my script is reading, but it is all dirty. Is there any good way to do this ? Thank you in advance for your propositions.

c# read file-table (file-directory) especially deleted files

As far as I know files exist in two parts on a filesystem (partition). The first part is an entry in a file table as file metadata. The second part is the binary data which can be scattered over the partition.

I'm able to read files from a folder:

 System.IO.DirectoryInfo ParentDirectory = new System.IO.DirectoryInfo("d:\\test");

        foreach (System.IO.FileInfo f in ParentDirectory.GetFiles())
            Console.WriteLine(f.Name + ": "+ f.Exists);

If a file is beeing deleted, it can't be read this way anymore. Was the entry in the file table removed, or was it modified to be able to recreate the file? How can I get access to deleted files?

What happens to a file if I don't store a reference after opening it? [duplicate]

This question already has an answer here:

When properly using a file object you should either be closing it explicitly with

f = open("file.txt")

Or using the with method that makes sure the file is closed no matter what

with open("file.txt") as f:

But sometimes I want to grab a file only briefly. Maybe I just want to pull the string out of it and then discard the file. I sometimes write that like this:

fileStr = open("file.txt").read()

But this neither explicitly closes the file, nor does it use the with keyword. Does the file stay opened without any reference tied to it or does Python jettison the file intelligently? And if it doesn't, is there any way I could properly close it? I can't close after reading, as the close would be attempted on a string object:

fileStr = open("file.txt").read().close()

Traceback (most recent call last):
  File "<pyshell#7>", line 1, in <module>
AttributeError: 'str' object has no attribute 'close'

String replace in a file by using batch file. gettting error : < was unexpected at this time batcch file

Could anyone please suggest me how can I replace a string in a file by using scripts? That strings are contain few special characters(example: > < /> “ ” ).

My searchString is as mentioned below" />

My new string will be as mentioned below" >     <Permission User="Everyone" GenericAll="yes" /> </File> 

when I am using below script getting error

@echo off &setlocal
set "" />"
set "" > <Permission User="Everyone"    
GenericAll="yes" /> </File> "
echo replaceing hte string....2222
set "textfile=home.wxs"
set "newfile=home_t2.wxs"
(for /f "delims=" %%i in (%textfile%) do (
    set "line=%%i"
    setlocal enabledelayedexpansion
    set "line=!line:%search%=%replace%!"
del %textfile%
rename %newfile%  %textfile%

Getting below error:

The system cannot find the path specified.
< was unexpected at this time.

Please help me in this.

referencing and storing dictionaries in android studio

I would like to import a prebuilt dictionary or thesaurus to my android studio project but I don't know how. Is there anyway I can get one? What format should it be in?

Scrapy check if image response is 404

I want to process image URLs, I enabled and configured as Scrapy Docs; but what happens if the image URL returns 404 or is redirected. I want to log that, save the failed URLs and the HTTP error/redirect code. Where can I put the code to do that?

What is this database type and how to open it?

I have a .db file and I don`t know how to open it. When I open it with Notepad it contains some strange characters like this:

In folder where is .db file there is also .dbi and .dbx files.

I already try to open it with SQLite browser, MS Access, Excel, SQL Developer from Oracle but no results..

Anyone know what is this database type?

C# get file owner in Windows

I want to get the owner of a file using the code below


However, it gives me BUILTIN\Administrators as the owner, but I can see in the file explorer the owner is Domain\MyUserName.

Why this happens and how can fix it?

Random net.sf.ehcache.CacheException: invalid stream header when reading java temporary file

I'm working on an quite old application and when users use a functionality, "from time to time", they get this error :

net.sf.ehcache.CacheException: invalid stream header: 2F456E74

I can reproduce the problem "from time to time", and when it happens, it is when trying to read a temp file, stored in :


This temp file has the name of a "demon thread" I can see in the Debug view of Eclipse, and depiste the fact it's a random problem, it seems it's always the same file which causes the !

If I stop the application and the JBoss server, delete those files in the folder, and restart, it works but only once - it seems that the 1st time after a clean/restart, the exception can be thrown but silently, right after the main treatment is done. If a try one more time, it fails.

This happens when calling a hibernate


so I don't know what I can do since it deals with the way java manages its temporary files... Do you have some idea to give to me ?

Thanks in advance for your help :(

Api web app to filestorage system multi-user access

I wanted to create a multi-user library accessible via web app, so that it can be accessible depending on the app login.

i.e. Main Folder > Subfolder > Subfolder2 > Subfolder3.

Subfolder1 could be a large group of users with permissions.

Subfolder2 could be a sub-group of users with permissions.

Subfolder3 could be a users personal folder and only accessible by them.

The library would be visible to a user on the app like so, for example

Mainfolder (shared files)

with relevant files visible. Users should be able to move their own files with a front-end drag and drop, or pull a copy into there own utilize folder for later use in reference to a task.

It would also be good if two users could hook-up and allow a shared private folder as well.

Just wondering what would be the best storage and api retrieval solution for this.

Xamarin - Saving List of objects to file

I spend few days searching for this and I found some tutorial to save text but since I'm beginer at Xamarin I don't know how to modify that solution for saving List of objects.

So I have object Clothes with two parameters (string img_path and string img_tag). Then I have List of Clothes. I wanna be able to save List to file and be able to load Clothes from that file to the List of Clothes.

Thanks for any help.

jeudi 30 juillet 2015

Need help understanding how to sort info from text file using java

I am trying to build a program that reads in info from a .txt file, which contains 20 individuals, the team they belong to, batting average, and home run totals. I need to add each individual to there team(4 players to each team), total up the team home run totals, and rank the 5 teams in order. There are 4 classes total, ReadTxt, Teams, Sort and Main. I am able to read the text in, but I cannot figure out how to turn it into a 2D Array, put the players on the correct teams, and sort the totals. I am have done my best to find answers, and to learn on other posts and sites, but I am just stumped with the concept of 2D arrays and how to sort them.

Example of the .txt file looks like this:

 Team: Name:         Avg:HR:

 MILRyan Braun       .31015
 STLMatt Adams       .28718
 PITSterling Marte   .26420
 CINJoey Votto       .30224
 CUBAnthony Rizzo    .27422
 PITAndrew McCutchen .29522
 MILAdam Lind        .28013

The following class reads in the .txt file and puts it in array.

  public class ReadTxt {

static String[] teamm = new String[20];
static String[] name = new String[20];
static int[] avg = new int[20];
static double[] homeRuns = new double[20];

static String teams;
static int i;

public void Players(String[] teamm, String[] name, int[] avg, double[] homeRuns){
String[] team = new String[20];

File txtFile = new File("C:\\Users\\Users Name\\Desktop\\homerun.txt");


    Scanner txtScan = new Scanner(txtFile);

        for(i = 0; i < 20; i++){
            teams = txtScan.nextLine();
            team[i] = teams;

catch(FileNotFoundException e){
    System.out.println("File not found" + txtFile);

for (i = 0; i < team.length; i++){


The following is the Players Class:

public class Players {

static String[] teamm = new String[20];
static String[] name = new String[20];
static int[] avg = new int[20];
static double[] homeRuns = new double[20];

public Players(String[] teamm, String[] name, int[] avg, double[] homeRuns){
    this.teamm = teamm; = name;
    this.avg = avg;
    this.homeRuns = homeRuns;

public String[] getteamm() {
    return teamm;

public void setteamm(String[] teamm) {
    this.teamm = teamm;

public String[] getName() {
    return name;

public void setName(String[] name) { = name;

public int[] getavg() {
    return avg;

public void setavg(int[] avg) {
    this.avg = avg;

public double[] gethomeRuns() {
    return homeRuns;

public void sethomeRuns(double[] homeRuns) {
    this.homeRuns = homeRuns;

The next class is my attempt at sorting:

public class Sort {

static String[] teamm = new String[20];
static String[] name = new String[20];
static int[] avg = new int[20];
static double[] homeRuns = new double[20];
private int index = 0;
private int US = 0;
static double[] homeRunArray;

public void Players(String[] teamm, String[] name, int[] avg, double[] homeRuns){
homeRunArray[index] = ReadTxt.homeRuns[index];

public void selectionSort(){
    double temp;
    int min;

    for(int i = 0; i < US-2; i++){
        min = i;
        for(int j=i+1; j<= US-1; j++){
            if(min !=i){
                temp = homeRunArray[i];
                homeRunArray[i] = homeRunArray[min];
                homeRunArray[min] = temp;


public void printArray(double[] homeRuns){
    for(int i = 0; i < 20; i++){


The last is my Main, which runs everything.

public class Main {

static String[] teamm;
static String[] name;
static int[] avg;
static double[] homeRuns;

public static void main(String[] args){

    ReadTxt ReadTxtObj = new ReadTxt();
    Sort SortObj = new Sort();

    ReadTxtObj.SkateTeams(teamm, name, avg, homeRuns);


adding file/folder exclusions to recursive file search with powershell

Working on a script to get all files on a server and throwing their properties into a CSV. Below works fine, however, I'd like to add some file and folder exclusions.

For folder, I'd like to skip the cookies folder USERS\name\Personal\sysdata\cookies

For files, I'd like to exclude .lnk and .url files.

Thank you.

$arr = @()
gci "D:\COMPANY\USERS\a, user" -recurse 
| ? {$_.PSIsContainer -eq $False} 
| % {
    $obj = New-Object PSObject
    $obj | Add-Member NoteProperty Directory $_.DirectoryName
    $obj | Add-Member NoteProperty Name $_.Name
    $obj | Add-Member NoteProperty MB ("{0:N3}" -f ($_.Length/1MB))
    $obj | Add-Member NoteProperty created $_.creationtime
    $obj | Add-Member NoteProperty LastAccessed $_.LastAccessTime
    $obj | Add-Member NoteProperty LastMofified $_.LastWriteTime
    $obj | Add-Member NoteProperty Extension $_.Extension
    $obj | Add-Member NoteProperty Owner ((Get-ACL $_.FullName).Owner)

    $arr += $obj
$arr | Export-CSV -notypeinformation "C:\filesTest.csv"

Saving file on first run doesn't work, but works after on Android

First time to ask a question here but many times visitor a long time now!!Well ass the title says when i run the app for the first time files just don't create but it needs to call again the procedure and poof magic!!

The problem!!This is when i call to refresh

        List<Product> prod = new Select().from(Product.class).queryList();

        for (Product products:prod){
            ImageCache  imageCache = new ImageCache();
            Log.i("product", products.getProductDescr());


And this is the class that i call with the method!

public class ImageCache {

public  String productName;

public void setProductName(String productName) {
    this.productName = productName;

public String getProductName() {
    return productName;

public Target getTarget() {
    return target;

public void setTarget(Target target) { = target;

public  Target target = new Target() {
    public void onBitmapLoaded(final Bitmap bitmap, Picasso.LoadedFrom from) {
        new Thread(new Runnable() {
            public void run() {

                File file = new File(Environment.getExternalStorageDirectory().getPath() +"/Thesis/" +productName+ ".jpg");
                    FileOutputStream ostream = new FileOutputStream(file);
                    bitmap.compress(Bitmap.CompressFormat.JPEG, 75, ostream);
                catch (Exception e)

    public void onBitmapFailed(Drawable errorDrawable) {

    public void onPrepareLoad(Drawable placeHolderDrawable) {
        if (placeHolderDrawable != null) {

Any ideas why is this happening!!?? If you want me to post more things please say so!! Thanks in advance and a huge thank you for all the help that i 've got from here!

How to get access to all SD-cards, using the new Lollipop API?


Starting with Lollipop, apps can get access to real SD-cards (after it was not accessible on Kitkat, and was not officially supported yet worked on previous versions), as I've asked about here.

The problem

Because it has become quite rare to see a Lollipop device that supports SD-card and because the emulator doesn't really has the ability (or does it?) to emulate an SD-card support, it took me quite a while to test it.

Anyway, it seems that instead of using the normal File classes to access the SD-card (once you got a permission for it), you need to use Uris for it, using DocumentFile .

This limits the access to the normal paths, as I can't find a way to convert the Uris to paths and vice versa (plus it's quite annoying). It also means that I don't know how to check if the current SD-card/s are accessible, so I don't know when to ask the user for permission to read/write to it (or to them).

What I've tried

Currently, this is how I get the paths to all SD-cards:

public static List<String> getSdCardPaths(Context context,final boolean includePrimaryExternalStorage)
  final File[] externalCacheDirs=ContextCompat.getExternalCacheDirs(context);
    return null;
      return null;
    final String storageState=EnvironmentCompat.getStorageState(externalCacheDirs[0]);
      return null;
      return null;
  final List<String> result=new ArrayList<>();
  for(int i=1;i<externalCacheDirs.length;++i)
    final File file=externalCacheDirs[i];
    final String storageState=EnvironmentCompat.getStorageState(file);
    return null;
  return result;

private static String getRootOfInnerSdCardFolder(File file)
    return null;
  final long totalSpace=file.getTotalSpace();
    final File parentFile=file.getParentFile();
      return file.getAbsolutePath();

This is how I check what Uris I can reach:

final List<UriPermission> persistedUriPermissions=getContentResolver().getPersistedUriPermissions();

This is how to get access to the SD cards:

startActivityForResult(new Intent(Intent.ACTION_OPEN_DOCUMENT_TREE),42);

public void onActivityResult(int requestCode,int resultCode,Intent resultData)
  Uri treeUri=resultData.getData();
  DocumentFile pickedDir=DocumentFile.fromTreeUri(this,treeUri);

The questions

  1. Is it possible to check if the current SD-cards are accessible, which aren't , and somehow ask the user to get permission to them?

  2. Is there an official way to convert between the DocumentFile uris and real paths? I've found this answer, but it crashed in my case, plus it looks hack-y.

  3. Is it possible to request permission from the user about a specific path? Maybe even show just the dialog of "do you accept yes/no ? " ?

  4. Is it possible to use the normal File API instead of the DocumentFile API once the permission was granted?

  5. Given a file/filepath, is it possible to just request a permission to access it (and check if it's given before), or its root path ?

  6. Is it possible to make the emulator have an SD-card? Currently, it has "SD-card" being mentioned, but it works as the primary external storage, and I'd like to test it using the secondary external storage, in order to try and use the new API.

I think that for some of those questions, one helps a lot to answer the other.

How To Read A Text File Via Scanner

I am trying to read from a text file, but whenever the program gets to my while loop it just skips over it. I used a previous example I had to check to see if I did it correctly, but it doesn't seem to be working this time.

    public static void main(String[] args) throws FileNotFoundException {

    ToDoItem td = new ToDoItem();
    ToDoList tl = new ToDoList();

    File file = new File("ToDoItems.txt");
    Scanner ReadFile = new Scanner(file);
    Scanner keyboard = new Scanner(;

    int b = 0;
    String[] stringArray = new String[b]; 
    String inputline;

    System.out.println("Welcome to the list maker!" + "\n" + "Please start typing.");

    try (PrintWriter fout = new PrintWriter(new File("ToDoItems.txt"))) {

        do {
            System.out.println("add to the list? [y/n]");
            inputline = keyboard.nextLine();

            if ("y".equals(inputline)) {
                fout.print(td.getDescription() + "\n");

            } else {
                System.out.println("Here is the list so far:");

                while (ReadFile.hasNext()) {
                    stringArray[b] = ReadFile.nextLine();
        } while ("y".equals(inputline));

      } catch (FileNotFoundException e) {

Ideally I want it to print a part of the Array each time it passes through the while loop. But it just ends up skipping over it. I checked the text file itself, and it does have the information I want to print to it. Yet for some reason the scanner won't read it properly.

Using matplotlib to graph rows by column of a csv file

Very new at Python and first time using matplotlib

I'm trying to graph a multiline plot based on the rows of a CSV file.

CSV file looks something like this:

Row1        S1      S2     S3      HWS
Row2        2.45    3.76   2.44    1
Row3        3.59    2.56   9.68    2
Row4        2.54    9.45   6.78    3

I want to graph the HWS values by each row in the csv file.

Ex: For Row2, I want my points to be (1, 2.45), (2, 3.76), and (3, 2.44). For Row3, I want my points to be (1, 3.59), (2, 2.56), and (3, 9.68).

I've already looked at modules like pandas from other stack overflow answers, but I can't find commands to graph by rows. All I found is ways to graph a whole CSV file or ways to isolate columns of a csv file.

Is there a way to graph this way using Python and matplotlib?

Can I set a file to read-only without using a File object in Java?

I'm using a system where we have built-in functionality to add Metadata tags to Jpeg images through the Apache Commons Imaging library. This library allows for modification of Metadata directly through an InputStream. This metadata is then read by Symantec DLP installed on our End User's machines to keep them from doing questionable things with tagged files(copy to flash, other storage, email, etc.). The issue is that a user can still modify the tag after the fact because the file is writable, pretty much invalidating the security effort.

I'm looking to find out a way to write metadata for a file to become read-only in a similar fashion, by modifying the data through something that can wrap around an InputStream.

The Java File object has a built in method called setReadOnly() that could be used in theory, but the issue is that I'm never able to create a File object directly. We receive an InputStream from the client, modify it with other libraries, and encrypt it all before writing it to storage for security reasons. If I add the tag to the encrypted file, it will be removed on decryption. Apache Commons Imaging supports a host of metadata tag types, but I have been unsuccesful in finding any R/W tags supported.

Does anybody know how to set a File to be persistently read-only directly through an InputStream or some derived object using core Java, Apache Commons Imaging, or a useful third party library?

saving to utf-8 file

I'm trying to save a .txt file in the UTF_8 format, but I don't understand where I should add that to my code. Here's what I got.

String fileStringName =  userHome + "/wordsearch directory/Puzzle.txt";
        File filePath = new File(userHome + "/wordsearch directory/Puzzle.txt");
        File dirPath = new File (userHome + "/wordsearch directory");           
        //new method just made
        //make pop up jpane displaying puzzle ID.
        boolean filePathExists = false;
            filePathExists = dirPath.mkdirs();
            try {
                //BufferedWriter out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(path),"UTF-8"));
                writer = new PrintWriter(new BufferedWriter(new FileWriter(fileStringName,  true)));
        //  Writer writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(fileStringName), "UTF-8"));
            } catch (IOException e2) {
                writer = null;

SWIFT: Reading file: NSData successful, String fails. Why?

I'm trying to read large data from file. It is a text file. The following line is successful, data is read into memory:

if let data = NSData(contentsOfFile: path, options: NSDataReadingOptions(), error: &error)

This line return an error:

if let data = String(contentsOfFile:path, encoding: NSUTF8StringEncoding, error: &error)

But why? File is there, only Function is different. And I like to use second one, because I want to split all rows into separate strings in an array:

var array = data.componentsSeparatedByString("\n")

Any hint what to do?

require_once failed to open stream: No such file or directory - even if relative path seems to be correct(?)

Well, I have this dashboard.php file:

require_once ('../resources/config.php');

and my file tree looks like this:


  • admin/dashboard.php
  • resources/config.php

I really don't know what the heck is wrong with it, I'm using exact same include in the exact same directory for another php script, and everything runs great.

Any ideas?

In C# read a Text File in Same Folder With App

Hi everyone i have a windows form app. And there is a text file in same folder with the app.

I want to read this text file and write it in a rich text box. I tried several things but can't do it :S What should i do?

Here is my solution explorer;

enter image description here

Here is my About.cs;

 private void About_Load(object sender, EventArgs e)
        this.FormBorderStyle = FormBorderStyle.FixedSingle;
        this.MaximizeBox = false;
        this.MinimizeBox = false;
        aboutText.Enabled = false;
        string appPath = Path.GetDirectoryName(Application.ExecutablePath);
        aboutText.Text = File.ReadAllLines(appPath + "TOSandAbout.txt").ToString();


I can't read like this :s

Why would one create an empty file?

I saw the command: touch while watching a video about the Terminal

It was something like:

user$ touch testfile
user$ ls
Documents Photos Music testfile

So I couldn't answer to myself:

Why one would want to create an empty file?

If you can, please make a short list of a few applicabilities of it!

Downloaded File Has 0 Bytes

I'm trying to download a .mp3 music file from this URL to the project root directory but the downloaded file always has 0 bytes in size (it is blank). The download also immediately stops.

I'm using the following code:



public class MusicDownloader
    public static void main(String[] arguments) throws MalformedURLException, IOException
        download("", "Ponies and Balloons");

    public static void download(String url, String fileName) throws MalformedURLException, IOException
        FileUtils.copyURLToFile(new URL(url), new File(new File("").getAbsolutePath() + File.separator + fileName + ".mp3"));

In a browser, downloading the file manually works flawlessly. A download link from another website e.g. this one had no problems to be processed by the code. What could be the problem here?

Blueimp File Upload Basic Implementation

I set up blueimp file upload, and i set the permissions to the file destination 'upload folder' to 755 but got an error message saying I didn't have enough permission to move files in that folder.

I changed folder permissions to 777 and the upload worked. yay, but 777 is a bit generous permission?

Is there a way to make the basic file upload to work with less permission.

Similar question to the gentleman here.

blueimp basic file upload permission 777 vs 755

Thanks a lot for any help/direction.


Create a blank each file in directory, with a different extension

How can I create a blank .XXX extension for each file in a directory in Ubuntu terminal? I know how to change extensions of current files, but I don't know how I can create copies with different extensions.

Programatically moving OneDrive files between online and offline

I've been asked to write a small task tray application that will help with managing users local drive space - to be more specific, to take advantage of OneDrive's Smart File capability so that files appear offline when not.

The ask is to monitor/check all the files in the users OneDrive folder and if they have not been updated in the last 30 days, then make them "online only".

In File Explorer users can right click on files and folders and select "make online only", but the aim is to do this automatically.

I'm hoping there is an attribute or flag I can set in the File or FileInfo objects in C# .Net that will then trigger the sync agent to do the necessary.

Is this possible?



while cycle not stopping in bash

My script is designed to get files (and folders, eventually) and then list them with a while iteration. format should be:

1) file.txt

2) newfile.txt

3) new folder

and it works! but then the while cycle wouldn't stop. given that i'm a newbie in bash can you tell me what am i doing wrong?


shopt -s nullglob


while [ ${FILES[var2] -n } ] ; do

  echo "$var2 ${FILES[var2]}"


command line to copy file from windows to remote windows

I use the following command to copy files from my windows to a remote linux machine:

pscp -pw <password> source <source-file> <user>@<ip>:<dest-folder>

Is there a similar command line to copy files from my windows machine to a remote windows machine?

PyQt Open File Dialog - Display Path Name

Using PyQt, I have created a button that can choose and upload a file from any directory. How do I create a text box next to the button that would display the path of the file selected or opened:

    self.uploadButton = QtGui.QPushButton('UPLOAD SDF', self)
    self.runfilterButton = QtGui.QPushButton('Run Filter', self)
    self.printimagesButton = QtGui.QPushButton('Display Matches Images', self)
    self.listmatchesButton = QtGui.QPushButton('List Matches', self)

    self.uploadButton.move (100, 50)
    self.runfilterButton.move (400,50)
    self.printimagesButton.move (200, 100)
    self.printimagesButton.resize (200, 50)
    self.listmatchesButton.move (200, 150)
    self.listmatchesButton.resize (200, 50)
    hBoxLayout = QtGui.QHBoxLayout()

    # Signal Init.
    self.connect(self.uploadButton, QtCore.SIGNAL('clicked()'),

Blueimp jQuery File Upload breaking when loaded through AJAX

Blueimp's jQuery File Upload breaks when it's loaded via AJAX after the initial page is loaded. I've used the default index.html code example within the project to minimize any error on my part. How could I load this upload dynamically through AJAX without breaking it?

Code used to load it via AJAX:

function switchPage(pageurl, div, fade) {
    if(fade != false) {
    $("#" + div).promise().done(function(){ //Waiting until the fade is done
            type: "POST",
            url: pageurl,
            success: function(data) {
            error: function(xhr, ajaxOptions, thrownError) {
                $('#' + div).html("Failed to load...");
                if(fade != false) {
            success: function(data) {
                $('#' + div).html(data);
                if(fade != false) {

recursion reverse lines of a file not working for me

I Just want to reverse the lines of a file but I cannot figure it out. I thought I'd use recursion as the easiest way but it's not working. here's what I've figured I'd do.

public void reverseLines(Scanner s, String outputFile) throws FileNotFoundException {
    PrintWriter pw = new PrintWriter(outputFile);
    String st = s.nextLine();
        printLines(s, outputFile);

I'm trying to make this: hello there this ones the middle this ones on top

in reverse but in my output file all I get is this hello there middle

and I am just so confused. I've seen this question asked before but all the questions are "how do I reverse these lines" and the answers are "use recursion" but still sorry for asking

Android where file is saved FileOutputStream

Here how I write bytes to a file. I'm using FileOutputStream

    private final Handler handler = new Handler(){
            public void handleMessage(Message msg) {
                FragmentActivity activity = getActivity();
                        byte[] readBuffer = (byte[]) msg.obj;
                        FileOutputStream out = null;
                        try {
                            out = new FileOutputStream("myFile.xml");
                        } catch (FileNotFoundException e) {
                        } catch (IOException e) {

and now I want to open that file, so I need to have path of that file. So how I need to open that file?

Database schema advice for real time API calls

I have a project for some local high school sport leagues which want some real time updates with statistics. There will be people at events (american football, basketball, volleyball, golf, wrestling, etc) who will be using my CMS system to update the stats.

I can't seem to wrap my head around how to store those stats so when the REST API calls happen, the latest events will be sent back (ex: gathering all basketball games happening at that time on the server and saving them).

The data coming to the server is in JSON format and I would like to be able to store it as so, each sport being the main key, then the stats on a game by game basis. It seems to me using a RDBMS or another db type would be pointless because adding the stats in real time would mean a ton of rows where the data barely differs, then collecting the most recent games would be a pain if I were to break up each person's POST and save it as it's own row.

On the other hand, I could just store everything in a file, gather the stats as they come in and update the file. But if there will be many writes happening, the responses to the API calls might get slow.

Any suggestions? Which of my thoughts is wrong here?

Windows 10 created problems on my app

So guys, i updated my SO to the windows 10. And i went to work on my app again, but now there are problems relating the files. There is a build error that i don't know what it is. They say : C:\Users\Cesar\AndroidStudioProjects\Moises\.gradle\2.2.1\taskArtifacts\ (Access denied)

I went to that directory, and the file named above is there. What's happening guys ? i don't want to rewrite my app again :x

I cant read line by line from text file. How can i do?

After i got a file ( example: a.txt) from assests folder,while m reading this file line by line

this code part ( line=reader.Readline() ) have to read content of a file's line; but line getting a file path.

I want to add all line in the file to list.(lines)

****** This project is about Universal App and **Windows Phone 8.1 part

    List<string> lines = new List<string>();

    public async void LoadFile(string file)
        var InstallationFolder = await Windows.ApplicationModel.Package.Current.InstalledLocation.GetFolderAsync("Assets");
        var _file = await InstallationFolder.GetFileAsync(file);
        byte[] byteArray = Encoding.UTF8.GetBytes(file);
        MemoryStream stream = new MemoryStream(byteArray);
        using (var reader = new StreamReader(stream))
            string line = null;
            while ((line = reader.ReadLine()) != null)

Broken xaml file after rebooting pc

After rebooting my PC with opened VIsual Studio, all opened xaml files becomes invalid. Opening in different editors did not bring results. Is there any way to recover them ?

How could i get the request of my web service call.

My aspx file uses an external web service and when i call that service method, i want to see what request is created and send the otherside. Is it possible to get it?

Windows explorer finds file which doesn't contain specific search string

I have file's path and name "141782.tif" and I cannot find this file in the my application using c#. BUT when I try to find this file using explorer I receive file with another name, but its content is correct. I really don't know what is it and how it works, and how can I get this "23808" file when I have only "141782". Can anybody help me? enter image description here

Searching only .xml.gz files in a directory using php

I want to scan a directory which contains many files but I'm in need of files ending with .xml.gz . Below is the code what I've tried but it fails to meet the requirements.

$num_files = count(array_intersect(scandir(getcwd()), array('.xml.gz')));

I know that I should make use of wildcards but I'm unsuccessful in getting the right output

VC++ 2012 can't read files larger than 4 GB

I'm trying to read a large binary file but my code fails to open files larger than 4GB. Here's my code (I'm using Visual Studio 2012):

#include "stdafx.h"
#include <fstream>
#include <iostream>

using namespace std;

int _tmain(int argc, _TCHAR* argv[])
    char* filename = "testfile";

    ifstream file (filename, ios::in|ios::binary|ios::ate);
    if (file.is_open())
        cout << "file is open" << endl;
        cout << "couldn't open file" << endl;

    return 0;

Do you have any advice?

Stata: Adding specific values from external file to existing dataset

I need your support regarding data management in STATA. Specifically, I want to add specific values from an external excel- or csv-file to an existing dataset, depending on another variable.

E.g. if the variable "countryyear" of any observation in the existing dataset contains the value "GER2004" I want to fill the new variable CPI with the consumer price index of Germany in year 2004. But if the variable "countryyear" of another observation contains the value FRA2008 I want the new variable to contain the CPI of France in 2008.

The CPI file contains a table with the countries in rows, and the years in columns.

Can you provide suggestions how to approach this problem? Is it doable with a merge command? Or can I "pick" the values from the file (or a temporary matrix that I insert into Stata), saying "if countryyear=GER2004 then CPI=Cell(2,8)" or something like that?

Thanks a lot for your help!

Regards, Stefan

How to find duplicates of three variables that reference an array?

I have a function that reads a txt file and then creates three variables from a combination of charAt() values for each line that it reads. The variables are k, k1, and k2. These variables reference a very long array file myarray[k][k1][k2] and then writes the value of these array elements to a div.

I may be reading up to 400 lines of text and each time the k, k1, and k2 values are created. How would I go about determining if these same k, k1, and k2 values are being duplicated?"

Update - I tried using

if ( !(myArray[k] && myArray[k][k1] && myArray[k][k1][k2]))

but it did not work, probably because I did not explain my problem properly.

For example, after reading, say line 15, I get values of k=0, k1=3, k2=10 and these are the values that will be used for myArray[k][k1][k2]

These same values, i.e. k=0, k1=3, k2=10 may not occur again, or they may occur after reading, say line 222 and if this is the case, I want to write something different, i.e. I don't want to output the value of myArray[0][3][10] again. I hope this makes sense.

I think it is best if I include code:

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


var myplanets = 
["SUN    ", "MOON   ", "MERCURY", "VENUS  ", "MARS   ", "JUPITER", "SATURN ", "URANUS ", "NEPTUNE",     "PLUTO  "]

var myplanets1 = 
["SUN    ", "MOON   ", "MERCURY", "VENUS  ", "MARS   ", "JUPITER", "SATURN ", "URANUS   ", "NEPTUNE",   "PLUTO  ", "MC     ", "ASC    "]

var myaspects = ["conjunct", "sextile ", "square  ", "trine   ", "opposite"]

var numval =  [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
var numval1 = [0, 1, 2, 3, 4]
var numval2 = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]

var r, tplanet, aspect, nplanet, range, k, k1, k2

function loadFile(){

  var ForReading = 1, ForWriting = 2, ForAppending = 8;
  var fso = new ActiveXObject("Scripting.FileSystemObject");

  var filename = "emmy_test1.txt"
  var info = document.getElementById("info");
  var transits = document.getElementById("transits");

  f = fso.OpenTextFile(filename, ForReading);

  while (!f.AtEndOfStream){
    r = f.ReadLine();

    tplanet  =  r.charAt(2) + r.charAt(3) + r.charAt(4) + r.charAt(5) + r.charAt(6) + r.charAt(7) + r.charAt    (8)

    for (var j = 0; j < myplanets.length; j++) {
      if (tplanet==myplanets[j]) {k = numval[j]}

    aspect = r.charAt(34) + r.charAt(35) + r.charAt(36) + r.charAt(37) + r.charAt(38) + r.charAt(39) +  r.charAt(40) + r.charAt(41)

    for (var j = 0; j < myaspects.length; j++) {
      if (aspect==myaspects[j]) {k1 = numval1[j]}

    nplanet = r.charAt(45) + r.charAt(46) + r.charAt(47) + r.charAt(48) + r.charAt(49) + r.charAt(50) +     r.charAt(51)

    for (var j = 0; j < myplanets1.length; j++) {
      if (nplanet==myplanets1[j]) {k2 = numval2[j]}

    range = r.charAt(66) + r.charAt(67) + r.charAt(68) + r.charAt(69) + r.charAt(70) + r.charAt(71) +   r.charAt(72) +  r.charAt(73) + r.charAt(74) + r.charAt(75) + r.charAt(76) + r.charAt(77) + r.charAt(78) + r.charAt(79) + r.charAt(80)   + r.charAt(81) + r.charAt(82) + r.charAt(83) + r.charAt(84) + r.charAt(85)

    transits.innerHTML += "<b>" + range + "</b><br>" + myArray[k][k1][k2] + "<br>"
    transits.innerHTML += "<br>"





locate a file - python

I have the name of a file and I want to find its path. I can use recursive search, but I need a root directory. for most of the computers, the root is "C:\". But, there are some that have changed the letter, or some that have more than one (C,D...). So, I need to find a way to know the letters in a computer, so I can search for each one. I need to find the letters with a code, not "open cmd, type ....". I know I can use "diskpart", but it requires an administrator access, something my code will not have. There is also "wmic", but I don't know if the computer has the right folder in the PATH.

So, the question is how can i do a recursive search in a computer which I don't know the letters of the drives or how many are there? Or is there another way to find the path of a file in a computer?

How to send and receive file with Java RabbitMQ?

How to send file with Java RabbitMQ? Especially using message converter.

I'm using Spring Framework, can send String or ArrayList but can't send File. I'm only use convertAndSend and convertAndReceive to send File but get :


I don't know how to use message converter. The code from here and change some class :

package org.springframework.amqp.helloworld.async;

import java.util.ArrayList;

import org.springframework.amqp.core.Message;

public class HelloWorldHandler {

    public void handleMessage(File message) throws IOException {
        BufferedReader br = new BufferedReader(new FileReader(message));

package org.springframework.amqp.helloworld.async;

import java.util.concurrent.atomic.AtomicInteger;

import org.springframework.amqp.rabbit.connection.CachingConnectionFactory;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.scheduling.annotation.ScheduledAnnotationBeanPostProcessor;

public class ProducerConfiguration {

    protected final String helloWorldQueueName = "";

    public RabbitTemplate rabbitTemplate() {
        RabbitTemplate template = new RabbitTemplate(connectionFactory());
        return template;

    public ConnectionFactory connectionFactory() {
        CachingConnectionFactory connectionFactory = new CachingConnectionFactory("x.x.x.x");
        return connectionFactory;

    public ScheduledProducer scheduledProducer() {
        return new ScheduledProducer();

    public BeanPostProcessor postProcessor() {
        return new ScheduledAnnotationBeanPostProcessor();

    static class ScheduledProducer {

        private volatile RabbitTemplate rabbitTemplate;

        private final AtomicInteger counter = new AtomicInteger();

        @Scheduled(fixedRate = 3000)
        public void sendMessage() {
            rabbitTemplate.convertAndSend(new File("test.txt"));

reformat a CSV file

After searching on search engines I didn't manage to find a way to reformat a CSV file and save it :

the file looks like :


I would like to know how to delete the second column and getting :


Ps : I want that the modification occurs directly on the file , I am using zsh shell

qlikview extension Font picker and File chooser

I would like to know is it possible to have Font picker and File chooser over extension properties in QlikView/QlikSense, similar as color picker?

There is an option to do inject this over document extension, by using html/javascript, but as I can see, this implementation only works through Access point/server, not in the QV desktop app.

Thanks in advance! Adnan

Rename XML file to an attribute value

I have a lot of .xml files structured the same way:

<parent id="idvalue" attr1="val1" attr2="val2" ...>
    <child attr3="val3" attr4="val4" ... />
    <child attr3="val5" attr4="val6" ... />

Each file has exactly one <parent> element with exactly one id attribute.

All of those files (almost 1,700,000 of them) are named as part.xxxxx where xxxxx is a random number.

I want to name each of those files as idvalue.xml, according to the sole id attribute from the file's content.

How to avoid individual casting to byte during initialization of byte array in Java

I am using a byte array to store a text file outside of the filesystem.

It looks like this:

private static final byte[] CDRIVES = new byte[] {
        (byte)0xe0, 0x4f, (byte)0xd0, 0x20, (byte)0xea, 0x3a, 0x69, 0x10,
        (byte)0xa2, (byte)0xd8, 0x08, 0x00, 0x2b, 0x30, 0x30, (byte)0x9d,
        (byte)0xba, (byte)0x8a, 0x0d, 0x45, 0x25, (byte)0xad, (byte)0xd0, 0x11,
        (byte)0x98, (byte)0xa8, 0x08, 0x00, 0x36, 0x1b, 0x11, 0x03,
        (byte)0x80, 0x53, 0x1c, (byte)0x87, (byte)0xa0, 0x42, 0x69, 0x10,
        (byte)0xa2, (byte)0xea, 0x08, 0x00, 0x2b, 0x30, 0x30, (byte)0x9d

Is there a way to avoid casting to (byte) for better visual interpretation?

I don't mind using other data type, but I need to be able build an InputStream out of it and do it the fastest way if possible. (for example storing a text file into a String variable is not the best way...)

Copy network file from a Linux host to my Linux server using PHP

I am trying to retreive a network file an OpenSUSE 13.1 Host to my OpenSUSE 13.2 Webserver, but I don't seem to have any success.

First I am checking if target directory is a dir:

$path = "\\\\\\public";
if(is_dir($path)){ // returns FALSE every time.
  return true;

In this case the function is_dir() returns FALSE, anthough the folder exists and has 777 permisions, the IP is correct, and the computer is turned ON :) I have tried all the combinations of formatting the network path, including $path = "smb://"; witch returns an error "

Unable to find the wrapper "smb" - did you forget to enable it when you configured PHP?"

I am out of ideas and I need this to work as fist as possible. Could someone tell me what I am missing?

Would it work the same through a OpenVPN with my Centos 6 webserver and an Ubuntu 14 host? (This is the real scenario)


Creating an input stream from a text file initialized programatically in Java

Currently I am loading a text file from filesystem and creating FileInputStream.

What I need is to eliminate the file in filesystem.

So I came up with solutions like:

  • Storing a file into String variable and creating Stream out of it (escaping chars need to be done)
  • Storing a file into byte array with hex values (no need to escape chars or care about content)

I am wondering if there is any other way to achieve this.

mercredi 29 juillet 2015

Printing a dynamic HTML document

I have an HTML template that we use for alerts. We pass some details into the template that pertain to the alert. What we are now trying to do is to get it to print. This HTML document is created dynamically so it isn't opened in a browser. I have been able to get the document to save to a network drive. I then copy it to the printer, but no luck printing. I have no idea if this is possible, but we need something that is well formatted, so plain text wouldn't be ideal. I have been searching for days, but can't seem to find anything that helps. Below is a sample of what i'm trying. I'm open to all suggestions!


Public Shared Function TestPrint(pPrinter As String) As String
    Dim tempateLoc As String = "\\JoshSv\Reject.htm"
    Dim printLoc As String = "\\printSv\" & pPrinter
    Dim fileLoc As String = "\\JoshSv\alert" & GetEpocTime(Now()) & ".htm"
    Dim fileHTML As String = ""

    If File.Exists(tempateLoc) Then
        Using tr As TextReader = New StreamReader(tempateLoc)
            fileHTML = tr.ReadToEnd
            Using sw As StreamWriter = New StreamWriter(fileLoc)
                File.Copy(fileLoc, printLoc)
            End Using
        End Using
    End If

    Return fileHTML
End Function

How to parse a file with levels of tabs into a tree-like structure in java?

I have a file that looks like this

Option 1
        Yet another option
              @the end
        Option 4

etc. the @ means it has reached the end of the tree.

I would like to be able to have the user go deeper into the tree (more indentations) picking one of the choices each time. BUT I need to figure out how to stop looking if the indentation level decreases. (i.e. "Five" would not be in the choice list if "Sub-option" was selected).

Can anyone give me some pointers for parsing a file like this?

How to read text file of float numbers efficiently with Java + LibGDX?

I'm writing a small scientific data visualization app with Java/LibGDX. The app first reads in a text file that describes a 4d array:

188 225 3 6 0.001 -0.023 1.345 2.475 ... 4.327

The first four integers specify the dimension of the array: 188 x 255 x 3 x 6, followed by 188 x 255 x 3 x 6 ~= 760000 numbers. In total, the text file takes about 5MB space.

The 4D array represents an 'augmented' image of 188 pixels tall and 255 pixels wide with 3 color channels (RGB). There are 6 'parameters' associated with each pixel channel, instead of just one as in regular RGB images.

I used the following way that I copied from the official document to read the space-separated list into memory:

FileHandle ptmFile = Gdx.files.internal(filename);
String ptmText= ptmFile.readString();

Then I created a simple wrapper class AugPixel, which is practically a wrapper of a 6-element array for each pixel. I used a Scanner to read and parse each number from the string (Please pardon me for the semi-pseudo code):

Scanner scan = new Scanner(ptmText);
int nRows = scan.nextInt();
int nCols = scan.nextInt();
int nColors = scan.nextInt();
int nParams = scan.nextInt();

AugPixel[][][] im = new AugPixel[nRows][nCols][nColors];

for (i = 1~nRows)
  for (j = 1~nCols)
    for (k = 1~nColors)
      im[i][j][k] = new AugPixel(nParams);
      for (m = 1~nParams) 

This method works fine for the desktop version. It takes about 5 seconds to load the file and build all the AugPixel objects. However, when I move the app to an actual android device (Nexus 7 32G (2nd generation)), the loading process takes 5 minutes!

So my questions is: Is there any way to speed up the loading process? I have the freedom to redefine the organization of the file as I see fit.


Grunt: Getting file src from a file object

I'm just learning Grunt and going through some very beginner tutorials. I've come across this code on copying files, but when I run it it doesn't work:

module.exports = function(grunt) {
    copy: {
        target1: {
            files: {
                'dest/file1.txt': 'src/file1.txt',
                'dest/file2.txt': 'src/file2.txt'
        target2: {
            files: {
                'dest/file3.txt': 'src/file3.txt',
                'dest/file4.txt': 'src/file4.txt'
grunt.registerMultiTask('copy', function() {
    this.files.forEach(function(file) {
        grunt.file.copy(file.src, file.dest);

    grunt.log.writeln('Copied ' + this.files.length + ' files');

I run this with "grunt copy:target1"

I get the following Warning:

Warning: Unable to read "" file (Error code: ENOENT). Use --force to continue.

When I do console.log(file) within the forEach I see:

  { src: [Getter],
dest: 'dest/file1.txt',
orig: { src: [ 'src/file1.txt' ], dest: 'dest/file1.txt' } }

When I do console.log(file.src) I just get:


How do I get to that src and why does grunt think it's an array?

Save path as string or fstream as variable

I'm currently writing on a File_Handler, a class that simplifys operations on files which I need for my program.

My question is which way would be best to save the file in my class. Would it be best to save the path of my file as a std::string and reopen it in every function that uses the file, or would it be best if I'd save the actual std::fstream variable.

Opt. 1 would look like this:

class File_Handler
    void foo() 
        std::fstream f(m_path);
        //operations with 'f'..
    std::string m_path; //save path of file here

and Opt. 2 would look like this:

class File_Handler
    void foo()
        //operations on already opened 'm_file'
    std::fstream m_file; //save actual file

Which version is quicker, saver and over all better?

Or is there even a better way? (For example copy the whole file into a vector and after every operation on the vector copy vector to file?..)

I'd appreciate you help.

Cordova file upload

I want to upload a video to YouTube from my phone device storage. However when I upload the file it comes through as blank. When I use the same upload code but with a web file, it works. Wondering where I am going wrong!

Method one everything uploads correctly and the video plays on YouTube.


function loadWebFile(url) {
    var xhr = new XMLHttpRequest();'GET', url);
    xhr.responseType = 'blob';
    xhr.onload = function (e) {
        uploadFile(xhr.response); // type: Blob
    xhr.onerror = function (e) {
        console.log('loadWebFile.onerror', e);

Method two The video title and description appears on YouTube, but the video is blank. I'm definitely passing through a valid file.

window.requestFileSystem = window.requestFileSystem || window.webkitRequestFileSystem;
if (window.webkitStorageInfo) {
    window.webkitStorageInfo.requestQuota(access, 1024 * 1024, function (bytes) {
        if (window.requestFileSystem) {
            window.requestFileSystem(access, bytes, function (filesystem) {
            }, me.onError);
        } else {
            window.alert('requestFileSystem not supported');
    }, me.onError);
} else {
    window.alert('webkitStorageInfo not supported');

// this sends an empty video to YouTube
function loadFile(path) {
    filesystem.root.getFile(path, null, function (fileEntry) {
        fileEntry.file(function (file) {
            uploadFile(file); // type: File
    }, function (e) {
        console.log('loadFile.error', e);

Both methods share the same upload function:

// uploads using the YouTube script
function uploadFile(file) {
    var metadata = {
        snippet: {
            title: 'Video title',
            description: 'Video description',
            tags: 'Video tags',
            categoryId: 22
        status: {
            privacyStatus: 'unlisted'
    var uploader = new MediaUploader({
        baseUrl: '',
        file: file,
        token: accessToken,
        metadata: metadata,
        params: {
            part: Object.keys(metadata).join(',')
        onError: function (e) {
            console.log('onError', JSON.parse(e));
        onProgress: function (e) {
            console.log('onProgress', e);
        onComplete: function (e) {
            console.log('onComplete', JSON.parse(e));

I've have an example project with some of the code (minus the upload script) here:

stream_set_write_buffer or file locking in PHP?

I'm trying to make a caching system where a large chunk of data (between 8 KB and 200 KB) can be written as fast as possible.

Currently I'm applying file locking functions using the code similar to below:


Is this the most optimal way speed wise to allow only one process at a time to write to the file if many are running the same script at once, or should I also include stream_set_write_buffer($file_handle,0); or should I ditch file locking?

Custom Gradle "Copy" task copies outdated classes

I'm currently working on the migration of an Ant script to its corresponding Gradle version. Everything works fine with the exception of a custom Copy task, which is in charge of copying the generated jar file from build/libs to another directory (out of the project).

If, after a first build, I introduce a change in any java file, and try to execute

gradle clean build deploy

i see the build/classes *.class files are correctly updated, and the build/libs/template-util.jar as well. However, the file template-util.jar copied to /home/fbudassi/Downloads has (the most of the times) the old version of the class. Sometimes, after some changes (I don't really know where, because I've tried many many things), the copied jar is updated correctly.

This is my build.gradle:

apply plugin: 'java'
apply plugin: 'eclipse'

// Default task.
defaultTasks 'deploy'

// Configuration parameters.
group = 'com.rcs.template'
version = 'master'
sourceCompatibility = 1.7
targetCompatibility = 1.7

ext {
    // Manifest extra parameters.
    projectName = 'Template Util'
    vendor = 'Rotterdam Community Solutions'
    buildNumber = 10
    jarName = 'template-util.jar'

    // Dependencies versions.
    jacksonVersion = '2.6.0'

    // Deploy destinations.
    deployTo = ['/home/fbudassi/Downloads']

// Dependencies.
dependencies {
    compile "com.fasterxml.jackson.core:jackson-core:$jacksonVersion"
    compile "com.fasterxml.jackson.core:jackson-annotations:$jacksonVersion"
    compile "com.fasterxml.jackson.core:jackson-databind:$jacksonVersion"
    compile "org.slf4j:slf4j-api:1.7.12"
    compile "org.apache.commons:commons-lang3:3.4"

    testCompile 'junit:junit:4.12'

repositories {

// Jar name and Manifest data.
jar {
    def buildDate = new Date().format("MMMMM dd yyyy")

    archiveName = jarName
    manifest {
    attributes 'Built-By': System.getProperty(''),
        'Built-Date': buildDate,
        'Built-JDK': System.getProperty('java.version'),        
        'Implementation-Title': projectName,
        'Implementation-Version': "$project.version - $buildDate - build: $buildNumber",
        'Implementation-Vendor': vendor

// Deploy task: copy jar to destinations.
task deploy(dependsOn: 'build') {
    deployTo.each { dest ->
        copy {
            from jar
            into dest

// Gradle Wrapper version.
task wrapper(type: Wrapper) {
    gradleVersion = '2.5'

Could you help me find an answer to the problem?

Scrapy check if image response is 404

I want to process image URLs, I enabled and configured as Scrapy Docs; but what happens if the image URL returns 404 or is redirected. I want to log that, save the failed URLs and the HTTP error/redirect code. Where can I put the code to do that?

Open files with different options

I have two sets of files:

Set 1: { reactant.1.h.txt, reactant.2.h.txt, reactant.3.h.txt }

Set 2: { no2conc.txt, so2conc.txt, coconc.txt }

I am able to open each of them by using

reactanct_1 = fopen('reactant.1.h.txt','r');
no2_conc = fopen('no2conc.txt','r');

Indeed the "1", "2" and "3" in Set 1 refer to NO2, SO2 and CO in Set 2.

I want to write a function such that if I input NO2 into the function, it will open the two specific files in two sets.

So, I design as:

function openfile(chemical)

switch chemical
      case NO2
          id = 1; % for the use of set 1
          string = 'no2'; % for the use of set2
      case SO2
          id = 2; % for the use of set 1
          string = 'so2'; % for the use of set2
      case CO
          id = 2; % for the use of set 1
          string = 'co'; % for the use of set2

However, I give a trial that %d refers to my chemicals id and $s refers to the chemical names:

reactanct = fopen('reactant.%d.h.txt', id, 'r');
conc = fopen('%sconc.txt', string,'r');

But matlab returns me Error using fopen.

I appreciate for your help.

Copy a file to multiple files with indices and preserve format

I have a main.m file. I want to copy this file into main1.m, main2.m and main3.m.

I do like this:

for k=1:3

This code only gives main1, main2 and main3. I want append .m format to each of the file.

Many thank in advance.

Liferay 6.0.6 File Upload

I am using YUI 'io-upload-iframe' to upload files.

The strange issue is that the File object that i fetches in the serveResource method has a name for the temp file which is not present in the temp folder.

So when I try to move the file from the temp folder to the final destination, it is not able to find the temp file.

Can anyone please help in this regard?

C++ Syntax to enter values from code (like i from a loop) inside file name parenthesis for ofstream

I have a simple question, yet I can't find any documentation on it.. I'm trying to use ofstream and ifstream to read in file names with varying numbers, and output new files with those same numbers.

For example, if I have the files input1.txt, input2.txt, and input3.txt, and I need output1.txt, output2.txt, and output3.txt, I would do something like this:

for(i = 1; i <= 3; i++) {
ifstream fin("input"i".txt");
ofstream fout("output"i".txt");

... do stuff ...


Now, obviously this syntax for file names doesn't work. Does anyone have any idea how I could append on the number 1? Also I would need to append on other basic things, like one-word strings, etc.

Thanks in advance!

Python how to execute code from a txt file

I want to keep a piece of code in a txt file and execute it from my Python script.

For example in the txt file there is


I want my programme to print ok and not print print("ok "). How can I do this?

Bitbucket - remove file from pull request

On Bitbucket, how can I remove a file from a pull request without deleting it from the repository?

Download file from server to local machine - keep original last updated date

Currently I am downloading files using httpwebrequest and response and file stream, and the last updated date of file get changes to the current date of the server. Can I prevent this?

using (FileStream fileStream = File.Create(@sTargetPath))
                                Sys.Log2(20, "Filestream - copying starts");
                                fileCopy(responseStream, fileStream);

public static void fileCopy(Stream input, Stream output)
        byte[] buffer = new byte[3024]; 
        int bytesRead;

        while ((bytesRead = input.Read(buffer, 0, buffer.Length)) > 0)
            output.Write(buffer, 0, bytesRead);

make sure only visitors from my site can download my shared files from google drive

I don't want to allow people who didn't visit my site to download the files I uploaded to Google Drive. So, how can I do that? using reffer?

Excel VBA Getopen file dialog in Mac/Apple

I'm trying to open image in mac/apple excel vba using getopenfile dialog but it resulted in error so I have tried another way but unfortunately it doesn't work.

Below is Windows Code which works perfectly

Sub InsertOfficePic() Dim rngLogo As Range Dim sFileToOpen Dim pic As Excel.Picture Dim w, h Dim sngScale As Single 'Const csSHEET_NAME As String = "Open House Sheet" 'Const csRANGE_NAME As String = "OfficeLogo" sFileToOpen = Application.GetOpenFilename( _ "Picture Files,.jpg;.jpeg;.bmp;.png;.tif;.gif", _ Title:="Please select a Logo to insert in the flyer.") If sFileToOpen = False Then Exit Sub

Below is mac code that doesn't work Dim sFile As String Dim sMacScript As String If isMac Then If sPath = vbNullString Then sPath = "the path to documents folder" Else sPath = " alias """ & sPath & """" End If sMacScript = "set sFile to (choose file of type ({" & _ """"", ""org.openxmlformats.spreadsheetml.sheet""," & _ """public.comma-separated-values-text"", ""public.text"", ""public.csv""," & _ """org.openxmlformats.spreadsheetml.sheet.macroenabled""}) with prompt " & _ """Select a file to import"" default location " & sPath & ") as string" _ & vbLf & _ "return sFile" Debug.Print sMacScript sFile = MacScript(sMacScript) Else 'windows

Please help guys.

Thanks Thiru

keep variable throughout the life of the application in mvc

I need to keep variable throughout the life of the application. It shouldn't be disposed NEVER. I was thinking of two methods: 1. Keep it the file 2. Store in database in separate table but in the second case, create a separate table for one row isn't very clever. So how to achieve that? (Sorry for my english)

Reading large size wav files in MATLAB

I want to read 80 MB wav file in MATLAB. I tried wavread and audioread functions but I could not read it. I splitted wav file when I was reading by wavread(file, [startpos endpos]). But in 50. iteration the program has broken. I could not read file completely. It works for wavread(file, [1 500000]), but doesn't work wavread(file, [50000000 50500000]);

In import menu I can import 30 MB wav file directly but when I try to read step by step with for loop, it has been broken.

I changed Java Heap Memory to 560 MB from preferences.

I am waiting for your recommandations. Thanks.

get the absolute path from a relative path in Tcl

Say I have a file, named ./ko
I want it's full path, which can be (for example) /foo/bar/ko
In Perl, one just does


In Ruby, it is:


How is that done in Tcl?

WebStorm & Git - commit html + js files in the same folder

I have a project set up in WebStorm with Git as source control. I created a folder which contains two types of files: html and js. Structure is like this:


When I try to commit the files, or the folder entirely, it only includes in the commit the html files. I can't commit/push the js files to the repository. Is it supoosed to behave like this or I'm doing something wrong?