mardi 30 juin 2015

Use of LockableFileWriter class?

I am new to Java and my project led me to dive straight into apache.commons.io library, I cannot understand the purpose of LockableFileWriter class. Any specific usage example would help.

Can LockableFileWriter class in Apache Commons Library be used to perform an exclusive write operation through a java program?

Will the following snippet of code prevent concurrent writes through the java program?

Here is the Javadoc for LockableFileWriter class: http://ift.tt/1T4EgNY

Here is the Javadoc for IOUtils: http://ift.tt/1GJrv4H

File file = new File(fileName);
     LockableFileWriter writer = new LockableFileWriter(file,true);
     writer.flush();
     org.apache.commons.io.IOUtils.writeLines(lines,"\n",writer);
     writer.close();

Read file and add lines to array

I need to make my program read and write stuffs into text document. All would be simple but my C++ Doesn't have eof command which sets me on RAGE.

And because im using Embarcadero RAD studio... I have everything totally... Screwed(Hard not to insult it)

At first:
  ofstream myfile;
  myfile.open ("example.txt");
  myfile << "Writing this to a file.\n";
  myfile.close();
  ;

DOES NOTHING

Second:

EOF is NOT something RAD studio likes. I JUST DON'T HAVE IT. None in libraries.

Third: IT just screws up almost everything.

Any help? Where I can find commands for putting something in file or reading lines from file?

Stupid questions that must be asked and answers for them: Libraries?

#include "fstream"
#include "iostream"
#include "string"
#include "stdlib"
#include <stdio.h>

Did you created file? Yes.

Android, Files are not displayed when arrives to my created external folder

I have an issue with my app, files when arrive , pictures or other kind of files are stored in my custom file that is in the external storage, it saves them very well, for example i wanna watch a pictured that someone sent me, so when i go to gallery it doesn't show up anything like if there were no pictures, but when i see the file manager it is there.

It is displayed after a reboot. why is it happening? can someone give me any hint or an answer please i would appreciate it. i would like to know if there is a way to refresh it to see the files that arrived to my folder.

Absolute paths of files in iOS applications in swift

I need to be able to reference a file which is stored in my Xcode project in the following way:

thing

I want to be able to use files which I have stored inside of the "data" folder.

How do I reference it to be able to read its contents? What is it's directory path?

Segmentation Fault on fputs

I am pretty new to C and memory allocation in general. Basically what I am trying to do is copy the contents of an input file of unknown size and reverse it's contents using recursion. I feel that I am very close, but I keep getting a segmentation fault when I try to put in the contents of what I presume to be the reversed contents of the file (I presume because I think I am doing it right....)

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int recursive_back(char **lines, int lineNumber, FILE *input) {

   char *input_line = malloc(sizeof(char) * 1000);
   lines = realloc(lines, (lineNumber) * 1000 * sizeof(char));
   if(fgets(input_line, 201, input) == NULL) {
      *(lines + lineNumber) = input_line;
      return 1;
   }  
   else {
      printf("%d\n", lineNumber);
      return  (1+recursive_back(lines, ++lineNumber, input));

   }

}

void backward (FILE *input, FILE *output, int debugflag )   {
   int i;
   char **lines;                            //store lines in here
   lines = malloc(1000 * sizeof(char *) ); //1000 lines

   if(lines == NULL) {         //if malloc failed
      fprintf(stderr, "malloc of lines failed\n");
      exit(1);
   }

   int finalLineCount, lineCount;
   finalLineCount = recursive_back(lines, 0, input);

   printf("test %d\n", finalLineCount);

   for(i = finalLineCount; i > 0; i--) {     
      fputs(*(lines+i), output);            //segfault here
   }

}

I am using a simple input file to test the code. My input file is 6 lines long that says "This is a test input file". The actual input files are being opened in another function and passed over to the backward function. I have verified that the other functions in my program work since I have been playing around with different options. These two functions are the only functions that I am having trouble with. What am I doing wrong?

VHDL textio, reading image from file

I am trying to learn how to implement image processing algorithms in an FPGA and to do this I am working with a txt file that contains a bmp image (converted using MATLAB).

I am havin problems using the textio package, so by now I am only able to read the first column of data (but not the entire row of data).

The txt file have this aspect:

    1,1,0,0,0
    0,1,1,1,1
    1,0,0,0,0
    0,0,1,1,0
    1,1,1,1,1

a 5x5 matrix separated by commas. The output of the entity I have now in my simulations is

    1 0 1 0 1 

that corresponds to the first column. I don't understand why the code doesn't read all the line and when it ends jump to the next line.

Here is the process for read the file (I have add a variable named comma so I could detect the comma and skip it but still doesn't work ):

reading : process 

    constant filename : string := "C:\DOCUMENTACION\PROYECTOS\Envio_salida_VGA_atraves_FPGA\MatLab\Procesado de imagen con Toolbox\prueba.txt";
    file f : text open read_mode is filename;
    variable L : line;
    variable data_read : integer;
    variable comma : character;
begin
    while not endfile(f) loop
        wait until rising_edge(clk); 
            readline(f, L);
            read(L, data_read);

            while L = ',' loop
                read(L, comma);
            end loop;

            d_out <= data_read;
    end loop;

what is wrong with my code?

IOException while trying to read the file

me and my friend are creating android application for our studies which works like KeePass.

The problem is that this application works on my friend phone with Android 4.0.3 and on my phone with Android 4.4.2 KitKat it doesn't. Why?

I can create database file with no exceptions, but when I try to log in it throws IOException. We think that this exception might be thrown by FileInputStream but we don't have any idea why.

Here is the code where the exception appears:

public void onClickLogon(View view){
    _db = null;
    FileInputStream fis = null;
    try {
        fis = openFileInput(this.login.getText().toString() + ".db");
        _db = (PasswordDatabase) com.example.tomus.passwordwalletbeta.Security.decrypt(fis, this.login.getText().toString(), this.password.getText().toString());
        fis.close();
        if(_db==null){
            this.info.setText("Wrong informations.");
        }
        else {
            Intent intent = new Intent(MainActivity.this, LoggedActivity.class);
            Bundle bundle = new Bundle();
            bundle.putSerializable("db", _db);
            bundle.putString("login", login.getText().toString());
            bundle.putString("password", password.getText().toString());
            intent.putExtras(bundle);
            this.login.setText("");
            this.password.setText("");
            startActivity(intent);
        }
    } catch (InvalidKeyException | NoSuchPaddingException | NoSuchAlgorithmException e) {
        this.info.setText("Wrong informations.");
    } catch (FileNotFoundException e) {
        this.info.setText("FileNotFound");
    } catch (IOException e) {
        this.info.setText("IOException");
    }
}

Java/Android: Byte to file not saving?

I'm wondering what's wrong with this code:

public class MainActivity extends ActionBarActivity {
  protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        textView = (TextView) findViewById(R.id.textview);
        start();
    }
 public void start(){
        File file = new File("file.file");   
        try{

            FileOutputStream fos;
            fos = openFileOutput("file.file", Context.MODE_PRIVATE);
            BufferedOutputStream bos = new BufferedOutputStream(fos);

            if(file.length() == 0){
                BigInteger bi = new BigInteger("1000");
                bos.write(bi.toByteArray());
                bos.flush();
                bos.close();
                textView.setText(""+file.length()); //This is always 0, why? 
            }
            else{
             //do stuff, but since file.length() is always 0, this never happens. 
            }


}

So basically I want to check if the file is empty, if it's empty then add stuff to it. So what I expect is that when I open the application next time, the length shouldn't be empty since I've written to it earlier. However, the length of the file is always 0, why is that? File.length() says it returns the amount of bytes.

Android 4.4 doesnt create a file, but all works fine in Android 4.0.3

i have problem with creating file in Android. I create file in my CreateDatabaseActivity like this:

if(!Security.checkLogin(this._login.getText().toString()) || !Security.checkPassword(this._password.getText().toString()) || ( this._password.getText().toString().compareTo(this._passwordconfirm.getText().toString()) != 0 ))
{
    this._warning.setText(R.string.CDB_Warning);
}
else
{
    PasswordDatabase nowa = new PasswordDatabase();
    FileOutputStream fos = null;
    try {
        fos = this.getApplicationContext().openFileOutput(this._login.getText().toString() + ".db",MODE_WORLD_WRITEABLE);
        Security.encrypt(nowa,fos,this._login.getText().toString(), this._password.getText().toString());
        fos.close();
        this.finish();
    } catch (IOException e) {
        Log.e("Błąd","openFileOutput\r\n");
    } 


}

and open it in other activity with this code

_db = null;
FileInputStream fis = null;
try {
    fis = openFileInput(this.login.getText().toString() + ".db");
    _db = (PasswordDatabase) com.example.tomus.passwordwalletbeta.Security.decrypt(fis, this.login.getText().toString(), this.password.getText().toString());
    fis.close();
    if(_db==null){
        this.info.setText("Podano nieprawidłowe informacje.");
    }
    else {
        Intent intent = new Intent(MainActivity.this, LoggedActivity.class);
        Bundle bundle = new Bundle();
        bundle.putSerializable("db", _db);
        bundle.putString("login", login.getText().toString());
        bundle.putString("password", password.getText().toString());
        intent.putExtras(bundle);
        this.login.setText("");
        this.password.setText("");
        startActivity(intent);
    }
} catch (InvalidKeyException | NoSuchPaddingException | NoSuchAlgorithmException e) {
    this.info.setText("Podano nieprawidłowe informacje.");
} catch (FileNotFoundException e) {
    this.info.setText("Podano nieprawidłowe informacje. FileNotFound");
} catch (IOException e) {
    this.info.setText("Podano nieprawidłowe informacje. IOException");
}

}

This is the encrypt and decrypt methods:

public static void encrypt(PasswordDatabase object, OutputStream ostream, String login, String password){ try{ SecretKeySpec sks = new SecretKeySpec(generateKey(login,password),transformation);

    Cipher cipher = Cipher.getInstance(transformation);
    cipher.init(Cipher.ENCRYPT_MODE,sks);
    SealedObject sealedobject = new SealedObject(object,cipher);

    CipherOutputStream cos = new CipherOutputStream(ostream,cipher);
    ObjectOutputStream outputStream = new ObjectOutputStream(cos);

    outputStream.writeObject(sealedobject);
    outputStream.close();
    cos.close();
}catch(Exception e){
}

}

public static Object decrypt(InputStream istream, String login, String password) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, IOException{ SecretKeySpec sks = new SecretKeySpec(generateKey(login,password),transformation); Cipher cipher = Cipher.getInstance(transformation); cipher.init(Cipher.DECRYPT_MODE, sks);

CipherInputStream cipherInputStream = new CipherInputStream(istream, cipher);
ObjectInputStream inputStream = new ObjectInputStream(cipherInputStream);
SealedObject sealedobject;
try{
    sealedobject = (SealedObject) inputStream.readObject();
    inputStream.close();
    cipherInputStream.close();
    return sealedobject.getObject(cipher);
}catch(IOException | ClassNotFoundException | IllegalBlockSizeException | BadPaddingException e){
    Log.e("Błąd", "Jakis Exception....");
    return null;
}

So, why it works on my 4.0.3 but not on 4.4. How can I fix that?

Reading numeric keys from JSON file

Let's say I store a dictionary's values in JSON file. Here is the simplified code:

test = {}
for i in range(10):
    for j in range(15):
        test['{},{}'.format(i, j)] = i * j

with open('file1.json', 'w') as f:
    json.dump(test, f)

I have hard time reading back from this file. How can I read back from this file into a dictionary with elements like key as [i,j] and value as i*j?

Using argparse, how can I put the user input into a list?

I need the file path and os.path.dirname does not give me the complete path (it does not include the file itself - e.g. home/a/b instead of home/a/b/filename). Also I need the file name so that I can print it later. Since the argument the user inputs IS the filename, I need a way to store the input into a list.

import sys
import argparse
import inspect, os
import os.path

file_list = []

if __name__ == '__main__':
    parser = argparse.ArgumentParser()      
    parser.add_argument('file', type=argparse.FileType('r'), nargs='*')
    args = parser.parse_args()

    for f in args.file:
        with f:
            data = f.read()
            print data
            x = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
            print x
            file_list.append(x+#I need the filename here)

php file download sometimes not working (gzopen, gzwrite, gzclose)

<?php
set_time_limit(0);
$myfile = gzopen($constpath . '.gz', 'w');
if (!$myfile){
    throw new \UnexpectedValueException('could not open datafeed.gz file');
}
$mystream = gzopen($constURL, 'r');
if (!$mystream){
    throw new \UnexpectedValueException('could not open gzip remote file');
}
echo '1<br>';
while (!gzeof($mystream)){
$data = gzread($mystream, 8096);
gzwrite($myfile, $data);
}
echo '4<br>';
gzclose($mystream);
gzclose($myfile);
echo '5<br>';
echo 'down done';

//begin ungzip

$fp = fopen($constpath . '.csv', 'w');
$gz = gzopen($constpath . '.gz', 'r');

if (!$gz){
    throw new \UnexpectedValueException(
         'could not open gzip file'
    );
}
if (!fp){
    gzclose($gz);
    throw new \UnexpectedValueException(
        'could not open destination file'
    );
}

while (!gzeof($gz)) {
    fwrite($fp, gzread($gz, 8096));
}
gzclose($gz);
fclose($fp);
echo 'ungzip done';
?>

Hi, guys so above is my code, it intermittently allows me to download the gz file then unzip it, however it does not seem to be doing this in any sort of pattern or anything else, is there anything i need to know about how to use these functions like maybe is there a limit on the URL length (it's currently about 2.5K characters) but unfortunately not something i can change. what would people recommend on how to debug if there're bugs? or what i can do?

thanks!

Variables from a text file in ruby

So what I want to do is store data from a text based game I'm making in a file, but I can't figure out how.

After the user sets the variables from the program (ex: example1: true example 2: false example 3: true) And then after the set that, it goes to a settings file.

recursive deleting file linux C (discussion)

I am referring this question to the stackoverflow Answer How to clear directory contents in c++ on Linux (basically, i want to do 'rm -rf <directorypath>/*' . I just want to know few things which i was failed to interpret i.e is about nftw() and unlink_cb(const char *fpath, const struct stat *sb, int typeflag, struct FTW *ftwbuf).

Related to nftw(path, unlink_cb, 64, FTW_DEPTH | FTW_PHYS); i was able to understand whats the purpose of the parameter in nftw() through man nftw, and but i got confused that whats the purpose of these parameters in unlink_cb():

const struct stat *sb; ??

int typeflag; // which is FTW_DEPTH | FTW_PHYS ? is that correct?

struct FTW *ftwbuf; ??

Anyon who can explain it to me.

Python find word behind key word in a txt file

tree = open("start.txt")

for line in tree:
    if re.search("bodies name",line):
        liste.append(line.rstrip())

i have to append the word behind the key word bodies name. the txt file looks like: bodies name="Testname"

so i should append after bodies name=" until the next ">

is that possible

Thanks for help !!

One ifstream variable, multiple files c++ (programming help)

Can you use one ifstream variable to have multiple files?

I have a program that successfully reads all the files in a directory. However, while reading, the program only reads the first file, and puts all its lines into a vector. All the other files are not read. Basically, I am trying to identify all the functions in a c++ file.

I tried to use the clear() function but it still doesn't work. Help please!

Here is the code:

void getDefinitions(bool start){
    if (start == true){

        //vector<string> filesInDirectory;//files in the directory

        string input;

        cout << "\n\nEnter The Folder Location For Arduino Cores:";
        cin >> input;
        string dir = string(input);
        vector<string> files;// = vector<string>();

        getdir(dir,files);

        if (showVerbose == true){
            cout << "\nFiles Found in The Specified Folder: \n";
            for (unsigned int i = 0;i < files.size();i++) {
                cout << files[i] << endl;
            }

        }

        for (int i = 0; i < files.size();i++){
            if (files[i].find(".h") != string::npos){
                files.erase(files.begin() + i);
            }
        }

        for (int i = 0; i < files.size();i++){
            if (files[i].find(".h") != string::npos){
                files.erase(files.begin() + i);
            }
        }
    //do this multple times because doing it once misses some files for some reason

        for (int i = 0; i < files.size();i++){
            if (files[i].find(".h") != string::npos){
                files.erase(files.begin() + i);
            }
        }

    //erasing .h files as they are not needed

        if (showVerbose == true){
            cout << "\nFiltered Files: \n";
            for (unsigned int i = 0;i < files.size();i++) {
                cout << files[i] << endl;
            }

        }

        int iteratora = -1;

        string line;//variable for holding the characters in one line
        vector<string> programFile = vector<string> ();
        vector<string> librariesIncluded;



        for (unsigned int i = 0; i < files.size();i++ ){//for loop start

    iteratora++;
    string filename1 = files[iteratora];

        cout << "\n" << filename1 << ".\n";
        cout << "Iterator: " << iteratora << ".\n";

    programFile.clear();
    fstream afile (filename1);//(filename1);


    string line;//variable for holding the characters in one line



    if (afile.is_open())
    {
        while ( getline (afile,line) )
        {
            //cout << line << '\n';
            if (line != ""){
            programFile.push_back(line);
            line = "";
            }

        }
        afile.close();
    }

    afile.clear();

   print_vector(programFile);//used to know what is in the file

   int iteratore = 0;

            for (int i = 0; i < programFile.size(); i ++){  
                string programLine = programFile[iteratore];
                iteratore++;


                vector<int> qPositions;
                vector<int> tPositions;

                if (programLine.find("#include") != string::npos){

                    int qpos = programLine.find('"', 0);

                    while (qpos != string::npos){
                        qPositions.push_back(qpos);
                        qpos = programLine.find('"',qpos + 1);
                    }

                    if (qPositions.size() != 0){
                        programLine = programLine.substr(qPositions[0],qPositions[1]);

                    //  librariesIncluded.push_back(programLine);
                    }

                    int tpos = programLine.find('<', 0);

                    while (tpos != string::npos){
                        tPositions.push_back(tpos);
                        tpos = programLine.find('>',tpos + 1);
                    }

                    if (tPositions.size() != 0){
                        programLine = programLine.substr(tPositions[0],tPositions[1]);

                        librariesIncluded.push_back(programLine);
                        finalLibraries.push_back(programLine);
                    }


                    if (showVerbose = true){
                        cout <<"\nFound libary '"<< programLine << "'.\n";
                    }




                }


            }

}//loop end





    system("pause");









    }


 }


int getdir (string dir, vector<string> &files)
{
    DIR *dp;
    struct dirent *dirp;
    if((dp  = opendir(dir.c_str())) == NULL) {
        cout << "Error(" << errno << ") opening " << dir << endl;
        return errno;
        system("pause");
        exit(EXIT_FAILURE);
    }

    while ((dirp = readdir(dp)) != NULL) {
        files.push_back(string(dirp->d_name));
    }
    closedir(dp);
    return 0;
}

Thanks!

show a list of installed applications

When you press the right button in a picture from My Computer , Windows displays a list of installed applications associated with that type of file "OPen with..." how do I get the same list of programs using the WinAPi and creating a function in C ++ language

Search and Execute?

I'm new to coding and have a project I am currently undertaking. I have accomplished most of the code, but have gotten stuck on a certain aspect of the project.This would be on how to search for a specific folder for a text file, and get the dir info for that file to be used in third party applications. As of now, I can have the program be completed by having the user manually click on a "browse" button, and load the file selected, which the rest of the program will automate afterwards. My issue is having the program do this without user input.

For example, when the program initially executes, I would like it to search a specific folder for the first text file by date and time, and get the dir info. From that point on, I can load the file name in a text box to have the user visually see what they are about to send, and load the file into a few third party applications. I would then like the user to hit ,"send", have the file sent through the processes, delete itself in the end, and then have the program load the next file in the same folder. My only issue at the moment is having the program load the first file automatically. Like i said before, I was able to accomplish every other task, but by only having a browse option and having the user manually select the file. Any help in this matter would be greatly appreciated!

Renaming files en mass in MATLAB

When collecting data, I've currently named my files in the following format:

1_10.mat

Where the number before the underscore is a continent:

1- Africa
2- South America
3- Central America

The second number is the day in that continent the measurement was made on. What I'd like to do is to add the country the measurements were made in onto the end of the filename as well. For example:

1_1 --> 1_10 I want to rename each one to 1_1_Zaire --> 1_10_Zaire

1_11 --> 1_14, I want to rename each one to 1_11_Kenya --> 1_11_Kenya

How could I do this while keeping all the .mat files in the same folder? I'd prefer to use MATLAB for the renaming if possible.

I understand the algorithm will be something like the following:

  1. name a directory with all the .mat files
  2. make a for loop from bound 1 to bound x
  3. concatenate the phrase I want

The only problem is, I don't know how to get the length of the loop, and I don't understand how MATLAB reads files in a directory.

Android display files from URL GET

I'm working on the Android version of an app I did for iOS. I have some files (could be PDF, DOC, PNG, etc) in cloud storage and I retrieve them using an ASPX handler (like http://ift.tt/1LAkGXR).

In iOS I used a UIWebView and it would download and preview the file as long as the OS could handle that file type.

What is the best approach for Android? I've tried the following:

  • WebView and embedding in google docs (http://ift.tt/1hRPyTl) - DOES NOT WORK FOR PNG
  • Launching a new Activity using myIntent.setDataAndType(myFileURI, myFileMIME); where myFileMIME = MimeTypeMap.getSingleton().getMimeTypeFromExtension(myFileTypeExtension). For PNGS I get "No activity for type image/png"

Java- Find and use numbers from an xml file

I need to go in a url. it looks like an xml file. I need to find a specific set of numbers ( you can find them because the line would look something like this. Long = xyz.xyz Lat = xyz.xyz ) I need those numbers and I need to do some basic calculations with those numbers. How would I go about doing this. (its for work) I am a beginner Java programmer. I dont know exactly how to find those numbers in my data file. And then once I have them put them into variables so I can use them. Thanks!!!

ClassNotFoundException with dynamically generated and compiled source code [duplicate]

This question is an exact duplicate of:

The following code works correctly but in some cases when Class.forName method accesses the file it throws ClassNotFoundException because the file is not completely written, I solve the problem in those cases by increasing the sleep time.

But I want a way that forces the thread sleeps until file becomes completely written in stead of the static sleep(5000) ?

public void run(String className, String code) {
    String pkgname = "pkg" + (int) (Math.random() * 10000);
    String sb = "";
    sb += "package " + pkgname + ";\n";
    sb += code;

    File javaFile = new File(serverPath + pkgname + "/" + className + ".java");
    if (javaFile.getParentFile()
            .exists() || javaFile.getParentFile().mkdirs()) {
                try {
                FileWriter writer = new FileWriter(javaFile);
                writer.write(sb);
                writer.flush();
                writer.close();
                try {
                    Thread.sleep(5000);// here is the problem 
                } catch (InterruptedException ex) {
                    Logger.getLogger(InlineCompiler.class.getName()).log(Level.SEVERE, null, ex);
                }
                JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
                int compilationResult = compiler.run(null, null, null, javaFile.getPath());
                try {
                    String[] params = new String[0];
                    Method method = Class.forName(pkgname + "." + className).getMethod("main", String[].class);
                    method.invoke(null, (Object) params);

                } catch (NoSuchMethodException | SecurityException | IllegalArgumentException | InvocationTargetException | IllegalAccessException ex) {
                    Logger.getLogger(InlineCompiler.class.getName()).log(Level.SEVERE, null, ex);

                }

            } catch (IOException | ClassNotFoundException exp) {
                Logger.getLogger(InlineCompiler.class.getName()).log(Level.SEVERE, null, exp);

            }
}}

Again: my problem is not the logic of the code or of Compiling and executing the file dynamically but it is only related to the sleeping time.

Exception when I decreased sleep to 2000

    Jun 27, 2015 3:06:28 AM compile.InlineCompiler run
SEVERE: null
java.lang.ClassNotFoundException: pkg5958.test
    at java.net.URLClassLoader$1.run(URLClassLoader.java:372)
    at java.net.URLClassLoader$1.run(URLClassLoader.java:361)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:360)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
    at java.lang.Class.forName0(Native Method)
    at java.lang.Class.forName(Class.java:259)
    at compile.InlineCompiler.run(InlineCompiler.java:49)

How can you detect file changes with a OSX Library directory?

You can use NSMetadataQuery to detect any file changes within the home directory of a user. However it seems like it doesn't index and therefor detect any file changes in the users Library path.

Luckily for my purpose I know exactly where my file is and I like to know if the files changes and react on it. Do I need to right my own listener class? That will mimic the behavior of NSMetadataQuery by checking if the modification date changes or is there a simpeler way?

    var resource: AnyObject?
    fileURL?.getResourceValue(&resource, forKey: NSURLContentModificationDateKey, error: nil)
    if let fileDate = resource as? NSDate {
        println(fileDate)
    }

Trouble understanding file scope in C

I'm having trouble wrapping my head around files in C, specifically scope and duration. Say I create a file using

fopen("random.dat", "w");

How long does this file exist for? Does it get deleted once my program is finished running, or is it somehow reset? If I reopen the file further down in my code, only this time with the "r" reading argument, or "a", will I have conflicting streams since I'm opening a file that is already technically opened?

Store Path File in Database

I want to know to use files in my ASP.NET MVC App. I need to store the path of the file in the database (SQL Server), but where do I have to save the file (not the path)? Do I have to store them in the IIS? I'm really confused. A good reference will be awesome.

Hope you can help me. Thanks a lot.

Photo Website ( Database / Disk / Folders) Management

I'm planning to make a photo website and i'm having some doubts about how to proceed.

There will be several users and i'm wondering about how to store/retrieve their uploaded pictures etc...

I'm guessing , the links to the pictures location/names will be stored in the mysql database linked to their account. (Php)

However , i'm not sure if all the pics (from all users) should be uploaded to a single main folder or if i should have a specific folders for each user.

Will it be feasible to have a folder for each user , so their uploaded pics go directly there.

Like if there are many users and i also allow them to create albums(new folders within their main one) - how will it fare in the long run.

Will it be more resource consuming for the server or make no difference.


If anyone has any better ideas how to proceed with my current dilemma , please share your thoughts.

Thanks

how to read a large file line by line using tcl?

i written one code by using while loop but it will take much time to read the file line by line,can any one help me please. my code :

set a [open myfile r]
while {[gets $a line]>=0} {
"do somethig by using the line variable" }

file processing or sqllight?

I'm developing an application which is only about text like a book, when click on one title, the app open text of that title. Can you suggest me that, is better to use file or sqllight?

Converting Workbook object to File object

I have the workbook object of type:

org.apache.poi.ss.usermodel.Workbook
Workbook mybook;

I want to convert the same object to File:

java.io.File
File File;

How can i do that?

Thanks in advance

Scanning the contents of a directory which is stored in an Xcode project in swift

This seems to be a problem which is very difficult to explain. I am trying to read data from a folder full of files and the way I am trying to do this is by scanning the whole directory for all of the files. The file in question is stored in my Xcode project in the same directory as the view controllers and storyboards. Like so:

thing

I would like to be able to scan the contents of the "data" folder. Consider the following code:

var tmpDir = NSTemporaryDirectory()
var error: NSError?

let filesInDirectory: [String]! = fileManager.contentsOfDirectoryAtPath(tmpDir, error: &error) as? [String]

This scans the contents of the app's local folder and returns it as an array of the file names. I would like to be able to do this with the "data" folder in my Xcode project. The following code will find the contents of a single file which is stored in the same directory as the "data" folder.

let files = NSBundle.mainBundle().pathForResource("sampleFile", ofType: "csv")
var contents = String(contentsOfFile: path!, encoding: NSUTF8StringEncoding, error: nil)!

Is there a way in which I can combine the capabilities of the two in order to scan the contents of the "data" folder in the Xcode project and then return the file names as an array?

FFTW exports wisdom file but cannot load it

I am trying to achieve better performance for FFTW operations. For that reason I decided to use wisdom files for plan creation, but the problem is that it can't load the plans from wisdom files (exporting wisdoms works well). I tried to export the wisdom to a file and on the next program run to load it backthe wisdom file, but the function always returns 0 for any filename (even for non existing ones). I also tried it woth loading from a string but it doesn't work either.

There seem to be similar questions asked here, but none of them are answered or the problem was somewhere else. So is this a bug from the library, or am I doing something wrong?

As shown belove, is the code for loading the wisdom from a string using a file for content import (to show that the content is available in the file):

FILE * pfile;
string str="";
pfile=fopen("Gotham.txt","r");

if(pfile==0)
    cout<<"Could not open file"<<endl;
else
    cout<<"interesting"<<endl;

vector <char> buffer=0;
long length;

if(pfile)
{
    fseek(pfile,0,SEEK_END);
    length=ftell(pfile);
    fseek(pfile,0,SEEK_SET);
    buffer.assign(length,'\0');
    if(buffer)
        fread(buffer,1,length,pfile);
    fclose(pfile);
}
string stra(buffer);
cout<<stra<<endl;   //content could be read
free(buffer);

int ret=fftwf_import_wisdom_from_string(reinterpret_cast<const char*>(&buffer[0]));

HTML image upload results in loss of other form data

I have a simple upload form to upload multiple images

<form enctype="multipart/form-data" method="post" action="news/insert_news.php" class="form_news" id="newsform">
    <input type="text" class="inputHeading" name="heading" id="heading" maxlength="1000" placeholder="Überschrift" /><br /><br />
    <textarea rows="15" name="text" id="text" maxlength="10000" placeholder="Newstext"></textarea>
    <br /><br />
    <input placeholder="Datum (KLICK)" name="date" id="datepicker" /><br /><br />
    <input type="text" name="author" id="author" placeholder="Autor" /><br /><br />
    <input id="img" name="img[]" type="file" accept="image/*" multiple="multiple" /><br /><br />
    <button type="submit" id="sub">Absenden</button>
</form>

In my action file I check if the required fields are empty

if($title == "" || $text == "" || $author == "" || $date == "") {
    $_SESSION["formError"] = "<p class='formError'>Please fill in all fields.</p>";
    Header("Location: ../news_add.php");
    exit();
}

The values are catched via post

$title = mysql_real_escape_string(strip_tags($_POST["heading"]));
$text = nl2br(mysql_real_escape_string(strip_tags($_POST["text"], "<a><ul><li>")));
$text = trim($text);
$text = preg_replace('/<script\b[^>]*>(.*?)<\/script>/is', "", $text);
$author = mysql_real_escape_string(strip_tags($_POST["author"]));
$date = mysql_real_escape_string(strip_tags($_POST["date"]));

When I upload a small number of images (like 5) it works very well. But when I try to upload a larger number of images (like 20) the data like title, text etc. gets lost and the error to fill in all fields is printed.

How can I prevent this behaviour or is there any way to do so?

Java: Login System Won't Work [duplicate]

This question already has an answer here:

I've been making a login system prototype for my game, sad thing is it doesn't work! I'm not sure why but here's my code:

This is the code for my main class:`

package darkbyte.tests;

import java.util.Scanner;

public class Main {

    private static FileCreator creator = new FileCreator();
    private static FileReader reader = new FileReader();

    private static void login() {
        Scanner input = new Scanner(System.in);

        boolean passwordExists;

        System.out.println();
        System.out.println("Please enter your username: ");
        String username = input.nextLine();
        System.out.println("Please enter your password: ");
        String password = input.nextLine();

        reader.openFile(username + ".user");
        if(reader.doesStringExist(password)) {
            passwordExists = true;
        } else {
            passwordExists = false;
        }

        reader.closeFile();

        if(passwordExists) {
            System.out.println("Welcome back to Darkbyte " + username + "!");
        } else {
            System.out.println("The password you entered is incorrect!");
            login();
        }
    }

    private static void register() {
        Scanner input = new Scanner(System.in);

        System.out.println();
        System.out.println("Please enter the username you desire: ");
        String username = input.nextLine();
        System.out.println("Please enter the password you desire: ");
        String password = input.nextLine();

        creator.openFile(username + ".user");
        creator.writeString(username);
        creator.writeString(password);
        creator.closeFile();
    }

    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);

        System.out.println("Welcome to Darkbyte!");
        System.out.println("Would you like to login or register an account?"); 
        System.out.println("Enter 0 to login and any other number to register: ");
        int choice = input.nextInt();

        if(choice == 0) {
            login();
        } else {
            register();
        }
    }
}

This is the code for my FileCreator class:

package darkbyte.tests;

import java.io.*;

import java.util.*;

public class FileCreator {

    private Formatter format;

    public void openFile(String file) {
        try {
            format = new Formatter(file);
        } catch(Exception e) {
            System.err.println("Darkbyte: There was an error in opening the file!");
        }
    }

    public void closeFile() {
       format.close();
    }

    public void writeInteger(int i) {
        format.format("%i%n", i);
    }

    public void writeFloat(float f) {
        format.format("%f%n", f);
    }

    public void writeString(String s) {
        format.format("%s%n", s);
    }

    public void appendInt(String file, int i) {
        try(PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(file, true)))) {
            out.println(i);
        }catch (IOException e) {
            System.err.println("Darkbyte: Couldn't find file!");
        }
    }

    public void appendFloat(String file, float f) {
        try(PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(file, true)))) {
            out.println(f);
        }catch (IOException e) {
            System.err.println("Darkbyte: Couldn't find file!");
        }
    }

    public void appendString(String file, String s) {
        try(PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(file, true)))) {
            out.println(s);
       }catch (IOException e) {
             System.err.println("Darkbyte: Couldn't find file!");
        }
    }
}

This is the code for my FileReader class:

package darkbyte.tests;

import java.io.*;

import java.util.*;

public class FileReader {

    private Scanner scanner;

    public void openFile(String file) {
        try {
            scanner = new Scanner(new File(file));
        } catch(Exception e) {
            System.err.println("Darkbyte: Couldn't find file!");
        }
    }

    public void closeFile() {
        scanner.close();
    }

    public void readInt(int i, int lookingFor) {
        while(i != lookingFor) {
            if(scanner.hasNext()) {
                i = Integer.parseInt(scanner.next());
            }
        }
    }

    public void readFloat(float f, float lookingFor) {
        while(f != lookingFor) {
            if(scanner.hasNext()) {
                f = Float.parseFloat(scanner.next());
            }
        }
    }

    public void readString(String s, String lookingFor) {
        while(s != lookingFor) {
            if(scanner.hasNext()) {
                s = scanner.next();
            }
        }
    }

    public boolean doesIntExist(int i) {
        boolean intIsFound = false;
        int tempInt;

        while(scanner.hasNext()) {
            if(!intIsFound) {
                tempInt = Integer.parseInt(scanner.next());
                if(tempInt == i) {
                    intIsFound = true;
                } else {
                    intIsFound = false;
                }
            }
        }

        return intIsFound;
    }

    public boolean doesFloatExist(float f) {
        boolean floatIsFound = false;
        float tempFloat;

        while(scanner.hasNext()) {
            if(!floatIsFound) {
                tempFloat = Float.parseFloat(scanner.next());
                if(tempFloat == f) {
                    floatIsFound = true;
                } else {
                    floatIsFound = false;
                }
            }
        }

        return floatIsFound;
    }

    public boolean doesStringExist(String s) {
        boolean stringIsFound = false;
        String tempString;

        while(scanner.hasNext()) {
            if(!stringIsFound) {
                tempString = scanner.next();
                if(tempString == s) {
                    stringIsFound = true;
                } else {
                    stringIsFound = false;
                }
            }
        }

        return stringIsFound;
    }
}

The issue is, when I try to login, even if my username and password are correct, it still says that my details are incorrect!

I'm not sure why but can you help me out please!

what are the concern regarding simultaneous read and write to a file?

consider the following scenario:

  1. Process 1 (Writer) continuously appends a line to a file ( sharedFile.txt )
  2. Process 2 (Reader) continuously reads a line from sharedFile.txt

my questions are:

In java is it possible that :

  1. Reader process somehow crashes Writer process (i.e. breaks the process of Writer)?
  2. Reader some how knows when to stop reading the file purely based on the file stats (Reader doesn't know if others are writing to the file)?

to demonsterate

Process one (Writer):

...
while(!done){
 String nextLine;//process the line
 writeLine(nextLine);
 ...
}
...

Process Two (Reader):

...
while(hasNextLine()){
  String nextLine= ReadLine();
  ...
}
...

gallery file selector javascript

I have a drag and drop upload page that uploads images to my server, and through php i am able to select images and generate a gallery etc, but what i want to do is select the files in a more visually appealing way. At the minute i essentially have a long table with a corresponding check box and a thumbnail for each images and tick the images i want and add them to a gallery i have created earlier. but i would like to be able to select the files using something that looks more like the bulk selection tool in the media section of wordpress? could someone even just point me in the direction of looking for something like this? I don't know how to verbalise what it is i am looking for?

Codeigniter - show file name with extension

I am using Codeigniter framework. i have codeigniter view record page.

where im showing file name. but now i want to show file name and file extension seperately. like this

file name  |  file ext

how to remove the downloded file after clicking on the download link from server

i am generating a .MSI file and giving a link to download it .but after download i need to delete that file (in case of user selected to 'save' not cancel).please give some inputs to me on this regard.thanks in advance.

i thought to use readfile() but it will through output to browser.which is not my case. i need to download the MSI file on clik.

Php: $_POST is not set after form is sent to iframe

I have just spent 4 hours researching and nothing has fixed my problem, so here I am. I am trying to design my own little chunk file uploader, and all is working quite well.

I have a main upload page that lets you set a file to upload. It then automatically cuts the first chunk out of the bytes of the file, and puts it into a form, along with some other bits of information:

    <form id="hiddenform" name="hiddenform" action="SecretChunkUploader.php" target="iframe" enctype="multipart/form-data" method="post">
        <hidden id="Bytes" name="Bytes" value="" />
        <hidden id="Pass" name="Pass" value="<?php echo $_POST['Pass'];?>" />
        <hidden id="FileName" name="FileName" value="" />
        <hidden id="PackageNumber" name="PackageNumber" value="" />
</form>

Every <hidden> has its value correctly sent when the form is submitted through this javascript command:

document.forms["hiddenform"].submit();

The form is submitted to an iframe:

<iframe id="iframe" name="iframe" onload="" style="display:block"></iframe>

When submitted, the iframe navigates to the page specified in the form's action attribute.

Everything works well, except for when the form is received. The page loads, but there is no post data, and the variables for post are not set.

Here is the code for SecretChunkUploader.php:

    <?php
echo "Password: ".$_POST["Pass"]."<br/>";
echo "FileName: ".$_POST["FileName"]."<br/>";
echo "PackageNumber: ".$_POST["PackageNumber"]."<br/>";
echo "Bytes: ".$_POST["Bytes"];
?>

The loaded page from SecretChunkUploader.php looks like:

Password:
FileName:
PackageNumber:
Bytes: 

I have tried testing isset() and it returned false for all of the post variables.

What on Earth am I doing wrong? I have tested and know that the form is fully working, it just doesn't pass the values onwards.

Thanks in advance for any help!

Lost a file in notepad++

I'm working on a website, and I regularly save my files after editing. However, after trying to save, notepad++ crashed. When i started it again, the file I tried to save is totally empty...

Is there a way (a temp file or anything) to recover my lost file? It has like 2200+ lines, and I really wish to recover it...

Thank you very much.

wwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwww

Delete a chunk of text from a text file (Python)

I am looking for a solution for a code. I need to delete a section of writing in a file using python, the chunk is 5 lines here's an example.

Numberplate: BN30CWS

Time In: Time In: 11:11:3

Time Out: Time In: 11:11:51

Speed: Your Speed: 48MPH

Was this vechile speeding?: No

(Without the gaps )

So if i enter BN30CWS i want those 5 lines to be deleted from the file (fileDocStandard) Please help. Thank you Mike

Where are files saved in MVC4 2010 project where no path is declared?

I've created a file with the filepath of simply "test.txt" using File.Create method.

I've managed to email this file to myself using an email class and the filepath of "test.txt".

I want to find the actual file in my project folder, but can't see to find it even with a search for test.txt.

Is it a temp file, and where would it be saved to?

Upload file using jQuery and post it to Controller

I'm wondering if it would be possible at all to upload a file by posting it to a controller action in ASP.NET MVC. The dialog for this upload form will be dynamically generated and will be inside a jQuery dialog in my case.

I'm aware of the file input element but I'm not sure how to send the file to a controller action, not sure how to set the action parameter

Nlogo file refusing to open - error message "File is not a valid Netlogo model file"

Please please can someone help me. I have been working on a netlogo model for weeks and yesterday saved my latest version as 'Glen Creran1.nlogo'. Today when I go to open it I get the message 'File is not a valid Netlogo model file'. Earlier versions of the same file are opening fine (such as Glen Creran.nlogo). I dont understand what is going on.
Please please can someone help. I have worked so hard on this code.... Any suggestions very welcome - maybe I can find a backup somewhere? Many thanks, Sally.

Loading multiple .mat files containing the same variable name and changing the variable names simultaneously?

So I have a directory that has many .mat files:

apples.mat, oranges.mat, bananas.mat, grapes.mat, apricots.mat, pears.mat, pineapple.mat

All of these .mat files has a variable name "calories" assigned a value. How do I load all of these .mat files simultaneously in MATLAB and change the variables for each one from calories to calories_(fruit name) so that I can have all the variable values in the workspace to play with?

For example, I want to load apples.mat and change its variable name from calories to calories_apple, then load oranges.mat and change is variable name from calories_orange, etc. without doing it all manually.

I know it's something along the lines of creating a string with the different fruit names, and the indexing along the string to load a file and change its variable from variable to variable_%s with the %s indicating the fruit content generated along the loop. It's a big mess for me, however, I don't think I'm structuring it right. Would anyone care to help me out?

NodeJs + OracleDB + load sql file

The problem is simple, I cant load an sql file using the oracledb connector. It seems it doesn´t supoport more than one sentence.

Any idea how to load an sql file?

var oracledb = require('oracledb');
var fs = require('fs');

fs.readFile("test.sql", function(err, data) {
    if (err) {
        throw err;
    }

    connect(data.toString());
});

function connect(sql) {
    oracledb.getConnection({
            user: "****",
            password: "***",
            connectString: "****"
        },
        function(err, connection) {
            if (err) {
                console.error(err.message);
                return;
            }
            connection.execute(
                sql, [],
                function(err, result) {
                    if (err) {
                        console.error(err.message);
                        doRelease(connection);
                        return;
                    }
                    console.log(result.metaData);
                    console.log(result.rows);
                    doRelease(connection);
                });
        });
}

function doRelease(connection) {
    connection.release(
        function(err) {
            if (err) {
                console.error(err.message);
            }
        });
}

It throws an error:

ORA-00911: invalid character

The sql is here:

select * from DEFECTO;
select * from ESQUEMA;

lundi 29 juin 2015

Scanner not reading content from file

I am trying to write the number 0 to a file called amountSessions the first time it is created as you can see in the if statement below the comment "On the first run" which works so far, but later on in the program (at the end of the writeToFile method) below the comment "Increment number each run" I want to increment the 0 I discussed earlier by 1 each time the program runs. Unfortunetly when I do compile and run the program I am given the following error. Why is this? Thank you very much everybody!

Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:862)
at java.util.Scanner.next(Scanner.java:1485)
at java.util.Scanner.nextInt(Scanner.java:2117)
at java.util.Scanner.nextInt(Scanner.java:2076)
at math_program.fileWriting.getInt(fileWriting.java:62)
at math_program.fileWriting.writeToFile(fileWriting.java:41)

//Test

package testing;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
import javax.swing.JOptionPane;

public class Kappa
{
    String numberFilePath = "/Users/john/Desktop/numProblems.txt";
    String sessionFilePath = "/Users/john/Desktop/amountSessions.txt";
    File testFile = new File(numberFilePath);
    File amountSessions = new File(sessionFilePath); 

    public void writeToFile() throws IOException
    {

        //On the first run
        if(!testFile.exists())
        {
            testFile.createNewFile();
        } else if(!amountSessions.exists())
        {
            amountSessions.createNewFile();
            FileWriter sessionWriter = new FileWriter(amountSessions);
            sessionWriter.write("0");
            sessionWriter.close();
        }

        FileWriter durationWriter = new FileWriter(testFile);
        FileWriter sessionWriter = new FileWriter(amountSessions);

        //Write Duration
        String ans = prompt();
        durationWriter.write(ans);
        durationWriter.close();

        //Increment number each run
        sessionWriter.write(getInt());
        sessionWriter.close();

        System.exit(0); 
    }

    public void grab() throws FileNotFoundException
    {
        Scanner numProblemsReader = new Scanner(new File("/Users/john/Desktop/numProblems.txt"));
        Scanner numSessionReader = new Scanner(new File("/Users/john/Desktop/amountSessions.txt"));
        int number = numProblemsReader.nextInt();
        int numSessions = (numSessionReader.nextInt() + 1);

        System.out.println("The number read from the file is: " + number);
        File replaceFile = new File("/Users/john/Desktop/session" + numSessions + ".txt");
        testFile.renameTo(replaceFile);
    }

    public String getInt() throws FileNotFoundException
    {
        Scanner numSessionReader = new Scanner(new File("/Users/john/Desktop/amountSessions.txt"));
        int numSessions = ((numSessionReader.nextInt()) + 1);
        String newNum = Integer.toString(numSessions);
        return newNum;
    }

    public String prompt()
    {
        String ans = JOptionPane.showInputDialog ("Enter the new amount of problems per training session (with number in minutes):");                        

        while(!ans.matches("[0-9]+"))
        {
            ans = JOptionPane.showInputDialog ("Please re-enter the new amount of problems per training session (with number in minutes):" ); 
        }    

        return ans;
    }
}

I'm trying to install BigVideo.js using Bower for my first time - and all instructions have left me lost

Here's what I've done:

  • Got familiar with command line.
  • Installed: Node & NPM, Git & installed Bower globally.
  • installed and $ bower init the project

And here's I stand in the terminal ...

....."

bigvideo.js#1.1.5 bower_components/bigvideo.js
├── imagesloaded#3.1.8
├── jquery#2.1.4
├── jquery-ui#1.11.4
└── video.js#4.12.10
TODD-HANEYs-MacBook:~ toddhaney1$ bower install bigvideo.js --save
bower cached        git://github.com/dfcb/BigVideo.js.git#1.1.5
bower validate      1.1.5 against git://github.com/dfcb/BigVideo.js.git#*
bower no-json       No bower.json file to save to, use bower init to create one
TODD-HANEYs-MacBook:~ toddhaney1$ bower init
? name: "video-big"
? version: 0.0.0
? description: "Background Video Plug in for websites"
? main file: 

".....

I don't know where my project folder is or what's in it, but, in order to make a json file, I am supposed to answer very specific questions about what's inside of it when I don't even know where it is.

None of the help, articles or tutorials explained "how," they just say "what" to do with technical terms that don't help the beginner.

If anyone could tell me what my next steps are, (where my file is) and basically HOW I get started with bower and any advice on what to use, Grunt etc...

Thanks in advance to anyone who offers an answer...

Read file in ruby getting output as spaces in character

I have stored variable output to the file through powershell script. Ex: 7644511AAFCFBA6A0CC4706F3AA795BB86 stored in file.txt

After that I read the data from the file and stored it in the variables using ruby script.

When I print the variable it is printing the data with spaces in between characters. Ex: ■7 6 4 4 5 1 1 A A F C F B A 6 A 0 C C 4 7 0 6 F 3 A A 7 9 5 B B 8 6 E D 5 3 3 0

I want to store the data in a variable with out any spaces between characters. I tried a lot, but could not find the solution. Please give me your valuable suggestions.

I am doing this in windows platform

tomcat 8 file download speed issue

Thanks in advance, I am using Tomcat 8 and I have functionality to download large files from tomcat server places in context docbase folder. Below was the piece of code I am using the file to download PrintWriter out = response.getWriter();
response.setContentType("APPLICATION/OCTET-STREAM");
response.setHeader("Content-Disposition", "attachment; filename=filename);
FileInputStream fileInputStream = new FileInputStream("filepath");
int i;
while ((i=fileInputStream.read()) != -1) {
out.write(i);
}
fileInputStream.close();
out.close(); When i download a file it was downloading with a speed of 65KB/sec from the save server if I place the same file in Apache server and tries to download the download speed is 135KB/sec

Could some one help me how to speed up the file download from tomcat

Referencing directories within an Xcode project for an iOS app

I need to be able to reference specific files within a directory inside of my xCode project. So far I have this code:

let files = NSBundle.mainBundle().pathForResource("sampleFile", ofType: "csv")
var contents = String(contentsOfFile: path!, encoding: NSUTF8StringEncoding, error: nil)!

Which works to open a single file, but I would like to be able to open a file that is stored inside one or two directories within the main bundle.

Does anybody know how to do this?

Can't get php to display access.txt file in html

This may be a noob question. In which case, sorry. I can't get this php script to read the contents of a txt file in the same directory. It outputs

';?>

and

.$theData.

here is the code

<article> 
<?php
$Color = "red";
$myFile = "access.txt";
$fh = fopen($myFile, 'r');
$theData = fread($fh, 5);
fclose($fh);
echo '<div style="Color:'.$Color.'">'.$theData.'</div>';
?>
</article>

max length for "value" attribute of a html input text field

How long a string can I fit into the value attribute of a html input field?

<input type="text" value="how-long-long-long-long" size="21" />

I'm trying to add comma separated values into a hidden text field - but these values are getting fetched from another developer. I tried to look up for this threshold value in The Bible but they don't have it there.

Please help me.

Finding all of the files within a directory within the main bundle of an iOS app - swift

I have a folder in my Xcode project called data and I need to be able to reference specific files within that directory. So far I have this code:

let files = NSBundle.mainBundle().pathForResource("sampleFile", ofType: "csv")
var contents = String(contentsOfFile: path!, encoding: NSUTF8StringEncoding, error: nil)!

Which works to open a single file, but I would like to be able to open a file that is stored inside one or two directories within the main bundle.

Does anybody know how to do this?

Variables from a text file in ruby

So what I want to do is store data from a text based game I'm making in a file, but I can't figure out how.

After the user sets the variables from the program (ex: example1: true example 2: false example 3: true) And then after the set that, it goes to a settings file.

read commands from .txt sd in reverse order arduino

I'm wondering what the best method is to either reverse a text file from an SD card or read the command strings, last line to first line.

The strings will likely be lengthy so I don't want to create an array that will crash the arduino. Also, I want to avoid using .position and .seek methods because the commands are being stored in chunks of many lines and I feel logging/referencing all the unsigned long data would become too complex for me.

I would like to create a new text file that is a copy but in reverse order so I can read and execute a command one line at a time. If it is too difficult to do that, i will consider changing my code to integrate unsigned long time and pointers.

The text lines are of the form: "i, millis(), val, \r\n"

My code is very rough but any help or direction would be greatly appreciated, Thanks.

One ifstream variable, multiple files c++ (programming help)

Can you use one ifstream variable to have multiple files?

I have a program that successfully reads all the files in a directory. However, while reading, the program only reads the first file, and puts all its lines into a vector. All the other files are not read.

I tried to use the clear() function but it still doesn't work. Help please!

Here is the code:

//This part prints all the files and works fine.

    for (unsigned int i = 0;i < files.size();i++) {
            cout << files[i] << endl;
    }



int iteratora = -1;

string line;//variable for holding the characters in one line
vector<string> programFile = vector<string> ();
//ignore this line vector<string> librariesIncluded;



for (unsigned int i = 0; i < files.size();i++ ){//for loop start

    iteratora++;
    string filename1 = files[iteratora];

        cout << "\n" << filename1 << ".\n";
        cout << "Iterator: " << iteratora << ".\n";

    programFile.clear();
    fstream afile (filename1);//(filename1);


    string line;//variable for holding the characters in one line



    if (afile.is_open())
    {
        while ( getline (afile,line) )
        {
            //cout << line << '\n';
            if (line != ""){
            programFile.push_back(line);
            line = "";
            }

        }
        afile.close();
    }

    afile.clear();

   print_vector(programFile);//used to know what is in the file
    /*

      do stuff with 'programFile'


    */  

}//loop end

print_vector() definition

void print_vector(const vector<string> &v)
{
    for (auto i = v.begin(); i != v.end(); ++i)
    {
        cout << "\n";
        std::cout << *i;
        cout << "\n";
    }
}

Thanks!

File processing in C; won't take input

I'm starting to learn file processing in C. The point of this specific program is to make a file called "clients.dat" where I store the account number, name, and balance of clients at a bank, lets say. I've worked and refined the code so that its a perfect replica of what the textbook provides as an example, yet for some reason mine loops endlessly after the first "scanf" and reprints question marks unto oblivion, without ever making it to the scanf statement inside the while loop. Would anyone have any suggestions as to why this is happening? My compiler is Netbeans and I'm running it on Linux-Ubuntu.

#include <stdio.h>
#include <stdlib.h>

/*
 * 
 */
int main() {

    unsigned int actNumber;
    char actName[30];
    long double actBalance;

    FILE *fPtr;

    if((fPtr = fopen("clients.dat", "w")) == NULL) {
        printf("File could not be found.\n");
    }

    else {
        printf("Enter the Account Number, Name, and Balance.\n Hit the EoF to exit.\n");
        printf("%s","?");
        scanf("%d%29s%lf", &actNumber, actName, &actBalance);

        while (!feof(stdin)) {            
            fprintf(fPtr, "%d, %29s, %.2lf\n", actNumber, actName, actBalance);
            printf("%s", "?");
            scanf("%d%29s%lf", &actNumber, actName, &actBalance);                        
        }

        fclose(fPtr);
    }
    return;
}

Ruby - Can't write to file after checking if empty

The program should write "File Empty" if the file is empty; otherwise, it should write "File Full". Here's what I have so far:

fname = "fileTest.txt"
somefile = File.open(fname, "w")

if File.readlines(somefile).grep(/monitor/).size == 0
    somefile.write("File Empty")
else
    somefile.write("File Full.")
end

somefile.close

When I run this the first time, fileText.txt is empty, so the program writes "File Empty". When I run it a second time, the program should write "File Full", but the file still reads "File Empty".

The if statement should be checking if the file is empty, but I don't it is working correctly. What am I doing wrong?

addition with python into a .txt file

i am creating a chatroom bot using python 2.7.9 and i wanna know how to take the number i have in the .txt file and add a number to it, im stuck and i wanna know how to do this so i can add currency to my chatroom bot. ive tried to do this before but i am having too many problems with it. "args" is the argument/number i want to add "yp" is the currency i am using this is what i have, but it isnt working Definition for the currency:

yp = []
f = open("yp.txt", "r")
time.sleep(1)
for currency in f.readlines():
    if len(currency.strip())>0: yp.append(currency.strip())
f.close()

what i use to save the numbers to the file:

def saveyp(user):
f = open("yp.txt", "w")
f.write("\n".join(wl+args))
f.close()

and my command i have for the bot:

if used_prefix and cmd == "test" and user.name in owners:
    if args:
        yp.append(yp+args)
        saveyp(yp+args)
        room.message("$"+args+" has been added to your currency :)")
        room.message(user.name.capitalize()+", you now have $"+yp)
    else:
        room.message("ERROR!")

Data will not parse and extract into excel file?

import pandas as pd 
import os
import time 
from datetime import datetime


path = "C:\\Users\s\Downloads\H\intraQuarter"

def Key_Stats(gather = "Total Debt/Equits (mrq) "):
statspath = path + '/_KeyStats'
stock_list = [x[0] for x in os.walk(statspath)]
df = pd.DataFrame(columns = ['Date','Unix','Ticker','DE Ratio'])

for each_dir in stock_list[1:25]: 
    each_file = os.listdir(each_dir)
    ticker = each_dir.split("\\")[-1] 
    if len(each_file) > 0: 
        for file in each_file:
            date_stamp = datetime.strptime(file, '%Y%m%d%H%M%S.html')
            unix_time = time.mktime(date_stamp.timetuple())
            full_file_path = each_dir+'/'+file

            source = open(full_file_path,'r').read()
            try:
                value = float(source.split(gather+':</td><td class="yfnc_tabledata1">')[1].split('</td>')[0])
                df - df.append({'Date':date_stamp,'Unix':unix_time,'Ticker':ticker,'DE Ratio':value,}, ignore_index = True)
            except Exception as e:
                pass

save = gather.replace(' ','').replace(')','').replace('(','').replace('/','')+('.csv')
print(save)
df.to_csv(save)



Key_Stats()

This is my code and everytime I open the excel sheet it just has the headers of the table but non of the data it should be extracting from the files. any idea on why its not copying the data?

Go: "tail -f"-like generator

I had this convenient function in Python:

def follow(path):
    with open(self.path) as lines:
        lines.seek(0, 2)  # seek to EOF

        while True:
            line = lines.readline()
            if not line:
                time.sleep(0.1)
                    continue
                yield line 

It does something similar to UNIX tail -f: you get last lines of a file as they come. It's convenient because you can get the generator without blocking and pass it to another function.

Then I had to do the same thing in Go. I'm new to this language, so I'm not sure whether what I did is idiomatic/correct enough for Go.

Here is the code:

func Follow(fileName string) chan string {

    out_chan := make(chan string)

    file, err := os.Open(fileName)
    if err != nil {
        log.Fatal(err)
    }

    file.Seek(0, 2)
    bf := bufio.NewReader(file)

    go func() {
        for {
            line, _, err := bf.ReadLine()

            if err == io.EOF {
                time.Sleep(10)
            } else {
                out_chan <- string(line)
            }
        }

        defer file.Close()
        close(out_chan)
    }()

    return out
}

Is there any cleaner way to do this in Go? I have a feeling that using an asynchronous call for such a thing is an overkill, and it really bothers me.

move_upload_file uploading old file?

I'm working on an "Edit post" page which allows users to upload a picture to replace their old picture (displayed at the bottom of the post). Here's the code:

if (isset($_FILES['pic']['tmp_name']) && $_FILES['pic']['name']!=NULL) {

            $target_file1 = $dir . $postid . "." . $imageFileType1;
            $target_png1 = $dir . $postid . ".png";
            $target_jpg1 = $dir . $postid . ".jpg";
            $target_jpeg1 = $dir . $postid . ".jpeg";

            if (file_exists($target_png1)) {
                unlink($target_png1);
            }
            if (file_exists($target_jpg1)) {
                unlink($target_jpg1);
            }
            if (file_exists($target_jpeg1)) {
                unlink($target_jpeg1);
            }
            move_uploaded_file($_FILES["pic"]["tmp_name"], $target_file1);
        }

Through doing testing, I know that it works fine as long as the new picture is a different extension from the original. But if it's the same extension it deletes the old one and the move_uploaded_file reuploads the old one.

I know this because I commented out the "move_uploaded_files" and it successfully deleted the old file.

Any clues why it would be reuploading the old file instead of the uploaded one?

Django 1.8 File Upload Example

I’m new to the Django development platform. I have been struggling to create a basic file upload app in Django 1.8.2 (latest version). I could not find any up-to-date example/snippet. So I appreciate if you could post here or refer me to a minimal but complete (Model, View, Template) example code to do so.

I’ve observed many other examples online but I notice that my version does not have the MEDIA_ROOT or MEDIA_URL attributes by default. For example:

MEDIA_ROOT = '/path/to/myproject/media/'
MEDIA_URL = '/media/'

Here is my Models.py page

from django.db import models

# Create your models here.

class Test(models.Model):
   first_name = models.SlugField()
   last_name = models.SlugField()
   email = models.EmailField()
   timestamp = models.DateTimeField(auto_now_add = True, auto_now = False)
   updated = models.DateTimeField(auto_now_add = False, auto_now = True)

def __unicode__(self):
    return self.email
Here is my Forms.py page

from django import forms
from .models import Test

class EmailForm(forms.Form):
    first_name = forms.CharField(required=False)
    last_name = forms.CharField(required=False)
    email = forms.EmailField()

class TestForm(forms.ModelForm):
    class Meta:
    model = Test

Here is my Views.py page

from django.shortcuts import render
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse

# Create your views here.
from .forms import EmailForm, TestForm
from .models import Test

def home(request):
   # print request.POST["email"], request.POST["email2"]

   form = EmailForm(request.POST or None)
   if form.is_valid():
      first_name = form.cleaned_data['first_name']
      last_name = form.cleaned_data['last_name']
      email = form.cleaned_data['email']
      new_test, created = Test.objects.get_or_create(email = email,        first_name = first_name, last_name = last_name)

# # This is using Model Forms
# form = TestForm(request.POST or None)
# if form.is_valid():
#     new_test = form.save(commit = False)
#     #We Might Do Something Here
#     email = form.cleaned_data['email']
#     new_test_old, created = Test.objects.get_or_create(email = email)
#     # new_test.save()

context = {"form": form}
template = "home.html"
return render(request, template, context)

This is my URLs.py page

from django.conf.urls import patterns, include, url
from django.conf import settings
from django.conf.urls.static import static

from django.contrib import admin
admin.autodiscover()

urlpatterns = patterns('',
# Examples:
url(r'^$', 'tests.views.home', name='home'),
# url(r'^home2/$', 'lwc.views.home2', name='home'),
# url(r'^blog/', include('blog.urls')),

#This admin can be changed to anything but the
#link must also be changed to access admin area
url(r'^admin/', include(admin.site.urls)),
)

The objective of my app is to allow users to upload a file and submit to the associated SQLite database. How do I accomplish this without a MEDIA_ROOT or MEDIA_URL?

Copy version history of Sharepoint 2010 documents using Javascript

So I am have an html file which I am linking a content editor on a document library in SharePoint. So far it works to do what I was intending for it to do which is copy a file from one sharepoint doc library to another one somewhere else on the site. (The JSfiddle won't work because the links are obviously broken to my sharepoint but I put it in there to organize it a bit better.) Please note I am pretty noob at web languages but I work for the government so I have been waiting weeks for a Visual Studios license for my work computer so I can write this in C# but... Its the government.. It'll be a few more weeks before that's an option.

When its in Sharepoint and the links are correct, it loads the files from source doc library and creates checkbox HTML tags with the file name, the user then selects the files they want by checking the appropriate boxes, then it copies each selected file over to the target doc library. Simple stuff.

HOWEVER, I am running into an issue when I was told just this morning I need to move SP version history and any other file metadata along with the file. From the research I've done on the subject I have sort of figured out the moveTo() method can move metadata but it won't leave a copy of the file in the source doc library which won't work for my purposes. And the copyTo() method simply starts the new copy of the file at version 1.0 or 0.1.

So my question is.. Is there a simple way to move metadata of a file with out significantly altering my code? I have noticed there is a property in SP.File called versions.. I haven't figured out how to use it but I was hoping some one would know how to move that property along with the file.

Thanks in advance for any help you can provide and here's my code.

http://ift.tt/1C1Rirs

Here is the ENTIRE html file I'm linking to in the content editor incase you wanna test it out. You just need to edit the trgURL and srcURL to doc library relative URLs on your SharePoint site.

<!DOCTYPE html>
<html>
<Head>
    <title>Copy Function</title>
    <!--Programmer:James Harrington. Intern, SGT inc. 2015-->
    <script src="http://ift.tt/1rfghyb">
</script>
<style>
h1 { color: #223355; font-family: 'Open Sans', sans-serif; font-size: 24px;}
p { color: #223355; font-family: 'Open Sans', sans-serif; font-size: 12px;}
    .b
    {
        padding-left:10px;
        padding-right:10px;
        color: white;
        border-radius: 4px;
        text-shadow: 0 1px 1px rgba(0,0,0,0.2);
        background-color: #223355;
    }

    #FormContainer
    {
    background-color:#eeeeee;

    -webkit-box-shadow:0 1px 4px rgba(0, 0, 0, 0.3), 0 0 40px rgba(0, 0, 0, 0.2) inset;
       -moz-box-shadow:0 1px 4px rgba(0, 0, 0, 0.3), 0 0 40px rgba(0, 0, 0, 0.2) inset;
            box-shadow:0 1px 4px rgba(0, 0, 0, 0.3), 0 0 40px rgba(0, 0, 0, 0.2) inset;
            margin:10px;
            padding-left:20px;
            padding-top:20px;
            padding-bottom:20px;
            width: 400px;
    }

    #FileContainer
    {
        padding-bottom:20px;
    }

    #brand
    {
        width:70px;
        height:70px;
    }

</style>
</Head>
<body>

<!--Button to load checkbox list-->
<div id="FormContainer">
    <!--EDIT IMAGE URL IN LINE BELOW!!!-->
    <img id="brand" style="display:block; position: absolute; margin-left:280px;" src="meatball.png" />
    <h1 id="fromto">Copy Files: </h1>
    <input id="FileGetter" class="b" type="button" onclick="getFilesInFolder()" value="Load Files"></input><br>

    <!--Contains checkboxes--->
    <div id="FileContainer">

    </div>

    <!--Performs file fetch-->
    <input id="FileLoader"  class="b" type="button" onclick="ProcessFiles()" value="Copy"></input><br>
</div>


<script type="text/javascript">

//EDIT TARGET/SOURCE URLS BELOW
    var trgURL = "PUT YOUR TARGET DOC LIBRARY RELATIVE URL HERE";
    var srcURL = "PUT YOUR SOURCE DOC LIBRARY RELATIVE URL HERE";
//EDIT TARGET/SOURCE URLS ABOVE

    //On Document Load
    $(document).ready(function()
    {
        //Hide the load button until files are listed
        $('#FileLoader').hide();
        setToFromTitle(trgURL, srcURL);
    });

    //set From/To Title
    function setToFromTitle(trg, src)
    {
        var trgFolderName = trgURL.substr(0, trgURL.length-1);
        trgFolderName = trgFolderName.split("/").pop();
        var srcFolderName = srcURL.substr(0, srcURL.length-1);
        srcFolderName = srcFolderName.split("/").pop();
        $('#fromto').html("<p style='font-size:100%'>Copy Files: </p><p>" + srcFolderName + "  >>>  " + trgFolderName + "</p>");
    }

    var files;//list of files
    //Attempt to find files in input URL.
    function getFilesInFolder()
    {
        var context = SP.ClientContext.get_current();
        var web = context.get_web();
        var folder = web.getFolderByServerRelativeUrl(srcURL);
        files = folder.get_files();
        context.load(files);
        context.executeQueryAsync(Function.createDelegate(this, this.OnSuccess), Function.createDelegate(this, this.OnFailure));
    }
    //If file list is loaded correctly
    function OnSuccess()
    {
        var listItemEnumerator = files.getEnumerator();
            //Loops through every file URL in folder
            while (listItemEnumerator.moveNext())
            {   
                //gets URL of current URL
                var fileUrl = listItemEnumerator.get_current().get_serverRelativeUrl();
                //splices file name off of end of URL
                var fileName = fileUrl.split("/").pop();
                //adds a check box with proper info
                var htmlToAdd = "<input class='docbox' class='check' type='checkbox' name='"+fileUrl+"'>"+fileName+"</input><br>"
                $('.check').css("margin-bottom","5px");
                $('#FileContainer').append(htmlToAdd);
            }
        //show file checkboxes and copy button
        $('#FileContainer').hide();
        $('#FileContainer').slideDown("slow");
        $('#FileGetter').hide();
        $('#FileLoader').show();
    }
    //If file list is loaded incorrectly
    function OnFailure(sender, args) {
        alert("Failed. Message:" + args.get_message());
    }

    //file fetch on selected check boxes
    function ProcessFiles()
    {
        $('.docbox').each(function()
        {
            var check = $(this);
            var url = this.name
            var file = url.split("/").pop();
            if(check.is(':checked'))
            {
                copy(file, url);
            }
        });

        $('#FileGetter').show();
        $('#FileContainer').empty()
        $('#FileLoader').hide();
    }

//uses SP.File.copyTo() funtion to move individual file from source doc lib to target doc lib
    function copy(filename, exacturl)
    {
        try
        {
            var context = SP.ClientContext.get_current();
            var web = context.get_web();
            var file = web.getFileByServerRelativeUrl(exacturl);//target file to look at
            var target = trgURL+filename;//build target location url
            file.copyTo(target, true);//copy set 2nd parameter: true=overwrite - false=do not overwrite
            context.executeQueryAsync(Function.createDelegate(this, this.successHandler), Function.createDelegate(this, this.errorHandler));
        }
        catch(err)
        {
            alert(err.message);
        }
    }

    function successHandler() {
        alert("success!");
        location.reload(true);
    };

    function errorHandler() {
        alert("The file didn't copy. Please Try again or contact sharepoint admin if the problem persists.");
    };


</script>

</body>
</html>

How to retrieve as a text the value of a very long varcharmax in SSMS

I can't find the exact solution to this problem. I have a SQL script that creates another very long script in different steps.

What i do is, along the script, to add new pieces of script to a varchar(max) using concatenation. The final script is so long that it's difficult for me to get it. I use the following as the final instruction:

SELECT [processing-instruction(x)] = @MyScript 
FOR XML PATH(''), TYPE;

In this way I can manage to get quite long results with this but sometimes the result is so long that it seems SSMS runs out of memory.

I tried saving my variable @MyScript by selecting it and saving the result as a text or a file but it saves less than 20K characters. I have set the XML max output length as unlimited and it seems to work but when I click on the result cell with the blue content (the xml with the script) then SSMS freezes.

The nice thing is that APPEARENTLY the script is generated quite fast (I am logging with print the different steps) but I can't see the results of my efforts.

Is there some way i can get hold of the content of this lengthy varchar(max) ?

Thanks

mmap() and read(). what are they? cons and pros of each one?

I have a homework to compare mmap() and read(). while I've read some webpages, I didn't understand what exactly each does, especially mmap()!

now there are some questions that I didn't understand yet...

  1. what does mmap exactly does? does it bring the whole file to memory? or it only fetches the address to address space of the process? 2.does mmap() work due to demand paging?
  2. what does read() do exactly? what chunk is best for a file? (we know the file-size)
  3. when should we use mmap()? when read()?

as I mentioned above, the aim is to compare these two system calls (right?!). for this goal, I counted the number of printable characters and spaces in three files: 800MB , 8 MB , 38 kB. here is the result: (they show time for counting printable characters and spaces for each file) enter image description here why are those up and downs for? in other words, why mmap is not always better? (it seems it works best usually!)

Listening for new files and copy them with python script

Hi I want to make a script that listens for new files send to a folder and copy them to another folder how can I do this?

Get the first column of a file and save it into a File

I want to extract the first column in a file using the delimiter "," and save it into a new File. Output generates this exception :

Exception in thread "main" java.lang.NullPointerException
    at Extract.main(Extract.java:26)

Here is the code that I used butI am not sure if it is correct or not:

public class Extract {

    public Extract()
    {
    }

     public static void main(String[] args) {

            BufferedReader in = null;
            try {
                BufferedWriter out = new BufferedWriter(new FileWriter("/home/omar/Téléchargements/nursery.tmp"));


                in = new BufferedReader(new FileReader("pima.txt"));
                String read = null;
                while ((read = in.readLine()) != null) {
                    read = in.readLine();
                    String[] splited = read.split(",");
                    if (splited.length > 0)
                    {
                        out.append(splited[0].toString());
                        out.newLine();
                    }

                }

            } catch (IOException e) {
                System.out.println("There was a problem: " + e);
                e.printStackTrace();
            } finally {
                try {
                    in.close();

                } catch (Exception e) {
                }
            }
            File f = new File("prima.txt");
            f.delete();

            File f2 = new File("pima.tmp");
            f2.renameTo(new File("pima.txt"));

     }



}

downloading created excel file using jquery from asmx web service

I have a problem that has been driving me crazy. I am trying to create an asmx webservice to create an excel file and download it to the client machine.

I have written an asmx webservice, where I create the excel file perfectly and saveit on the server.then I send back the address of the excel file on the server to the client using this code

 $.ajax({
    type: "POST",
    url: '/API/Services/http://ift.tt/1LQrTB1',
    data: JSON.stringify(params),
    async: false,
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function (data) {

            window.location.replace(data);

    }
});

In my jquery I call the webservice, it runs, the excel is created and the physical address is returned.

the problem is that I do not know how to download the excel file to the client's machine.

I searched a lot and many posts said that its as easy as writing a window.location.replace(excellAddressOnServer).

However,when I do this, the page is redirected to another one, where the exceladdress is written in the address bar but the page shows an error which says that the address wasn'tundrestood.

The wonder is that when I press enter on the address bar, it starts to download the file without any problem.

what is wrong with my code?

PHP delete files with filename lower than pattern

I need to delete files with name of UNIX timestamp, those with lower number then I specified. I heard something about glob() but I'm not sure how to use it in this case. Best would be putting filenames in array to use loop to remove them

Thanks for your help!

Destination file that reflects source folders grunt

sorry if the name of this thread is a bit weird. It's hard to explain in one line.

Basically, this is what I want my folder setup to look like:

                html5
                  |
   src-----------------------build------_config
    |                           |           |
  master                      master    Gruntfiles etc
    |                           |
css-images-js-index.html        |
 |    |    |                    |
.css .jpg .js                   |
                                |
                           .css .jpg .js

From my root folder (html5) I have a src and a build folder. In both of them, there will be a lot of more folders than the master folder, all of which will have the same layout (different formats). What I basically want to happen, is I want the content in the src > master folder to be flattened into the corresponding build > master folder. I've tried the flatten option shown here, however, that flattens the entire thing, causing the contents of the master folder to be put straight in the build folder, which is not what I want. I've been messing some with the rename function, but it seems overly complicated for this task. Is there no other way to do this?

EDIT: I have this task:

    copy: {
        images: {
            files: [
                {
                    expand: true,
                    flatten: true,
                    cwd: "../src/",
                    src: ["**"],
                    dest: "../build/master",
                    filter: "isFile"
                },
            ]
        }
    },

Which does exactly what it's supposed to do. However, I really need the destination folder "master" to be dynamic. It should not be hard-coded like it is right now. It needs to be the corresponding folder that was copied from the src folder. It doesn't work to put "**" there unfortunately.

What is the easiest and best library to use when zipping files in C#?

I need to zip some files before they are uploaded to a ftp server and i need a very easy way that does not require a lot of skill

java8 class for composing file paths

I'm currently reworking some code of mine. This code looks currently something like this:

File makeFile() {

    StringBuilder builder = new StringBuilder();

    builder.append( "/" );

    if( a ) builder.append( foodir ).append( '/' );
    if( b ) builder.append( bardir ).append( '/' );

    builder.append( "file.txt" );

    return new File( b.toString() );
}

I really don't like this code very much because it uses StringBuilder to build something which should really be some kind of Path object in the first place.

So is there -- at least in Java8 -- some means of building Path or File objects in a more clean way?

(Note: I'm not looking for using Collections and later joining them. I'm looking for something working directly with filesystem objects.)

how to print null or zero for empty fields in the file

If while reading some fields are blank then how to print 0 for integer and null for string?what can I do??

Please help me with this. It is reading name,rollno,age,street,city and zip from file but if age or zip is empty I want to print 0 and if data type is string and field is empty we want to print null.

Can anyone help me with it.

code:-

public class PrintStudentsFromFile {

public static void main(String[] args) {

 List<Student> students= new PrintStudentsFromFile().populateData("path to text file");


 for (Student student : students) {
        System.out.println(student);
    }
}
/**
 * Reads Files and returns a List of Students
 * @param filename
 * @return 
 */
public List<Student> populateData(String filename){
Scanner s = null;
String nameAndRollNumber="";
    try {
        s = new Scanner(new File(filename));

    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }
    List<Student> list = new ArrayList<Student>();
    while (s.hasNext()) {
    nameAndRollNumber = s.nextLine();
    String[] nameAndRollNumbers = nameAndRollNumber.split("\\s+");
    String name = nameAndRollNumbers[0];
    String roll = nameAndRollNumbers[1];
    list.add(new Student(name, roll));
    }
    s.close();
    return  list;
}

} /** * * Student Object , with name and Roll Number Params */ class Student{

String name;
String rollNumber;

public Student(String name, String rollNumber) {
    this.name = name;
    this.rollNumber = rollNumber;
}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public String getRollNumber() {
    return rollNumber;
}

public void setRollNumber(String rollNumber) {
    this.rollNumber = rollNumber;
}

@Override
public String toString() {
    return "Name :"+name+"- Roll Number : "+rollNumber;
}

}

one of friend has helped me with this. but i am not getting how to enter 0 or null for empty fields

Get app apks without root

I want to get apps apk without getting Root I know that apks stored in /data/app/base.apk

But I have seen apps that do so get apk without requesting Root

Image browse not working in 5.1 android device

Hello friends i want to browse my gallery image in my so below is my code

enter image description here

see above image i click on Photos application .

Button Click

protected void importImage() 
{
    Intent intent = new Intent(
            Intent.ACTION_PICK,
            android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
    intent.setType("image/*");
    startActivityForResult(
            Intent.createChooser(intent, "Select File"),
            currentRequestCode);

}

onActivityResult

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) 
{
    super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == currentRequestCode) 
        {
            if (data!=null) {
                openGalleryImage(data);
                saveImage(uri_outputFileUri.getPath());
            }

        }
        else if (requestCode == REQUEST_CAMERA) {

            Bitmap thumbnail = null;

            try {
                thumbnail = (Bitmap) data.getExtras().get("data");
            } catch (Exception e) {
                // TODO: handle exception
            }


            try {
                if(thumbnail != null){
                    ByteArrayOutputStream bytes = new ByteArrayOutputStream();
                    thumbnail.compress(Bitmap.CompressFormat.PNG, 100, bytes);

                    File file = new File(Environment.getExternalStorageDirectory()
                            + File.separator + Long.toString(System.currentTimeMillis())+".png");
                    file.createNewFile();
                    FileOutputStream fo = new FileOutputStream(file);
                    fo.write(bytes.toByteArray());
                    fo.close();
                    mStringGetImagePath = String.valueOf(file);
                    saveImage(mStringGetImagePath);
                    System.out.println("mStringGetImagePath "+mStringGetImagePath);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        } 
}

openGalleryImage

private void openGalleryImage(Intent data) 
    {
        Uri selectedimg = data.getData();
        Uri uriselectedimage=data.getData();
        mString=uriselectedimage.getPath();
        try 
        {
            mInputStream=getActivity().getContentResolver().openInputStream(selectedimg);
        }
        catch (FileNotFoundException e) 
        {
            e.printStackTrace();
        }

        String[] path = { MediaStore.Images.Media.DATA };
        Cursor c = getActivity().getContentResolver().query(selectedimg, path, null, null,null);
        c.moveToFirst();
        int columnIndex = c.getColumnIndex(path[0]);
        selectedimage_paths=c.getString(columnIndex);

        uri_outputFileUri= Uri.parse(selectedimage_paths);
        c.close();
    }

When i run above code it gave me null pointer error at line this uri_outputFileUri= Uri.parse(selectedimage_paths);

this code is runable to all 4.0 ,4.1,4.2,4.3,4.4 device only problem in 5.0and 5.1 device

Good practice for working with files in ASP.NET web api?

I'm new working with files so i have done some reading, altough i feel that i'm still not certain how to deal with them using asp.net web api. What i want is to be able to reach images thru my web api. What i've read so far is that many people prefer saving the file and then call for its URI, instead of saving the image to the database u only save the URI there. So I then created a imageController on the web api that does exactly this(Atleast working using localhost). I now get some people arguing that i should use blob storage(since i use Azure).

My question is: Is it wrong or bad practice to have a folder where i save my image files? Else what would be the better way to save images?

How to read a xml file in android without internet connection?

I would be glad if you help me. I have an app. When I open the app, writing XML file to "sdcard/example.xml". (with internet connection) But when I open the app without internet connection, the app does not read XML file. Here is my code;

class RetrieveFeedTask extends AsyncTask<String, Void, String> {

    private Exception exception;

    protected String doInBackground(String... urls) {
        try {
            File xmlWriteSd = new File("/sdcard/example.xml");
            FileOutputStream fos = new FileOutputStream(xmlWriteSd);
            xmlDownload(fos,"http://ift.tt/1BQfs81");
            xmlRead();
            return null;
        } catch (Exception e) {
            this.exception = e;
            return null;
        }
    }

    protected void onPostExecute(String feed) {
    }
}

And the xmlDownload function is

public void xmlDownload(FileOutputStream fout, final String urlString) throws MalformedURLException, IOException {
    BufferedInputStream in =null;
    File file = new File("/sdcard/example.xml");
    if(!file.exists())//control
        return;
    try {

        in = new BufferedInputStream(new URL(urlString).openStream());

        final byte data[] = new byte[1024];
        int count;
        while ((count = in.read(data, 0, 1024)) != -1) {
            fout.write(data, 0, count);
        }
    } finally {
        if (in != null) {
            in.close();
        }
        if (fout != null) {
            fout.close();
        }
    }
}

and xmlRead function is;

private void xmlRead() {
    try {
        File fXmlFile = new File("/sdcard/example.xml");
        DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
        Document doc = dBuilder.parse(fXmlFile);
        doc.getDocumentElement().normalize();

        NodeList nList = doc.getElementsByTagName("item");

        for (int temp = 0; temp < nList.getLength(); temp++) {
            final ExampleObject  = new YemekNesne();

            Node nNode = nList.item(temp);

            if (nNode.getNodeType() == Node.ELEMENT_NODE) {

                Element eElement = (Element) nNode;

                ExampleObject .setDate(eElement.getElementsByTagName("Date").item(0).getTextContent());
                ExampleObject .setmain(eElement.getElementsByTagName("main").item(0).getTextContent());
                ExampleObject .setsecond(eElement.getElementsByTagName("second").item(0).getTextContent());
                ExampleObject .setextra(eElement.getElementsByTagName("extra").item(0).getTextContent());
                ExampleObject .setExample(eElement.getElementsByTagName("Example").item(0).getTextContent());
                listOfExample.put(ExampleObject .getDate(),ExampleObject );//hash map
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

How can i (ONLY) read xml file without internet?